Answer to Question #329093 in Python for ratul

Question #329093

Write a python function that takes a list as an argument. Your task is to create a new list where

each element can be present at max 2 times. Inside the function, print the number of

elements removed from the given list. Finally, return the new list and print the result.

=====================================================

Hint: You may use list_name.count(element) to count the total number of times an element is in

a list. list_name is your new list for this problem.

=====================================================

Function Call:

function_name([1, 2, 3, 3, 3, 3, 4, 5, 8, 8])

Output:

Removed: 2

[1, 2, 3, 3, 4, 5, 8, 8]

================================

Function Call:

function_name([10, 10, 15, 15, 20])

Output:

Removed: 0

[10, 10, 15, 15, 20]


1
Expert's answer
2022-04-20T12:41:09-0400
def remove_third(L):
    count = 0
    result = []
    for x in L:
        if result.count(x) >= 2:
            count += 1
        else:
            result.append(x)
    print('Removed:', count)
    return result


print('=====================================================')
L = [1, 2, 3, 3, 3, 3, 4, 5, 8, 8]
print('Function Call:')
print('remove_third((', L, ')', sep='')
print('Output:')
res = remove_third(L)
print(res)


print('=====================================================')
L = [10, 10, 15, 15, 20]
print('Function Call:')
print('remove_third((', L, ')', sep='')
print('Output:')
res = remove_third(L)
print(res)

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS