""" This program estimates the probability of getting a streak of >= n heads (0s) or tails (1s) in a random sequence of m/2 heads and m/2 tails. """ #Import functions. from random import shuffle #Set n and m as desired, as long as m is even. n = 7 m = 60 #Generate a list of m/2 0s and m/2 1s. list = [i for i in range(m)] for i in list: if list[i] % 2 == 0: list[i] = 0 else: list[i] = 1 #Shuffle the list. shuffle(list) """ Create a function that takes a list as input, and outputs the number of streaks > n in the list. """ def streak(input_list): countA = 0 for i in range(m - (n - 1)): countB = 0 for j in range(n): if input_list[(i + j)] == 0: countB = countB else: countB = countB + 1 if countB == 0: countA = countA + 1 elif countB == n: countA = countA + 1 else: countA = countA if countA == 0: return "It's not streaky:" else: return "It's streaky:" #Print whether the sample shuffled list is streaky or not. print(streak(list)) #Print the sample list to check to see if streakiness is calulated right. print(list) #Call the function 1000 times and keep track of the number of times it's streaky. countC = 0 for i in range(1000): shuffle(list) if streak(list) == "It's not streaky:": countC = countC else: countC = countC + 1 print(countC) #I need to figure out how to print in the format "p = .##" #p is the probability of seeing a streak. print("p = " + str(countC/1000))
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question