gpt4 book ai didi

python - 如何将算法转换为python

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:45:02 25 4
gpt4 key购买 nike

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”

最佳答案

您可以获得创建动态规划表的 block :

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

关于python - 如何将算法转换为python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7279641/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com