Можно ли упростить код:? Пытался через цикл, но не получалось
задачка про монетку
import random
a = ["O", "P"]
s = ""
s2 = ""
s3 = ""
s4 = ""
s5 = ""
s6 = ""
s7 = ""
s8 = ""
s9 = ""
s10 = ""
while ("PPP" not in s) and ("OOO" not in s):
s += random.choice(a)
print(s, "(попыток:"+str(len(s))+")")
while ("PPP" not in s2) and ("OOO" not in s2):
s2 += random.choice(a)
print(s2, "(попыток:"+str(len(s2))+")")
while ("PPP" not in s3) and ("OOO" not in s3):
s3 += random.choice(a)
print(s3, "(попыток:"+str(len(s3))+")")
while ("PPP" not in s4) and ("OOO" not in s4):
s4 += random.choice(a)
print(s4, "(попыток:"+str(len(s4))+")")
while ("PPP" not in s5) and ("OOO" not in s5):
s5 += random.choice(a)
print(s5, "(попыток:"+str(len(s5))+")")
while ("PPP" not in s6) and ("OOO" not in s6):
s6 += random.choice(a)
print(s6, "(попыток:"+str(len(s6))+")")
while ("PPP" not in s7) and ("OOO" not in s7):
s7 += random.choice(a)
print(s7, "(попыток:"+str(len(s7))+")")
while ("PPP" not in s8) and ("OOO" not in s8):
s8 += random.choice(a)
print(s8, "(попыток:"+str(len(s8))+")")
while ("PPP" not in s9) and ("OOO" not in s9):
s9 += random.choice(a)
print(s9, "(попыток:"+str(len(s9))+")")
while ("PPP" not in s10) and ("OOO" not in s10):
s10 += random.choice(a)
print(s10, "(попыток:"+str(len(s10))+")")
b = [len(s), len(s2), len(s3), len(s4), len(s5),\
len(s6), len(s7), len(s8), len(s9), len(s10)]
print("Минимальное количество попыток:", min(b))
print("Среднее количество попыток:", sum(b)/len(b))
print("Максимальное количество попыток:", max(b))
Ответы (1 шт):
Автор решения: Nenza
→ Ссылка
import random
s_all = []
b=[]
def f(index):
global s_all
while ("PPP" not in s_all[index]) and ("OOO" not in s_all[index]):
s_all[index]+=random.choice(a)
print(s_all[index], "(попыток:"+str(len(s_all[index]))+")")
for i in range(0, 10):
s_all.append('')
f(i)
for i in s_all:
b.append(len(i))
print("Минимальное количество попыток:", min(b))
print("Среднее количество попыток:", sum(b)/len(b))
print("Максимальное количество попыток:", max(b))