Jump to content

User:Lookup database/Scripts/Python/24game.py

From Wikipedia, the free encyclopedia
This is the current revision of this page, as edited by BrownHairedGirl (talk | contribs) at 20:19, 1 April 2021 (@Lookup database: Disable the categories on this page while it is still a draft, per WP:DRAFTNOCAT/WP:USERNOCAT (using Draft no cat v1.5). The easiest way to do this is by converting them to links, by adding a colon: "[[Category:" → "[[:Category:"). The present address (URL) is a permanent link to this version.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

User Page | User Talk | Lookup Database | Contribs | Subpages

Category:Lookup database


Here is a program which can solve the infamous "24 Game" for any 4 numbers, taken from user input.

def shuffle(nums):
    list = []

    for a in range(4):
        for b in range(4):
            for c in range(4):
                for d in range(4):
                    list.append([nums[a - 1], nums[b - 1], nums[c - 1], nums[d - 1]])

    return list

def num():
    in = input("Enter the 1st number: ");
    try:
        in = int(in)
        return in
    except:
        print("Enter an integer")
        return num()

#Generate list
import random
nums = [num(), num(), num(), num()]
print(nums)

#Check each possibility:
for list in shuffle(nums):
    for a in ['+', '-', '*', '/']:
        for b in ['+', '-', '*', '/']:
            for c in ['+', '-', '*', '/']:
                expression = str(list[0] + a + list[1] + b + list[2] + c + list[3])
                
                if int(eval(expression)) == 24:
                    print(expression)

Category:Python_(programming_language)