数字小游戏
- 请生成一个存储54个数字的list,这54 个数字包括:1-3各3个,4-6各10个,7-9各4个,10-12各1个(必须使用for 循环实现)。
- 请用random 包中提供的功能将这 54个数字随机打乱。
- 游戏1:从list 中取出一个数字,作为目标数宇,再从list 中取出2个数字作为运算数宇,请用加法或者减法将运算数字算成目标数字,将计算结果写到文件 resultl.txt 中(如果运算数字不能算出目标数字也需输出信息告知)。
然后再从 list 中取下一轮的目标数和运算数,直到list 中剩下的数宇个数小于3个。 -
游戏2:从list中取出一个数字,作为目标数字:再从 ist 中取出3个数字作为运算数字,请用加、减、乘、除四
种计算方式将运算数字算成日标数字,将计算结果写到文件 result2.txt 中(如果运算数字不能算出目标数宇也篇输出信息告知)。然后再从 list 中取下一轮的目标数和运算数,直到 list 中剩下的数字个数不足以构成一个计算局(也就是剩下数字个数小于4个)。
代码编写:
import random
# 生成包含54个数字的list
nums = []
for i in range(3):
nums.extend([1,2,3])
for i in range(10):
nums.extend([4,5,6])
for i in range(4):
nums.extend([7,8,9])
nums.extend([10,11,12])
# 将list随机打乱
random.shuffle(nums)
# 定义计算函数
def calc(target, nums, ops):
if len(nums) == 1:
if nums[0] == target:
return True, str(nums[0])
else:
return False, ''
for i in range(len(nums)):
for j in range(i+1, len(nums)):
a, b = nums[i], nums[j]
rest = [nums[k] for k in range(len(nums)) if k != i and k != j]
for op in ops:
if op == '+':
c = a + b
found, exp = calc(target, rest+[c], ops)
if found:
return True, str(a)+'+'+str(b)+'='+str(c)+'; '+exp
elif op == '-':
c = a - b
found, exp = calc(target, rest+[c], ops)
if found:
return True, str(a)+'-'+str(b)+'='+str(c)+'; '+exp
elif op == '*':
c = a * b
found, exp = calc(target, rest+[c], ops)
if found:
return True, str(a)+'*'+str(b)+'='+str(c)+'; '+exp
elif op == '/' and b != 0 and a % b == 0:
c = int(a / b)
found, exp = calc(target, rest+[c], ops)
if found:
return True, str(a)+'/'+str(b)+'='+str(c)+'; '+exp
return False, ''
# 游戏1
with open('result1.txt', 'w') as f:
while len(nums) >= 3:
target = nums.pop()
a, b = nums.pop(), nums.pop()
found, exp = calc(target, [a, b], ['+', '-', '*', '/'])
if found:
f.write(f"Target: {target}, Numbers: {a} {b}\n{exp}\n")
else:
f.write(f"Target: {target}, Numbers: {a} {b}\nNo solution\n")
# 游戏2
with open('result2.txt', 'w') as f:
while len(nums) >= 4:
target = nums.pop()
a, b, c = nums.pop(), nums.pop(), nums.pop()
found, exp = calc(target, [a, b, c], ['+', '-', '*', '/'])
if found:
f.write(f"Target: {target}, Numbers: {a} {b} {c}\n{exp}\n")
else:
f.write(f"Target: {target}, Numbers: {a} {b} {c}\nNo solution\n")