【问题标题】:How to convert algorithm to python如何将算法转换为python
【发布时间】: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)])

标签: python algorithm


【解决方案1】:

您可以通过以下方式获取创建动态编程表的块:

from collections import defaultdict

# T[x, i] is True if 'x' can be solved
# by a linear combination of data[:i+1]
T = defaultdict(bool)           # all values are False by default
T[0, 0] = True                # base case

for i, x in enumerate(data):    # i is index, x is data[i]
    for s in range(sum + 1):
        for c in range(s / x + 1):
            if T[s - c * x, i]:
                T[s, i + 1] = True

【讨论】:

  • 谢谢你的回答,rm。我更新了我的问题以显示输出。基本上我简化了我现有的脚本,但我试图获得与我的问题链接中的答案相同的输出。
  • 已更新 - 您仍然需要使用此表来获取您想要的答案,如果存在解决方案,这将只有一个 True T[(sum, len(data))]
  • T[a, b]T[(a, b)] 整洁。
  • @Chris,是的,谢谢。应该注意到了。 , 生成元组,而不是括号。
  • @Chris 实际上我更喜欢这里明确的tuple,否则我的大脑会将其解析为函数的多个参数。不错的答案rm。
【解决方案2】:

您可以使用列表列表创建您需要的表格:

t = [[False for i in range(len(data))] for z in range(sum)] #Creates table filled with 'False'

for i in range(len(data)):
    print(i)
    if i == 0:
        continue
    for z in range(sum):
        for c in range(int(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!")
                t[z][i] = True     # Sets element in table to 'True' 

至于你的TypeError,你不能说i = 1 to k,你需要说:for i in range(1,k+1):(假设你想包含k)。

另一个提示是你不应该使用sum 作为变量名,因为这已经是一个内置的python 函数。尝试将print sum([10,4]) 放入程序中的某个位置!

【讨论】:

  • 应该是for i in range(1, k+1)
  • @Keith Cheers,似乎永远不会出现一个接一个的错误!
猜你喜欢
  • 2022-01-14
  • 1970-01-01
  • 2013-09-23
  • 2019-09-21
  • 2021-08-07
  • 2018-09-10
  • 2012-01-27
  • 2021-02-06
  • 2017-11-27
相关资源
最近更新 更多