python新手,我很难将脚本转换为更有效的算法。帮助将算法转换为python代码
这里的Python代码:
#!/usr/bin/env python
import itertools
target_sum = 10
a = 1
b = 2
c = 4
a_range = range(0, target_sum + 1, a)
b_range = range(0, target_sum + 1, b)
c_range = range(0, target_sum + 1, c)
for i, j, k in itertools.product(a_range, b_range, c_range):
if i + j + k == 10:
print a, ':', i/a, ',', b, ':', j/b, ',', c, ':', k/c
(它只做只是举例3个变量,但我想要的到底是把它用在成千上万的变量)。
这里是我要找的结果(全部,使其产生10组合的):
1 : 0 , 2 : 1 , 4 : 2
1 : 0 , 2 : 3 , 4 : 1
1 : 0 , 2 : 5 , 4 : 0
1 : 2 , 2 : 0 , 4 : 2
1 : 2 , 2 : 2 , 4 : 1
1 : 2 , 2 : 4 , 4 : 0
1 : 4 , 2 : 1 , 4 : 1
1 : 4 , 2 : 3 , 4 : 0
1 : 6 , 2 : 0 , 4 : 1
1 : 6 , 2 : 2 , 4 : 0
1 : 8 , 2 : 1 , 4 : 0
1 : 10 , 2 : 0 , 4 : 0
问题Can brute force algorithms scale?更好的算法建议,但我有一个很难实现中的逻辑蟒蛇。新的测试代码:
# logic to convert
#for i = 1 to k
#for z = 0 to sum:
# for c = 1 to z/x_i:
# if T[z - c * x_i][i - 1] is true: #having trouble creating the table...not sure if thats a matrix
# set T[z][i] to true
#set the variables
sum = 10
data = [1, 2, 4]
# trying to find all the different ways to combine the data to equal the sum
for i in range(len(data)):
print(i)
if i == 0:
continue
for z in range(sum):
for c in range(z/i):
print("*" * 15)
print('z is equal to: ', z)
print('c is equal to: ', c)
print('i is equal to: ', i)
print(z - c * i)
print('i - 1: ', (i - 1))
if (z - c * i) == (i - 1):
print("(z - c * i) * (i - 1)) match!")
print(z,i)
对不起它显然相当混乱,我不知道如何来生成具有部分的表:
if T[z - c * x_i][i - 1] is true:
set T[z][i] to true
在其他地方,而转换算法中,我有更多的问题,因为像'或i = 1到k'这样的行将其转换为python会给我一个错误,提示“TypeError:'int'object is not utterable”
任何帮助或建议都会很棒。我已经学习了Python中的语法,但还没有用算法做任何事情(所以请和我一起裸照)。
在此先感谢。
你使用Python 3个工作?如果您使用Python 2,请执行print foo而不是print(foo)。 –
在Python 2.x中使用'print(foo)'并不错,所以如果他喜欢它,不要告诉他不要使用它!在这里发布时,我会自己花很多时间。 – steveha
嗯Chris..I在python2中写了这个,但最终会将它改为python3(现在我对python2更加熟悉,但是我试图为python3-ish尽可能为新手提供:-) – Lostsoul