Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

Python sorted list insertion

I need help for an exercise in python where I have to fill a preexistent code.

The function take an integer and a sorted list, it inserts the value a and then returns the new list, I have to replace the dots by the correct answer

It looks like this :

def insert(a, tab):
    l = list(tab)
    l.append(a)
    i = ...
    while a < ... :
        l[i+1] = ...
        l[i] = a
        i = ...
    return l

>>> insert(3,[1,2,4,5])
[1, 2, 3, 4, 5]

Thanks for the help.

question from:https://stackoverflow.com/questions/65940643/python-sorted-list-insertion

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
def insert(a, tab):
    l = list(tab)
    l.append(a)
    i = len(l) - 2
    while a < l[i] and i >= 0:
        l[i+1] = l[i]
        l[i] = a
        i -= 1
    return l

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...