如何遍历基本算术符号 [英] how to loop over the elementary arithmetic symbols

查看:184
本文介绍了如何遍历基本算术符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



I want to check if 7 digits can get to 100 when putting elementary arithmetic symbols between them.

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"

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

how can i replace the variables with the arithmetic symbols that are in the list?

推荐答案

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

Here is a sample code which search a pair of operators. the i in iadd means inplace add operator. You can simply switch to add. product creates duplicate permutation of operators.

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]))

这篇关于如何遍历基本算术符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆