简体   繁体   English

获取二进制 integer 作为 python 中的输入

[英]Get binary integer as input in python

I am solving Jumping on Clouds question, and I know the algo for solving this problem .我正在解决Jumping on Clouds问题,并且我知道解决此问题的算法 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. But my problem is with the syntax ,准确地说,我被困在这个问题上。

Requirement: I need to make an array of binary integer, plus it should either be 1 or 0 only.要求:我需要创建一个二进制 integer 数组,而且它应该是 1 或 0。 For example: [1, 0, 0, 1, 0, 1]例如: [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.现在我所做的是,获取 integer 元素的二进制数,然后将其切成 4 以获得二进制数的最后一位。 But it doesn't work with every every integer.但它不适用于每一个 integer。 Since I want the 0 or 1 from the binary number.因为我想要二进制数中的 0 或 1。

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我也尝试过这样做, to check whether the input is 0 or 1, if not do not add it但没有运气

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:)谢谢:)

If you just want a random array of 0s and 1s you can use the random module如果你只想要一个 0 和 1 的随机数组,你可以使用 random 模块

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

This will output a random array of 0s and 1s这将 output 0 和 1 的随机数组

As your second attempt getting the user input you need to use the append method.作为您第二次尝试获取用户输入,您需要使用 append 方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM