我正在开发一个递归函数。该代码目前快速且肮脏,但在优化之前我遇到了一个问题。
一旦递归函数调用出去(我的意思是我的算法正在向后),case_courante
变量就会从堆栈中弹出到以前的值,但数组的情况并非如此dernier_match
和tour
。我不明白为什么。
这是我的代码:
#!/usr/bin/python
temps_min=21
temps_max=45
nb_time_slot=245
categorie=[[6,6,6,4,4,2,2,99],[6,6,6,4,4,2,2,99],[6,6,6,4,4,2,2,99],[3,3,3,2,2,2,99],[3,3,3,2,2,2,99],[4,4,4,4,2,2,99],[6,6,6,2,2,2,99],[6,6,6,2,2,2,99],[6,6,6,2,2,2,99],[6,6,6,2,2,2,99],[1,1,1,1,1,1,1,1,1,1,1,1,1]]
dernier_match_depart=[0]*10
case_courante_depart=0
tour_depart=[0]*10
echeancier =[None]*(nb_time_slot+10)
profondeur =0
#function
def choix(prof, case_courante, dernier_match, tour):
global categorie,temps_min,temps_max,nb_time_slot,echeancier
for i in range (0,10):
print ("Profondeur:", prof)
print(i)
if (dernier_match[i] == 0):
for x in range (case_courante,case_courante + categorie[i][tour[i]]):
echeancier[x] = i
case_courante = case_courante + categorie[i][tour[i]]
dernier_match[i] = case_courante
tour[i] = tour[i] + 1
print echeancier
choix(prof+1, case_courante, dernier_match, tour)
print ("case courante:", case_courante)
print ("tour", tour)
print ("dernier_match",dernier_match)
if (categorie[i][tour[i]] != 99 and dernier_match[i]+temps_min < case_courante and dernier_match[i]+temps_max > case_courante and case_courante<nb_time_slot):
print ("if principal\n")
print ("slots dans ce tour",categorie[i][tour[i]])
for x in range (case_courante,case_courante + categorie[i][tour[i]]):
echeancier[x] = i
case_courante = case_courante + categorie[i][tour[i]]
dernier_match[i] = case_courante
tour[i] = tour[i] + 1
print echeancier
choix(prof+1, case_courante, dernier_match, tour)
for a in range (0,9):
if (categorie[a][tour[a]] != 99):
break
else:
if (a == 9):
print ("Solution trouvee\n")
print (echeancier)
exit()
#main
choix(0,case_courante_depart,dernier_match_depart, tour_depart)
最佳答案
这是因为您重新分配了case_courante
:
case_courante = case_courante + categorie[i][tour[i]]
但您只修改 tour
和 dernier_match
的元素:
dernier_match[i] = case_courante
tour[i] = tour[i] + 1
因此 case_courante
不断引用不同的不可变整数,但其他整数始终引用其原始列表
,而从不引用其他任何内容。
更新:
看起来您的递归函数有两个递归调用站点(两者相同):
choix(prof+1, case_courante, dernier_match, tour)
我最初的猜测(因为我不知道所需的功能)是传递列表的副本:
choix(prof+1, case_courante, dernier_match[:], tour[:])
关于python - Python 中数组的递归问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49793522/