Issue
I need to write a function rep(lst, k)
where lst
is a list of integers and k
is the number of times they occur. For example, if i have a list:
lst = [1,2,1,5,3,4,2,1,3,5,6]
and launch the command rep(lst,2)
, it needs to return a list without repetitions that contain the numbers repeated k times, like:
rep(lst, 2)
# returns [1,2,5,3]
How do i do this? i can write a function where i count the occurence of a specific variable, but i can't do this, counting only returns me the number of elements in the list.
Solution
How about using sets
for the task:
lst = [1,2,1,5,3,4,2,1,3,5,6]
def rep(the_list, rep):
return [x for x in set(the_list) if the_list.count(x) == rep]
print(rep(lst, 2)) # -> [2, 3, 5]
set(the_list)
the list is converted to set to make sure every unique element is only searched once.
Answered By - Ma0
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.