本帖最后由 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 = [4] * 50
- diff = 4 * 50 - 185
- while diff:
- choiced_index = random.randint(0,49)
- if return_list[choiced_index] == 4:
- return_list[choiced_index] = 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[change_index1] == 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[change_index2] == 4):
- NO_find_flag = False
- return_list[change_index1] = 3
- return_list[change_index2] = 5
- number_of_switch -= 1
- print(return_list)
复制代码
result:
[3, 4, 3, 4, 4, 3, 3, 4, 3, 5, 5, 3, 5, 4, 4, 4, 3, 5, 4, 3, 3, 3, 5, 3, 4, 3, 4, 3, 4, 5, 3, 3, 3, 4, 3, 3, 5, 3, 3, 4, 3, 3, 3, 5, 5, 5, 3, 4, 4, 3]
[4, 3, 3, 3, 4, 4, 4, 3, 4, 5, 3, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 4, 4, 3, 4, 4, 4, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 4, 4, 3, 3, 4, 3, 4, 3, 4, 3, 4, 4]
|