为什么python函数在我使用范围循环设置参数时失败?
我是Python新手,我正在尝试用脚本解决硬币兑换问题。我设法制作了一个函数,返回一个字典,其中包含每个硬币的编号,用于提供最佳的零钱。功能如下:为什么python函数在我使用范围循环设置参数时失败?,python,loops,Python,Loops,我是Python新手,我正在尝试用脚本解决硬币兑换问题。我设法制作了一个函数,返回一个字典,其中包含每个硬币的编号,用于提供最佳的零钱。功能如下: def optimal_change(c, l_coins): ncoins=[] dicts=[] l_coins.reverse() if c==0: return 0 for i in range(0, len(l_coins)): x=0 y=c
def optimal_change(c, l_coins):
ncoins=[]
dicts=[]
l_coins.reverse()
if c==0:
return 0
for i in range(0, len(l_coins)):
x=0
y=c
d={}
for j in range(i, len(l_coins)):
while y-l_coins[j]>=0:
y=y-l_coins[j]
x=x+1
if l_coins[j] not in d:
d[l_coins[j]]=1
else:
d[l_coins[j]]+=1
ncoins.append(x)
dicts.append(d)
return dicts[ncoins.index(min(ncoins))]
该函数可能效率很低,但在给定单个参数时它可以工作。问题是,当我使用设置不同参数的范围循环执行它时,对位置会给出奇怪的结果。例如:
l_coins = [1, 3, 4, 5]
for c in range(1, 10):
print(c, optimal_change(c, l_coins))
产出:
1 {1: 1}
2 {}
3 {3: 1}
4 {}
5 {5: 1}
6 {4: 1}
7 {4: 1, 3: 1}
8 {5: 1}
9 {5: 1, 4: 1}
我知道这不是奇偶数值的问题,而是奇偶位置的问题。
有人能告诉我发生了什么事吗?提前谢谢 由于
l\u coins
是一个列表,在Python中是一个可变类型,因此reverse()
方法会更改函数范围之外的对象。换言之,你不断地来回倒换l_硬币
,这破坏了算法。一个快速修复方法是在函数中创建一个l_硬币的副本
,然后反转副本而不是原始副本。以下是解决原始问题的概念证明
def optimal_change(c, l_coins):
ncoins=[]
dicts=[]
l_copy = list(l_coins)
l_copy.reverse()
if c==0:
return 0
for i in range(0, len(l_copy)):
x=0
y=c
d={}
for j in range(i, len(l_copy)):
while y- l_copy [j]>=0:
y=y- l_copy [j]
x=x+1
if l_copy [j] not in d:
d[l_copy [j]]=1
else:
d[l_copy [j]]+=1
ncoins.append(x)
dicts.append(d)
return dicts[ncoins.index(min(ncoins))]
l_coins = [1, 3, 4, 5]
for c in range(1, 10):
print(c, optimal_change(c, l_coins))