+ 1

Flip coin till 3 heads or 3 tails in a row - help with my code?

Hi guys - I wrote this code (named "3heads" in Code Playground) where the computer should flip a coin consecutively till they get 3 of the same results in a row. Technically it runs, but I don't think it runs right because my "while" loop is wrong. Everytime, I get results in less than 5 flips, so what am I doing incorrectly? Code is named "3heads" in the playground - I don't know how to link it directly here. Thanks! ------ #run program till you get 3 heads or 3 tails in a row consecutively import random sides = ["heads", "tails"] i = 0 while i<10: flip1 = random.choice(sides) flip2 = random.choice(sides) flip3 = random.choice(sides) if flip1 != flip2 and flip2 != flip3: print(flip1, flip2, flip3) i += i elif flip1 == flip2 and flip2 == flip3: print(flip1, flip2, flip3) break

2nd Jun 2017, 3:51 PM
Nasheed Shams
Nasheed Shams - avatar
5 Antworten
+ 7
Try this: import random sides = ['heads', 'tails'] i = 0 while True: flip1 = random.choice(sides) flip2 = random.choice(sides) flip3 = random.choice(sides) i += 1 print(flip1, flip2, flip3) if flip1 == flip2 == flip3: break print('After', i, 'tries')
2nd Jun 2017, 5:18 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
2nd Jun 2017, 8:32 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 4
True. I thought we were looking for triplets being the same. As a matter of fact, looping until three in a row are the same is not much harder...
2nd Jun 2017, 8:20 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 2
@kuba: I was looking for triplets being the same. But now, I'm gonna try to solve 3 in a row.
2nd Jun 2017, 8:22 PM
Nasheed Shams
Nasheed Shams - avatar
0
@Kuba: this will not detect 3 in a row in: heads tails tails tails heads heads
2nd Jun 2017, 7:57 PM
Igor B
Igor B - avatar