Advertisements
Advertisements
प्रश्न
Write a function that takes a list that is sorted in ascending order and a number as arguments. The function should do the following:
- Insert the number passed as argument in a sorted list.
- Delete the number from the list.
कोड लेखन
Advertisements
उत्तर
The first function inserts the number at its correct sorted position. The second function deletes the first occurrence of the number, if present.
def insert_sorted(data_list, number):
"""Insert number into an ascending sorted list."""
position = 0
# Find the correct insertion position
while position < len(data_list) and data_list[position] < number:
position += 1
data_list.insert(position, number)
return data_list
def delete_number(data_list, number):
"""Delete the first occurrence of number from the list."""
if number in data_list:
data_list.remove(number)
return data_list
print("Element not found")
return data_list
numbers = [2, 6, 7, 10, 14, 15, 16, 19]
print(insert_sorted(numbers, 12))
print(delete_number(numbers, 12))
[2, 6, 7, 10, 12, 14, 15, 16, 19]
[2, 6, 7, 10, 14, 15, 16, 19]shaalaa.com
क्या इस प्रश्न या उत्तर में कोई त्रुटि है?
