第二章Python 介绍
2.1编写一个程序,处理三个变量X、Y和Z,然后输出他们中最大的奇数,如果没有奇数输出一段文字来说明:
'''return the biggest odd number in a number list''' defreturn_biggest_number(A_LIST): odd=[]
foreach_numin A_LIST: if each_num%2==1: odd.append(each_num) if odd==None:
print('no odd number is found')
return sorted(odd)[-1]
print(return_biggest_number([5, 11, 3]))
2.2 编写一个程序,要求用户输入10个整数,然后输出其中最大的奇数。如果没有输入奇数,输出一条信息来说明:
defreturn_biggest_number(A_LIST): odd=[]
foreach_numin A_LIST: if each_num%2==1: odd.append(each_num) if odd==None:
print('no odd number is found') return sorted(odd)[-1] num_list=[]
foreach_numin range(10):
num=input('input the '+str(each_num)+'th number') num_list.append(int(num))
print(return_biggest_number(num_list))
1
第三章一些简单的数值类程序
3.1 编写一个程序,要求用户输入一个整数并输出两个整数root和pwr,满足0 defreturn_abs_root(x,pwr): ans=0 whileans**pwr ifans**pwr!=abs(x): return -1 else: returnans defreturn_root_pwr(x): ans_list=[] forpwr_numin range(5): pwr_num+=1#pwr_num should not be 0 ,it can cause a disaster! abs_root=return_abs_root(x,pwr_num) ifabs_root !=-1: if x>0and pwr_num%2==0: ans_list.append((abs_root,pwr_num)) ans_list.append((-abs_root,pwr_num)) else: if x>0and pwr_num%2==1: ans_list.append((abs_root,pwr_num)) if x<0and pwr_num%2==1: ans_list.append((-abs_root,pwr_num)) returnans_list x=int(input('input a integer')) print(return_root_pwr(x)) 2 3.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=0 foreach_numinfloat_list: ans+=each_num returnans print(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.0 while abs(ans**3-x)>=epsilon**3: ifans**3-x>0: high=ans else: low=ans ans=(low+high)/2.0 returnans print(dichotomy(-27)) 3.5二进制数10011对应的十进制数是多少(16+2+1=19): defbinary_to_decimal(a_list): a_list=str(a_list) ans=0 foreach_numin range(len(a_list)): ans+=int(a_list[-1-each_num])*(2**each_num) returnans print(binary_to_decimal('10011')) 3 3.6 给牛顿-拉夫逊方法的具体实现添加一些代码,跟踪寻找解的次数。使用这个次数来比较牛顿—拉夫逊方法和二分法的查找效率。 defdichotomy_square(x,epsilon=0.01): dic_n=0 low=0 high=max(x,1.0) ans=(low+high)/2.0 while abs(ans**2-x)>=epsilon: dic_n+=1 ifans**2-x>0: high=ans else: low=ans ans=(low+high)/2.0 return [ans,dic_n] defnewton(x,epsilon=0.01): guess=x/2.0 n_newton=0 while abs(guess**2-x)>=epsilon: guess=guess-((guess**2-x)/(2*guess)) n_newton+=1 return [guess,n_newton] print(dichotomy_square(24)) print(newton(24)) 4 第四章 4.1 编写一个函数isIn,接受两个字符串作为参数,如果一个字符串出现在另一个字符串中就返回True,否则返回False。提示:你可能需要使用str中的内建操作in。 defisIn(s1,s2): if s1 in s2: returnTrue else: returnFalse print(isIn('sb','sb250')) 5 百度搜索“70edu”或“70教育网”即可找到本站免费阅读全部范文。收藏本站方便下次阅读,70教育网,提供经典综合文库编程导论作业答案在线全文阅读。
相关推荐: