-
1. 设计一个将两个有序列表合并成一个有序列表的函数:给定两个列表,从小到大排列,每个列表没有重复元素。将这两个列表合并成一个从小到大的列表,它包含输入的所有元素,但是没有重复元素。请按照要求实现下列函数,并将其定义为模块merge, 即存储在merge.py中:
def merge(aList, bList):"""aList and bList are two integer lists in ascending order.The function returns a new integer list in ascending order with all elements in aList and bList but no repetitions.for example, merge([2,3, 4,5],[1,3,5]) returns [1,2,3,4,5]."""def merge(aList, bList): l,r = 0,0 result=[] while l<len(aList) and r<len(bList): if aList[l] < bList[r]: result.append(aList[l]) l += 1 else: result.append(bList[r]) r += 1 result += aList[l:] result += bList[r:] result2=list(set(result)) return result2
可参照内容中MIT幕课关于归并排序的归并实现录像。这里的归并与录像中的归并的区别是没有重复元素。2. 实现下列函数, 并将其定义为模块selection, 即存储在selection.py中:def selection(aList, i):"""exchange aList[i] with the first smallest element in aList[i:], where i is a valid index. Don't change other elements. """函数的进一步解释请参照内容中的录像selection.mp4.def selection(aList, i): temp_list=aList smallest = i for j in range(i+1,len(temp_list)): #如果找到比当前值小的index,则进行两值交换 if(temp_list[j]<temp_list[smallest]): smallest=j tmp = temp_list[i] temp_list[i] = temp_list[smallest] temp_list[smallest]=tmp return temp_list
3. 实现下列函数, 并将其定义为模块getnums, 即存储在getnums.py中:def getnums(filename):"""filename is a text file which contains many integers separated by white spaces and commas.The function read the file filename and returns a list of all the integers in filename in the order of their occurrences.""""如果一个文件不是很大,在内存放得下,可以用readlines()方法一次读入内存,即用一个列表存储文件内容,然后对列表进行处理:f = open(filename, 'r') #返回文件对象lines = f.readlines() #lines是filename中各行字符串构成的列表。lines只是个变量名,可取任何变量名。f.close() # 关闭文件对象接着在这里处理lines, 返回所需要的结果。比如,for line in lines: #这里line当然只是一个变量,可以用任何名称。你的处理语句你可能需要str类型对象的方法split()和strip()。一个数据文件例子 numbers.txt , getnums('numbers.txt')将返回列表 [12, 34, 23, 45, 11, 23, 48, 56, 50, 123, 100]。假定参数表示的文件filename与脚本getnums.py在同一个目录。def split4list(numberlist): totallist = [] for item in numberlist: sublist = item.strip().strip(',').split(' ') for i in sublist: res=i.strip(',') if res.isdigit(): totallist.append(res) return totallist def getnums(filename): result=[] f = open(filename, 'r') #返回文件对象 #lines是filename中各行字符串构成的列表。lines只是个变量名,可取任何变量名。 lines = f.readlines() result=split4list(lines) return result
最后一题的输出还有点问题,就是列表的每个元素前后都会带着单引号,所以还没有实现去除单引号的输出。
Python课程学习记录_16周作业
猜你喜欢
转载自blog.csdn.net/cyanchen666/article/details/80787249
今日推荐
周排行