简体   繁体   中英

How do you print the output this [6,4,2,0] in a single row rather that sequence

I am using the below manual method which happens to find the high bits =1 of the binary value for a given integer.

For eg: when we enter 85, the 6th, 4th, 2nd and 0th bit are high and I am getting the output as 6 4 2 0 in sequence. Actually I need an output like this: [6,4,2,0] . Could any one help me in this ?

def high_bit(num):
    for i in range(0,100):
        if (num/(pow(2,i)))==1: 
            print i
            num = (num - (pow(2,i)))
            y = high_bit(num)
            return y

I find your recursion a bit confusing, but it can work:

def high_bit(num, lst=None):
    if lst == None:
        toplevel = True
        lst = []
    else:
        toplevel = False
    for i in range(0,100):
        if (num/(pow(2,i)))==1: 
            lst.append(i)
            num = (num - (pow(2,i)))
            high_bit(num, lst)
    if toplevel:
        print lst

high_bit(85) # prints [6, 4, 2, 0]

I would recommend doing it iteratively, though.

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