萌新写的第16讲改进抛硬币的代码
和小甲鱼的答案不一样,po上自己写的,目前没发现跑起来有什么问题,如果有小伙伴愿意的话可以帮看看哈哈~有问题的话感谢指出!import random
counts = int(input('请输入抛硬币的次数:'))
i = 0
a = 0
b = 0
c = 0
mc = 0
d = 0
md =0
print("开始抛硬币实验...")
if counts < 100:
while i < counts:
num = random.randint(1,10)
if num % 2:
print('正面',end = ' ')
a += 1
c += 1
d = 0
if mc <= c:
mc = c
else:
mc = mc
else:
print('反面',end = ' ')
b += 1
c = 0
d += 1
if md <= d:
md = d
else:
md = md
i = i + 1
else:
while i < counts:
num = random.randint(1,10)
if num % 2:
a += 1
c += 1
d = 0
if mc <= c:
mc = c
else:
mc = mc
else:
b += 1
c = 0
d += 1
if md <= d:
md = d
else:
md = md
i = i + 1
print('\n一共模拟了',counts,'次抛硬币,结果如下:',sep = ' ')
print('正面:',a,'次')
print('反面:',b,'次')
print('最多连续正面:',mc,'次')
print('最多连续反面:',md,'次') {:5_106:} dd 本帖最后由 傻眼貓咪 于 2021-9-4 23:51 编辑
樓主,你的代碼已經很好了,不錯
獻醜了,我的代碼:
import random
def games(n: int):
maxFlip = {"head": 0, "tail": 0}
now, count, flip = None, 0, []
for i in range(n):
res = random.choice(["head", "tail"])
flip.append(res)
if now == res:
count += 1
else:
maxFlip, count, now = max(count, maxFlip), 0, res
return (flip.count("head"), flip.count("tail"), maxFlip["head"], maxFlip["tail"])
def main():
times = int(input("輸入拋硬幣次數:\n"))
head, tail, x, y = games(times)
print(f"一共模擬了 {times} 次拋硬幣,輸出結果:\n正面:{head} 次,反面:{tail} 次\n正面最多連續次數為:{x} 次\n反面最多連續次數為:{y} 次")
if __name__ == "__main__":
main()
页:
[1]