J.Doe
J.Doe

Reputation: 71

Using for loops in sorting numbers in list

def insert3(x,ss):
    left = [] #why this need to add properly by list, or not it just return the recent result.
    while ss!= []:
        for y in ss:
            if x<= ss[0]:
                return left + [x] + ss[0:]
            else:
                ss, left = ss[1:], left + [ss[0]]
        return left + ss + [x]

print(insert3(6,[2,4,5,7,8]))

Is this the correct usage of for loop for the function?

I've changed a bit of it. Is this correct?

def insert3(x,ss):
    left = []
    for y in ss:
        if x<= ss[0]:
            return left + [x] + ss[0:]
        else:
            ss, left = ss[1:], left + [ss[0]]
    return left + ss + [x]

print(insert3(6,[2,4,5,7,8])) 

Upvotes: 1

Views: 373

Answers (2)

Robert E
Robert E

Reputation: 401

Using bisect from this question would be a good way to solve the problem. Also see wikipedia. But a simpler example of what you're trying to do is:

def Insert(val, list):
    for i, entry in enumerate(list):
        if val < entry:
            return list[0:i] + [val] + list[i:]
print(Insert(6,[2,4,5,7,8]));

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881383

Why are you writing complex code to insert into a sorted list? You can just use something like:

>>> x = [2,4,5,7,8]
>>> x.append(6)
>>> x.sort()
>>> x
[2, 4, 5, 6, 7, 8]

Unless you strike a huge performance bottleneck, you're better off just using the features of the language. I like to call this optimising for development effort.

Upvotes: 1

Related Questions