您好,欢迎访问三七文档
1第二章Python介绍2.1编写一个程序,处理三个变量X、Y和Z,然后输出他们中最大的奇数,如果没有奇数输出一段文字来说明:'''returnthebiggestoddnumberinanumberlist'''defreturn_biggest_number(A_LIST):odd=[]foreach_numinA_LIST:ifeach_num%2==1:odd.append(each_num)ifodd==None:print('nooddnumberisfound')returnsorted(odd)[-1]print(return_biggest_number([5,11,3]))2.2编写一个程序,要求用户输入10个整数,然后输出其中最大的奇数。如果没有输入奇数,输出一条信息来说明:defreturn_biggest_number(A_LIST):odd=[]foreach_numinA_LIST:ifeach_num%2==1:odd.append(each_num)ifodd==None:print('nooddnumberisfound')returnsorted(odd)[-1]num_list=[]foreach_numinrange(10):num=input('inputthe'+str(each_num)+'thnumber')num_list.append(int(num))print(return_biggest_number(num_list))2第三章一些简单的数值类程序3.1编写一个程序,要求用户输入一个整数并输出两个整数root和pwr,满足0pwr6并且rootpwr和用户输入的整数相等。如果不存在满足条件的整数对,输出一条信息来说明。(肯定存在的好吗==!)defreturn_abs_root(x,pwr):ans=0whileans**pwrabs(x):ans=ans+1ifans**pwr!=abs(x):return-1else:returnansdefreturn_root_pwr(x):ans_list=[]forpwr_numinrange(5):pwr_num+=1#pwr_numshouldnotbe0,itcancauseadisaster!abs_root=return_abs_root(x,pwr_num)ifabs_root!=-1:ifx0andpwr_num%2==0:ans_list.append((abs_root,pwr_num))ans_list.append((-abs_root,pwr_num))else:ifx0andpwr_num%2==1:ans_list.append((abs_root,pwr_num))ifx0andpwr_num%2==1:ans_list.append((-abs_root,pwr_num))returnans_listx=int(input('inputainteger'))print(return_root_pwr(x))33.2假设S是包含多个小数的字符串,小数之间使用逗号分割,例如,s=’1.23,2.4,3.123’。编写一个程序,输出s中的数字的和:defsum_string(a_str):str_list=a_str.strip().split(',')float_list=[float(each_item)foreach_iteminstr_list]ans=0foreach_numinfloat_list:ans+=each_numreturnansprint(sum_string('3.23,2.4,3.123'))3.3如果把图3-4中的语句x=25改成x=-25会发生什么?(自己敲代码试试,试之前请先把电脑该保存的东西都保存一下!==!)3.4如果要让图3-4中的代码既可以寻找负数的立方根又可以寻找正数平方根,该如何进行修改?defdichotomy(x,epsilon=0.01):low=min(x,-1.0)high=max(x,1.0)ans=(low+high)/2.0whileabs(ans**3-x)=epsilon**3:ifans**3-x0:high=anselse:low=ansans=(low+high)/2.0returnansprint(dichotomy(-27))3.5二进制数10011对应的十进制数是多少(16+2+1=19):defbinary_to_decimal(a_list):a_list=str(a_list)ans=0foreach_numinrange(len(a_list)):ans+=int(a_list[-1-each_num])*(2**each_num)returnansprint(binary_to_decimal('10011'))43.6给牛顿-拉夫逊方法的具体实现添加一些代码,跟踪寻找解的次数。使用这个次数来比较牛顿—拉夫逊方法和二分法的查找效率。defdichotomy_square(x,epsilon=0.01):dic_n=0low=0high=max(x,1.0)ans=(low+high)/2.0whileabs(ans**2-x)=epsilon:dic_n+=1ifans**2-x0:high=anselse:low=ansans=(low+high)/2.0return[ans,dic_n]defnewton(x,epsilon=0.01):guess=x/2.0n_newton=0whileabs(guess**2-x)=epsilon:guess=guess-((guess**2-x)/(2*guess))n_newton+=1return[guess,n_newton]print(dichotomy_square(24))print(newton(24))5第四章4.1编写一个函数isIn,接受两个字符串作为参数,如果一个字符串出现在另一个字符串中就返回True,否则返回False。提示:你可能需要使用str中的内建操作in。defisIn(s1,s2):ifs1ins2:returnTrueelse:returnFalseprint(isIn('sb','sb250'))
本文标题:编程导论作业答案
链接地址:https://www.777doc.com/doc-4177074 .html