मराठी

Write a function that takes a list that is sorted in ascending order and a number as arguments. The function should do the following: a. Insert the number passed as argument in a sorted list.

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:

  1. Insert the number passed as argument in a sorted list.
  2. 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
  या प्रश्नात किंवा उत्तरात काही त्रुटी आहे का?
पाठ 5: Liner List Manipulation - EXERCISE [पृष्ठ १०४]

APPEARS IN

सीबीएसई Computer Science with Python [English] Class 12
पाठ 5 Liner List Manipulation
EXERCISE | Q 7. | पृष्ठ १०४
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×