import random
while True:
s , d = 0 , []
for _ in range(50):
x = random . randint(3 , 5)
d . append(x)
s += x
if s == 185:
break
print(d)
运行实况
D:\0002.Exercise\Python>python x.py
D:\0002.Exercise\Python>python x.py
D:\0002.Exercise\Python> 你这题有2种解法,一种是不管效率,直接程序解题,一种是提升效率数学方法解题
一、程序法
import random
def new():
'''执行50次随机数'''
temp = []
for i in range(50):
temp.append(random.randint(3,5))
return temp
def check(list1):
'''检查列表的和'''
temp = 0
for each in list1:
temp += each
return temp == 185
while True:
list1 = new()
if check(list1):
print('大功告成')
print(list1)
break 数学法:
全5和3情况:
50*5-185=40,除以差额2,等于20
也就是最多只能有30个5
全4和3情况:
50*4-185=15,除以差额1,等于15
最多只能有35个4
--------------知道这2个逻辑以后,在随机生成列表的时候,每插入一个随机数,就检查下其中4和5的数量是否超上限,超过则自动重新生成,效率会稍微高点 本帖最后由 python初学者021 于 2021-3-24 15:51 编辑
我写的代码
原理
1:先产生一个列表,包括50个4
2:因为sum是185,所以先将 15个元素从4换成3,满足和是185
3:在剩下的4中,随机选出N组(2个4元素),将 4,4 换成 3,5
这一步保证sum不变
#!/usr/bin/python3
import random
return_list = * 50
diff = 4 * 50 - 185
while diff:
choiced_index = random.randint(0,49)
if return_list == 4:
return_list = 3
diff -= 1
number_of_4 = return_list.count(4)
number_of_switch = random.randint(0,int(number_of_4/2))
while number_of_switch:
NO_find_flag = True
while NO_find_flag:
change_index1 = random.randint(0,49)
if return_list == 4:
NO_find_flag = False
NO_find_flag = True
while NO_find_flag:
change_index2 = random.randint(0,49)
if (change_index1 != change_index2) & (return_list == 4):
NO_find_flag = False
return_list = 3
return_list = 5
number_of_switch -= 1
print(return_list)
result:
页:
[1]