Python核心编程(第二版)一些习题答案心得

来源:互联网 发布:python post文件 编辑:程序博客网 时间:2024/04/30 06:49

2-15.用户输入3个数,保存至不同的变量中。不使用列表或排序算法,自己写代码来对这3个数进行排序:从大到小,从小到大。


第一反应是用if将每个数都比较排序,是个相当繁琐笨拙的做法。之后改良一些,用了.format()。

</pre><pre name="code" class="python">a1 = raw_input('enter number:')b2 = raw_input('enter number:')c3 = raw_input('enter number:')a,b,c = a1,b2,c3  if a > b:      a, b = b, a # swap two value  if a > c:      a, c = c, a  if b > c:      b, c = c, b  print('{}<{}<{}'.format(a, b, c))  


6-15.

year_1 = raw_input('enter 1 date,like date/month/year:')a1=year_1.find('/')b1=year_1.rfind('/')date_1 = year_1[:a1]year1 = year_1[b1+1:]month_1 = year_1[a1+1:b1]M_1 =month_1 #word transfor numbersdef monthcount(year,month):if int(year) % 4 != 0:if int(month) == 1:return 0elif int(month) == 2:return 31elif int(month) == 3:return 59elif int(month) == 4:return 90elif int(month) == 5:return 120elif int(month) == 6:return 151elif int(month) == 7:return 181elif int(month) == 8:return 212elif int(month) == 9:return 243elif int(month) == 10:return 273elif int(month) == 11:return 304elif int(month) == 12:return 334elif int(year)%4 == 0:if int(month) == 1:return 0elif int(month) == 2:return 32elif int(month) == 3:return 60elif int(month) == 4:return 91elif int(month) == 5:return 121elif int(month) == 6:return 152elif int(month) == 7:return 182elif int(month) == 8:return 213elif int(month) == 9:return 244elif int(month) == 10:return 275elif int(month) == 11:return 305elif int(month) == 12:return 335M_1 = monthcount(year1,month_1)sum_1 = int(year1)/4*366+(int(year1)-int(year1)/4)*365+int(M_1)+int(date_1)year_2 = raw_input('enter 1 date again,like date/month/year:')a2=year_2.find('/')b2=year_2.rfind('/')date_2 = year_2[:a2]year2 = year_2[b2+1:]month_2 = year_2[a2+1:b2]M_2 =month_2M_1 = monthcount(year2,month_2)sum_2 = int(year2)/4*366+(int(year2)-int(year2)/4)*365+int(M_2)+int(date_2)Sum = sum_2 - sum_1print'the day is:%r'%Sum

0 0