【问题标题】:With a string of numbers generate variations with addition, subtraction or nothing to make 100用一串数字产生变化,加法、减法或什么都没有,使 100
【发布时间】:2021-07-25 21:57:56
【问题描述】:

我有一串数字,string="123456789",我想打印所有变体,在数字之间插入加法、减法或什么都不加,得到 100。大多数数字的顺序保持不变。

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

我什至不知道如何开始。我想列出所有可能的 +-x 组合(x 代表什么)并插入每个组合并对其进行测试,但这似乎需要很长时间。 有什么建议吗?

【问题讨论】:

  • 3^8 只有 6561,所以枚举所有可能性看起来很可行
  • 我该怎么做呢?我需要 8 个值,但只有 3 个东西可以放入其中。我发现的代码只支持少于起始长度的值(例如 itertools.combinations)

标签: python python-3.x sequence variations


【解决方案1】:

您可以使用itertools 模块中的productzip_longest 来实现。我们建立所有可能的组合,然后evaluate 它们只过滤出评估为 100 的组合。

from itertools import product, zip_longest

operations = ['-', '+', '']
s = '123456789'

combinations = (zip_longest(s, ops, fillvalue='') for ops in product(operations, repeat=8))

to_eval = (''.join(i + j for i, j in combination) for combination in combinations)

print([i for i in to_eval if eval(i) == 100])

>>> ['1+2+3-4+5+6+78+9', '1+2+34-5+67-8+9', '1+23-4+5+6+78-9', '1+23-4+56+7+8+9', '12-3-4+5-6+7+89', '12+3-4+5+67+8+9', '12+3+4+5-6-7+89', '123-4-5-6-7+8-9', '123-45-67+89', '123+4-5+67-89', '123+45-67+8-9']

eval() 本质上并不坏,只是如果任何用户输入可以进入您正在评估的事物中,它可能会导致严重的安全问题(这里不是这种情况)。为个人项目执行此操作很好。在生产环境中,您可能希望自己解析字符串或找到不同的方法。

优化说明请看这里:Most pythonic way to interleave two strings

【讨论】:

  • Eval 本身并不是坏事,只是如果任何用户输入可以进入您正在评估的内容(这里不是这种情况),它可能会导致严重的安全问题。为个人项目执行此操作很好。在生产环境中,您可能希望自己解析字符串或找到不同的方法。
【解决方案2】:
a = ['+', '-', '']
nb = '123456789'
target = 100
N = len(nb)-1

for n in range(3**N):
    attempt = nb[0]
    for i in range(N):
        attempt += a[n % 3]
        attempt += nb[i+1]
        n = n // 3
    if eval(attempt) == target:
        print(attempt, ' = ', target)

导致

1+23-4+56+7+8+9  =  100
12+3-4+5+67+8+9  =  100
1+2+34-5+67-8+9  =  100
1+2+3-4+5+6+78+9  =  100
123-4-5-6-7+8-9  =  100
123+45-67+8-9  =  100
1+23-4+5+6+78-9  =  100
12-3-4+5-6+7+89  =  100
12+3+4+5-6-7+89  =  100
123-45-67+89  =  100
123+4-5+67-89  =  100

【讨论】:

    猜你喜欢
    • 2012-04-12
    • 1970-01-01
    • 1970-01-01
    • 2012-12-09
    • 2018-11-15
    • 2020-12-06
    • 2010-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多