<分区>
代码如下:
from random import *
numStars = int(input("Number of stars: ").strip())
planetTypeDict = {'O':0, 'B':0, 'A':0, 'F':0, 'G':0, 'K':0, 'M':0}
for star in range (numStars):
planetTypeChanceNum = uniform (0, 100)
if planetTypeChanceNum < 76.45:
planetType = 'M'
planetTypeDict['M'] += 1
elif planetTypeChanceNum < 12.1:
planetType = 'K'
planetTypeDict['K'] += 1
elif planetTypeChanceNum < 7.6:
planetType = 'G'
planetTypeDict['G'] += 1
elif planetTypeChanceNum < 3:
planetType = 'F'
planetTypeDict['F'] += 1
elif planetTypeChanceNum < 0.6:
planetType = 'A'
planetTypeDict['A'] += 1
elif planetTypeChanceNum < 0.13:
planetType = 'B'
planetTypeDict['B'] += 1
elif planetTypeChanceNum < 0.0003:
planetType = 'O'
planetTypeDict['O'] += 1
print(planetTypeDict)
问题是代码输出大约有 75% 的“M”星,除此之外没有其他内容。例如,当我使用 1000 作为 numStars 的值时,我得到的结果是:
{'O': 241, 'B': 0, 'A': 0, 'F': 0, 'G': 0, 'K': 0, 'M': 759}
我已尽我所能来修复此错误,包括将逻辑更改为:
if planetTypeChanceNum > 100 - 'chance here':
# stuff
请帮忙!
如果您使用的是 Python 3,请使用 random.choices
如 Patrick Artner 所示。
否则,只需颠倒检查顺序即可:
if planetTypeChanceNum < 0.0003:
planetType = 'O'
elif planetTypeChanceNum < 0.13:
planetType = 'B'
elif planetTypeChanceNum < 0.6:
planetType = 'A'
elif planetTypeChanceNum < 3:
planetType = 'F'
elif planetTypeChanceNum < 7.6:
planetType = 'G'
elif planetTypeChanceNum < 12.1:
planetType = 'K'
elif planetTypeChanceNum < 76.45:
planetType = 'M'
planetTypeDict[planetType] += 1
如果第一次检查失败,planetTypeChanceNum
仍然可以小于 0.13(并且暗示 0.0003 <= planetTypeChanceNum
)。
但是,如果planetTypeChanceNum >= 76.45
,行星类型是什么? ?你缺少一个 else
子句,或者可能是初始的 if
如果在这种情况下根本没有行星,则声明提前继续循环。
if planetTypeChanceNum < 0.0003:
planetType = 'O'
elif planetTypeChanceNum < 0.13:
planetType = 'B'
elif planetTypeChanceNum < 0.6:
planetType = 'A'
elif planetTypeChanceNum < 3:
planetType = 'F'
elif planetTypeChanceNum < 7.6:
planetType = 'G'
elif planetTypeChanceNum < 12.1:
planetType = 'K'
elif planetTypeChanceNum < 76.45:
planetType = 'M'
else:
planetType = ???
或
if planetType >= 76.45:
# No planet at all
continue
elif planetTypeChanceNum < 0.0003:
planetType = 'O'
elif planetTypeChanceNum < 0.13:
planetType = 'B'
elif planetTypeChanceNum < 0.6:
planetType = 'A'
elif planetTypeChanceNum < 3:
planetType = 'F'
elif planetTypeChanceNum < 7.6:
planetType = 'G'
elif planetTypeChanceNum < 12.1:
planetType = 'K'
elif planetTypeChanceNum < 76.45:
planetType = 'M'
这两个都将详尽地覆盖区间 [0, 100]。