我试图为D& D制作一个随机字符发生器。到目前为止,我能够根据两个最大的统计数据来决定选择什么类,但由于某种原因,我偶尔会得到答案。我的代码很好,据我所知,但我是python的初学者。我很想知道为什么它不会总是回答答案以及如何解决它。
data = [str,int,dex,con,wis,cha]
largest = None
second_largest = None
for a in data:
if not largest or a > largest:
if largest:
second_largest = largest
largest = a
if largest == wis and second_largest == cha or largest == cha and second_largest == str or largest == str and second_largest == cha or largest == str and second_largest == int:
print ("PALADIN")
elif largest == str and second_largest == dex or largest == str and second_largest == con or largest == con and second_largest == str:
print ("BARBARIAN")
elif largest == str and second_largest == wis or largest == con and second_largest == wis or largest == wis and second_largest == str or largest == wis and second_largest == con:
print ("CLERIC")
elif largest == int and second_largest == str or largest == int and second_largest == con or largest == con and second_largest == int or largest == wis and second_largest == int:
print ("WIZARD")
elif largest == int and second_largest == dex or largest == dex and second_largest == int or largest == cha and second_largest == wis:
print ("ROGUE")
elif largest == int and second_largest == wis:
print ("DRUID")
elif largest == int and second_largest == cha or largest == con and second_largest == cha or largest == cha and second_largest == int:
print ("SORCERER")
elif largest == dex and second_largest == str:
print ("MONK")
elif largest == dex and second_largest == con or largest == con and second_largest == dex:
print ("FIGHTER")
elif largest == dex and second_largest == wis or largest == wis and second_largest == dex:
print ("RANGER")
elif largest == dex and second_largest == cha:
print ("BARD")
elif largest == cha and second_largest == dex or largest == cha and second_largest == con:
print ("WARLOCK")
答案 0 :(得分:2)
获得最大和第二大的代码是不对的:
largest = None
second_largest = None
for a in data:
if not largest or a > largest:
if largest:
second_largest = largest
largest = a
如果最大属性出现在第二大属性之前,则second_largest
将不会被填充。一个简短且可读的方法就是使用排序,假设效率不是那么大的问题:< / p>
largest, second_largest = sorted(data, reverse=True)[:2]
答案 1 :(得分:1)
如果您的第一个元素是第一个,那么您永远不会获得second_largest。 您可以将其更改为:
entlargest = -float('inf')
second_largest = -float('inf')
for a in data:
if a > second_largest:
second_largest = a
if second_largest > largest:
largest, second_largest = second_largest, largest