Reputation: 9
This function generates a list of 10 random numbers. I need to modify this function to select and print the smallest number from the randomly generated list Please help, I am having a very hard time with it:
import random
my_randoms=[]
for i in range (10):
my_randoms.append(random.randrange(1,101,1))
print (my_randoms)
Upvotes: 0
Views: 168
Reputation: 8378
This sounds to me like some sort of homework assignment. If you need to make minimum number of changes to the existing function and you need to find minimum yourself (without calling built-in functions), then I would suggest:
In [14]: import random
...: my_randoms=[]
...: minv = None
...: for i in range (10):
...: my_randoms.append(random.randrange(1,101,1))
...: if minv is None:
...: minv = my_randoms[-1]
...: elif my_randoms[-1] < minv:
...: minv = my_randoms[-1]
...:
...: print (my_randoms)
...: print(minv)
...:
[94, 24, 79, 75, 12, 57, 39, 37, 7, 96]
7
Even better, but at the expense of modifying/restructuring function's code:
In [15]: import random
...: minv = random.randrange(1,101,1)
...: my_randoms = [minv]
...: for i in range (9):
...: v = random.randrange(1,101,1)
...: my_randoms.append(v)
...: if v < minv:
...: minv = v
...:
...: print (my_randoms)
...: print(minv)
...:
[67, 33, 2, 83, 66, 93, 51, 57, 43, 55]
2
If you are allowed to use built-in functions, then simply call min(my_randoms)
as suggested by @Aran-Frey.
Upvotes: 0
Reputation: 26017
I would use numpy
import numpy as np
np.random.randint(1, 101, 10).min()
Short explanation:
np.random.randint(1, 101, 10)
will print something like this
array([91, 57, 53, 26, 95, 9, 31, 47, 29, 78])
and then you just access the minimum value with min()
.
In your implementation you would just do
min(my_randoms)
as @Austin mentioned in the comments
Upvotes: 0