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 13:43, 10 September 2020 (Created page). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

Here is a program which can solve the infamous "24 Game" for any numbers.

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

                    
#Generate list
import random
nums = [str(random.randint(1, 9)), str(random.randint(1, 9)), str(random.randint(1, 9)), str(random.randint(1, 9))]
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)