KnowledgeBoat Logo

Computer Science

Implement the following function for a linear list, which find outs and returns the number of unique elements in the list

def unique(lst):
"""passed parameter lst is a list of 
integers (could be empty)."""

After implementing the above function, test it with following lists and show the output produced by above function along with the reason for that output.

(i) lst = []

(ii) lst = [1, 2, 3]

(iii) lst = [1, 2, 2]

(iv) lst = [1, 2, 2, 3, 3]

Linear Lists

2 Likes

Answer

def unique(lst):
    c = 0
    for i in range(0, len(lst)):
        if lst[i] not in lst[i+1:]:
            c += 1   
    return c

lst = eval(input("Enter the list: "))
print(unique(lst))  
Output
Enter the list: []
0
Enter the list: [1, 2, 3]
3
Enter the list: [1, 2, 2]
2
Enter the list: [1, 2, 2, 3, 3]
3

(i) lst = [] — The output is 0 because the list is empty.

(ii) lst = [1, 2, 3] — The output is 3 because the list contains 3 unique elements — 1, 2, 3.

(iii) lst = [1, 2, 2] — The output is 2 because the list contains 2 unique elements — 1, 2.

(iv) lst = [1, 2, 2, 3, 3] — The output is 3 because the list contains 3 unique elements — 1, 2, 3.

Answered By

1 Like


Related Questions