Check if last three flips were all heads or all tails in Python

So, I have a task in which I have to create a program that simulates a flip of a coin, creating a random number corresponding to heads or tails. When three simultaneous "H" (heads) or "T" (tails) are output, my program should stop. I tried to make this work, here is my code:

import random
active=True
list1 = []
b = 0
while active:
    l=random.randint(0,1)
    b += 1
    i='a'
    if l == 0:
        i = 'H'
    else:
        i = 'T'
    list1.append(i)

    if list1[:-3] is ['H','H','H']:
        active = False
    elif list1[:-3] is ['T','T','T']:
        active = False
    else:
        active = True
    print(list1),

It seems that the only thing that doesn't work is the part that checks for the presence of three matching heads or tails, does anyone know how I can correctly encode this part?

+4
source share
2 answers

, , , list1[:-3] list1[-3:] ( , ), == is. :

import random
active=True
list1 = []
b = 0
while active:
    l=random.randint(0,1)
    b += 1
    i='a'
    if l == 0:
        i = 'H'
    else:
        i = 'T'
    list1.append(i)

    if list1[-3:] == ['H','H','H']:
        active = False
    elif list1[-3:] == ['T','T','T']:
        active = False
    else:
        active = True
    print(list1)

, , :

import random

flips = []
while flips[-3:] not in (['H'] * 3, ['T'] * 3):
    flips.append(random.choice('HT'))
    print(flips)
+4

, . , . , , . 3, while:

import random

flipping = True
flips = []
flip_status = {0: "H", 1: "T"}
current_flip = None

while flipping:
    current_flip = flip_status[random.randint(0,1)]
    print current_flip

    if len(flips) == 0:
        flips.append(current_flip)

    else:
        if current_flip == flips[-1]:
            flips.append(current_flip)
            if len(flips) == 3:
                break
        else:
            flips = []
            flips.append(current_flip)

print "Flips: " + str(flips)

:

T
T
H
T
T
H
T
H
H
T
T
T
Flips: ['T', 'T', 'T']
+2

Source: https://habr.com/ru/post/1675197/


All Articles