I'm pretty new to Python and have a task where I am supposed to iterate through a sorted list to find the place where to insert an element into the list at the right place. So far I have managed to get it to work, except for when the list is empty. I have tried to read up on the "append"-function to see how I can do to not make it print "None", but without any results.
If someone has a good answer to how I can adjust the first if-statement to make it possible to add the value x to the list and print the updated list it would be amazing. I want the first test with the (2, []) to show [2].
# Task 1a
# Create a function that places an element x in a sorted list
def insert_in_sorted (x, sorted_list):
for i in range(len(sorted_list)):
if not sorted_list:
sorted_list.append(x)
return sorted_list
if x > max(sorted_list) or not sorted_list:
sorted_list.append(x)
return sorted_list
elif sorted_list[i] > x:
sorted_list.insert(i,x)
return sorted_list
elif sorted_list[i-1] and sorted_list[i 1] == x:
sorted_list.insert(i,x)
return sorted_list
print(insert_in_sorted(2,[]))
print(insert_in_sorted(5,[0,1,3,4]))
print(insert_in_sorted(2,[0,1,2,3,4]))
print(insert_in_sorted(2,[2,2]))
CodePudding user response:
your look will only iterate if there are items in the list, so just take the first if outside the loop to check if the list is empty or not
# Task 1a
# Create a function that places an element x in a sorted list
def insert_in_sorted(x, sorted_list):
if not sorted_list:
sorted_list.append(x)
return sorted_list
for i in range(len(sorted_list)):
if x > max(sorted_list) or not sorted_list:
sorted_list.append(x)
return sorted_list
elif sorted_list[i] > x:
sorted_list.insert(i, x)
return sorted_list
elif sorted_list[i - 1] and sorted_list[i 1] == x:
sorted_list.insert(i, x)
return sorted_list
print(insert_in_sorted(2, []))
print(insert_in_sorted(5, [0, 1, 3, 4]))
print(insert_in_sorted(2, [0, 1, 2, 3, 4]))
print(insert_in_sorted(2, [2, 2]))
OUTPUT
[2]
[0, 1, 3, 4, 5]
[0, 1, 2, 2, 3, 4]
[2, 2, 2]
CodePudding user response:
it seems you are doing left insert
import bisect
def insert_in_sorted (x, sorted_list):
bisect.insort_left(sorted_list,x)
return sorted_list
print(insert_in_sorted(2,[]))
print(insert_in_sorted(5,[0,1,3,4]))
print(insert_in_sorted(2,[0,1,2,3,4]))
print(insert_in_sorted(2,[2,2]))
[2]
[0, 1, 3, 4, 5]
[0, 1, 2, 2, 3, 4]
[2, 2, 2]