to change value from 0 to 1 in a list of zeroes

Question:

n and k are user inputs, L is a list of zeroes.
if k is even, change the value to 1 of even indexes.
if k is odd, change the value to 1 of odd indexes.

but the output is just ones

[‘1′,’1′,’1′,’1’]

can someone please guide me?

n=int(input())
k=int(input())

L=[0]*n
   for i in range(len(L)):
      if(k%2==0):
         L[i]='1'

      elif(k%2!=0):
         L[i]='1'


print(L)
Asked By: Gray

||

Answers:

You’re current for loop modifies every item, you need to add a test to see if you’;re looking at an odd or even item in the list:

n=int(input())
k=int(input())

L=[0]*n
for i in range(len(L)):
    if k % 2 == 0 and i % 2 == 0:
        L[i] = 1
    elif k % 2 != 0 and i % 2 != 0:
        L[i] = 1


print(L)
Answered By: RoadieRich

well any number should be either even or odd
and the user enter the value of k once

here you change the value to one in case the number is even

if(k%2==0):
     L[i]='1'

here you change the value to one in case the number is odd

if(k%2!=0):
     L[i]='1'

in either cases you change the value to one and accordingly the output is obvious to be ones => ['1','1','1', ...]

I am not sure what you want to do but I can see two problems
first: the value of k is constant across the whole loop (probably you should use i instead of k)
second: you may change L[i]='1' to L[i]='0' in any of the two conditions

Answered By: Mahmoud Noor

Your current logic reads like this: If k is odd, set the item to 1; if it is even, do the same. You do not consider the even- or odd-ness of the index at all. Instead, compare the even-ness of k to that of the index i:

for i in range(len(L)):
    if k % 2 == i % 2:
        L[i] = '1'

Or, use range with (start, stop, step) parameters to only iterate the even or odd indices in the first place:

for i in range(k % 2, len(L), 2):
    L[i] = '1'

Also, your original list has the int value 0, and you are replacing those with the str value '1'. You probably use int consistently, i.e. L[i] = 1

In this case, you can also use a list comprehension:

L = [int(i % 2 == k % 2) for i in range(n)]
Answered By: tobias_k

In your logic, whether the value is even or odd, you are doing the same process at both steps. You should consider whether the index is odd or even in your logic.

to do this, modify your if statements to incorporate the index:

 for i in range(len(L)):
  if(k % 2 == 0 and i % 2 == 0):
     L[i]= 1

  elif(k % 2 != 0 and i % 2 != 0):
     L[i]= 1

This checks to ensure that not only the value you’re concerned with is even or odd, but if their index value is as well.

Answered By: Mike
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.