假设有一禁忌表(20行8列的矩阵),然后我定义了一个函数,用来随机生成一个向量。现在我想对每次生成的向量进行判断:如果新生成的向量在禁忌表中已经存在,那么就要重新生成。我想用递归来完成这个操作,下面是我写的代码的一部分。
def create_new_x(t, x):
if 0 <= t < 30:
s = []
while len(s) < 6:
a = np.random.randint(0, 8)
if a not in s:
s.append(a)
x[s[0]], x[s[1]] = x[s[1]], x[s[0]]
x[s[2]], x[s[3]] = x[s[3]], x[s[2]]
x[s[4]], x[s[5]] = x[s[5]], x[s[4]]
x_new = x
if x in tabu_list:
x = create_new_x(t, x)
elif 30 <= t < 70:
s = []
while len(s) < 4:
a = np.random.randint(0, 8)
if a not in s:
s.append(a)
x[s[0]], x[s[1]] = x[s[1]], x[s[0]]
x[s[2]], x[s[3]] = x[s[3]], x[s[2]]
x_new = x
if x in tabu_list:
create_new_x(t, x)
else:
s = []
while len(s) < 4:
a = np.random.randint(0, 8)
if a not in s:
s.append(a)
x[s[0]], x[s[1]] = x[s[1]], x[s[0]]
x[s[2]], x[s[3]] = x[s[3]], x[s[2]]
x = x
if x_new in tabu_list:
create_new_x(t, x)
return x_new
其中t是一个自然数,每次迭代后t+=1,x就是我生成的向量,这个函数也就是生成向量的函数。tabu_list也就是我说的那个禁忌表,初始情况下tabu_list=[]。
程序执行的时候就报错,报错内容如下:
Traceback (most recent call last):
File "C:/Users/dell/Desktop/SimulatedAnnealing/SA.py", line 1243, in
x_New = create_new_x(t, x)
File "C:/Users/dell/Desktop/SimulatedAnnealing/SA.py", line 1211, in create_new_x
create_new_x(t, x)
File "C:/Users/dell/Desktop/SimulatedAnnealing/SA.py", line 1211, in create_new_x
create_new_x(t, x)
File "C:/Users/dell/Desktop/SimulatedAnnealing/SA.py", line 1211, in create_new_x
create_new_x(t, x)
[Previous line repeated 990 more times]
File "C:/Users/dell/Desktop/SimulatedAnnealing/SA.py", line 1203, in create_new_x
a = np.random.randint(0, 8)
File "mtrand.pyx", line 726, in numpy.random.mtrand.RandomState.randint
File "C:\Program Files\Python37\lib\site-packages\numpy\core_dtype.py", line 347, in name_get
if _name_includes_bit_suffix(dtype):
File "C:\Program Files\Python37\lib\site-packages\numpy\core_dtype.py", line 326, in _name_includes_bit_suffix
elif np.issubdtype(dtype, np.flexible) and _isunsized(dtype):
File "C:\Program Files\Python37\lib\site-packages\numpy\core\numerictypes.py", line 392, in issubdtype
if not issubclass(arg1, generic):
File "C:\Program Files\Python37\lib\site-packages\numpy\core\numerictypes.py", line 328, in issubclass_
return issubclass(arg1, arg2)
RecursionError: maximum recursion depth exceeded while calling a Python object
请问各位大佬,这样子的递归要怎么写才可以啊