标签:单位 style 一个 rand one 排序 replace oat str
用Python编写简单的发红包程序:
第一种解法:数轴方法解决
import random def red_packet(money,num): money = money * 100 #将钱数转换成分为单位 ret = random.sample(range(1,money),num-1) #在最低钱数1分与总钱数之间生成人数减1个数作为数轴的节点 ret.sort() #对列表进行排序 ret.insert(0,0) ret.append(money) for i in range(len(ret)-1): yield (ret[i+1]-ret[i])/100 ret_g = red_packet(100,10) for money in ret_g: print(money)
第二种解法:用概率解决
def red_packet(money,person): dic_person_money = {} for i in range(person): num = random.randint(1,100) dic_person_money[‘Person%s‘ % (i+1)] = num num_sum = 0 for i in dic_person_money: num_sum += dic_person_money[i] for i in dic_person_money: x = round(dic_person_money[i]/num_sum*money,2) dic_person_money[i] = ‘$%s‘ % x return dic_person_money result = red_packet(1,10) print(result)
用Python设计一个简单的计算器:
import re def atom_cal(exp): if ‘*‘ in exp: a,b = exp.split(‘*‘) return str(float(a)*float(b)) elif ‘/‘ in exp: a, b = exp.split(‘/‘) return str(float(a) / float(b)) def format_exp(exp): exp = exp.replace(‘--‘,‘+‘) exp = exp.replace(‘+-‘, ‘-‘) exp = exp.replace(‘-+‘, ‘-‘) exp = exp.replace(‘++‘, ‘+‘) return exp def mul_div(exp): while 1: ret = re.search(‘\d+(\.\d+)?[*/]-?\d+(\.\d+)?‘,exp) if ret: atom_exp = ret.group() res = atom_cal(atom_exp) exp = exp.replace(atom_exp,res) else:return exp def add_sub(exp): ret = re.findall(‘[+-]?\d+(?:\.\d+)?‘,exp) sum = 0 for i in ret: sum += float(i) return sum def cal(exp): exp = mul_div(exp) exp = format_exp(exp) return add_sub(exp) def main(exp): exp = exp.replace(‘ ‘,‘‘) while 1: ret = re.search(‘\([^()]+\)‘,exp) if ret: cal_exp = ret.group() res = str(cal(cal_exp)) exp = exp.replace(cal_exp,res) else:break return cal(exp) s = ‘1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )‘ print(main(s))
标签:单位 style 一个 rand one 排序 replace oat str
原文地址:https://www.cnblogs.com/fengchong/p/9520171.html