|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
0.
while循环,中断和被打败等价于break
1.
少一个=
2.
45
3.
会
4.
ctrl+c
5.
B,逻辑通畅
----------------------
0.
while True:
slogan = input("please input a slogan(end with stop):")
if slogan == "stop":
break
print(slogan)
1.
2.
import random
counts = int(input("请输入抛硬币的次数:"))
i = 0
front = 0
back = 0
tfront = 0
tback = 0
ffront = 0
fback = 0
print("开始抛硬币实验:")
while i < counts:
num = random.randint(1, 10)
if counts < 100:
if num % 2:
print("正面", end=" ")
front += 1
flag = 0
else:
print("反面", end=" ")
back += 1
flag = 1
if flag == 0:
tfront += 1
tback = 0
if ffront < tfront:
ffront = tfront
else:
tback += 1
tfront = 0
if fback < tback:
fback = tback
i += 1
else:
if num % 2:
front += 1
flag = 0
else:
back += 1
flag = 1
if flag == 0:
tfront += 1
tback = 0
if ffront < tfront:
ffront = tfront
else:
tback += 1
tfront = 0
if fback < tback:
fback = tback
i += 1
print("the number of simulation is ",front+back,"times,the result is as follow:")
print("front:",front)
print("back:",back)
print("the most time of front is:",ffront)
print("the most time of back is:",fback)
**************************************
1.小甲鱼写的更优雅
import random
counts = int(input("请输入抛硬币的次数:"))
# 利用 ignore 变量来判断是否打印每次的结果
if counts > 100:
ignore = True
else:
ignore = False
heads = 0 # 统计正面的次数
tails = 0 # 统计反面的次数
i = 0
print("开始抛硬币实验……")
while i < counts:
num = random.randint(1, 10)
if num % 2:
heads += 1
if not ignore:
print("正面", end=" ")
else:
tails += 1
if not ignore:
print("反面", end=" ")
i += 1
print("")
print("一共模拟了", counts, "次抛硬币,结果如下:")
print("正面:", heads, "次", sep="")
print("反面:", tails, "次", sep="")
2.
import random
counts = int(input("请输入抛硬币的次数:"))
# 利用 ignore 变量来判断是否打印每次的结果
if counts > 100:
ignore = True
else:
ignore = False
heads = 0 # 统计正面的次数
tails = 0 # 统计反面的次数
last = 0 # 记录上一次的状态,如果是正面设置为1, 反面则设置为2
c_heads = 0 # 统计连续正面的次数
c_tails = 0 # 统计连续反面的次数
max_heads = 0 # 统计连续正面的最多次数
max_tails = 0 # 统计连续反面的最多次数
i = 0
print("开始抛硬币实验……")
while i < counts:
num = random.randint(1, 10)
if num % 2:
heads += 1
c_heads += 1
if not ignore:
print("正面", end=" ")
# 如果上一次是反面:将连续正面的次数设置为1
if last == 2:
c_heads = 1
# 判断连续正面的次数是否比max_heads大,如果是,取而代之
if c_heads > max_heads:
max_heads = c_heads
# 将上一次的状态设置为正面
last = 1
else:
tails += 1
c_tails += 1
if not ignore:
print("反面", end=" ")
# 如果上一次是正面:连续反面的次数设置为1
if last == 1:
c_tails = 1
# 判断连续反面的次数是否比max_tails大,如果是,取而代之
if c_tails > max_tails:
max_tails = c_tails
# 将上一次的状态设置为反面
last = 2
i += 1
print("")
print("一共模拟了", counts, "次抛硬币,结果如下:")
print("正面:", heads, "次", sep="")
print("反面:", tails, "次", sep="")
print("最多连续正面:", max_heads, "次", sep="")
print("最多连续反面:", max_tails, "次", sep="")
|
|