python生成1到100的数组_Python实现1-9数组形成的结果为100的所有运算式的示例,python1-9...

Python实现1-9数组形成的结果为100的所有运算式的示例,python1-9

问题:

编写一个在1,2,…,9(顺序不能变)数字之间插入+或-或什么都不插入,使得计算结果总是100的程序,并输出所有的可能性。例如:1 + 2 + 34–5 + 67–8 + 9 = 100。

from functools import reduce

operator = {

1: '+',

2: '-',

0: ''

}

base = ['1', '2', '3', '4', '5', '6', '7', '8', '9']

def isHundred(num):

#转化为8位3进制数,得到运算符数组

arr = []

for index in range(8):

index = 7 - index

arr.append(num // (3 ** index))

num -= (num // (3 ** index)) * (3 ** index)

arr = map(lambda x: operator[x], arr)

#合并得到运算式

formula = reduce(lambda x, y: x + y, zip(base, arr))

formula = list(formula)

formula.append('9')

formula = ''.join(formula)

#计算运算式结果

res = eval(formula)

return res, formula

if __name__ == '__main__':

#所有可能的结果

total = 3 ** 8

for i in range(total):

res, formula = isHundred(i)

if res == 100:

print(formula+' = 100')

结果:

/usr/bin/python3.5 /home/kang/workspace/Qt3d/test.py

123+45-67+8-9 = 100

123+4-5+67-89 = 100

123-45-67+89 = 100

123-4-5-6-7+8-9 = 100

12+3+4+5-6-7+89 = 100

12+3-4+5+67+8+9 = 100

12-3-4+5-6+7+89 = 100

1+23-4+56+7+8+9 = 100

1+23-4+5+6+78-9 = 100

1+2+34-5+67-8+9 = 100

1+2+3-4+5+6+78+9 = 100

以上这篇Python实现1-9数组形成的结果为100的所有运算式的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持帮客之家。

要在Python生成0到100范围内的100道四则运算练习题,可以使用随机数生成函数`random.randint`来生成两个随机数,然后在这两个随机数之间随机选择加、减、乘、除运算。这里需要注意的是,除法时要避免除以零的情况,并且要确保结果在0到100的范围内。以下是一个简单的示例代码: ```python import random # 函数用于生成四则运算题目 def generate_question(min_val=0, max_val=100, num_questions=100): questions = [] for _ in range(num_questions): num1 = random.randint(min_val, max_val) num2 = random.randint(min_val, max_val) operation = random.choice(['+', '-', '*', '/']) if operation == '/': # 确保除法不为零,并且结果为整数 while num2 == 0 or (num1 % num2) != 0: num2 = random.randint(min_val, max_val) num1 /= num2 else: num1 = eval(f"{num1} {operation} {num2}") # 确保结果在0到100之间 if num1 < min_val or num1 > max_val: continue # 构建题目并添加到列表中 if operation == '/': question = f"{num1:.2f} {operation} {num2} = ?" else: question = f"{num1} {operation} {num2} = ?" questions.append(question) return questions # 生成题目并打印 questions = generate_question() for question in questions: print(question) ``` 这段代码首先定义了一个生成题目的函数`generate_question`,它会创建100道题目,每道题目随机选择0到100之间的两个数和一种运算符,并确保除法时除数不为零且结果为整数。最后,构建题目的字符串形并返回一个包含所有题目的列表。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值