【发布时间】:2011-09-02 05:45:05
【问题描述】:
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? 建议使用更好的算法,但我很难在python 中实现逻辑。新的测试代码:
# 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
在其他地方,在转换算法时,我遇到了更多问题,因为在像 'or i = 1 to k' 这样的行中,将它转换为 python 会给我一个错误,说“TypeError:'int' object is not utterable”
【问题讨论】:
-
你在使用 Python 3 吗?如果您使用的是 Python 2,请使用
print foo而不是print(foo)。 -
在 Python 2.x 中使用
print(foo)并没有错,所以如果他喜欢它,不要告诉他不要使用它!我在这里发帖时经常自己这样做。 -
嗯,克里斯..我在 python2 中编写了这个,但最终会努力将其更改为 python3(现在我对 python2 有点熟悉,但我尽量像 python3-ish一个新手:-)
-
range(z/i) 中的 c 行不正确 -- 尝试 range(int(z/i))
-
index_accumulator.append([lol[i][indices[i]] for i in range(len(lol))])的拼写更惯用index_accumulator.append(l[index] for l, index in zip(lol, indices)])。