使用Python3的24游戏

时间:2019-05-10 05:21:38

标签: python-3.x

24是一种心理算术游戏,首先使用扑克牌玩。给定四个整数,目标是使用标准算术运算符+,-,*和/生成数字24,同时在此过程中消耗所有四个数字。 例如,给定数字{2,3,5,6},一个人可以做。 。 。 2 * 3 = 6,5 * 6 = 30,30-6 = 24等等

注意:给定数字可以以任何顺序使用以产生24。 编写一个包含四个整数的程序,并确定是否可以从这些数字达到24。您可以假设数字0不会成为输入的一部分。

我不确定如何让函数运行我的4个输入

import itertools
ints = input('Enter 4 integers: ').split()
n1=int(ints[0])
n2=int(ints[1])
n3=int(ints[2])
n4=int(ints[4])
def with_brackets(lst, ops_lst):
    for op in ops_lst: #calculate when no brackets
        expr1 = '('+lst[0]+op[0]+lst[1]+')'+op[1]+lst[2]+op[2]+lst[3]
        expr2 = '('+lst[0]+op[0]+lst[1]+op[1]+lst[2]+')'+op[2]+lst[3]
        expr3 = lst[0]+op[0]+'('+lst[1]+op[1]+lst[2]+')'+op[2]+lst[3]
        expr4 = '('+lst[0]+op[0]+lst[1]+')'+op[1]+'('+lst[2]+op[2]+lst[3]+')'

        for expr in [expr1, expr2, expr3, expr4]:
            try:
                t=eval(expr)
            except: #except zerodivision error
                pass
            if abs(t-24) < 0.001:
                return expr
    return 0
#return 4 numbers to calculate 24
def hasMethod(numbers, ops_lst):
    for lst in itertools.permutations(numbers):
        lst = list(map(lambda x:str(x), lst))
        #without brackets
        for op in ops_lst:
            expr = lst[0]+op[0]+lst[1]+op[1]+lst[2]+op[2]+lst[3]
            if abs(eval(expr)-24) < 0.001:
                return expr
        #with brackets
        expr = with_brackets(lst, ops_lst)
        if expr != 0:
            return expr
    return 0
#method of return 4 numbers to calculate 24,no way return"No Method"
def cal_24(numbers):
    ops = ['+','-','*','/']
    ops_lst = [[i,j,k] for i in ops for j in ops for k in ops]
    expr = hasMethod(numbers, ops_lst)
    if expr != 0:
    return expr
    else:
        return 'No method!'
#ways to calculate 24 at all situaions
def main():
    numbers_lst = [[i,j,k,l] for i in range(1,14) for j in range(1,14)\
                         for k in range(1,14) for l in range(1,14)]
    for numbers in numbers_lst:
        a = list(map(lambda x: str(x), numbers))
        methodInfo = "[%s,%s,%s,%s]: %s\n"%(a[0],a[1],a[2],a[3],cal_24(numbers))
        print(methodInfo)

main()

预期结果:

示例1:

Enter 4 integers: 2 3 5 6

Yes! 24 is reachable from { 2, 3, 5, 6 }

示例2:

Enter 4 integers: 1 1 1 1

Noooo :( 24 is unreachable from { 1, 1, 1, 1 }

示例3:

Enter 4 integers: hello

Input must consist of 4 integers

1 个答案:

答案 0 :(得分:1)

这个问题很有趣。

from __future__ import division, print_function
import random, ast, re
import sys

if sys.version_info[0] < 3: input = raw_input

def choose4():
    'four random digits >0 as characters'
    return [str(random.randint(1,9)) for i in range(4)]

def welcome(digits):
    print (__doc__)
    print ("Your four digits: " + ' '.join(digits))

def check(answer, digits):
    allowed = set('() +-*/\t'+''.join(digits))
    ok = all(ch in allowed for ch in answer) and \
         all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \
         and not re.search('\d\d', answer)
    if ok:
        try:
            ast.parse(answer)
        except:
            ok = False
    return ok

def main():    
    digits = choose4()
    welcome(digits)
    trial = 0
    answer = ''
    chk = ans = False
    while not (chk and ans == 24):
        trial +=1
        answer = input("Expression %i: " % trial)
        chk = check(answer, digits)
        if answer.lower() == 'q':
            break
        if answer == '!':
            digits = choose4()
            print ("New digits:", ' '.join(digits))
            continue
        if not chk:
            print ("The input '%s' was wonky!" % answer)
        else:
            ans = eval(answer)
            print (" = ", ans)
            if ans == 24:
                print ("Thats right!")
    print ("Thank you and goodbye")   

if __name__ == '__main__': main()