-2
def maxdex(banks):
  high = 0
  maxdex = 0
  for i in enumerate(banks):
    if(i[1] > high):
      maxdex,high = i[0],i[1]
  return([maxdex,high])
banks = [14,0,15,12,11,11,3,5,1,6,8,4,9,1,8,4]
states = []
cycles = 0
while True:
  states = states + [banks]
  maxer = maxdex(banks)
  blocks = maxer[1]
  target = (maxer[0]+1)%len(banks)
  while blocks > 0:
    banks[target] = banks[target]+1
    print(banks)
    print(states)
    target = (target+1)%len(banks)
    blocks -= 1
  cycles += 1
  if(banks in states):
    break
print(cycles)

When I run the code, states is changing when I try to increment a specific index in banks. What's going on?

(Btw, I'm solving a problem from Advent of code)

Endzeit
  • 4,810
  • 5
  • 29
  • 52
  • 1
    `states = states + [banks]` This does not make a _copy_ of banks; it uses the _actual object_ banks. So of course when you change banks, states also changes. – John Gordon May 11 '21 at 17:01
  • 1
    BTW, that's usually written as `states.append(banks)` – Barmar May 11 '21 at 17:02

1 Answers1

0

How about this?

def maxdex(banks):
  high = 0
  maxdex = 0
  for i in enumerate(banks):
    if(i[1] > high):
      maxdex,high = i[0],i[1]
  return([maxdex,high])
banks = [14,0,15,12,11,11,3,5,1,6,8,4,9,1,8,4]
states = []
cycles = 0
while True:
    #list.copy implemented
  states = states + list.copy(banks)
  maxer = maxdex(banks)
  blocks = maxer[1]
  target = (maxer[0]+1)%len(banks)
  while blocks > 0:
    banks[target] = banks[target]+1
    print(banks)
    print(states)
    target = (target+1)%len(banks)
    blocks -= 1
  cycles += 1
  if(banks in states):
    break
print(cycles)
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Shawn Ramirez
  • 796
  • 1
  • 5
  • 10