1

I have a problem with correct initialization within a list

import random

a = [random.randint(0,1) for x in range(10)] # getting random 0 and 1

b = a[:] # copying 'a' list for purpose of analysis 

for x,y in enumerate(b): # adding + 1 where value is 1
    if y != 0:
        b[x] += b[x-1]



print(a) # > [1, 0, 0, 1, 1, 1, 0, 0, 1, 1]  
print(b) # > [2, 0, 0, 1, 2, 3, 0, 0, 1, 2]
# wanted # > [1, 0, 0, 1, 2, 3, 0, 0, 1, 2]

from a[1:] everything is ok. Python does correct initialization, however if a[0] == 1 and a[9] == 1, Python ofcourse takes a[9] as a start value in my case.

I am just asking if there is any pythonic way to solve this > explaining python to just start initialization from 0 at a[0] and passing a[9] as first value.

Thanks

6
  • I'm not sure exactly what you're asking. Your code produces the output I would expect it to, and I think it lines up with your explanation of what you want. Could you clarify what exactly is wrong, and provide what you expect the output to be? Commented Jun 16, 2016 at 17:52
  • Please check the code again. I added the wanted result. Commented Jun 16, 2016 at 17:54
  • 4
    Change the if condition to - if y!=0 and x!=0 Commented Jun 16, 2016 at 17:54
  • :D Great solution thank you. Commented Jun 16, 2016 at 17:56
  • I like hashcode55's solution. The problem is that b[0-1] references the last item in the list, which could be a 1. Commented Jun 16, 2016 at 17:57

1 Answer 1

2

You can skip the first value rather easily:

for x,y in enumerate(b[1:]): # adding + 1 where value is 1
    if y != 0:
        b[x + 1] += b[x]

b[1:] just skips the first value from the list for the enumeration. This way the first number is untouched. But because the indexes in x are now all one too low, we have to add one in both cases, turning x into x + 1 and x - 1 into x. This way we access the right index.

Using your test list, it produced the following output:

[1, 0, 0, 1, 1, 1, 0, 0, 1, 1]  # original list
[1, 0, 0, 1, 2, 3, 0, 0, 1, 2]  # processed list
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.