【问题标题】:how to loop over the elementary arithmetic symbols如何遍历基本算术符号
【发布时间】:2017-12-03 07:04:35
【问题描述】:

我想检查 7 位数字在它们之间放置基本算术符号时是否可以达到 100。

def is_hundred(n1,n2,n3,n4,n5,n6,n7):
    p = [+,-,*,/]
    for p1 in p:
        for p2 in p:
            for p3 in p:
                for p4 in p:
                    for p5 in p:
                        for p6 in p:
                            if n1 p1 n2 p2 n3 p3 n4 p4 n5 p5 n6 p6 n7 == 100:
                                return "success"

如何用列表中的算术符号替换变量?

【问题讨论】:

  • 你最好解构循环
  • 什么意思?
  • 每个运营商都有自己的电路,因此试图找到“通用电路”可能是不可能的。而是使用 'if (p1='+') plus(n1,n2); if (p1='*') times(n1,n2)' 等...
  • 两位数很简单,但我想做到 7
  • 你的伪代码对 7 不起作用

标签: python-3.x for-loop elementary-functions


【解决方案1】:

如果您没有听到:使用eval 是邪恶的。所以这绝对是我投入生产的不是代码。也就是说,这个练习也是我可能永远不必部署到产品...

想法:使用参数和“蛮力”在它们之间添加操作的所有可能性。将这些选项构造为字符串,并在完成后对每个选项进行评估(使用eval),如果总数为 100 - 将其打印到标准输出:

def is_hundred(args, res=''):
    if res == '':
        res = args[0]
        args = args[1:]
    if not args:
        if eval(res) == 100:
            print(res)
    else:
        first = args[0]
        for op in ['+','-','*','/']:
            is_hundred(args[1:], "{}{}{}".format(res, op, first))


# you can pass any number of arguments in a list: 7, 8, 15...
is_hundred([2,3,4,8,10,11])  # 2+3+4+8*10+11

【讨论】:

  • 你能解释一下什么是eval,args,什么是.format?
  • 在答案中添加了指向eval 的链接,args - 是您传递给函数的数字列表,format 是一个字符串方法,在上面的示例中:@ 987654327@ 相当于:res + op + str(first)
【解决方案2】:

这是一个搜索一对运算符的示例代码。 iadd 中的 i 表示就地 add 运算符。您可以简单地切换到addproduct 创建运算符的重复排列。

from operator import iadd, isub, imul, itruediv
from itertools import product

operators = (iadd, isub, imul, itruediv)

def is_hundred(values):
    n_operators = len(values) - 1

    for ops in product(operators, repeat=n_operators):
        value = values[0]
        for op, v in zip(ops, values[1:]):
            value = op(value, v)
        if value == 100:
            print(list(ops))
            return True
    else:
        return False

print(is_hundred([99,1,1,1,1,1]))
print(is_hundred([1,1,1,1]))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多