我一直在 python 中达到最大递归深度。想不出解决办法
I keep hitting maximum recursion depth in python. can't figure out a solution
我正在尝试使用 python 的枕头库生成大约 6000 张随机图像。现在我一次不能创建超过 300 个,否则我的程序会达到最大递归深度。我知道这是因为我的递归不是用“n-1”情况调用的。由于所有图像都是使用随机数选择的,因此我不确定如何解决此问题。这是我的代码:
## Generate Traits
TOTAL_IMAGES = 300 # Number of random unique images we want to generate
all_images = []
# A recursive function to generate unique image combinations
def create_new_image():
new_image = {}
# For each trait category, select a random trait based on the weightings
new_image ["Plant"] = random.choices(plant, plant_weights)[0]
new_image ["Pot"] = random.choices(pot, pot_weights)[0]
new_image ["Face"] = random.choices(face, face_weights)[0]
if new_image in all_images:
return create_new_image()
else:
return new_image
# Generate the unique combinations based on trait weightings
for i in range(TOTAL_IMAGES):
new_trait_image = create_new_image()
all_images.append(new_trait_image)
也许您可以使用 while True:
循环来代替递归:
def create_new_image():
while True:
new_image = {}
# For each trait category, select a random trait based on the weightings
new_image ["Plant"] = random.choices(plant, plant_weights)[0]
new_image ["Pot"] = random.choices(pot, pot_weights)[0]
new_image ["Face"] = random.choices(face, face_weights)[0]
if new_image not in all_images:
return new_image
我发现我的思路有问题。递归确实可以正常工作。因为目前我只有 7^3 种可能性(由于没有完成其他属性),所以我的递归只是不必要地最大化。一旦我包含了未来的属性,我的程序就可以毫无问题地产生 6000 种独特的可能性,因为有 7^8 种可供选择。
感谢@chepner 在评论中的提示
我正在尝试使用 python 的枕头库生成大约 6000 张随机图像。现在我一次不能创建超过 300 个,否则我的程序会达到最大递归深度。我知道这是因为我的递归不是用“n-1”情况调用的。由于所有图像都是使用随机数选择的,因此我不确定如何解决此问题。这是我的代码:
## Generate Traits
TOTAL_IMAGES = 300 # Number of random unique images we want to generate
all_images = []
# A recursive function to generate unique image combinations
def create_new_image():
new_image = {}
# For each trait category, select a random trait based on the weightings
new_image ["Plant"] = random.choices(plant, plant_weights)[0]
new_image ["Pot"] = random.choices(pot, pot_weights)[0]
new_image ["Face"] = random.choices(face, face_weights)[0]
if new_image in all_images:
return create_new_image()
else:
return new_image
# Generate the unique combinations based on trait weightings
for i in range(TOTAL_IMAGES):
new_trait_image = create_new_image()
all_images.append(new_trait_image)
也许您可以使用 while True:
循环来代替递归:
def create_new_image():
while True:
new_image = {}
# For each trait category, select a random trait based on the weightings
new_image ["Plant"] = random.choices(plant, plant_weights)[0]
new_image ["Pot"] = random.choices(pot, pot_weights)[0]
new_image ["Face"] = random.choices(face, face_weights)[0]
if new_image not in all_images:
return new_image
我发现我的思路有问题。递归确实可以正常工作。因为目前我只有 7^3 种可能性(由于没有完成其他属性),所以我的递归只是不必要地最大化。一旦我包含了未来的属性,我的程序就可以毫无问题地产生 6000 种独特的可能性,因为有 7^8 种可供选择。
感谢@chepner 在评论中的提示