-1

I cannot understand why iterator skips values in my function. Could someone help me with that? If it is needed the task is to create a new list that contains each number of list at most N times, without reordering.

from itertools import repeat


def delete_nth(order, max_e):

    def remove_from_list(i, list1):   # function to remove specific values from existing list
        if i in list1:
            list1.remove(i)
            return remove_from_list(i, list1)
        else:
            return list1

    new_list = []
    for x in order:     # SKIPS value 7
        if order.count(x) <= max_e:
            new_list.extend(repeat(x, order.count(x)))
            order = remove_from_list(x, order)
        else:
            new_list.extend(repeat(x, max_e))
            remove_from_list(x, order)

    return new_list


print(delete_nth([1,1,3,3,7,2,2,2,2], 3))

I tried to change a little order, then it skips some others values too, but I cannot find the connection.

Mat
  • 202,337
  • 40
  • 393
  • 406
  • you're modifying the list that you are iterating on – njzk2 Apr 01 '23 at 16:22
  • Lists are not their own iterators. The `list_iterator` instance tracks the index it uses to access the "next" list item, and that index does not get (and cannot be, at least not easily) updated if the underlying list changes. – chepner Apr 01 '23 at 18:05

1 Answers1

0

You are accidentally removing alternate items from your original list

Because many of your numbers are repeated, you haven't noticed, and you think it is just "7" that is being deleted.

Try this and you will see:

print(delete_nth([1,2,3,4,5,6,7,8,9], 3))

Result:

[1, 3, 5, 7, 9]

Solution: Do not delete items from your original list

from itertools import repeat


def at_most_n_times(source, n):
    
    result_counts = {}
    result = []

    for x in source:
        
        if x not in result_counts:
            result_counts[x]=0
        result_counts[x]+=1

        if result_counts[x]<=n:
            result.append(x)

    return result

print(at_most_n_times([1,1,3,3,7,2,2,2,2], 3))
ProfDFrancis
  • 8,816
  • 1
  • 17
  • 26