Jump to content

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

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Lookup database (talk | contribs) at 14:00, 10 September 2020. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

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)