[英]How can i create a list of 50 random numbers where the even numbers are twice the odd numbers?
can you help me with this problem please?你能帮我解决这个问题吗? I have to create a list of 50 random numbers from 1 to 10 where the odd numbers frequency is aproximately twice the even number frequency.
我必须创建一个从 1 到 10 的 50 个随机数的列表,其中奇数频率大约是偶数频率的两倍。
Try two list, one with 33 random odd numbers and the other with 17 random even numbers, and then merge the two lists.尝试两个列表,一个有 33 个随机奇数,另一个有 17 个随机偶数,然后合并两个列表。
Solution as simplified简化的解决方案
import random
odd=[item for item in range(1,11,2)]
even=[item for item in range(2,11,2)]
# twice chance 50/3 ~17 odd=33 even=17
random_even=[random.choice(even) for _ in range(17)]
random_odd=[random.choice(odd) for _ in range(33)]
random_number=random_even+random_odd # sum
random.shuffle(random_number) # messing up order
print("even",len(random_even),"odd",len(random_odd)) #check len
print("len list : ",len(random_number))#check len
print(random_number)#show list
random.choices
has an argument weights
, which can makes the odd number roughly twice as many as the even number: random.choices
有一个参数weights
,它可以使奇数大约是偶数的两倍:
>>> nums = range(1, 11)
>>> random.choices(nums, weights=[2 / 3, 1 / 3] * 5, k=50)
[7, 4, 4, 2, 1, 1, 7, 9, 6, 9, 3, 9, 9, 5, 9, 3, 2, 1, 9, 10, 9, 3, 7, 5, 3, 8, 8, 10, 9, 5, 2, 9, 9, 6, 5, 5, 10, 5, 6, 5, 1, 3, 3, 2, 5, 6, 5, 5, 5, 2]
>>> sum(i % 2 == 0 for i in _)
16
>>> (50 - 16) / 16
2.125
If you have strict requirements on their quantitative relationship, you can generate two lists, concatenate and shuffle:如果对它们的数量关系有严格要求,可以生成两个列表,concatenate 和 shuffle:
>>> n_even = 50 // 3
>>> n_odd = 50 - n_even
>>> rand = random.choices(nums[::2], k=n_odd) + random.choices(nums[1::2], k=n_even)
>>> random.shuffle(rand)
>>> rand
[2, 10, 5, 8, 7, 10, 3, 5, 1, 7, 8, 10, 7, 5, 3, 9, 3, 10, 3, 2, 1, 10, 9, 8, 7, 6, 1, 1, 8, 1, 5, 4, 9, 9, 2, 1, 5, 1, 4, 7, 1, 2, 5, 7, 7, 1, 7, 1, 1, 5]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.