Reputation: 45
My problem: I need to print the smallest number in a random list which is regenerated 3 times. my final output has to be the smallest number in the first list, second smallest in the second, third in the third. for example. Output:
[18, 16,9,4,8]
4
[4,8,1,9,15]
4
[18,21,13,24,25]
21
However, it is only printing out the smallest number in every list, and it is not including the second and third smallest.
My Output:
[18, 16,9,4,8]
4
[4,8,1,9,15]
1
[18,21,13,24,25]
13
My Code:
import random
def smallest():
x = 0
randomlist = []
for i in range(0,5):
n = random.randint(1,30)
randomlist.append(n)
randomlist.sort()
print(randomlist)
print(randomlist[x])
x = x+1
smallest()
smallest()
smallest()
I was using variable x to signify which number to pull out of the sorted list, however it seems to stay the same throughout each call back to smallest(). Does anyone have any ideas on how to fix this?
Upvotes: 0
Views: 137
Reputation: 1391
Your variable x gets updated to x=0 every time you call the function smallest() and holds x=1 at the end of the each function call
import random
def smallest(x):
randomlist = []
for i in range(0,5):
n = random.randint(1,30)
randomlist.append(n)
randomlist.sort()
print(randomlist)
print(randomlist[x])
for i in range(3):
smallest(i)
This code will do what you wanted. Try to use for loops for iterations
Upvotes: 1