如何解决我几天无法解决的Array任务?

时间:2018-08-22 12:54:23

标签: python arrays list

我正在尝试制作一个程序,输出所有可能在数字1,2,…,9之间加+或-或不加任何运算,使得结果为100

可以理解,有些人已经在互联网上上传了解决方案,但是我想提出自己的解决方案。这是无效的代码:

"""
This program outputs all possibilities to put + or - or nothing between the numbers 1,2,…,9 (in this order) such that the result is 100
"""

class solver:

def __init__(self):
        """
        self.possibilities stores Arrays of type : [0]- always the sum of all operations 
        [1:9] all operations in int, where 0 equals plus, 1 equals minus, 2 equals nothing
        """
        self.possibilities = []

        self.possibilities.append([100])

        for i in range(7):
            self.possibilities.extend(self.makeNewIteration(i+1))

        print(self.possibilities)

        for obj in self.possibilities:
            if 100 is obj[0]:
                print(obj)

def makeNewIteration(self, i):
        for obj in self.possibilities:
            if(len(obj)<9):
                if(obj[-1] is 3):#if case 3
                    #recalculate the result
                    currentResult = int(obj[0] + self.conceal(i-1, i))
                else: currentResult = int(obj[0])
                #print(obj)
                possibilitiesNew = []
                possibilitiesNew.append([currentResult + i] + obj[1:] + [1])#case 1
                possibilitiesNew.append([currentResult - i] + obj[1:] + [2])#case 2
                possibilitiesNew.append([currentResult] + obj[1:] + [3])#case 3

                print("Iteration: "+str(i)+" : "+str(possibilitiesNew))

                self.possibilities.remove(obj)#remove the old object
            else:
                print("finished.")
        return possibilitiesNew

def conceal(self, x, y):
    # makes 12 out of x=1 and y=2
    return int(f'{x}{y}')

solve = solver()

我思考得越多,我遇到的问题就越多。 我曾经以OOP的心态来学习编程,而事实上这是很久以前的事了,而且程序操作流程使这个问题变得容易得多,这让我陷入了困境。例如,如果连续两次“什么都没有”会发生什么? 1,2,3,4变成12,23? ...我希望有人可以修复该代码,并找出我做错了什么

2 个答案:

答案 0 :(得分:0)

我的第一个方法是

import itertools as it
import re

all_those_terms = (''.join([(sgn + str(i+1)) for i, sgn in enumerate(tpl)]) for tpl in it.product(['', '-', '+'], repeat=9) if tpl[0]!='')
for s in all_those_terms:
    r = re.findall('[+-]\d+', '+'+s)
    calc = sum(map(int, r))
    if calc == 100:
        print(s, '=', 100)

-1+2-3+4+5+6+78+9 = 100
+123-45-67+89 = 100
+123-4-5-6-7+8-9 = 100
+123+45-67+8-9 = 100
+123+4-5+67-89 = 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

但是,eval应该替换,因为这很危险...

我会再编辑一遍...

编辑:替换为eval ...

答案 1 :(得分:0)

Although eval should be avoided, here's another solution that uses it:

from itertools import product

[''.join(i) for i in product(*[[str(j)+'+', str(j) + '-', str(j)] for j in range(1, 9)] + ['9']) if eval(''.join(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+67-89', '123+45-67+8-9', '123-4-5-6-7+8-9', '123-45-67+89']