我正在做一些学习Python的练习练习,并注意到我在下面写的代码总是产生完全相同数量的奇数和偶数值,无论我运行多少次。
它产生不同的列表值,所以它是真正随机的吗?
任何人都可以解释这是正常的还是打击它的方法?
输出
[834,7719,2279,7403,241,7198,4278,2339,7492,928,1372,226,8134,165,3999,5367,8807,5838,9637,5850,2945,6419,5131, 1597,775,2493,518,9175,5980,7705,1259,7884,7220,7746,2144,7542,5939,3435,2723,7887,3978,1483,3799,7447,416,5977,303,9011, 5707,3085,41,1441,4119,677,1048,4399,5737,9032,5629,2953,8979,4165,6820,1830,7193,5760,7446,6383,2937,9591,6700,9505,4896, 2843,5994,5420,5063,1480,9187,5160,3191,1715,324,8124,5275,7265,5757,8441,4573,9946,8735,3455,4823,7777,7555,8140,4801,7034, 1074,8325]
奇数是50
即使是50
代码:
import random
numbers = []
even = 0
odd = 0
for x in range(100):
numbers = numbers + [random.randint(1,9999)]
for y in range(len(numbers)):
if int(y) % 2 == 0 :
even = even + 1
elif int(y) % 2 == 1:
odd = odd + 1
print(str(numbers))
print('Odd is ' + str(odd))
print('Even is ' + str(even))
答案 0 :(得分:4)
for y in range(len(numbers)):
您不会在那里迭代随机生成的数字。你正在从0到99迭代整数。其中只有一半是偶数,其中一半是奇数。
答案 1 :(得分:0)
我已根据其中一条评论修改了代码,并发现这有效。
感谢您的帮助
import random
numbers = []
even = 0
odd = 0
for x in range(100):
random.shuffle
numbers = numbers + [random.randint(1,9999)]
for y in range(len(numbers)):
if int(numbers[y]) % 2 == 0 :
even = even + 1
elif int(numbers[y]) % 2 == 1:
odd = odd + 1
print(str(numbers))
print('Odd is ' + str(odd))
print('Even is ' + str(even))