|
发表于 2018-9-5 11:25:06
|
显示全部楼层
- # 思路:随机生成8个数字,大了就减,小了就加
- import random
- def num_40():
- # 初始化
- number = []
- number_str = ""
- # 生成8个随机数(0,9)之间
- for i in range(8):
- value = random.randint(0,9)
- number.append(value)
- # 生成等于40 的数
- if sum(number) < 40:
- add_num_40(number)
- else:
- sub_num_40(number)
- for j in range(8):
- number_str += str(number[j])
- return number_str
- # 定义加法模式
- def add_num_40(addnum):
- add_value = 40 - sum(addnum)
- while add_value !=0:
- for each in addnum:
- if add_value + addnum[each] <= 9:
- add_every_value = random.randint(0,add_value)
- add_value -= add_every_value
- addnum[each] += add_every_value
- if add_value == 0:
- break
- else:
- add_every_value = random.randint(0,9-addnum[each])
- add_value -= add_every_value
- addnum[each] += add_every_value
- if add_value == 0:
- break
- return addnum
- # 定义减法模式
- def sub_num_40(subnum):
- sub_value = sum(subnum) - 40
- while sub_value != 0:
- for each in subnum:
- if sub_value <= subnum[each]:
- sub_every_value = random.randint(0,sub_value)
- sub_value -= sub_every_value
- subnum[each] -= sub_every_value
- if sub_value == 0:
- break
- else:
- sub_every_value = random.randint(0,subnum[each])
- sub_value -= sub_every_value
- subnum[each] -= sub_every_value
- if sub_value == 0:
- break
- return subnum
- print(num_40())
复制代码 |
|