1

I'm trying to make a program that tracks how an (example) cell colony would grow. It's very simple;

  • cell starts at age 0
  • at age 1 cell is adult able to reproduce, creating 1 cell each year (slow, I know)
  • at age m cell dies
  • we want the number of cells after n years Example:n = 6 and m = 3 results in 4 cells

I tried to solve this by creating two lists:

babies = [0] (one starting cell)
adults = []

My plan was moving each baby_cell to the adult list after the baby would be age 1, this is also where the problem lies. This is what I wrote:

    index = 0
    for baby in babies:
        if baby == 1:
            adults.append(baby)
            del babies[index]
        index += 1

It only moves one cell, so if babies = [1, 1] it will only remove one of the two and leave the other one there. Over time these accumulate, and you end up with a babies list full of adults...

I have never been this stuck since I started programming. I'm probably overlooking something simple, but still, I need help!

RobertT
  • 4,300
  • 3
  • 29
  • 36
GotYa
  • 121
  • 1
  • 8
  • 1
    Deleting elements from a list while you're iterating over it simply does not work - you end up skipping items. The simplest solution is to iterate over a copy of the list: `for baby in babies[:]` perhaps. – jasonharper Sep 16 '18 at 12:09

1 Answers1

0

The reason it does not work is covered in the dupe: How to remove items from a list while iterating - the error stems from editing the same list that you are iterating at this moment.


Instead you could use list comprehensions (and one single list) to simulate this:

cells = [0]
adult = 1
death = 3
simulateTime = 6

print(f"Time 0: {cells}")

for t in range(simulateTime):
    # advance age, die if too old - use < death if age 3 should not breed anymore
    cells[:] = [x+1 for x in cells if x+1 <= death]
    # breed adult ones
    cells.extend( (0 for x in cells if x >= adult)  )

    print(f"Time {t+1}: {cells}")

Output:

Time 0: [0]
Time 1: [1, 0]
Time 2: [2, 1, 0, 0]
Time 3: [3, 2, 1, 1, 0, 0, 0, 0]
Time 4: [3, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0]
Time 5: [3, 3, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Time 6: [3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0,
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

I seem to miss some criteria, as with death on age 3 and 6 iterations, I get far more then 4 cells ;o).

Result for list comp with x+1 < death:

Time 0: [0]
Time 1: [1, 0]
Time 2: [2, 1, 0, 0]
Time 3: [2, 1, 1, 0, 0, 0]
Time 4: [2, 2, 1, 1, 1, 0, 0, 0, 0, 0]
Time 5: [2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]
Time 6: [2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69