Use the Built-In Bit-Count Functionality

Яйця Еліуда
Яйця Еліуда у треку Python
Caution

This approach does not follow the instructions, as it uses the bit-count functionality from the standard library. It is only described here to show what an idiomatic way of counting bits in a different context would be.

def egg_count(display_value):
    return display_value.bit_count()

This approach uses int.bit_count() from the Python standard library to count the number of ones in the binary representation of display_value.

This works because Python does not have separate types for binary, octal, or hexadecimal numbers. Instead, all of these are considered representations or display formats of int. Even if a binary literal is declared with the 0b prefix, Python stores it internally as type int:

>>> 0b110101 # <- 53 in binary
53
>>> type(0b110101)
<class 'int'>

>>> 0o65 # <- 53 in octal
53
>>> type(0o65)
<class 'int'>

Due to this, all methods that work with binary numbers in the standard library actually operate on ints.

Variation #1: Using str.count()

def egg_count(display_value):
    return bin(display_value).count("1")

This variant uses bin() (or any other method discussed in the convert to a binary string approach) to convert display_value to a binary string. Then, str.count() is used to count how many times "1" appears in the string.

Though one could argue that this technically doesn't use the built-in bit-count functionality, the solution still defeats the purpose of the exercise.

Variation #2: Using Function Aliasing

egg_count = int.bit_count

This solution is the shortest of them all, but it can also be rather confusing (and it does not follow the instructions). It also can throw what appears to be an unrelated error:

>>> egg_count(3.5)
Traceback (most recent call last):
  File "<python-input-77>", line 1, in <module>
    egg_count(3.5)
    ~~~~~~~~~^^^^^
TypeError: descriptor 'bit_count' for 'int' objects doesn't apply to a 'float' object

This variant makes clever use of function/method aliasing, which creates a new name that refers to the existing int.bit_count() method. This means that when egg_count(display_value) is called, int.bit_count(display_value) is being used. However, you should be careful when using function aliasing, as it often makes code less readable (as with the error shown above), and it doesn't have many practical applications outside of backward compatibility.

This solution works because int.bit_count(<integer_variable>) is just another way of saying <integer_variable>.bit_count(), as instance methods of a class (the class here being int) have self implicitly passed as the first argument when called on an instance (but not when called directly on the class!). See the Classes Concept in the Syllabus or the Official Python Classes Tutorial for more detail on how self works.

23 Вересня 2026 · Це було корисно?