简体   繁体   English

我计算最大二进制间隙的函数不起作用,但我不知道为什么

[英]My Function To Count The Largest Binary Gap Doesn't Work But I Can't Figure Out Why

I'm working through the Codility problems and I have gotten the first one almost correct.我正在解决 Codility 问题,我得到的第一个问题几乎是正确的。 The task is to write a function which returns the longest binary gap (a sequence of 0s in between 1s) in a binary number.任务是编写一个函数,它返回二进制数中最长的二进制间隙(1 之间的 0 序列)。 I have gotten all of the test numbers correct apart from 9, which should be 2 (its binary representation is 1001) but which my function returns as 0. I can't seem to figure out why.除了 9 之外,我得到的所有测试数字都是正确的,它应该是 2(它的二进制表示为 1001),但我的函数返回为 0。我似乎无法弄清楚为什么。

My function is as follows:我的功能如下:

def Solution(N):
  x = bin(N)[2:]
  x_string = str(x)
  y = (len(x_string))
  count = 0
  max = 0
  for index, item in enumerate(x_string):
      if item == "1":
          count = 0
      elif item == "0" and x_string[index + 1:y-1] != "0"*(y -1 - (index + 1)):
          count = count + 1
          if count > max:
              max = count
  print(max)

The complicated indexing and second condition in the elif statement is so that when a 0 is not contained between two 1s then it isn't recognised as the beginning of a binary gap eg when the for loop looks at the second character in bin(16) = 10000, it doesn't set count to 1 because all of the remaining characters in the string are also zero. elif 语句中的复杂索引和第二个条件是,当两个 1 之间不包含 0 时,它不会被识别为二​​进制间隙的开始,例如当 for 循环查看 bin(16) 中的第二个字符时= 10000,它不会将计数设置为 1,因为字符串中所有剩余的字符也都为零。

Simple solution简单的解决方案

x_string[index + 1:y-1] != "0"

this bit wants to take a look at the whole string that's left, but the end argument isn't inclusive,it's exluded, so if string length = 4;这一点想看看剩下的整个字符串,但结束参数不包含在内,它被排除在外,所以如果字符串长度= 4; string[0:4] is the whole string. string[0:4] 是整个字符串。

source: https://docs.python.org/3/tutorial/introduction.html来源: https ://docs.python.org/3/tutorial/introduction.html

-Sam -山姆

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

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