subject

Programming question: Given a number, eg. 8, try to calculate and output a list/array of
that in each number's binary form - how many '1' in each number? (should not use string. count('1') in the Python. Efficiency is most important!)
Example: number is 8.
Expected output is - [0, 1, 1, 2, 1, 2, 2, 3, 1]
See some good code snippet (listed below), but not quite understand it? Can you help explain?
```code:
from typing import List

def countBits(num: int) -> List[int]:
""" count all numbers: from 0 to num (eg. 8)
-each number's binary bit in '1':

>>> countBits(8)
[0, 1, 1, 2, 1, 2, 2, 3, 1]
"""
def countBits(num: int) -> List[int]:
res = [0]
while len(res) <= num:
for i in res[:num+1 - len(res)]: # :8 - 7- 6 -5 1
res += [i + 1]
return res

ansver
Answers: 2

Other questions on the subject: Computers and Technology

image
Computers and Technology, 23.06.2019 16:50, lukeakalucas
15: 28read the summary of "an indian's view of indian affairs."15 betterin "an indian's view of indian affairs," it is asserted that conflicts could be reduced if white americansunderstood native americans..pswhich of the following would make this summary more complete? eleo the fact that chief joseph believes the great spirit sees everythinthe fact that chief joseph was born in oregon and is thirty-eight years oldo the fact that chief joseph states that he speaks from the hearthehehethe fact that chief joseph of the nez percé tribe made this claimebell- ==feetle===-felsefe ==submitmark this and retum.=
Answers: 3
image
Computers and Technology, 24.06.2019 15:30, taylorpayne525p8qxky
What is not a type of text format that will automatically be converted by outlook into a hyperlink?
Answers: 1
image
Computers and Technology, 24.06.2019 17:00, yobanajk
Aman travel 200m towards east< br /> from his house then takes left< br /> to turn and moves 200 m north< br /> find the displacement & distance.< br />
Answers: 3
image
Computers and Technology, 24.06.2019 17:30, mariahdelossantos031
Which computer network component connects two different networks together and allows them to communicate? a is a node (or a device) that connects two different networks together and allows them to communicate.
Answers: 2
You know the right answer?
Programming question: Given a number, eg. 8, try to calculate and output a list/array of
that...

Questions in other subjects:

Konu
Mathematics, 29.08.2020 01:01