ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [알고리즘 스터디] python coin flips 문제 풀기
    5) etc. 2022. 6. 16. 15:47
    반응형

    문제

    Create a program that uses Python’s random number generator to simulate flipping a coin several times. The simulated coin should be fair, meaning that the probability of heads is equal to the probability of tails. Your program should flip simulated coins until either 3 consecutive heads of 3 consecutive tails occur. Display an H each time the outcome is heads, and a T each time the outcome is tails, with all of the outcomes for one simulation on the same line. Then display the number of flips that were needed to reach 3 consecutive occurrences of the same outcome. When your program is run it should perform the simulation 10 times and report the average number of flips needed. Sample output is shown below:

     

    H T T T 4 flips

    H H T T H T H T T H H T H T T H T T T 19 flips

    T T T 3 flips

    T H H H 4 flips

    H H H 3 flips

    T H T T H T H H T T H H T H T H H H 18 flips

    H T T H H H 6 flips

    T H T T T 5 flips

    T T H T T H T H T H H H 12 flips

    T H T T T 5 flips

    On average, 7.9 flips were needed.

     

     

    코드

    import random
    
    print('##################### solution #####################')
    coin= {0:'H', 1:'T'}
    result_num = []
    for i in range(10):
        cnt = 1
        q = list()
        while cnt <3:
            n = random.randrange(0, 2)
            if len(q) >0:
                if q[-1] == coin[n]:
                    cnt +=1
                else:
                    cnt=1
            q.append(coin[n])
        result_num.append(len(q))
        print(*q, f'{len(q)} flips')
    print(f'On average, {sum(result_num)/len(result_num)} flips were needed.')
    반응형

    '5) etc.' 카테고리의 다른 글

    블리자드 무한인증 해결방법, 휴먼계정 해제, blizzard  (19) 2020.12.23

    댓글

Designed by Tistory.