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
Suggest corrections for the errors in both the previous questions.
Write a program that uses a function called findinlist() to check for the position of the first occurrence of v in the list passed as parameter (lst) or -1 if not found. The header for the function is given below :
def find_in_list(lst, v): """ lst - a list v - a value that may or may not be in the list """
Use a list comprehension to create a list, CB4. The comprehension should consist of the cubes of the numbers 1 through 10 only if the cube is evenly divisible by four. Finally, print that list to the console. Note that in this case, the cubed number should be evenly divisible by 4, not the original number.
Take two lists, say for example these two :
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes. Write this in one line of Python using at least one list comprehension. Run the complete program and show output.