简体   繁体   中英

how to count consecutive number of ones given a decimal number?

def decToBin(n):
    x=str(bin(n))
    x=x[2:]
    return x

def result(x):
    print(len(max(x.split('0'))))
    

if __name__ == '__main__':
    n = int(input().strip())
    decToBin(n)
    result(x)

I have tried this code but i am getting an error saying undefined "x" I want to know what is wrong in this code.

There are several issues in your code.

  1. You aren't returning anything from decToBin function, you should put this at the end of the function: return x
  2. You aren't storing the result of decToBin function anywhere, you can either store it in a variable or put decToBin directly in the result function like this: result(decToBin(n))
  3. Your code is not formatted according to PEP8 in some places, I highly recommend you to read it and use it as it should be always used when programming in Python

I'm also not sure if this is what you wanted to do according to your question title

Here is the final code:

def decToBin(n):
    x = str(bin(n))
    x = x[2:]
    return x


def result(x):
    print(len(max(x.split('0'))))


if __name__ == '__main__':
    n = int(input().strip())
    result(decToBin(n))

The problem is that the value x is defined in your method decToBin , but never returned. So it is only valid inside of that method.

def decToBin(n):
    x=str(bin(n))
    x=x[2:]
    return x

def result(x):
    print(len(max(x.split('0'))))
    

if __name__ == '__main__':
    n = int(input().strip())
    x = decToBin(n)
    result(x)

EDIT: But your code is not counting the ones in a decimal number, but in the binary representation of the number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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