【问题标题】:maximum number of consecutive 's in the binary for a given wrong给定错误的二进制文件中连续的最大数量
【发布时间】:2017-07-01 14:45:22
【问题描述】:

我的代码有什么问题

import sys

x=0
y=[]
n = bin(int(input()))
for i in n:
    if i == 1:
        x +=1
    else:
        y.append(x)
        x=0
y.append(x)
print(max(y))

输出

5
0b101    
0

预期输出

5
0b101
1

(给定十进制的二进制连续一个)

【问题讨论】:

  • 目前输入了什么?
  • 连续的 1 是什么意思

标签: python python-3.x binary decimal


【解决方案1】:
>>> '1' == 1
False

你正在迭代一个字符串,所以元素是一个字符的字符串。

>>> list(bin(5))
['0', 'b', '1', '0', '1']

【讨论】:

    【解决方案2】:

    您可以使用groupby1s 打包在一起。

    正如@joshlee 提到的,您需要检查字符串是否相等:

    from itertools import groupby
    
    n = bin(int(input()))
    
    print(n)
    print(max([len(list(bits)) for bit, bits in groupby(n[2:]) if bit == '1']))
    

    5

    5
    0b101
    1
    

    还有31

    31
    0b11111
    5
    

    这一次,groupby 在分组之前不排序是一个优势。对于13

    13
    0b1101
    2
    

    结果应该是2,而不是3"1"s 的总数)

    【讨论】:

      【解决方案3】:

      试试这个

      import sys
      
      
      n = int(input().strip())
      bin_n = "{0:b}".format(n)
      
      count = 0
      count_l = []
      for each in bin_n:
          if each == '1':
              count+=1
          else:
              count_l.append(count)
              count = 0
      
      print(max(count_l))
      

      【讨论】:

        【解决方案4】:
        binary_string = str(bin(int(input())))[2:]
        print(max(list(map(len, binary_string.split('0')))))
        

        【讨论】:

          【解决方案5】:
          import sys
            n = int(input())
              binary = bin(n)[2:]
          
              count = 0
              count_no=[]
              for num in binary:
                  if num=='1':
                      count += 1
                  else:
                      count_no.append(count)
                      count = 0 
              count_no.append(count)
              print(max(count_no))
          

          【讨论】:

            猜你喜欢
            • 2019-01-28
            • 2020-07-19
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-11-07
            • 1970-01-01
            • 2013-04-07
            • 1970-01-01
            相关资源
            最近更新 更多