2014-10-03 16 views
1

我是新來的蟒蛇,我試圖創建一個coinflip循環,將不斷翻轉和計數翻轉的數量,直到頭的數量=尾部的數量,它將停止並打印達到該數量所需的翻轉總數。我試圖得到結果,以便在數學課程上工作,但我似乎無法弄清楚如何讓它停止或打印結果,而當我這樣做時打印0.這是我的代碼遠:蟒蛇 - 無限投幣翻轉,停止當頭數=尾數

import random 
heads = 1 
tails = sum(random.choice(['head', 'tail']) == 'tail' 
count = 0 
while True: 
    coinresult = random.randint(1, 2) if heads == tails: 
    break 

print("The number of flips was {count}".format(count = heads + tails)) 
+0

你基本上是在隨機行走。它可能需要很長時間才能終止。我跑了20次詹姆斯肯特的算法,並在數千人中進行了兩次散步。 – 2014-10-03 08:53:42

+0

我跑步遞歸100次,平均跑步是360次,因爲你說最高的是成千上萬 – 2014-10-03 09:31:46

回答

1

不知道是怎麼回事你的縮進,但試試這個:

import random 
heads = 0 #initialize the count variables 
tails = 0 

while True: 
    coinresult = random.randint(1, 2) #flip coin 
    if coinresult == 1: #if result = 1 then increment heads counter 
     heads += 1 
    elif coinresult == 2: #if result = 2 then increment tails counter 
     tails += 1 
    if heads == tails: #check if counts are equal and break loop if they are 
     break 

print("The number of flips was {count}".format(count = heads + tails)) 
0
import itertools as it 
import random 

def flips(): 
    while True: 
     yield (random.getrandbits(1)<<1) - 1 

def cumsum(seq): 
    s = 0 
    for i in seq: 
     s += i 
     yield s 

def length(seq): 
    n = 0 
    for _ in seq: 
     n += 1 
    return n 

print("The number of flips was {}".format(length(it.takewhile((0L).__cmp__, cumsum(flips()))))) 
0

我認爲這將是一個很好的實現

import random 

s = 0 
iteration = 0 
while True: 
    coin = random.sample([-1,1], 1)[0] 
    s = s + coin 
    iteration = iteration + 1 
    if s == 0: 
     break 

print(iteration)