Write a simple red envelope program in Python:
The first solution: the number of axes method solves
ImportRandomdefRed_packet (money,num): money= Money * 100#convert the amount of money to the component unitret = random.sample (range (1,money), num-1)#A node with a number of 1 and a total amount reduced by 1 numbers as a number of axesRet.sort ()#sort the listRet.insert (0,0) ret.append (money) forIinchRange (len (ret)-1): yield(Ret[i+1]-ret[i])/100Ret_g= Red_packet (100,10) forMoneyinchRet_g:Print(Money)
The second solution: using probability to solve
defRed_packet (Money,person): Dic_person_money= {} forIinchRange (person): num= Random.randint (1,100) dic_person_money['person%s'% (i+1)] =Num num_sum=0 forIinchDic_person_money:num_sum+=Dic_person_money[i] forIinchdic_person_money:x= Round (dic_person_money[i]/num_sum*money,2) Dic_person_money[i]='$%s'%xreturnDic_person_moneyresult= Red_packet (1,10)Print(Result)
Use Python to design a simple calculator:
ImportRedefatom_cal (exp):if '*' inchexp:a,b= Exp.split ('*') returnSTR (FLOAT (a) *float (b))elif '/' inchExp:a, b= Exp.split ('/') returnSTR (float (a)/float (b))defFORMAT_EXP (exp): Exp= Exp.replace ('--','+') Exp= Exp.replace ('+-','-') Exp= Exp.replace ('-+','-') Exp= Exp.replace ('++','+') returnExpdefMUL_DIV (exp): while1: Ret= Re.search ('\d+ (\.\d+)? [*/]-?\d+ (\.\d+)?', exp)ifRet:atom_exp=Ret.group () Res=atom_cal (ATOM_EXP) exp=exp.replace (atom_exp,res)Else:returnExpdefadd_sub (exp): RET= Re.findall ('[+-]?\d+ (?: \. \d+)?', exp) sum=0 forIinchRet:sum+=float (i)returnsumdefCAL (exp): Exp=MUL_DIV (exp) Exp=FORMAT_EXP (exp)returnadd_sub (exp)defMain (exp): Exp= Exp.replace (' ',"') while1: Ret= Re.search ('\([^()]+\)', exp)ifRet:cal_exp=Ret.group () Res=Str (CAL (CAL_EXP)) exp=exp.replace (cal_exp,res)Else: Break returnCAL (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))
Use Python to write a simple red Envelope program and calculator principle