2

I'm doing some practice problems and one program is asking me to change numbers in the list to 99, only if the number previously is even. I'm running into the trouble that when I change the number to 99, when it moves on the the next number, it checks to see if 99 is even, which I don't want, I want it to check the original value I had there, not what I changed it to .

d = [9, 8, 2, 15, 6, 33, 10, 4]
i = 1
while i < len(d) - 1 :
    if d[i-1]%2 == 0 :
        d[i] = 99
    i = i + 1

print d

returns [9, 8, 99, 15, 6, 99, 10, 4]

I want it to return [9,8,99,99,6,99,10,99]

How would I add 99 into the original list without changing its original value if that makes any sense? List methods like pop or insert can not be used.

cfi
  • 10,915
  • 8
  • 57
  • 103
Zach Santiago
  • 381
  • 7
  • 18
  • 1
    Be very careful about your wording (I understand English might not be your first language). You said `"if the number previously is even`". I think you mean "if *the previous number* was even". There's a big difference. – Jonathon Reinhart Oct 23 '13 at 07:19
  • Shouldnt the output be `[9, 8, 99, 15, 6, 99, 10, 99]`? – thefourtheye Oct 23 '13 at 07:20
  • and how would i do the "was" part in python. do i make like a temporary values assigned to the previous value or something? – Zach Santiago Oct 23 '13 at 07:22
  • and no because 2 was even, so 15 should be changed to 99 – Zach Santiago Oct 23 '13 at 07:23
  • possible duplicate of [Unexpected IndexError while removing list items](http://stackoverflow.com/questions/19312021/unexpected-indexerror-while-removing-list-items) – aIKid Oct 23 '13 at 07:50

4 Answers4

5

Try this.

d = [9, 8, 2, 15, 6, 33, 10, 4]
for i in reversed(xrange(1, len(d))):
  d[i] = 99 if d[i - 1] % 2 == 0 else d[i]
moofins
  • 150
  • 2
  • 4
4

I would advice to iterate descending:

d = [9, 8, 2, 15, 6, 33, 10, 4]
for x in xrange(len(d)-1, 0, -1):
    if d[x - 1] % 2 == 0:
        d[x] = 99
print d

In this case next iteration will operate not changed values.

Or You can create new list

or You can add variable for previous value and use it in if statement

d = [9, 8, 2, 15, 6, 33, 10, 4]
previous = d[0]
for i, x in enumerate(d[1:]):
    if previous % 2 == 0 :
        previous = d[i]
        d[i] = 99
    else:
        previous = d[i]

print d
oleg
  • 4,082
  • 16
  • 16
0

search the list backwards

  1. see last and before last value (n-1, n-2)
  2. change the last value if needed
  3. move to previous values (n-2,n-3)
  4. repeat until whole list is updated
Spektre
  • 49,595
  • 11
  • 110
  • 380
0

Try this:

d = [9, 8, 2, 15, 6, 33, 10, 4]

prev=d[0]
for i,j in enumerate(d):
        if prev%2==0:
                prev=j
                d[i]=99
        else:
                prev=j

print d
Darknight
  • 1,132
  • 2
  • 13
  • 31