-
实现下列函数,并将其定义为模块insert, 即存储在insert.py中:
def insert(aList, i):"""aList[0:i] are in ascending order,
i.e. aList[0] <= aList[1]<= ... <= aList[i-1].
insert(aList, i) will insert aList[i] into proper postion and
make aList[0:i+1] in asceding order and aList[i+1:] unchanged.
"""
这里主要实现一个插入排序def insert(aList, i): key=aList[i] j=i-1 while j>=0 and aList[j] > key: aList[j+1]=aList[j] j-=1 aList[j+1]=key return aList
-
二. 请使用递归实现以下函数,并将其定义为模块seqrec, 即存储在seqrec.py中。
def seq_rec(n):
"""Return the nth term of the sequence defined by a0=1, a1=2,a2 = 2, an = an-1+an-2+an-3,
i.e., seq_rec(n) returns an.
"""
def seq_rec(n): if n == 0: return 1 elif n == 1 or n == 2: return 2 else: return seq_rec(n-1)+seq_rec(n-2)+seq_rec(n-3)
三. 请使用迭代(非递归)实现以下函数,并将其定义为模块seqiter, 即存储在seqiter.py中。def seq_iter(n):
"""Return the nth term of the sequence defined by a0=1, a1=2,a2 = 2, an = an-1+an-2+an-3,
扫描二维码关注公众号,回复: 2288411 查看本文章i.e., seq_iter(n) returns an.
"""实现
def seq_iter(n): a=[1,2,2] if n == 0: return a[0] elif n == 1 or n == 2: return a[1] else: i=3 for i in range(3,n+1): temp=a[i-1]+a[i-2]+a[i-3] a.append(temp) return a[n]
Python课程学习记录_15周作业
猜你喜欢
转载自blog.csdn.net/cyanchen666/article/details/80674971
今日推荐
周排行