I create a list of 'a' random numbers. And than I need to change odd numbers to the minimum number of this list. but it doesn't change any number, what's wrong?
import random
a = int(input('Num -> '))
s = []
for i in range(a):
s.append(random.randint(0,10))
if s[i]%2!=0:
s[i]=min(s)
You program does, indeed, change the numbers as you requested. I added trivial print
statements to track this:
import random
a = 10
s = []
for i in range(a):
s.append(random.randint(0,10))
if s[i]%2==0:
print("Changing", i)
print("\tbefore", s)
s[i]=min(s)
print("\t after", s)
Output:
Changing 1
before [3, 10]
after [3, 3]
Changing 6
before [3, 3, 5, 9, 9, 1, 8]
after [3, 3, 5, 9, 9, 1, 1]
Changing 7
before [3, 3, 5, 9, 9, 1, 1, 6]
after [3, 3, 5, 9, 9, 1, 1, 1]
Changing 8
before [3, 3, 5, 9, 9, 1, 1, 1, 6]
after [3, 3, 5, 9, 9, 1, 1, 1, 1]
Changing 9
before [3, 3, 5, 9, 9, 1, 1, 1, 1, 0]
after [3, 3, 5, 9, 9, 1, 1, 1, 1, 0]
As you can see, the even numbers do get replaced with the list minimum. Your claim that it doesn't change any number is incorrect.
If you want to change odd numbers, then you need to invert your check:
if s[i]%2 == 1:
changed if s[i]%2==0
to if s[i]%2!=0
to pick out the odd numbers. The first way will change even numbers
import random
a = int(input('Num -> '))
# creates your list of x random numbers
s = []
for i in range(a):
s.append(random.randint(0,10))
# change odd numbers to the min of the original list
for i in range(a):
if s[i]%2!=0:
s[i]=min(s)
so let's say a is 10:
>>> [2, 2, 8, 1, 2, 2, 10, 7, 5, 7]
now change all odd numbers to min (in this case it's '1')
>>> [2, 2, 8, 1, 2, 2, 10, 1, 1, 1]
The answer below works too, it's just a matter of if you need it to change after each iteration of creating the list, or create the list first, and then apply your rule.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.