我正在尝试使用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)
我在思想上发现了错误。递归确实可以正常工作。因为我目前只有7^3种可能性(由于没有完成其他属性),所以我的递归只是在不必要地进行最大化。一旦我将未来属性包括在内,我的程序就不会有任何问题,因为有7^8个选项可供选择,所以我可以推出6000个独特的可能性
感谢@chepner在评论中提供的提示
也许您可以使用
while True:
循环来替换递归:相关问题 更多 >
编程相关推荐