Reputation: 45
I started programming 2 weeks ago for the first time in my life and I have come across something that I cannot figure out. I am trying to make it so a loop that calculates a median from a set amount of random numbers can repeat itself many times (say 10,000) while storing all the median values into a list. I already have everything up to the point where a list is created from the random integers (numbList) from which the median (listMedian) is calculated. I would just like to be able to repeat this process a number of times while generating a list of all the calculated medians. Sample size is how many numbers that are per list and upper limit determines what the range is for each individual number, thanks! I am using Python 3.
import random
def median(numbList):
srtd = sorted(numbList)
mid = len(numbList)//2
if len(numbList) % 2 == 0:
return (srtd[mid-1] + srtd[mid]) / 2.0
else:
return srtd[mid]
sampleSize = int(input("What is your desired sample size? "))
upperLimit = int(input("What is your desired upper limit? "))
numbList = []
totalMedians = []
biggerList = []
while sampleSize > 0:
sampleSize -= 1
randomNum = random.randrange(0,upperLimit+1)
numbList.append(randomNum)
numbList.sort(key=int)
listMedian = median(numbList)
Upvotes: 1
Views: 18292
Reputation: 1
say you have this
print ('hello')
to loop it you would need to add : for #1 in range(#2)
: at the start (#1 any variable, #2 how many times it will repeat)
for example
for somevariable in range(3)
print('hello')
hello
hello
hello
Upvotes: 0
Reputation: 25908
Here's a simple example of what you want:
#!/usr/bin/python
import random
def create_list(sampleSize, upperLimit):
numbList = []
while sampleSize > 0:
sampleSize -= 1
randomNum = random.randrange(0,upperLimit+1)
numbList.append(randomNum)
numbList.sort(key=int)
return numbList
def median(numList):
list_len = len(numList)
if list_len % 2:
return numList[list_len / 2]
else:
return (numList[list_len / 2] + numList[list_len / 2 - 1]) / 2.0
def main():
number_lists = 4
sample_size = 5
upper_limit = 50
lists = []
median_list = []
for i in range(number_lists):
lists.append(create_list(sample_size, upper_limit))
for current_list in lists:
current_median = median(current_list)
print current_list, " : median (", current_median, ")"
median_list.append(current_median)
print "Median list is ", median_list
if __name__ == "__main__":
main()
which outputs, for example:
paul@MacBook:~/Documents/src/scratch$ ./sample.py
[3, 18, 20, 26, 46] : median ( 20 )
[18, 22, 38, 44, 49] : median ( 38 )
[28, 29, 34, 42, 43] : median ( 34 )
[4, 21, 27, 31, 46] : median ( 27 )
Median list is [20, 38, 34, 27]
paul@MacBook:~/Documents/src/scratch$
Upvotes: 1