0

I am solving Jumping on Clouds question, and I know the algo for solving this problem. But my problem is with the syntax I have just now started my journey with python and to be precise I am stuck on this.

Requirement: I need to make an array of binary integer, plus it should either be 1 or 0 only. For example: [1, 0, 0, 1, 0, 1]

I have tried my level best to achieve this but no luck.

MY Code:

Now what I have done is, to get the binary number of the integer element, and then slice it off by 4 to get the last digit of the binary number. But it doesn't work with every every integer. Since I want the 0 or 1 from the binary number.

c = []
for i in range(0, 6):
  c[i] = int(bin(any_random_number)[4:])

I have also tried of doing this, to check whether the input is 0 or 1, if not do not add it but no luck

Second Attempt:

c = []
for i in range(0, 6):
  data = int(input())
  if(data == 0 or data == 1):
    c[i] = data
  else:
    data = 0
    c[i] = data

Any help would be appreciated. I just want to learn this, and take it to my work. Thanks :)

2
  • 2
    Notice that you can't access c[i] if there is no i'th element in c. Use c.append(data) instead. Commented Sep 19, 2019 at 6:34
  • Thanks, I was doing it in a wrong way. c.append() works. Commented Sep 19, 2019 at 6:38

1 Answer 1

3

If you just want a random array of 0s and 1s you can use the random module

[random.choice([1,0]) for _ in range(0,6) ]

This will output a random array of 0s and 1s

As your second attempt getting the user input you need to use the append method.

c = []
for i in range(0, 6):
  data = int(input())
  if(data == 0 or data == 1):
    c.append(data)
  else:
    c.append(0)
Sign up to request clarification or add additional context in comments.

1 Comment

No I want to take the input from the user only.

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.