python3练习100题——039

原题链接:http://www.runoob.com/python/python-exercise-example39.html

题目:有一个已经排好序的数组。现输入一个数,要求按原来的规律将它插入数组中。

我的代码:

def compare():
    ls=[]
    while True:
        a=input("please enter a number:")
        if not a:
            break
        ls.append(int(a))
    for i in range(0,len(ls)):
        for j in range(0,len(ls)-i-1):
            if ls[j]<ls[j+1]:
                ls[j],ls[j+1]=ls[j+1],ls[j]
    return fun(ls)

def fun(l=None):
    l = [] if l is None else l
    print(l)
    num=int(input("Enter a number:"))
    l.append(num)
    for i in range(len(l)-1,0,-1):
        if l[i]>l[i-1]:
            l[i],l[i-1]=l[i-1],l[i]
    print(l)


if __name__ =='__main__':
    compare()

思考:

在36题冒泡法的基础上先获得一个由大到小排列的list,返回一个函数,用来输入一个数并找到它的位置。其实第二个函数也是用的冒泡法,只用对1个数进行排序,所以一个循环也就够了。

当然,如果用sort 、insert等函数 ,也容易多了。

posted @ 2018-06-22 09:44  Drifter_y  阅读(600)  评论(0编辑  收藏  举报