From c937152a6b9641797c4becda319a56e3f25ec47b Mon Sep 17 00:00:00 2001 From: Yrahcaz7 <74512479+Yrahcaz7@users.noreply.github.com> Date: Wed, 3 Jun 2026 18:18:01 -0400 Subject: [PATCH 01/17] add first approach --- .../eliuds-eggs/.approaches/config.json | 15 ++++ .../eliuds-eggs/.approaches/introduction.md | 46 +++++++++++ .../parameter-modification/content.md | 80 +++++++++++++++++++ .../parameter-modification/snippet.txt | 6 ++ 4 files changed, 147 insertions(+) create mode 100644 exercises/practice/eliuds-eggs/.approaches/config.json create mode 100644 exercises/practice/eliuds-eggs/.approaches/introduction.md create mode 100644 exercises/practice/eliuds-eggs/.approaches/parameter-modification/content.md create mode 100644 exercises/practice/eliuds-eggs/.approaches/parameter-modification/snippet.txt diff --git a/exercises/practice/eliuds-eggs/.approaches/config.json b/exercises/practice/eliuds-eggs/.approaches/config.json new file mode 100644 index 00000000000..36d652d6973 --- /dev/null +++ b/exercises/practice/eliuds-eggs/.approaches/config.json @@ -0,0 +1,15 @@ +{ + "introduction": { + "authors": ["yrahcaz7"], + "contributors": [] + }, + "approaches": [ + { + "uuid": "27fb20ed-a4c2-4f73-a8fc-86ba384c7b35", + "slug": "parameter-modification", + "title": "Modify the Parameter in a Loop", + "blurb": "Modify the Parameter in a while-loop to Calculate the Number of Eggs.", + "authors": ["yrahcaz7"] + } + ] +} diff --git a/exercises/practice/eliuds-eggs/.approaches/introduction.md b/exercises/practice/eliuds-eggs/.approaches/introduction.md new file mode 100644 index 00000000000..101f76bcf0d --- /dev/null +++ b/exercises/practice/eliuds-eggs/.approaches/introduction.md @@ -0,0 +1,46 @@ +# Introduction + +There are many Pythonic approaches to solving the Eliud's Eggs exercise: + +- Using a `while-loop`, modifying the parameter on each iteration +- Looping over every binary digit _without_ modifying the parameter +- Converting the `int` to a binary string and counting the ones + +There are also some approaches that aren't recommended: + +- Using the bit-count functionality from the Python standard library, as the instructions forbid it +- Breaking up the proccess into many functions, overcomplicating the solution + + +## General guidance + +The goal of the Eliud's Eggs exercise is to count the number of ones in the binary representation of a number. +In essence, this requires you to loop over each bit (binary digit) of the number in some way. + +The approaches below represent categories of the most common ways of accomplishing this. + + +## Approach: Modifying the Parameter in a `while-loop` + +```python +def egg_count(display_value): + eggs = 0 + while display_value: + eggs += display_value % 2 + display_value //= 2 + return eggs +``` + +This approach uses a `while-loop` to count up all of the ones. +In the loop, we increment `eggs` by `display_value % 2`. +This adds the least significant bit (the rightmost digit in the binary representation) of `display_value` to `eggs`. + +Next, we divide `display_value` by `2`, discarding any remainder. +This essentially removes the least significant bit of `display_value`, setting up `display_value` for processing the next bit. + +The loop repeats until `display_value` reaches `0` (which indicates that we have no more bits to check), and then we return `eggs`. + +To see more variants of this solution, see the [modify the parameter in a loop][parameter-modification] approach. + + +[parameter-modification]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/parameter-modification diff --git a/exercises/practice/eliuds-eggs/.approaches/parameter-modification/content.md b/exercises/practice/eliuds-eggs/.approaches/parameter-modification/content.md new file mode 100644 index 00000000000..5e63df050e4 --- /dev/null +++ b/exercises/practice/eliuds-eggs/.approaches/parameter-modification/content.md @@ -0,0 +1,80 @@ +# Modify the Parameter in a Loop + +```python +def egg_count(display_value): + eggs = 0 + while display_value: + eggs += display_value % 2 + display_value //= 2 + return eggs +``` + +This approach uses a `while-loop` to count up all of the ones. +In the loop, we increment `eggs` by `display_value % 2`. +This adds the least significant bit (the rightmost digit in the binary representation) of `display_value` to `eggs`. + +Next, we divide `display_value` by `2`, discarding any remainder. +This essentially removes the least significant bit of `display_value`, setting up `display_value` for processing the next bit. + +The loop repeats until `display_value` reaches `0` (which indicates that we have no more bits to check), and then we return `eggs`. + + +## Variation #1: Using Boolean Operators + +```python +def egg_count(display_value): + eggs = 0 + while display_value > 0: + if display_value % 2 == 1: + eggs += 1 + display_value //= 2 + return eggs +``` + +This is essentially just a more verbose formulation of the previous version. +Instead of relying on Python converting `int`s to `bool`s, this solution manually compares `display_value` to `0`. +It also uses an `if` statement to check if `eggs` should be incremented by `1`, instead of directly using the result of `display_value % 2`. + +Even though this variant is more verbose, some may consider it to be more readable. + + +## Variation #2: Using Bitwise Operators + +```python +def egg_count(display_value): + eggs = 0 + while display_value > 0: + eggs += display_value & 1 + display_value >>= 1 + return eggs +``` + +This variant replaces the modulo (`%`) and floor division (`//`) with [bitwise operators][bitwise-operators]. +`&` is the bitwise AND operator, which results in a number whose binary representation only has ones where _both_ of its arguments has ones. +(All other bits are zeros.) + +For example, if we used the numbers `3` (`11` in binary) and `1` (`1` in binary), we get `1`: + +```python +0b011 & 0b001 +#=> 0b001 +``` + +This is because the only bit in both numbers that is `1` is least significant bit. +This property lets us extract the least significant bit of `display_value` by using `display_value & 1`. + +For the next step, we use `>>`, the [right-shift operator][right-shift-operator]. +The expression `a >> b` shifts all of `a`'s bits to the right by `b` places, and returns the resulting number. + +For example, if we used the numbers `5` (`101` in binary) and `1`, we get `2` (`10` in binary): + +```python +0b101 >> 1 +#=> 0b010 +``` + +You can see how `& 1` and `>>= 1` perform the same function as the `% 2` and `//= 2` used in earier variants. + + +[bitwise-operators]: https://www.w3schools.com/programming/prog_operators_bitwise.php +[right-shift-operator]: https://www.geeksforgeeks.org/software-engineering/right-shift-operator-in-programming/ diff --git a/exercises/practice/eliuds-eggs/.approaches/parameter-modification/snippet.txt b/exercises/practice/eliuds-eggs/.approaches/parameter-modification/snippet.txt new file mode 100644 index 00000000000..c3d5eeb7bf4 --- /dev/null +++ b/exercises/practice/eliuds-eggs/.approaches/parameter-modification/snippet.txt @@ -0,0 +1,6 @@ +def egg_count(display_value): + eggs = 0 + while display_value: + eggs += display_value % 2 + display_value //= 2 + return eggs \ No newline at end of file From 68179f77f24f023e00d24b4c89ec4fa8d470f9b8 Mon Sep 17 00:00:00 2001 From: Yrahcaz7 <74512479+Yrahcaz7@users.noreply.github.com> Date: Wed, 3 Jun 2026 21:02:18 -0400 Subject: [PATCH 02/17] add second approach --- .../eliuds-eggs/.approaches/config.json | 9 +- .../eliuds-eggs/.approaches/introduction.md | 30 +++++- .../no-parameter-modification/content.md | 91 +++++++++++++++++++ .../no-parameter-modification/snippet.txt | 7 ++ .../parameter-modification/content.md | 2 +- 5 files changed, 135 insertions(+), 4 deletions(-) create mode 100644 exercises/practice/eliuds-eggs/.approaches/no-parameter-modification/content.md create mode 100644 exercises/practice/eliuds-eggs/.approaches/no-parameter-modification/snippet.txt diff --git a/exercises/practice/eliuds-eggs/.approaches/config.json b/exercises/practice/eliuds-eggs/.approaches/config.json index 36d652d6973..22b9f975c58 100644 --- a/exercises/practice/eliuds-eggs/.approaches/config.json +++ b/exercises/practice/eliuds-eggs/.approaches/config.json @@ -8,7 +8,14 @@ "uuid": "27fb20ed-a4c2-4f73-a8fc-86ba384c7b35", "slug": "parameter-modification", "title": "Modify the Parameter in a Loop", - "blurb": "Modify the Parameter in a while-loop to Calculate the Number of Eggs.", + "blurb": "Modify the parameter in a while-loop to calculate the number of eggs.", + "authors": ["yrahcaz7"] + }, + { + "uuid": "65fd717c-0e50-444b-a4b2-b51862f1f810", + "slug": "no-parameter-modification", + "title": "Loop Without Modifying the Parameter", + "blurb": "Loop over the bits without modifying the parameter to determine the number of eggs.", "authors": ["yrahcaz7"] } ] diff --git a/exercises/practice/eliuds-eggs/.approaches/introduction.md b/exercises/practice/eliuds-eggs/.approaches/introduction.md index 101f76bcf0d..35ddfde82e3 100644 --- a/exercises/practice/eliuds-eggs/.approaches/introduction.md +++ b/exercises/practice/eliuds-eggs/.approaches/introduction.md @@ -40,7 +40,33 @@ This essentially removes the least significant bit of `display_value`, setting u The loop repeats until `display_value` reaches `0` (which indicates that we have no more bits to check), and then we return `eggs`. -To see more variants of this solution, see the [modify the parameter in a loop][parameter-modification] approach. +To see more variations of this solution, see the [modify the parameter in a loop][approach-parameter-modification] approach. -[parameter-modification]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/parameter-modification +## Approach: Looping Without Modifying the Parameter + +```python +from math import ceil, log2 + +def egg_count(display_value): + eggs = 0 + for bit_position in range(ceil(log2(display_value + 1))): + eggs += (display_value >> bit_position) & 1 + return eggs +``` + +This solution uses a `for-loop` with `range()` to iterate over all of the bits in `display_value`. +To determine how many bits `display_value` has, this solution imports `ceil` and `log2` from the `math` module. +It then feeds this number into `range()` to make the `for-loop` iterate over all the `bit_position`s. + +For each `bit_position`, we determine the value of the bit at that position by using the [right-shift operator][right-shift-operator] and the bitwise AND operator. +Once we determine the bit's value, we increment `eggs` by that number. + +After the loop ends, we know that we have checked all of the bits in `display_value`, thus we return `eggs`. + +For more details and variations, read the [loop without modifying the parameter][approach-no-parameter-modification] approach. + + +[approach-parameter-modification]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/parameter-modification +[approach-no-parameter-modification]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/no-parameter-modification +[right-shift-operator]: https://www.geeksforgeeks.org/software-engineering/right-shift-operator-in-programming/ diff --git a/exercises/practice/eliuds-eggs/.approaches/no-parameter-modification/content.md b/exercises/practice/eliuds-eggs/.approaches/no-parameter-modification/content.md new file mode 100644 index 00000000000..a2a93c01b37 --- /dev/null +++ b/exercises/practice/eliuds-eggs/.approaches/no-parameter-modification/content.md @@ -0,0 +1,91 @@ +# Loop Without Modifying the Parameter + +```python +from math import ceil, log2 + +def egg_count(display_value): + eggs = 0 + for bit_position in range(ceil(log2(display_value + 1))): + eggs += (display_value >> bit_position) & 1 + return eggs +``` + +This approach uses a loop with `range()` to iterate over all of the bits in `display_value`. + +To determine how many bits `display_value` has, this solution imports `ceil` and `log2` from the `math` module. +We then calculate the base 2 logarithm of `display_value` (plus 1) and round it up. +(Rounding up is neccessary because `range()` excludes the value of `` from its returned values.) + +Once we have the bit length of `display_value`, we feed this number into `range()` to make the `for-loop` iterate over all of `display_value`'s `bit_position`s. + +For each `bit_position`, we determine the value of the bit at that position by using the [right-shift operator][right-shift-operator] and the bitwise AND operator. +We do this by right-shifting `display_value` by `bit_position`, making the bit at `bit_position` become the least significant bit. +Then we use the bitwise AND operator with `1` to remove all bits that are not the least significant bit. + +~~~~exercism/note +You could also calculate the bit's value by using arithmetic operators instead of bitwise ones: + +```python +eggs += (display_value // (2 ** bit_position)) % 2 +``` +~~~~ + +Once we determine the bit's value, we increment `eggs` by that number. + +After the loop ends, we know that we have checked all of the bits in `display_value`, thus we return `eggs`. + + +## Variation #1: Using an `if` Statement + +```python +from math import ceil, log2 + +def egg_count(display_value): + eggs = 0 + for bit_position in range(ceil(log2(display_value + 1))): + if display_value & (1 << bit_position): + eggs += 1 + return eggs +``` + +In this variant, the loop uses an `if` statement to check if the digit at `display_value` is `1`. + + +## Variation #2: Using `sum()` with a Generator Expression + +```python +from math import ceil, log2 + +def egg_count(display_value): + return sum( + (display_value >> bit_position) & 1 + for bit_position in range(ceil(log2(display_value + 1))) + ) +``` + +This variant is actually a one-liner, it is just split up here for readability. +Here, we replace the `for-loop` with a [generator expression][generator-expression] and use `sum()` to collect the values into the result. + + +## Variation #3: Manually Tracking the Place Value + +```python +def egg_count(display_value): + eggs = 0 + place_value = 1 + while place_value <= display_value: + if display_value & place_value: + eggs += 1 + place_value <<= 1 + return eggs +``` + +This variant avoids `import`s by manually tracking the `place_value` of the current bit position. +This way, the `while-loop` can end when `place_value` becomes greater than `display_value`. + +The operations in the loop are rather similar to the "using an `if` statement" variant. +The main differences are not having to calculate the `place_value` from the bit position, and having to manually progress the iteration by left-shifting `place_value` by `1` (which is the same as multiplying `place_value` by `2`). + + +[generator-expression]: https://dbader.org/blog/python-generator-expressions +[right-shift-operator]: https://www.geeksforgeeks.org/software-engineering/right-shift-operator-in-programming/ diff --git a/exercises/practice/eliuds-eggs/.approaches/no-parameter-modification/snippet.txt b/exercises/practice/eliuds-eggs/.approaches/no-parameter-modification/snippet.txt new file mode 100644 index 00000000000..b2a163f2f28 --- /dev/null +++ b/exercises/practice/eliuds-eggs/.approaches/no-parameter-modification/snippet.txt @@ -0,0 +1,7 @@ +from math import ceil, log2 + +def egg_count(display_value): + eggs = 0 + for bit_position in range(ceil(log2(display_value + 1))): + eggs += (display_value >> bit_position) & 1 + return eggs \ No newline at end of file diff --git a/exercises/practice/eliuds-eggs/.approaches/parameter-modification/content.md b/exercises/practice/eliuds-eggs/.approaches/parameter-modification/content.md index 5e63df050e4..b1765f865d3 100644 --- a/exercises/practice/eliuds-eggs/.approaches/parameter-modification/content.md +++ b/exercises/practice/eliuds-eggs/.approaches/parameter-modification/content.md @@ -35,7 +35,7 @@ This is essentially just a more verbose formulation of the previous version. Instead of relying on Python converting `int`s to `bool`s, this solution manually compares `display_value` to `0`. It also uses an `if` statement to check if `eggs` should be incremented by `1`, instead of directly using the result of `display_value % 2`. -Even though this variant is more verbose, some may consider it to be more readable. +Even though this variant is more verbose than the others, some may consider it to be more readable. ## Variation #2: Using Bitwise Operators From 1679f0b038d07b66808ea62cfe19a24edac40d68 Mon Sep 17 00:00:00 2001 From: Yrahcaz7 <74512479+Yrahcaz7@users.noreply.github.com> Date: Sat, 6 Jun 2026 22:04:03 -0400 Subject: [PATCH 03/17] add third approach --- .../eliuds-eggs/.approaches/config.json | 7 ++ .../convert-to-binary-string/content.md | 111 ++++++++++++++++++ .../convert-to-binary-string/snippet.txt | 6 + .../eliuds-eggs/.approaches/introduction.md | 26 +++- 4 files changed, 149 insertions(+), 1 deletion(-) create mode 100644 exercises/practice/eliuds-eggs/.approaches/convert-to-binary-string/content.md create mode 100644 exercises/practice/eliuds-eggs/.approaches/convert-to-binary-string/snippet.txt diff --git a/exercises/practice/eliuds-eggs/.approaches/config.json b/exercises/practice/eliuds-eggs/.approaches/config.json index 22b9f975c58..eff40e6cf9a 100644 --- a/exercises/practice/eliuds-eggs/.approaches/config.json +++ b/exercises/practice/eliuds-eggs/.approaches/config.json @@ -17,6 +17,13 @@ "title": "Loop Without Modifying the Parameter", "blurb": "Loop over the bits without modifying the parameter to determine the number of eggs.", "authors": ["yrahcaz7"] + }, + { + "uuid": "df202fa9-3757-4808-a416-7ec3ee1e9680", + "slug": "convert-to-binary-string", + "title": "Convert to a Binary String", + "blurb": "Convert the parameter to a binary string and count its ones to determine the number of eggs.", + "authors": ["yrahcaz7"] } ] } diff --git a/exercises/practice/eliuds-eggs/.approaches/convert-to-binary-string/content.md b/exercises/practice/eliuds-eggs/.approaches/convert-to-binary-string/content.md new file mode 100644 index 00000000000..854a6e097c3 --- /dev/null +++ b/exercises/practice/eliuds-eggs/.approaches/convert-to-binary-string/content.md @@ -0,0 +1,111 @@ +# Convert to a Binary String + +```python +def egg_count(display_value): + binary_value = bin(display_value)[2:] + eggs = 0 + for digit in binary_value: + eggs += int(digit) + return eggs +``` + +This approach uses [`bin()`][bin-built-in] to convert `display_value` to a binary string. +Then, the first two characters of the binary string are removed, as the string has "0b" prefixed before the binary digits. + +After the binary digits are obtained, this solution loops across all of them, turning each one into an integer and adding it to `eggs`. +This effectively counts up all of the instances of "1" in the binary string, as 0 and 1 are the only valid binary digits. + +Those less familiar with binary may find this approach to be simpler than the others. +However, it does have the added overhead of converting to and from a string. + +~~~~exercism/note +There are three other Pythonic ways of obtaining the binary string. One is to use an [`f-string`][f-string]: + +```python +binary_value = f"{display_value:b}" +``` + +Another is to use [`str.format()`][str-format]: + +```python +binary_value = "{:b}".format(display_value) +``` + +Lastly, you could use the [`format()` built-in][format-built-in]: + +```python +binary_value = format(display_value, "b") +``` + +These methods have the added benefit of not producing the "0b" prefix that then needs to removed. +However, some variations of this approach use other ways to get around the prefix. + +[format-built-in]: https://docs.python.org/3/library/functions.html#format +[f-string]: https://docs.python.org/3/reference/lexical_analysis.html#f-strings +[str-format]: https://docs.python.org/3/library/stdtypes.html#str.format +~~~~ + + +## Variation #1: Using `sum()` with a Generator Expression + +```python +def egg_count(display_value): + return sum(int(digit) for digit in bin(display_value)[2:]) +``` + +This variant uses a [generator expression][generator-expression] with the `sum()` built-in to collect the digits into the result. +Otherwise, it is the same as the previous version. + + +## Variation #2: Using `sum()` Without String Slicing + +```python +def egg_count(display_value): + return sum(1 for digit in bin(display_value) if digit == "1") +``` + +Similar to the previous variant, this one uses `sum()` with a generator expression. +The main difference is that it avoids slicing the binary string by using an `if` clause in the generator expression. + + +## Variation #3: Using `len()` Instead of `sum()` + +```python +def egg_count(display_value): + return len([True for digit in bin(display_value) if digit == "1"]) +``` + +This variant replaces the generator expression with a [list comprehension][list-comprehension]. +This way, it can simply use `len()` to get the number of ones, after the comprehension filters the other digits out. + +Here, `True` is used for the list elements, but we could any other value as well, as we only care about the length of the list. + + +## Variation #4: Using `map()` Instead of a Generator Expression + +```python +def egg_count(display_value): + return sum(map(int, bin(display_value)[2:])) +``` + +Here, we directly `map` the elements of the binary string to `int`s without using a generator expression or a list comprehension. + +This variant is the most concise of them all, but it may be not very comprehensible to those unfamilar with functional programming. + + +## Variation #5: Using `filter()` with a `lambda` + +```python +def egg_count(display_value): + return len(list(filter(lambda digit: digit == "1", bin(display_value)))) +``` + +Another alternative to a generator expression (or list comprehension) is to use the `filter()` built-in along with a [`lambda` expression][lambda-expression]. +However, the creation and repeated calling of the `lambda` adds unnecessary overhead to the solution. + + +[bin-built-in]: https://docs.python.org/3/library/functions.html#bin +[f-string]: https://docs.python.org/3/reference/lexical_analysis.html#f-strings +[generator-expression]: https://dbader.org/blog/python-generator-expressions +[lambda-expression]: https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions +[list-comprehension]: https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions diff --git a/exercises/practice/eliuds-eggs/.approaches/convert-to-binary-string/snippet.txt b/exercises/practice/eliuds-eggs/.approaches/convert-to-binary-string/snippet.txt new file mode 100644 index 00000000000..01d46f1baea --- /dev/null +++ b/exercises/practice/eliuds-eggs/.approaches/convert-to-binary-string/snippet.txt @@ -0,0 +1,6 @@ +def egg_count(display_value): + binary_value = bin(display_value)[2:] + eggs = 0 + for digit in binary_value: + eggs += int(digit) + return eggs \ No newline at end of file diff --git a/exercises/practice/eliuds-eggs/.approaches/introduction.md b/exercises/practice/eliuds-eggs/.approaches/introduction.md index 35ddfde82e3..2b490a0b69b 100644 --- a/exercises/practice/eliuds-eggs/.approaches/introduction.md +++ b/exercises/practice/eliuds-eggs/.approaches/introduction.md @@ -1,6 +1,6 @@ # Introduction -There are many Pythonic approaches to solving the Eliud's Eggs exercise: +There are many different approaches to solving the Eliud's Eggs exercise: - Using a `while-loop`, modifying the parameter on each iteration - Looping over every binary digit _without_ modifying the parameter @@ -67,6 +67,30 @@ After the loop ends, we know that we have checked all of the bits in `display_va For more details and variations, read the [loop without modifying the parameter][approach-no-parameter-modification] approach. +## Approach: Converting the Parameter to a Binary String + +```python +def egg_count(display_value): + binary_value = bin(display_value)[2:] + eggs = 0 + for digit in binary_value: + eggs += int(digit) + return eggs +``` + +This approach uses [`bin()`][bin-built-in] (or some other means, such as an [`f-string`][f-string]) to convert `display_value` to a binary string. +Then, the first two characters of the binary string are removed, as the string has "0b" prefixed before the binary digits. + +After the binary digits are obtained, this solution loops across all of them, turning each one into an integer and adding it to `eggs`. +This effectively counts up all of the instances of "1" in the binary string, as 0 and 1 are the only valid binary digits. + +Many variations of this approach use a built-in function like `sum()` to make the iteration more concise. +For more details, check out the [convert to a binary string][approach-convert-to-binary-string] approach. + + [approach-parameter-modification]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/parameter-modification [approach-no-parameter-modification]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/no-parameter-modification +[approach-convert-to-binary-string]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/convert-to-binary-string +[bin-built-in]: https://docs.python.org/3/library/functions.html#bin [right-shift-operator]: https://www.geeksforgeeks.org/software-engineering/right-shift-operator-in-programming/ +[f-string]: https://docs.python.org/3/reference/lexical_analysis.html#f-strings From 0399ea11bfaf7ab6fa6d1f7eb7fcc301678cf58f Mon Sep 17 00:00:00 2001 From: Yrahcaz7 <74512479+Yrahcaz7@users.noreply.github.com> Date: Sat, 6 Jun 2026 22:49:51 -0400 Subject: [PATCH 04/17] add two more variations to the first approach --- .../eliuds-eggs/.approaches/introduction.md | 3 +- .../parameter-modification/content.md | 43 +++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/exercises/practice/eliuds-eggs/.approaches/introduction.md b/exercises/practice/eliuds-eggs/.approaches/introduction.md index 2b490a0b69b..141b10157a4 100644 --- a/exercises/practice/eliuds-eggs/.approaches/introduction.md +++ b/exercises/practice/eliuds-eggs/.approaches/introduction.md @@ -14,7 +14,7 @@ There are also some approaches that aren't recommended: ## General guidance -The goal of the Eliud's Eggs exercise is to count the number of ones in the binary representation of a number. +The goal of the Eliud's Eggs exercise is to count the number of ones in the binary representation of a [number][concept-numbers]. In essence, this requires you to loop over each bit (binary digit) of the number in some way. The approaches below represent categories of the most common ways of accomplishing this. @@ -92,5 +92,6 @@ For more details, check out the [convert to a binary string][approach-convert-to [approach-no-parameter-modification]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/no-parameter-modification [approach-convert-to-binary-string]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/convert-to-binary-string [bin-built-in]: https://docs.python.org/3/library/functions.html#bin +[concept-numbers]: https://exercism.org/tracks/python/concepts/numbers [right-shift-operator]: https://www.geeksforgeeks.org/software-engineering/right-shift-operator-in-programming/ [f-string]: https://docs.python.org/3/reference/lexical_analysis.html#f-strings diff --git a/exercises/practice/eliuds-eggs/.approaches/parameter-modification/content.md b/exercises/practice/eliuds-eggs/.approaches/parameter-modification/content.md index b1765f865d3..444d75efbc7 100644 --- a/exercises/practice/eliuds-eggs/.approaches/parameter-modification/content.md +++ b/exercises/practice/eliuds-eggs/.approaches/parameter-modification/content.md @@ -76,5 +76,48 @@ For example, if we used the numbers `5` (`101` in binary) and `1`, we get `2` (` You can see how `& 1` and `>>= 1` perform the same function as the `% 2` and `//= 2` used in earier variants. +## Variation #3: Using a `list` + +```python +def egg_count(display_value): + egg_positions = [] + + while display_value: + egg_positions.append(display_value % 2) + display_value //= 2 + + return egg_positions.count(1) +``` + +Here, we append the binary digits to a `list` and then count the number of ones using [`list.count()`][sequence-count]. +This solution would make sense if the positions of the eggs mattered, but since we only need the amount here, tracking the positions just adds unecessary overhead. + + +## Variation #4: Using `divmod()` + +```python +def egg_count(display_value): + eggs = 0 + while display_value: + display_value, remainder = divmod(display_value, 2) + eggs += remainder + return eggs +``` + +This variant uses the [`divmod()`][divmod-built-in] built-in instead of `%` and `//`. +(For `int` arguments, `divmod(a, b)` returns a [`tuple`][concept-tuples] of `(a // b, a % b)`.) + +In the loop, we use `divmod(display_value, 2)` to get both the quotient and the remainder of the division. +The `tuple` returned by `divmod()` is [unpacked][concept-unpacking-and-multiple-assignment] into `display_value` and `remainder` using [multiple assignment][concept-unpacking-and-multiple-assignment]. +Then, we increment `eggs` by `remainder`. + +As `display_value` is updated in the multiple assignment expression, we don't need to do anything else inside the loop. +Just like the previous variations, the loop will continue until `display_value` reaches 0, and then we return `eggs`. + + [bitwise-operators]: https://www.w3schools.com/programming/prog_operators_bitwise.php +[concept-tuples]: https://exercism.org/tracks/python/concepts/tuples +[concept-unpacking-and-multiple-assignment]: https://exercism.org/tracks/python/concepts/unpacking-and-multiple-assignment +[divmod-built-in]: https://docs.python.org/3/library/functions.html#divmod [right-shift-operator]: https://www.geeksforgeeks.org/software-engineering/right-shift-operator-in-programming/ +[sequence-count]: https://docs.python.org/3/library/stdtypes.html#sequence.count From a5ce8a24cced3e243f15fbb5fded18dc9bdbf1db Mon Sep 17 00:00:00 2001 From: Yrahcaz7 <74512479+Yrahcaz7@users.noreply.github.com> Date: Sun, 7 Jun 2026 15:01:48 -0400 Subject: [PATCH 05/17] add fourth approach --- .../.approaches/built-in-bit-count/content.md | 54 +++++++++++++++++++ .../built-in-bit-count/snippet.txt | 2 + .../eliuds-eggs/.approaches/config.json | 11 +++- .../convert-to-binary-string/content.md | 1 - .../eliuds-eggs/.approaches/introduction.md | 25 +++++++-- 5 files changed, 87 insertions(+), 6 deletions(-) create mode 100644 exercises/practice/eliuds-eggs/.approaches/built-in-bit-count/content.md create mode 100644 exercises/practice/eliuds-eggs/.approaches/built-in-bit-count/snippet.txt diff --git a/exercises/practice/eliuds-eggs/.approaches/built-in-bit-count/content.md b/exercises/practice/eliuds-eggs/.approaches/built-in-bit-count/content.md new file mode 100644 index 00000000000..941c6c4141e --- /dev/null +++ b/exercises/practice/eliuds-eggs/.approaches/built-in-bit-count/content.md @@ -0,0 +1,54 @@ +# Use the Built-In Bit-Count Functionality + +~~~~exercism/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. +~~~~ + +```python +def egg_count(display_value): + return display_value.bit_count() +``` + +This approach uses [`int.bit_count()`][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. +Even if a binary literal is declared with the `0b` prefix, Python still stores it as an `int`. +Due to this, all of the methods that work with binary numbers in the standard library just operate on `int`s. + + +## Variation #1: Using `str.count()` + +```python +def egg_count(display_value): + return bin(display_value).count("1") +``` + +This variant uses [`bin()`][bin-built-in] (or any other method discussed in the [convert to a binary string][approach-convert-to-binary-string] approach) to convert `display_value` to a binary string. +Then, [`str.count()`][sequence-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 + +```python +egg_count = int.bit_count +``` + +This solution is the shortest of them all, but it can also be rather confusing (and it still does not follow the instructions). + +This variant makes clever use of [function aliasing][function-aliasing], which creates a new name that refers to the same exact function. +However, you should be careful when using function aliasing, as it often makes code _less_ readable, and it doesn't have many practical applications outside of backward compatibility. + +This solution works because `int.bit_count()` is just another way of saying `.bit_count()`, as instance methods of a class have `self` implicitly passed as the first parameter when calling them on an instance (but not when calling them directly on the class). +See the [Classes Concept in the Syllabus][concept-classes: methods] or the [Official Python Classes Tutorial][class-method-objects-tutorial] for more detail on how this works. + + +[approach-convert-to-binary-string]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/convert-to-binary-string +[bin-built-in]: https://docs.python.org/3/library/functions.html#bin +[class-method-objects-tutorial]: https://docs.python.org/3/tutorial/classes.html#method-objects +[concept-classes: methods]: https://exercism.org/tracks/python/concepts/classes#h-methods +[function-aliasing]: https://tutorialreference.com/python/examples/faq/python-how-to-use-function-aliasing +[int-bit_count]: https://docs.python.org/3/library/stdtypes.html#int.bit_count +[sequence-count]: https://docs.python.org/3/library/stdtypes.html#sequence.count diff --git a/exercises/practice/eliuds-eggs/.approaches/built-in-bit-count/snippet.txt b/exercises/practice/eliuds-eggs/.approaches/built-in-bit-count/snippet.txt new file mode 100644 index 00000000000..96be0c4e833 --- /dev/null +++ b/exercises/practice/eliuds-eggs/.approaches/built-in-bit-count/snippet.txt @@ -0,0 +1,2 @@ +def egg_count(display_value): + return display_value.bit_count() \ No newline at end of file diff --git a/exercises/practice/eliuds-eggs/.approaches/config.json b/exercises/practice/eliuds-eggs/.approaches/config.json index eff40e6cf9a..240b5ec6c45 100644 --- a/exercises/practice/eliuds-eggs/.approaches/config.json +++ b/exercises/practice/eliuds-eggs/.approaches/config.json @@ -8,14 +8,14 @@ "uuid": "27fb20ed-a4c2-4f73-a8fc-86ba384c7b35", "slug": "parameter-modification", "title": "Modify the Parameter in a Loop", - "blurb": "Modify the parameter in a while-loop to calculate the number of eggs.", + "blurb": "Modify the parameter in a while-loop to determine the number of eggs.", "authors": ["yrahcaz7"] }, { "uuid": "65fd717c-0e50-444b-a4b2-b51862f1f810", "slug": "no-parameter-modification", "title": "Loop Without Modifying the Parameter", - "blurb": "Loop over the bits without modifying the parameter to determine the number of eggs.", + "blurb": "Loop over the bits without modifying the parameter to calculate the number of eggs.", "authors": ["yrahcaz7"] }, { @@ -24,6 +24,13 @@ "title": "Convert to a Binary String", "blurb": "Convert the parameter to a binary string and count its ones to determine the number of eggs.", "authors": ["yrahcaz7"] + }, + { + "uuid": "97b06094-7ce8-4874-b66a-af7391adc853", + "slug": "built-in-bit-count", + "title": "Use the Built-In Bit-Count Functionality", + "blurb": "Use Python's Built-In Bit-Count Functionality to calculate the number of eggs.", + "authors": ["yrahcaz7"] } ] } diff --git a/exercises/practice/eliuds-eggs/.approaches/convert-to-binary-string/content.md b/exercises/practice/eliuds-eggs/.approaches/convert-to-binary-string/content.md index 854a6e097c3..23f19182a7f 100644 --- a/exercises/practice/eliuds-eggs/.approaches/convert-to-binary-string/content.md +++ b/exercises/practice/eliuds-eggs/.approaches/convert-to-binary-string/content.md @@ -105,7 +105,6 @@ However, the creation and repeated calling of the `lambda` adds unnecessary over [bin-built-in]: https://docs.python.org/3/library/functions.html#bin -[f-string]: https://docs.python.org/3/reference/lexical_analysis.html#f-strings [generator-expression]: https://dbader.org/blog/python-generator-expressions [lambda-expression]: https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions [list-comprehension]: https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions diff --git a/exercises/practice/eliuds-eggs/.approaches/introduction.md b/exercises/practice/eliuds-eggs/.approaches/introduction.md index 141b10157a4..8ffe58e7aaf 100644 --- a/exercises/practice/eliuds-eggs/.approaches/introduction.md +++ b/exercises/practice/eliuds-eggs/.approaches/introduction.md @@ -88,10 +88,29 @@ Many variations of this approach use a built-in function like `sum()` to make th For more details, check out the [convert to a binary string][approach-convert-to-binary-string] approach. -[approach-parameter-modification]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/parameter-modification -[approach-no-parameter-modification]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/no-parameter-modification +## Approach: Using the Built-In Bit-Count Functionality + +~~~~exercism/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. +~~~~ + +```python +def egg_count(display_value): + return display_value.bit_count() +``` + +This approach uses [`int.bit_count()`][int-bit_count] from the Python standard library to count the number of ones in the binary representation of `display_value`. + +For more details and variations, read the [built-in bit-count][approach-built-in-bit-count] approach. + + +[approach-built-in-bit-count]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/built-in-bit-count [approach-convert-to-binary-string]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/convert-to-binary-string +[approach-no-parameter-modification]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/no-parameter-modification +[approach-parameter-modification]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/parameter-modification [bin-built-in]: https://docs.python.org/3/library/functions.html#bin [concept-numbers]: https://exercism.org/tracks/python/concepts/numbers -[right-shift-operator]: https://www.geeksforgeeks.org/software-engineering/right-shift-operator-in-programming/ [f-string]: https://docs.python.org/3/reference/lexical_analysis.html#f-strings +[int-bit_count]: https://docs.python.org/3/library/stdtypes.html#int.bit_count +[right-shift-operator]: https://www.geeksforgeeks.org/software-engineering/right-shift-operator-in-programming/ From e81f8ec565d877b35b21b62096cb5c0d1fd8d5fa Mon Sep 17 00:00:00 2001 From: Yrahcaz7 <74512479+Yrahcaz7@users.noreply.github.com> Date: Tue, 9 Jun 2026 14:45:43 -0400 Subject: [PATCH 06/17] add fifth approach --- .../eliuds-eggs/.approaches/config.json | 9 ++- .../.approaches/helper-functions/content.md | 73 +++++++++++++++++++ .../.approaches/helper-functions/snippet.txt | 8 ++ .../eliuds-eggs/.approaches/introduction.md | 44 ++++++++++- 4 files changed, 131 insertions(+), 3 deletions(-) create mode 100644 exercises/practice/eliuds-eggs/.approaches/helper-functions/content.md create mode 100644 exercises/practice/eliuds-eggs/.approaches/helper-functions/snippet.txt diff --git a/exercises/practice/eliuds-eggs/.approaches/config.json b/exercises/practice/eliuds-eggs/.approaches/config.json index 240b5ec6c45..2cd26165315 100644 --- a/exercises/practice/eliuds-eggs/.approaches/config.json +++ b/exercises/practice/eliuds-eggs/.approaches/config.json @@ -29,7 +29,14 @@ "uuid": "97b06094-7ce8-4874-b66a-af7391adc853", "slug": "built-in-bit-count", "title": "Use the Built-In Bit-Count Functionality", - "blurb": "Use Python's Built-In Bit-Count Functionality to calculate the number of eggs.", + "blurb": "Use Python's built-in bit-count functionality to calculate the number of eggs.", + "authors": ["yrahcaz7"] + }, + { + "uuid": "618491ca-480e-4e32-bf91-4940affb48a8", + "slug": "helper-functions", + "title": "Use Helper Functions", + "blurb": "Split the problem into multiple helper functions to calculate the number of eggs.", "authors": ["yrahcaz7"] } ] diff --git a/exercises/practice/eliuds-eggs/.approaches/helper-functions/content.md b/exercises/practice/eliuds-eggs/.approaches/helper-functions/content.md new file mode 100644 index 00000000000..2b6e0ef4817 --- /dev/null +++ b/exercises/practice/eliuds-eggs/.approaches/helper-functions/content.md @@ -0,0 +1,73 @@ +# Use Helper Functions + +```python +def egg_count(display_value): + return count_ones(convert_to_binary(display_value)) + + +def convert_to_binary(decimal_value): + binary_value = "" + + while decimal_value > 0: + binary_value += str(decimal_value % 2) + decimal_value //= 2 + + return binary_value[::-1] if binary_value else "0" + + +def count_ones(binary_value): + count = 0 + + for digit in binary_value: + count += int(digit) + + return count +``` + +This approach breaks the problem down into multiple helper functions that are called from `egg_count()`. +First, `convert_to_binary()` is used to convert `display_value` to a binary string. +Then, `count_ones()` is called to count the number of ones in that string. + +In this specific version of the approach, `convert_to_binary()` is implemented similarly to the [modify the parameter in a loop][approach-parameter-modification] approach. +The main differences are that the bits are converted to strings and appended together (rather being added together), and that a [ternary expression][ternary-expression] is used to handle the edge case of a `0`. + +~~~~exercism/note +Here, the [`or` operator][boolean-operations-default-or] could be used instead of a ternary expression: + +```python +return binary_value[::-1] or "0" +``` + +Which one to use is mostly a matter of preference and readability. + +[boolean-operations-default-or]: https://docs.python.org/3/reference/expressions.html#boolean-operations:~:text=if%20s%20is%20a%20string%20that%20should%20be%20replaced%20by%20a%20default%20value%20if%20it%20is%20empty,%20the%20expression%20s%20or%20'foo'%20yields%20the%20desired%20value. +~~~~ + +The `count_ones()` helper function is implemented very similarly to the [convert to a binary string][approach-convert-to-binary-string] approach. +The only difference is that it takes the binary string as a parameter, rather than calulating it itself. + +Though breaking the problem up into helper functions may facilitate code reuse, it also adds unnecessary overhead to the solution. +The approach is also complicated by additional edge cases, such as making `convert_to_binary()` return "0" instead of an empty string when given the number `0`. +In fact, the edge case of negative numbers is not handled, and doing so complicates the solution even further: + +```python +def convert_to_binary(decimal_value): + if decimal_value < 0: + return "-" + convert_to_binary(-decimal_value) + + binary_value = "" + + while decimal_value > 0: + binary_value += str(decimal_value % 2) + decimal_value //= 2 + + return binary_value[::-1] or "0" +``` + +Due to this, one may decide to not handle all of the edge cases. +However, if there are any unhandled edge cases, when you (or someone else) tries to reuse the function in the future, they could get incorrect results. + + +[approach-convert-to-binary-string]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/convert-to-binary-string +[approach-parameter-modification]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/parameter-modification +[ternary-expression]: https://docs.python.org/3/reference/expressions.html#conditional-expressions diff --git a/exercises/practice/eliuds-eggs/.approaches/helper-functions/snippet.txt b/exercises/practice/eliuds-eggs/.approaches/helper-functions/snippet.txt new file mode 100644 index 00000000000..70f0af05166 --- /dev/null +++ b/exercises/practice/eliuds-eggs/.approaches/helper-functions/snippet.txt @@ -0,0 +1,8 @@ +def egg_count(display_value): + return count_ones(convert_to_binary(display_value)) + +def convert_to_binary(decimal_value): + ... + +def count_ones(binary_value): + ... \ No newline at end of file diff --git a/exercises/practice/eliuds-eggs/.approaches/introduction.md b/exercises/practice/eliuds-eggs/.approaches/introduction.md index 8ffe58e7aaf..dfa50ff9ba6 100644 --- a/exercises/practice/eliuds-eggs/.approaches/introduction.md +++ b/exercises/practice/eliuds-eggs/.approaches/introduction.md @@ -14,7 +14,7 @@ There are also some approaches that aren't recommended: ## General guidance -The goal of the Eliud's Eggs exercise is to count the number of ones in the binary representation of a [number][concept-numbers]. +The goal of the Eliud's Eggs exercise is to count the number of ones in the [binary representation of a number][concept-numbers]. In essence, this requires you to loop over each bit (binary digit) of the number in some way. The approaches below represent categories of the most common ways of accomplishing this. @@ -100,13 +100,53 @@ def egg_count(display_value): return display_value.bit_count() ``` -This approach uses [`int.bit_count()`][int-bit_count] from the Python standard library to count the number of ones in the binary representation of `display_value`. +This solution uses [`int.bit_count()`][int-bit_count] from the Python standard library to count the number of ones in the binary representation of `display_value`. For more details and variations, read the [built-in bit-count][approach-built-in-bit-count] approach. +## Approach: Using Helper Functions + +```python +def egg_count(display_value): + return count_ones(convert_to_binary(display_value)) + + +def convert_to_binary(decimal_value): + binary_value = "" + + while decimal_value > 0: + binary_value += str(decimal_value % 2) + decimal_value //= 2 + + return binary_value[::-1] if binary_value else "0" + + +def count_ones(binary_value): + count = 0 + + for digit in binary_value: + count += int(digit) + + return count +``` + +This approach breaks the problem down into multiple helper functions that are called from `egg_count()`. +First, `convert_to_binary()` is used to convert `display_value` to a binary string. +Then, `count_ones()` is called to count the number of ones in that string. + +The actual implementations of `convert_to_binary()` and `count_ones()` could use almost any of the techniques mentioned in earlier approaches. + +Though breaking the problem up into helper functions may facilitate code reuse, it also adds unnecessary overhead to the solution. +It can also overcomplicate things, as you may need to consider additional edge cases, such as making `convert_to_binary()` return "0" instead of an empty string when given the number `0`. +If you do not handle all of these cases, when you (or someone else) tries to reuse the function later, they may get unexpected results, such as getting "0" when inputting a negative number. + +For more details, check out the [helper functions][approach-helper-functions] approach. + + [approach-built-in-bit-count]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/built-in-bit-count [approach-convert-to-binary-string]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/convert-to-binary-string +[approach-helper-functions]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/helper-functions [approach-no-parameter-modification]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/no-parameter-modification [approach-parameter-modification]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/parameter-modification [bin-built-in]: https://docs.python.org/3/library/functions.html#bin From 10ddffafa2120f69eaa65acea5f0cd3b5a3bac8b Mon Sep 17 00:00:00 2001 From: Yrahcaz7 <74512479+Yrahcaz7@users.noreply.github.com> Date: Tue, 9 Jun 2026 15:46:33 -0400 Subject: [PATCH 07/17] add another variation to the third approach also add more links to the docs for built-in functions --- .../convert-to-binary-string/content.md | 23 +++++++++++++++++-- .../no-parameter-modification/content.md | 3 ++- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/exercises/practice/eliuds-eggs/.approaches/convert-to-binary-string/content.md b/exercises/practice/eliuds-eggs/.approaches/convert-to-binary-string/content.md index 23f19182a7f..a41eaeab96f 100644 --- a/exercises/practice/eliuds-eggs/.approaches/convert-to-binary-string/content.md +++ b/exercises/practice/eliuds-eggs/.approaches/convert-to-binary-string/content.md @@ -88,7 +88,7 @@ def egg_count(display_value): return sum(map(int, bin(display_value)[2:])) ``` -Here, we directly `map` the elements of the binary string to `int`s without using a generator expression or a list comprehension. +Here, we directly [`map`][map-built-in] the elements of the binary string to `int`s without using a generator expression or a list comprehension. This variant is the most concise of them all, but it may be not very comprehensible to those unfamilar with functional programming. @@ -100,11 +100,30 @@ def egg_count(display_value): return len(list(filter(lambda digit: digit == "1", bin(display_value)))) ``` -Another alternative to a generator expression (or list comprehension) is to use the `filter()` built-in along with a [`lambda` expression][lambda-expression]. +Another alternative to a generator expression (or list comprehension) is to use the [`filter()` built-in][filter-built-in] along with a [`lambda` expression][lambda-expression]. However, the creation and repeated calling of the `lambda` adds unnecessary overhead to the solution. +## Variation #6: Using `functools.reduce()` with a `lambda` + +```python +from functools import reduce + +def egg_count(display_value): + return reduce(lambda eggs, digit: eggs + int(digit), bin(display_value)[2:], 0) +``` + +This variant uses [`reduce()`][functools-reduce] from the [`functools` module][functools-module] along with a `lambda` expression. +Here, `functools.reduce()` calls the `lambda` on each codepoint in `bin(display_value)[2:]`, accumulating the value of `eggs` from the initial `0`. + +Similar to the previous variant, the creation and repeated calling of the `lambda` causes extra overhead. + + [bin-built-in]: https://docs.python.org/3/library/functions.html#bin +[filter-built-in]: https://docs.python.org/3/library/functions.html#filter +[functools-module]: https://docs.python.org/3/library/functools.html +[functools-reduce]: https://docs.python.org/3/library/functools.html#functools.reduce [generator-expression]: https://dbader.org/blog/python-generator-expressions [lambda-expression]: https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions [list-comprehension]: https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions +[map-built-in]: https://docs.python.org/3/library/functions.html#map diff --git a/exercises/practice/eliuds-eggs/.approaches/no-parameter-modification/content.md b/exercises/practice/eliuds-eggs/.approaches/no-parameter-modification/content.md index a2a93c01b37..dbbe4ad2167 100644 --- a/exercises/practice/eliuds-eggs/.approaches/no-parameter-modification/content.md +++ b/exercises/practice/eliuds-eggs/.approaches/no-parameter-modification/content.md @@ -64,7 +64,7 @@ def egg_count(display_value): ``` This variant is actually a one-liner, it is just split up here for readability. -Here, we replace the `for-loop` with a [generator expression][generator-expression] and use `sum()` to collect the values into the result. +Here, we replace the `for-loop` with a [generator expression][generator-expression] and use [`sum()`][sum-built-in] to collect the values into the result. ## Variation #3: Manually Tracking the Place Value @@ -89,3 +89,4 @@ The main differences are not having to calculate the `place_value` from the bit [generator-expression]: https://dbader.org/blog/python-generator-expressions [right-shift-operator]: https://www.geeksforgeeks.org/software-engineering/right-shift-operator-in-programming/ +[sum-built-in]: https://docs.python.org/3/library/functions.html#sum From 3cc22a025c3ec8c4f6074019b7909c7f8a12a78a Mon Sep 17 00:00:00 2001 From: Yrahcaz7 <74512479+Yrahcaz7@users.noreply.github.com> Date: Tue, 9 Jun 2026 16:04:44 -0400 Subject: [PATCH 08/17] ternary operator -> conditional expression use "conditional expression" as the main name, and only mention "ternary operator" as another name for a "conditional expression" --- .../eliuds-eggs/.approaches/helper-functions/content.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/exercises/practice/eliuds-eggs/.approaches/helper-functions/content.md b/exercises/practice/eliuds-eggs/.approaches/helper-functions/content.md index 2b6e0ef4817..0adde9c44a3 100644 --- a/exercises/practice/eliuds-eggs/.approaches/helper-functions/content.md +++ b/exercises/practice/eliuds-eggs/.approaches/helper-functions/content.md @@ -29,10 +29,10 @@ First, `convert_to_binary()` is used to convert `display_value` to a binary stri Then, `count_ones()` is called to count the number of ones in that string. In this specific version of the approach, `convert_to_binary()` is implemented similarly to the [modify the parameter in a loop][approach-parameter-modification] approach. -The main differences are that the bits are converted to strings and appended together (rather being added together), and that a [ternary expression][ternary-expression] is used to handle the edge case of a `0`. +The main differences are that the bits are converted to strings and appended together (rather being added together), and that a [conditional expression][conditional-expression] (also called a ternary operator) is used to handle the edge case of a `0`. ~~~~exercism/note -Here, the [`or` operator][boolean-operations-default-or] could be used instead of a ternary expression: +Here, the [`or` operator][boolean-operations-default-or] could be used instead of a conditional expression: ```python return binary_value[::-1] or "0" @@ -70,4 +70,4 @@ However, if there are any unhandled edge cases, when you (or someone else) tries [approach-convert-to-binary-string]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/convert-to-binary-string [approach-parameter-modification]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/parameter-modification -[ternary-expression]: https://docs.python.org/3/reference/expressions.html#conditional-expressions +[conditional-expression]: https://docs.python.org/3/reference/expressions.html#conditional-expressions From 909ca846ef13b3f35913fd3a296851785b269207 Mon Sep 17 00:00:00 2001 From: Yrahcaz7 <74512479+Yrahcaz7@users.noreply.github.com> Date: Wed, 17 Jun 2026 21:18:23 -0400 Subject: [PATCH 09/17] Add "bad idea" variant to `parameter-modification` Courtesy of [this conversation in issue 4227][https://github.com/exercism/python/issues/4227#issuecomment-4736064222] --- .../parameter-modification/content.md | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/exercises/practice/eliuds-eggs/.approaches/parameter-modification/content.md b/exercises/practice/eliuds-eggs/.approaches/parameter-modification/content.md index 444d75efbc7..78a8d0fcd8f 100644 --- a/exercises/practice/eliuds-eggs/.approaches/parameter-modification/content.md +++ b/exercises/practice/eliuds-eggs/.approaches/parameter-modification/content.md @@ -115,9 +115,50 @@ As `display_value` is updated in the multiple assignment expression, we don't ne Just like the previous variations, the loop will continue until `display_value` reaches 0, and then we return `eggs`. +## Variation #5: Overcomplicated One-Liner + +~~~~exercism/caution +This approach is not idiomatic and can be quite confusing. +It is only provided here to show how one could apply various advanced techniques to turn this approach into a one-liner. +~~~~ + +```python +def egg_count(display_value): + return sum( + (value % 2, display_value := value // 2)[0] + for value in iter(lambda: display_value, 0) + ) +``` + +This variation uses [the `sum()` built-in][sum-built-in], a [generator expression][generator-expression], a [`lambda` expression][lambda-expression], and a [walrus operator (`:=`)][walrus-operator] to reduce the solution to a one-liner. +The line is only broken up here for readability. + +Here, the `while-loop` is converted into a generator expression, with `sum()` adding up the result of each iteration. +As the `while` keyword is not allowed in generator expressions, instead we iterate over an iterable with `for`. +This iterable is constructed from a `lambda` that returns `display_value`, with the [sentinel value][sentinel-value] set to `0`. +This means that [`iter()`][iter-built-in] returns an iterable that calls the `lambda` until the returned `display_value` equals `0`. + +For each iteration of the generator expression, we assign `value` to the return value of the `lambda`. +Then we construct a `tuple` with two elements, using `[0]` to get its first element and feed it to `sum()`. +That element is the least significant bit of `value`, which can be calculated via `value % 2` or `value & 1`, as shown in the previous variations. + +The second element is more complicated. +Here, we update `display_value`, cutting off the least significant bit (via `// 2` or `>> 1`) by using the walrus operator (`:=`). +The walrus operator acts like a simple assignment statement, except that it returns the right-hand value and it can be used anywhere that an expression can be used. +(See the [Python docs][assignment-expression-docs] for more details.) +Thus we can use walrus operator here to update `display_value` in the generator expression, then simply ignore the return value by only feeding the first element of the `tuple` to `sum()`. + + +[assignment-expression-docs]: https://docs.python.org/3/reference/expressions.html#assignment-expressions [bitwise-operators]: https://www.w3schools.com/programming/prog_operators_bitwise.php [concept-tuples]: https://exercism.org/tracks/python/concepts/tuples [concept-unpacking-and-multiple-assignment]: https://exercism.org/tracks/python/concepts/unpacking-and-multiple-assignment [divmod-built-in]: https://docs.python.org/3/library/functions.html#divmod +[generator-expression]: https://dbader.org/blog/python-generator-expressions +[iter-built-in]: https://docs.python.org/3/library/functions.html#iter +[lambda-expression]: https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions [right-shift-operator]: https://www.geeksforgeeks.org/software-engineering/right-shift-operator-in-programming/ +[sentinel-value]: https://python-patterns.guide/python/sentinel-object/ [sequence-count]: https://docs.python.org/3/library/stdtypes.html#sequence.count +[sum-built-in]: https://docs.python.org/3/library/functions.html#sum +[walrus-operator]: https://mathspp.com/blog/pydonts/assignment-expressions-and-the-walrus-operator From a13bd5e7c67379ff7ced6e5e1e6f550bfb4d7dbb Mon Sep 17 00:00:00 2001 From: BethanyG Date: Thu, 18 Jun 2026 15:45:38 -0700 Subject: [PATCH 10/17] Renamed parameter files to argument. --- .../argument-modification/content.md | 122 ++++++++++++++++++ .../argument-modification/snippet.txt | 6 + .../no-argument-modification/content.md | 97 ++++++++++++++ .../no-argument-modification/snippet.txt | 7 + 4 files changed, 232 insertions(+) create mode 100644 exercises/practice/eliuds-eggs/.approaches/argument-modification/content.md create mode 100644 exercises/practice/eliuds-eggs/.approaches/argument-modification/snippet.txt create mode 100644 exercises/practice/eliuds-eggs/.approaches/no-argument-modification/content.md create mode 100644 exercises/practice/eliuds-eggs/.approaches/no-argument-modification/snippet.txt diff --git a/exercises/practice/eliuds-eggs/.approaches/argument-modification/content.md b/exercises/practice/eliuds-eggs/.approaches/argument-modification/content.md new file mode 100644 index 00000000000..7634a7fb966 --- /dev/null +++ b/exercises/practice/eliuds-eggs/.approaches/argument-modification/content.md @@ -0,0 +1,122 @@ +# Modify the Argument in a Loop + +```python +def egg_count(display_value): + eggs = 0 + while display_value: + eggs += display_value % 2 + display_value //= 2 + return eggs +``` + +This approach uses a `while-loop` to count up the ones in the binary representation. +In the loop, we increment `eggs` by `display_value % 2`. +This adds the least significant bit (_the rightmost digit in the binary representation_) of `display_value` to `eggs`. + +Next, we divide `display_value` by `2`, discarding any remainder. +This essentially removes the least significant bit of the current `display_value`, setting up the next iteration's `display_value` for processing the next bit. + +This loop repeats until `display_value` reaches `0` (_which indicates that we have no more bits to process_), and then we return `eggs`. + + +## Variation #1: Using Boolean Operators + +```python +def egg_count(display_value): + eggs = 0 + while display_value > 0: + if display_value % 2 == 1: + eggs += 1 + display_value //= 2 + return eggs +``` + +This is essentially just a more verbose formulation of the previous version. +Instead of relying on Python converting `int`s to `bool`s, this solution manually compares `display_value` to `0`. +It also uses an `if` statement to check if `eggs` should be incremented by `1`, instead of directly using the result of `display_value % 2`. + +Even though this variant is more verbose than the others, some may consider it to be more readable. + + +## Variation #2: Using Bitwise Operators + +```python +def egg_count(display_value): + eggs = 0 + while display_value > 0: + eggs += display_value & 1 + display_value >>= 1 + return eggs +``` + +This variant replaces the modulo (`%`) and floor division (`//`) operators with [bitwise operators][bitwise-operators]. +`&` is the bitwise AND operator, which results in a number whose binary representation only has ones where _both_ of its arguments have ones (_all other bits become zeros_). + +For example, if we use the numbers `3` (`11` in binary) and `1` (`1` in binary), we get `1`: + +```python +0b011 & 0b001 +#=> 0b001 +``` + +This is because the only bit in both numbers that is `1` is their least significant bit. +This property lets us extract the least significant bit of `display_value` by using `display_value & 1`. + +For the next step we use `>>`, the [right-shift operator][right-shift-operator]. +The expression `a >> b` shifts all of `a`'s bits to the right by `b` places, and returns the resulting number. + +For example, if we use the numbers `5` (`101` in binary) and `1`, we get `2` (`10` in binary): + +```python +0b101 >> 1 +#=> 0b010 +``` + +You can see how `& 1` and `>>= 1` perform the same function as the `% 2` and `//= 2` used in earlier variants. + + +## Variation #3: Using a `list` + +```python +def egg_count(display_value): + egg_positions = [] + + while display_value: + egg_positions.append(display_value % 2) + display_value //= 2 + + return egg_positions.count(1) +``` + +Here, we append the binary digits to a `list` and then count the number of ones using [`list.count()`][sequence-count]. +This solution would make sense if the positions of the eggs mattered, but since we only need the amount here, tracking the positions just adds unnecessary overhead. +Further overhead is added when `list.count()` iterates through the `list` to obtain the total. + + +## Variation #4: Using `divmod()` + +```python +def egg_count(display_value): + eggs = 0 + while display_value: + display_value, remainder = divmod(display_value, 2) + eggs += remainder + return eggs +``` + +This variant uses the [`divmod()`][divmod-built-in] built-in instead of `%` and `//`. +(_For `int` arguments, `divmod(a, b)` returns a [`tuple`][concept-tuples] of `(a // b, a % b)`._) + +Within the loop, `divmod(display_value, 2)` is used to get both the quotient and the remainder of the division. +The `tuple` returned by `divmod()` is [unpacked][concept-unpacking-and-multiple-assignment] into `display_value` and `remainder` using [multiple assignment][concept-unpacking-and-multiple-assignment]. +`eggs` is then incremented by `remainder`. + +As `display_value` is updated in the multiple assignment expression, we don't need to do anything else inside the loop. +Just like the previous variations, the loop will continue until `display_value` reaches 0, and then we return `eggs`. + +[bitwise-operators]: https://www.w3schools.com/programming/prog_operators_bitwise.php +[concept-tuples]: https://exercism.org/tracks/python/concepts/tuples +[concept-unpacking-and-multiple-assignment]: https://exercism.org/tracks/python/concepts/unpacking-and-multiple-assignment +[divmod-built-in]: https://docs.python.org/3/library/functions.html#divmod +[right-shift-operator]: https://www.geeksforgeeks.org/software-engineering/right-shift-operator-in-programming/ +[sequence-count]: https://docs.python.org/3/library/stdtypes.html#sequence.count diff --git a/exercises/practice/eliuds-eggs/.approaches/argument-modification/snippet.txt b/exercises/practice/eliuds-eggs/.approaches/argument-modification/snippet.txt new file mode 100644 index 00000000000..c3d5eeb7bf4 --- /dev/null +++ b/exercises/practice/eliuds-eggs/.approaches/argument-modification/snippet.txt @@ -0,0 +1,6 @@ +def egg_count(display_value): + eggs = 0 + while display_value: + eggs += display_value % 2 + display_value //= 2 + return eggs \ No newline at end of file diff --git a/exercises/practice/eliuds-eggs/.approaches/no-argument-modification/content.md b/exercises/practice/eliuds-eggs/.approaches/no-argument-modification/content.md new file mode 100644 index 00000000000..03dd6e8a54a --- /dev/null +++ b/exercises/practice/eliuds-eggs/.approaches/no-argument-modification/content.md @@ -0,0 +1,97 @@ +# Loop Without Modifying the Argument + + +```python +from math import ceil, log2 + +def egg_count(display_value): + eggs = 0 + for bit_position in range(ceil(log2(display_value + 1))): + eggs += (display_value >> bit_position) & 1 + return eggs +``` + +This approach uses a loop with `range()` to iterate over the bits in `display_value`. + +To determine how many bits `display_value` has, this solution imports `ceil` and `log2` from the `math` module. +We then calculate the base 2 logarithm of `display_value` (_plus 1_) and round up. +(_Rounding up is necessary because `range()` excludes the value of `` from its returned values._) + + +Once we have the bit length of `display_value`, it is fed into `range()` to make the `for-loop` iterate over all of `display_value`'s `bit_position`s. + +For each `bit_position`, we determine the value of the bit at that position by using the [right-shift operator][right-shift-operator] and the bitwise AND operator. +We do this by right-shifting `display_value` by `bit_position`, making the bit at `bit_position` become the least significant bit. +Then we use the bitwise AND operator with `1` to remove all bits that are not the least significant bit. + + +~~~~exercism/note +You could also calculate the bit's value by using arithmetic operators instead of bitwise ones: + +```python +eggs += (display_value // (2 ** bit_position)) % 2 +``` +~~~~ + + +Once we determine the bit's value, we increment `eggs` by that number. + +After the loop ends, we know that we have checked all bits in `display_value`, thus we return `eggs`. + + +## Variation #1: Using an `if` Statement + + +```python +from math import ceil, log2 + +def egg_count(display_value): + eggs = 0 + for bit_position in range(ceil(log2(display_value + 1))): + if display_value & (1 << bit_position): + eggs += 1 + return eggs +``` + +In this variant, the loop uses an `if` statement to check if the digit at `display_value` is `1`. + + +## Variation #2: Using `sum()` with a Generator Expression + +```python +from math import ceil, log2 + +def egg_count(display_value): + return sum( + (display_value >> bit_position) & 1 + for bit_position in range(ceil(log2(display_value + 1))) + ) +``` + +This variant is actually a one-liner, it is just split up here for readability. +Here, we replace the `for-loop` with a [generator expression][generator-expression] and use [`sum()`][sum-built-in] to collect the values into the result. + + +## Variation #3: Manually Tracking the Place Value + +```python +def egg_count(display_value): + eggs = 0 + place_value = 1 + while place_value <= display_value: + if display_value & place_value: + eggs += 1 + place_value <<= 1 + return eggs +``` + +This variant avoids `import`s by manually tracking the `place_value` of the current bit position. +This way, the `while-loop` can end when `place_value` becomes greater than `display_value`. + +The operations in the loop are rather similar to the "using an `if` statement" variant. +The main differences are not having to calculate the `place_value` from the bit position, and having to manually progress the iteration by left-shifting `place_value` by `1` (which is the same as multiplying `place_value` by `2`). + + +[generator-expression]: https://dbader.org/blog/python-generator-expressions +[right-shift-operator]: https://www.geeksforgeeks.org/software-engineering/right-shift-operator-in-programming/ +[sum-built-in]: https://docs.python.org/3/library/functions.html#sum diff --git a/exercises/practice/eliuds-eggs/.approaches/no-argument-modification/snippet.txt b/exercises/practice/eliuds-eggs/.approaches/no-argument-modification/snippet.txt new file mode 100644 index 00000000000..b2a163f2f28 --- /dev/null +++ b/exercises/practice/eliuds-eggs/.approaches/no-argument-modification/snippet.txt @@ -0,0 +1,7 @@ +from math import ceil, log2 + +def egg_count(display_value): + eggs = 0 + for bit_position in range(ceil(log2(display_value + 1))): + eggs += (display_value >> bit_position) & 1 + return eggs \ No newline at end of file From 884bf0b6e1d95daf14127611eb010ebc7de185b7 Mon Sep 17 00:00:00 2001 From: BethanyG Date: Thu, 18 Jun 2026 15:56:48 -0700 Subject: [PATCH 11/17] Suggestions, additions, and fixes for approaches. --- .../.approaches/built-in-bit-count/content.md | 40 +++++++++++++++---- 1 file changed, 32 insertions(+), 8 deletions(-) diff --git a/exercises/practice/eliuds-eggs/.approaches/built-in-bit-count/content.md b/exercises/practice/eliuds-eggs/.approaches/built-in-bit-count/content.md index 941c6c4141e..64584e894a4 100644 --- a/exercises/practice/eliuds-eggs/.approaches/built-in-bit-count/content.md +++ b/exercises/practice/eliuds-eggs/.approaches/built-in-bit-count/content.md @@ -13,8 +13,22 @@ def egg_count(display_value): This approach uses [`int.bit_count()`][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. -Even if a binary literal is declared with the `0b` prefix, Python still stores it as an `int`. -Due to this, all of the methods that work with binary numbers in the standard library just operate on `int`s. +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`: + +```python +>>> 0b00110101 #<- 53 in binary +53 +>>> type(0b00110101) + + +>>> 0O65 #<- 53 in octal +53 +>>> type(0O65) + +``` + +Due to this, all methods that work with binary numbers in the standard library actually operate on `int`s. ## Variation #1: Using `str.count()` @@ -24,7 +38,7 @@ def egg_count(display_value): return bin(display_value).count("1") ``` -This variant uses [`bin()`][bin-built-in] (or any other method discussed in the [convert to a binary string][approach-convert-to-binary-string] approach) to convert `display_value` to a binary string. +This variant uses [`bin()`][bin-built-in] (_or any other method discussed in the [convert to a binary string][approach-convert-to-binary-string] approach_) to convert `display_value` to a `binary string`. Then, [`str.count()`][sequence-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. @@ -36,14 +50,24 @@ Though one could argue that this _technically_ doesn't use the built-in bit-coun egg_count = int.bit_count ``` -This solution is the shortest of them all, but it can also be rather confusing (and it still does not follow the instructions). +This solution is the shortest of them all, but it can also be rather confusing (_and does not follow the instructions_). +It also can throw what appears to be a non-related error: -This variant makes clever use of [function aliasing][function-aliasing], which creates a new name that refers to the same exact function. -However, you should be careful when using function aliasing, as it often makes code _less_ readable, and it doesn't have many practical applications outside of backward compatibility. +```python +>>> egg_count(3.5) +Traceback (most recent call last): + File "", line 1, in + egg_count(3.5) + ~~~~~~~~~^^^^^ +TypeError: descriptor 'bit_count' for 'int' objects doesn't apply to a 'float' object +``` -This solution works because `int.bit_count()` is just another way of saying `.bit_count()`, as instance methods of a class have `self` implicitly passed as the first parameter when calling them on an instance (but not when calling them directly on the class). -See the [Classes Concept in the Syllabus][concept-classes: methods] or the [Official Python Classes Tutorial][class-method-objects-tutorial] for more detail on how this works. +This variant makes clever use of [function/method aliasing][function-aliasing], which creates a new name that refers to the existing `int.bit_count()` method. +This means 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()` becomes just another way of saying `.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][concept-classes: methods] or the [Official Python Classes Tutorial][class-method-objects-tutorial] for more detail on how `self` works. [approach-convert-to-binary-string]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/convert-to-binary-string [bin-built-in]: https://docs.python.org/3/library/functions.html#bin From 0ecf9b6bfb12c62327a1ed06563681f9f8e910c9 Mon Sep 17 00:00:00 2001 From: BethanyG Date: Thu, 18 Jun 2026 15:57:06 -0700 Subject: [PATCH 12/17] Suggestions, additions, and fixes for approaches. --- .../convert-to-binary-string/content.md | 46 +++++++++++++------ 1 file changed, 31 insertions(+), 15 deletions(-) diff --git a/exercises/practice/eliuds-eggs/.approaches/convert-to-binary-string/content.md b/exercises/practice/eliuds-eggs/.approaches/convert-to-binary-string/content.md index a41eaeab96f..9f4b11c67ea 100644 --- a/exercises/practice/eliuds-eggs/.approaches/convert-to-binary-string/content.md +++ b/exercises/practice/eliuds-eggs/.approaches/convert-to-binary-string/content.md @@ -2,7 +2,7 @@ ```python def egg_count(display_value): - binary_value = bin(display_value)[2:] + binary_value = bin(display_value)[2:] #<- Slice off the first two characters. eggs = 0 for digit in binary_value: eggs += int(digit) @@ -10,39 +10,47 @@ def egg_count(display_value): ``` This approach uses [`bin()`][bin-built-in] to convert `display_value` to a binary string. -Then, the first two characters of the binary string are removed, as the string has "0b" prefixed before the binary digits. +Next, the first two characters of the binary string are removed via slice, as the string has "0b" as a prefix before the binary digits. -After the binary digits are obtained, this solution loops across all of them, turning each one into an integer and adding it to `eggs`. -This effectively counts up all of the instances of "1" in the binary string, as 0 and 1 are the only valid binary digits. +After the binary digits are obtained, this solution loops across all of them, turning each one into an `int` and adding it to `eggs`. +This counts up all of the instances of "1" in the binary string, as 0 and 1 are the only valid binary digits. Those less familiar with binary may find this approach to be simpler than the others. However, it does have the added overhead of converting to and from a string. + ~~~~exercism/note -There are three other Pythonic ways of obtaining the binary string. One is to use an [`f-string`][f-string]: +There are three other Pythonic ways of obtaining a binary string. +These strategies use the [string format specification][string-format-spec] in different ways. + +The first is to use an [`f-string`][f-string] ```python +# This uses the 'binary' format code. binary_value = f"{display_value:b}" -``` +``` Another is to use [`str.format()`][str-format]: ```python +# This also uses the 'binary' format code with different syntax. binary_value = "{:b}".format(display_value) ``` Lastly, you could use the [`format()` built-in][format-built-in]: ```python +# This uses the 'binary' format code passed as a quoted string. binary_value = format(display_value, "b") ``` These methods have the added benefit of not producing the "0b" prefix that then needs to removed. However, some variations of this approach use other ways to get around the prefix. -[format-built-in]: https://docs.python.org/3/library/functions.html#format [f-string]: https://docs.python.org/3/reference/lexical_analysis.html#f-strings +[format-built-in]: https://docs.python.org/3/library/functions.html#format [str-format]: https://docs.python.org/3/library/stdtypes.html#str.format +[string-format-spec]: https://docs.python.org/3/library/string.html#format-specification-mini-language ~~~~ @@ -65,7 +73,8 @@ def egg_count(display_value): ``` Similar to the previous variant, this one uses `sum()` with a generator expression. -The main difference is that it avoids slicing the binary string by using an `if` clause in the generator expression. +The main difference is that it avoids slicing & copying the binary string by using an `if` clause in the generator expression. +This also avoids the overhead of calling `int()` on each digit. ## Variation #3: Using `len()` Instead of `sum()` @@ -76,21 +85,28 @@ def egg_count(display_value): ``` This variant replaces the generator expression with a [list comprehension][list-comprehension]. -This way, it can simply use `len()` to get the number of ones, after the comprehension filters the other digits out. +This way, it can use `len()` to get the number of ones (_which evaluate to True_), after the comprehension filters the other digits (_which evaluate to False_) out. -Here, `True` is used for the list elements, but we could any other value as well, as we only care about the length of the list. +Here, `True` is used for the list elements, but we could use any other value as well, as we only care about the length of the "1"s list. +`bool()` could also be used here, but would require that each digit be converted via `int()` before evaluating: + +```python +def egg_count(display_value): + return len([bool(int(digit)) for digit in bin(display_value)[2:]]) +``` -## Variation #4: Using `map()` Instead of a Generator Expression +## Variation #4: Using `map()` Instead of a Generator Expression or List Comprehension ```python def egg_count(display_value): return sum(map(int, bin(display_value)[2:])) ``` -Here, we directly [`map`][map-built-in] the elements of the binary string to `int`s without using a generator expression or a list comprehension. +Here, we directly [`map`][map-built-in] the elements of the binary string to `int()` without using a generator expression or a list comprehension. -This variant is the most concise of them all, but it may be not very comprehensible to those unfamilar with functional programming. +This variant is the most concise, but it may be not very comprehensible to those unfamiliar with functional programming. +It also somewhat hides the overhead that is incurred calling `int()` on every digit. ## Variation #5: Using `filter()` with a `lambda` @@ -101,7 +117,7 @@ def egg_count(display_value): ``` Another alternative to a generator expression (or list comprehension) is to use the [`filter()` built-in][filter-built-in] along with a [`lambda` expression][lambda-expression]. -However, the creation and repeated calling of the `lambda` adds unnecessary overhead to the solution. +However, the creation and repeated calling of the `lambda` adds unnecessary overhead to the solution and `filter()` typically runs slower than the equivalent list comprehension. ## Variation #6: Using `functools.reduce()` with a `lambda` @@ -116,7 +132,7 @@ def egg_count(display_value): This variant uses [`reduce()`][functools-reduce] from the [`functools` module][functools-module] along with a `lambda` expression. Here, `functools.reduce()` calls the `lambda` on each codepoint in `bin(display_value)[2:]`, accumulating the value of `eggs` from the initial `0`. -Similar to the previous variant, the creation and repeated calling of the `lambda` causes extra overhead. +Similar to the previous variant, the creation and repeated calling of the `lambda` causes extra overhead, as does importing the `functools` module. [bin-built-in]: https://docs.python.org/3/library/functions.html#bin From 878df14e152c40410b35da1fa2e8a1c10e7cc870 Mon Sep 17 00:00:00 2001 From: BethanyG Date: Thu, 18 Jun 2026 15:57:30 -0700 Subject: [PATCH 13/17] Suggestions, additions, and fixes for approaches. --- .../.approaches/helper-functions/content.md | 21 ++++++++++--------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/exercises/practice/eliuds-eggs/.approaches/helper-functions/content.md b/exercises/practice/eliuds-eggs/.approaches/helper-functions/content.md index 0adde9c44a3..b9e7ef08f2e 100644 --- a/exercises/practice/eliuds-eggs/.approaches/helper-functions/content.md +++ b/exercises/practice/eliuds-eggs/.approaches/helper-functions/content.md @@ -1,5 +1,6 @@ # Use Helper Functions + ```python def egg_count(display_value): return count_ones(convert_to_binary(display_value)) @@ -28,8 +29,8 @@ This approach breaks the problem down into multiple helper functions that are ca First, `convert_to_binary()` is used to convert `display_value` to a binary string. Then, `count_ones()` is called to count the number of ones in that string. -In this specific version of the approach, `convert_to_binary()` is implemented similarly to the [modify the parameter in a loop][approach-parameter-modification] approach. -The main differences are that the bits are converted to strings and appended together (rather being added together), and that a [conditional expression][conditional-expression] (also called a ternary operator) is used to handle the edge case of a `0`. +In this specific version of the approach, `convert_to_binary()` is implemented similarly to the [modify the argument in a loop][approach-argument-modification] approach. +The main differences are that the bits are converted to strings and concatenated (_rather being added together_), and that a [conditional expression][conditional-expression] (_also called a ternary operator_) is used to handle the edge case of a `0`. ~~~~exercism/note Here, the [`or` operator][boolean-operations-default-or] could be used instead of a conditional expression: @@ -43,12 +44,13 @@ Which one to use is mostly a matter of preference and readability. [boolean-operations-default-or]: https://docs.python.org/3/reference/expressions.html#boolean-operations:~:text=if%20s%20is%20a%20string%20that%20should%20be%20replaced%20by%20a%20default%20value%20if%20it%20is%20empty,%20the%20expression%20s%20or%20'foo'%20yields%20the%20desired%20value. ~~~~ + The `count_ones()` helper function is implemented very similarly to the [convert to a binary string][approach-convert-to-binary-string] approach. -The only difference is that it takes the binary string as a parameter, rather than calulating it itself. +The only difference is that it takes the binary string as an argument rather than calculating it. -Though breaking the problem up into helper functions may facilitate code reuse, it also adds unnecessary overhead to the solution. -The approach is also complicated by additional edge cases, such as making `convert_to_binary()` return "0" instead of an empty string when given the number `0`. -In fact, the edge case of negative numbers is not handled, and doing so complicates the solution even further: +Though breaking a problem up into helper functions may facilitate code reuse, here it adds unnecessary overhead to the solution. +This approach is also complicated by additional edge cases, such as making `convert_to_binary()` return "0" instead of an empty string when given the number `0`. +The edge case of negative numbers is also not handled, and doing so would complicate the solution even further: ```python def convert_to_binary(decimal_value): @@ -64,10 +66,9 @@ def convert_to_binary(decimal_value): return binary_value[::-1] or "0" ``` -Due to this, one may decide to not handle all of the edge cases. -However, if there are any unhandled edge cases, when you (or someone else) tries to reuse the function in the future, they could get incorrect results. - +Due to these scenarios, one may decide to forego handling all the edge cases. +However, when your future self (_or someone else_) tries to reuse the function, edge cases could produce errors or unexpected results. +[approach-argument-modification]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/argument-modification [approach-convert-to-binary-string]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/convert-to-binary-string -[approach-parameter-modification]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/parameter-modification [conditional-expression]: https://docs.python.org/3/reference/expressions.html#conditional-expressions From 0e535563a5db78be5f673b2f26a4e7adad1cbe6c Mon Sep 17 00:00:00 2001 From: BethanyG Date: Thu, 18 Jun 2026 15:58:43 -0700 Subject: [PATCH 14/17] Suggestions, additions, and fixes for approaches. --- .../eliuds-eggs/.approaches/introduction.md | 51 ++++++++++--------- 1 file changed, 26 insertions(+), 25 deletions(-) diff --git a/exercises/practice/eliuds-eggs/.approaches/introduction.md b/exercises/practice/eliuds-eggs/.approaches/introduction.md index dfa50ff9ba6..4ed44aa2076 100644 --- a/exercises/practice/eliuds-eggs/.approaches/introduction.md +++ b/exercises/practice/eliuds-eggs/.approaches/introduction.md @@ -1,26 +1,26 @@ # Introduction -There are many different approaches to solving the Eliud's Eggs exercise: +There are many different approaches to solving the Eliud's Eggs exercise, among them are: -- Using a `while-loop`, modifying the parameter on each iteration -- Looping over every binary digit _without_ modifying the parameter -- Converting the `int` to a binary string and counting the ones +- Using a `while-loop` and modifying the function argument on each iteration +- Looping over every binary digit _without_ modifying the function argument +- Converting the `int` argument into a binary string and counting the "ones" in it There are also some approaches that aren't recommended: -- Using the bit-count functionality from the Python standard library, as the instructions forbid it -- Breaking up the proccess into many functions, overcomplicating the solution +- Using the bit-count functionality from the Python standard library, as the instructions ask this challenge be solved "manually". +- Breaking up the counting process into many small functions, which can overcomplicate or slow the solution. ## General guidance -The goal of the Eliud's Eggs exercise is to count the number of ones in the [binary representation of a number][concept-numbers]. -In essence, this requires you to loop over each bit (binary digit) of the number in some way. +The goal of the Eliud's Eggs exercise is to count the number of ones in a [binary representation of a number][concept-numbers] (_e.g. the "filled gg slots" a chicken coop_). +In essence, this requires you to iterate through each "slot" or bit (binary digit) of the binary number in some way. The approaches below represent categories of the most common ways of accomplishing this. -## Approach: Modifying the Parameter in a `while-loop` +## Approach: Modifying the Argument in a `while-loop` ```python def egg_count(display_value): @@ -31,19 +31,19 @@ def egg_count(display_value): return eggs ``` -This approach uses a `while-loop` to count up all of the ones. +This approach uses a `while-loop` to count up the ones in the calculated binary equivalent of `display value`. In the loop, we increment `eggs` by `display_value % 2`. -This adds the least significant bit (the rightmost digit in the binary representation) of `display_value` to `eggs`. +This adds the least significant bit (_the rightmost digit in the binary representation_) of `display_value` to `eggs`. -Next, we divide `display_value` by `2`, discarding any remainder. -This essentially removes the least significant bit of `display_value`, setting up `display_value` for processing the next bit. +Next, `display_value` is divided by `2`, discarding any remainder. +This removes the least significant bit of the current `display_value`, setting up the next iteration of `display_value` for processing. -The loop repeats until `display_value` reaches `0` (which indicates that we have no more bits to check), and then we return `eggs`. +The loop repeats until `display_value` reaches `0` (_which indicates that there are no more bits to process_), at which point `eggs` is returned. -To see more variations of this solution, see the [modify the parameter in a loop][approach-parameter-modification] approach. +To see more variations of this solution, read the [modify the argument in a loop][approach-argument-modification] approach. -## Approach: Looping Without Modifying the Parameter +## Approach: Looping Without Modifying the Argument ```python from math import ceil, log2 @@ -59,15 +59,15 @@ This solution uses a `for-loop` with `range()` to iterate over all of the bits i To determine how many bits `display_value` has, this solution imports `ceil` and `log2` from the `math` module. It then feeds this number into `range()` to make the `for-loop` iterate over all the `bit_position`s. -For each `bit_position`, we determine the value of the bit at that position by using the [right-shift operator][right-shift-operator] and the bitwise AND operator. +For each `bit_position`, we determine the value of the bit at that position by using the [right-shift operator][right-shift-operator] and the [bitwise AND][bit-AND] operator. Once we determine the bit's value, we increment `eggs` by that number. -After the loop ends, we know that we have checked all of the bits in `display_value`, thus we return `eggs`. +After the loop ends, we know that we have processed all bits in `display_value`, so we return `eggs`. -For more details and variations, read the [loop without modifying the parameter][approach-no-parameter-modification] approach. +For more details and variations, read the [loop without modifying the argument][approach-no-argument-modification] approach. -## Approach: Converting the Parameter to a Binary String +## Approach: Converting the Argument to a Binary String ```python def egg_count(display_value): @@ -79,9 +79,9 @@ def egg_count(display_value): ``` This approach uses [`bin()`][bin-built-in] (or some other means, such as an [`f-string`][f-string]) to convert `display_value` to a binary string. -Then, the first two characters of the binary string are removed, as the string has "0b" prefixed before the binary digits. +The first two characters of the binary string are removed as "0b" is used as a prefix to the binary digits. -After the binary digits are obtained, this solution loops across all of them, turning each one into an integer and adding it to `eggs`. +After the binary digits are obtained, this solution loops through them, turning each one into an integer and adding it to `eggs`. This effectively counts up all of the instances of "1" in the binary string, as 0 and 1 are the only valid binary digits. Many variations of this approach use a built-in function like `sum()` to make the iteration more concise. @@ -139,7 +139,7 @@ The actual implementations of `convert_to_binary()` and `count_ones()` could use Though breaking the problem up into helper functions may facilitate code reuse, it also adds unnecessary overhead to the solution. It can also overcomplicate things, as you may need to consider additional edge cases, such as making `convert_to_binary()` return "0" instead of an empty string when given the number `0`. -If you do not handle all of these cases, when you (or someone else) tries to reuse the function later, they may get unexpected results, such as getting "0" when inputting a negative number. +If you do not handle all of these cases, when you (_or someone else_) tries to reuse the function later, they may get unexpected results, such as "0" being returned when a negative number in input. For more details, check out the [helper functions][approach-helper-functions] approach. @@ -147,9 +147,10 @@ For more details, check out the [helper functions][approach-helper-functions] ap [approach-built-in-bit-count]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/built-in-bit-count [approach-convert-to-binary-string]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/convert-to-binary-string [approach-helper-functions]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/helper-functions -[approach-no-parameter-modification]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/no-parameter-modification -[approach-parameter-modification]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/parameter-modification +[approach-no-argument-modification]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/no-argument-modification +[approach-argument-modification]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/argument-modification [bin-built-in]: https://docs.python.org/3/library/functions.html#bin +[bit-AND]: https://docs.python.org/3/library/stdtypes.html#bitwise-operations-on-integer-types [concept-numbers]: https://exercism.org/tracks/python/concepts/numbers [f-string]: https://docs.python.org/3/reference/lexical_analysis.html#f-strings [int-bit_count]: https://docs.python.org/3/library/stdtypes.html#int.bit_count From 7b1a9d8a819b328e74e89fc2318a81b87dbe205f Mon Sep 17 00:00:00 2001 From: BethanyG Date: Thu, 18 Jun 2026 15:59:15 -0700 Subject: [PATCH 15/17] Suggestions, additions, and fixes for approaches. --- .../practice/eliuds-eggs/.approaches/config.json | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/exercises/practice/eliuds-eggs/.approaches/config.json b/exercises/practice/eliuds-eggs/.approaches/config.json index 2cd26165315..5e6072e4095 100644 --- a/exercises/practice/eliuds-eggs/.approaches/config.json +++ b/exercises/practice/eliuds-eggs/.approaches/config.json @@ -6,15 +6,15 @@ "approaches": [ { "uuid": "27fb20ed-a4c2-4f73-a8fc-86ba384c7b35", - "slug": "parameter-modification", - "title": "Modify the Parameter in a Loop", + "slug": "argument-modification", + "title": "Modify the Argument in a Loop", "blurb": "Modify the parameter in a while-loop to determine the number of eggs.", "authors": ["yrahcaz7"] }, { "uuid": "65fd717c-0e50-444b-a4b2-b51862f1f810", - "slug": "no-parameter-modification", - "title": "Loop Without Modifying the Parameter", + "slug": "no-argument-modification", + "title": "Loop Without Modifying the Argument", "blurb": "Loop over the bits without modifying the parameter to calculate the number of eggs.", "authors": ["yrahcaz7"] }, @@ -23,14 +23,16 @@ "slug": "convert-to-binary-string", "title": "Convert to a Binary String", "blurb": "Convert the parameter to a binary string and count its ones to determine the number of eggs.", - "authors": ["yrahcaz7"] + "authors": ["yrahcaz7"], + "contributors": ["BethanyG"] }, { "uuid": "97b06094-7ce8-4874-b66a-af7391adc853", "slug": "built-in-bit-count", "title": "Use the Built-In Bit-Count Functionality", "blurb": "Use Python's built-in bit-count functionality to calculate the number of eggs.", - "authors": ["yrahcaz7"] + "authors": ["yrahcaz7"], + "contributors": ["BethanyG"] }, { "uuid": "618491ca-480e-4e32-bf91-4940affb48a8", From d61ff8d944c518a8636af2771a7e93889453d90a Mon Sep 17 00:00:00 2001 From: BethanyG Date: Thu, 18 Jun 2026 16:01:28 -0700 Subject: [PATCH 16/17] Deletions for files that were renamed Directories and file links using 'Parameter' were renamed to 'Argument'. This is because parameters are when you write a function or class. Arguments are used when a function is *called*. --- .../argument-modification/content.md | 40 +++++ .../no-parameter-modification/content.md | 92 ---------- .../no-parameter-modification/snippet.txt | 7 - .../parameter-modification/content.md | 164 ------------------ .../parameter-modification/snippet.txt | 6 - 5 files changed, 40 insertions(+), 269 deletions(-) delete mode 100644 exercises/practice/eliuds-eggs/.approaches/no-parameter-modification/content.md delete mode 100644 exercises/practice/eliuds-eggs/.approaches/no-parameter-modification/snippet.txt delete mode 100644 exercises/practice/eliuds-eggs/.approaches/parameter-modification/content.md delete mode 100644 exercises/practice/eliuds-eggs/.approaches/parameter-modification/snippet.txt diff --git a/exercises/practice/eliuds-eggs/.approaches/argument-modification/content.md b/exercises/practice/eliuds-eggs/.approaches/argument-modification/content.md index 7634a7fb966..58876690a78 100644 --- a/exercises/practice/eliuds-eggs/.approaches/argument-modification/content.md +++ b/exercises/practice/eliuds-eggs/.approaches/argument-modification/content.md @@ -113,10 +113,50 @@ The `tuple` returned by `divmod()` is [unpacked][concept-unpacking-and-multiple- As `display_value` is updated in the multiple assignment expression, we don't need to do anything else inside the loop. Just like the previous variations, the loop will continue until `display_value` reaches 0, and then we return `eggs`. +## Variation #5: Overcomplicated One-Liner +~~~~exercism/caution +This approach is not idiomatic and can be quite confusing. +It is only provided here to show how one could apply various advanced techniques to turn this approach into a one-liner. +~~~~ + +```python +def egg_count(display_value): + return sum( + (value % 2, display_value := value // 2)[0] + for value in iter(lambda: display_value, 0) + ) +``` + +This variation uses [the `sum()` built-in][sum-built-in], a [generator expression][generator-expression], a [`lambda` expression][lambda-expression], and a [walrus operator (`:=`)][walrus-operator] to reduce the solution to a one-liner. +The line is only broken up here for readability. + +Here, the `while-loop` is converted into a generator expression, with `sum()` adding up the result of each iteration. +As the `while` keyword is not allowed in generator expressions, instead we iterate over an iterable with `for`. +This iterable is constructed from a `lambda` that returns `display_value`, with the [sentinel value][sentinel-value] set to `0`. +This means that [`iter()`][iter-built-in] returns an iterable that calls the `lambda` until the returned `display_value` equals `0`. + +For each iteration of the generator expression, we assign `value` to the return value of the `lambda`. +Then we construct a `tuple` with two elements, using `[0]` to get its first element and feed it to `sum()`. +That element is the least significant bit of `value`, which can be calculated via `value % 2` or `value & 1`, as shown in the previous variations. + +The second element is more complicated. +Here, we update `display_value`, cutting off the least significant bit (via `// 2` or `>> 1`) by using the walrus operator (`:=`). +The walrus operator acts like a simple assignment statement, except that it returns the right-hand value and it can be used anywhere that an expression can be used. +(See the [Python docs][assignment-expression-docs] for more details.) +Thus we can use walrus operator here to update `display_value` in the generator expression, then simply ignore the return value by only feeding the first element of the `tuple` to `sum()`. + + +[assignment-expression-docs]: https://docs.python.org/3/reference/expressions.html#assignment-expressions [bitwise-operators]: https://www.w3schools.com/programming/prog_operators_bitwise.php [concept-tuples]: https://exercism.org/tracks/python/concepts/tuples [concept-unpacking-and-multiple-assignment]: https://exercism.org/tracks/python/concepts/unpacking-and-multiple-assignment [divmod-built-in]: https://docs.python.org/3/library/functions.html#divmod +[generator-expression]: https://dbader.org/blog/python-generator-expressions +[iter-built-in]: https://docs.python.org/3/library/functions.html#iter +[lambda-expression]: https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions [right-shift-operator]: https://www.geeksforgeeks.org/software-engineering/right-shift-operator-in-programming/ +[sentinel-value]: https://python-patterns.guide/python/sentinel-object/ [sequence-count]: https://docs.python.org/3/library/stdtypes.html#sequence.count +[sum-built-in]: https://docs.python.org/3/library/functions.html#sum +[walrus-operator]: https://mathspp.com/blog/pydonts/assignment-expressions-and-the-walrus-operator diff --git a/exercises/practice/eliuds-eggs/.approaches/no-parameter-modification/content.md b/exercises/practice/eliuds-eggs/.approaches/no-parameter-modification/content.md deleted file mode 100644 index dbbe4ad2167..00000000000 --- a/exercises/practice/eliuds-eggs/.approaches/no-parameter-modification/content.md +++ /dev/null @@ -1,92 +0,0 @@ -# Loop Without Modifying the Parameter - -```python -from math import ceil, log2 - -def egg_count(display_value): - eggs = 0 - for bit_position in range(ceil(log2(display_value + 1))): - eggs += (display_value >> bit_position) & 1 - return eggs -``` - -This approach uses a loop with `range()` to iterate over all of the bits in `display_value`. - -To determine how many bits `display_value` has, this solution imports `ceil` and `log2` from the `math` module. -We then calculate the base 2 logarithm of `display_value` (plus 1) and round it up. -(Rounding up is neccessary because `range()` excludes the value of `` from its returned values.) - -Once we have the bit length of `display_value`, we feed this number into `range()` to make the `for-loop` iterate over all of `display_value`'s `bit_position`s. - -For each `bit_position`, we determine the value of the bit at that position by using the [right-shift operator][right-shift-operator] and the bitwise AND operator. -We do this by right-shifting `display_value` by `bit_position`, making the bit at `bit_position` become the least significant bit. -Then we use the bitwise AND operator with `1` to remove all bits that are not the least significant bit. - -~~~~exercism/note -You could also calculate the bit's value by using arithmetic operators instead of bitwise ones: - -```python -eggs += (display_value // (2 ** bit_position)) % 2 -``` -~~~~ - -Once we determine the bit's value, we increment `eggs` by that number. - -After the loop ends, we know that we have checked all of the bits in `display_value`, thus we return `eggs`. - - -## Variation #1: Using an `if` Statement - -```python -from math import ceil, log2 - -def egg_count(display_value): - eggs = 0 - for bit_position in range(ceil(log2(display_value + 1))): - if display_value & (1 << bit_position): - eggs += 1 - return eggs -``` - -In this variant, the loop uses an `if` statement to check if the digit at `display_value` is `1`. - - -## Variation #2: Using `sum()` with a Generator Expression - -```python -from math import ceil, log2 - -def egg_count(display_value): - return sum( - (display_value >> bit_position) & 1 - for bit_position in range(ceil(log2(display_value + 1))) - ) -``` - -This variant is actually a one-liner, it is just split up here for readability. -Here, we replace the `for-loop` with a [generator expression][generator-expression] and use [`sum()`][sum-built-in] to collect the values into the result. - - -## Variation #3: Manually Tracking the Place Value - -```python -def egg_count(display_value): - eggs = 0 - place_value = 1 - while place_value <= display_value: - if display_value & place_value: - eggs += 1 - place_value <<= 1 - return eggs -``` - -This variant avoids `import`s by manually tracking the `place_value` of the current bit position. -This way, the `while-loop` can end when `place_value` becomes greater than `display_value`. - -The operations in the loop are rather similar to the "using an `if` statement" variant. -The main differences are not having to calculate the `place_value` from the bit position, and having to manually progress the iteration by left-shifting `place_value` by `1` (which is the same as multiplying `place_value` by `2`). - - -[generator-expression]: https://dbader.org/blog/python-generator-expressions -[right-shift-operator]: https://www.geeksforgeeks.org/software-engineering/right-shift-operator-in-programming/ -[sum-built-in]: https://docs.python.org/3/library/functions.html#sum diff --git a/exercises/practice/eliuds-eggs/.approaches/no-parameter-modification/snippet.txt b/exercises/practice/eliuds-eggs/.approaches/no-parameter-modification/snippet.txt deleted file mode 100644 index b2a163f2f28..00000000000 --- a/exercises/practice/eliuds-eggs/.approaches/no-parameter-modification/snippet.txt +++ /dev/null @@ -1,7 +0,0 @@ -from math import ceil, log2 - -def egg_count(display_value): - eggs = 0 - for bit_position in range(ceil(log2(display_value + 1))): - eggs += (display_value >> bit_position) & 1 - return eggs \ No newline at end of file diff --git a/exercises/practice/eliuds-eggs/.approaches/parameter-modification/content.md b/exercises/practice/eliuds-eggs/.approaches/parameter-modification/content.md deleted file mode 100644 index 78a8d0fcd8f..00000000000 --- a/exercises/practice/eliuds-eggs/.approaches/parameter-modification/content.md +++ /dev/null @@ -1,164 +0,0 @@ -# Modify the Parameter in a Loop - -```python -def egg_count(display_value): - eggs = 0 - while display_value: - eggs += display_value % 2 - display_value //= 2 - return eggs -``` - -This approach uses a `while-loop` to count up all of the ones. -In the loop, we increment `eggs` by `display_value % 2`. -This adds the least significant bit (the rightmost digit in the binary representation) of `display_value` to `eggs`. - -Next, we divide `display_value` by `2`, discarding any remainder. -This essentially removes the least significant bit of `display_value`, setting up `display_value` for processing the next bit. - -The loop repeats until `display_value` reaches `0` (which indicates that we have no more bits to check), and then we return `eggs`. - - -## Variation #1: Using Boolean Operators - -```python -def egg_count(display_value): - eggs = 0 - while display_value > 0: - if display_value % 2 == 1: - eggs += 1 - display_value //= 2 - return eggs -``` - -This is essentially just a more verbose formulation of the previous version. -Instead of relying on Python converting `int`s to `bool`s, this solution manually compares `display_value` to `0`. -It also uses an `if` statement to check if `eggs` should be incremented by `1`, instead of directly using the result of `display_value % 2`. - -Even though this variant is more verbose than the others, some may consider it to be more readable. - - -## Variation #2: Using Bitwise Operators - -```python -def egg_count(display_value): - eggs = 0 - while display_value > 0: - eggs += display_value & 1 - display_value >>= 1 - return eggs -``` - -This variant replaces the modulo (`%`) and floor division (`//`) with [bitwise operators][bitwise-operators]. -`&` is the bitwise AND operator, which results in a number whose binary representation only has ones where _both_ of its arguments has ones. -(All other bits are zeros.) - -For example, if we used the numbers `3` (`11` in binary) and `1` (`1` in binary), we get `1`: - -```python -0b011 & 0b001 -#=> 0b001 -``` - -This is because the only bit in both numbers that is `1` is least significant bit. -This property lets us extract the least significant bit of `display_value` by using `display_value & 1`. - -For the next step, we use `>>`, the [right-shift operator][right-shift-operator]. -The expression `a >> b` shifts all of `a`'s bits to the right by `b` places, and returns the resulting number. - -For example, if we used the numbers `5` (`101` in binary) and `1`, we get `2` (`10` in binary): - -```python -0b101 >> 1 -#=> 0b010 -``` - -You can see how `& 1` and `>>= 1` perform the same function as the `% 2` and `//= 2` used in earier variants. - - -## Variation #3: Using a `list` - -```python -def egg_count(display_value): - egg_positions = [] - - while display_value: - egg_positions.append(display_value % 2) - display_value //= 2 - - return egg_positions.count(1) -``` - -Here, we append the binary digits to a `list` and then count the number of ones using [`list.count()`][sequence-count]. -This solution would make sense if the positions of the eggs mattered, but since we only need the amount here, tracking the positions just adds unecessary overhead. - - -## Variation #4: Using `divmod()` - -```python -def egg_count(display_value): - eggs = 0 - while display_value: - display_value, remainder = divmod(display_value, 2) - eggs += remainder - return eggs -``` - -This variant uses the [`divmod()`][divmod-built-in] built-in instead of `%` and `//`. -(For `int` arguments, `divmod(a, b)` returns a [`tuple`][concept-tuples] of `(a // b, a % b)`.) - -In the loop, we use `divmod(display_value, 2)` to get both the quotient and the remainder of the division. -The `tuple` returned by `divmod()` is [unpacked][concept-unpacking-and-multiple-assignment] into `display_value` and `remainder` using [multiple assignment][concept-unpacking-and-multiple-assignment]. -Then, we increment `eggs` by `remainder`. - -As `display_value` is updated in the multiple assignment expression, we don't need to do anything else inside the loop. -Just like the previous variations, the loop will continue until `display_value` reaches 0, and then we return `eggs`. - - -## Variation #5: Overcomplicated One-Liner - -~~~~exercism/caution -This approach is not idiomatic and can be quite confusing. -It is only provided here to show how one could apply various advanced techniques to turn this approach into a one-liner. -~~~~ - -```python -def egg_count(display_value): - return sum( - (value % 2, display_value := value // 2)[0] - for value in iter(lambda: display_value, 0) - ) -``` - -This variation uses [the `sum()` built-in][sum-built-in], a [generator expression][generator-expression], a [`lambda` expression][lambda-expression], and a [walrus operator (`:=`)][walrus-operator] to reduce the solution to a one-liner. -The line is only broken up here for readability. - -Here, the `while-loop` is converted into a generator expression, with `sum()` adding up the result of each iteration. -As the `while` keyword is not allowed in generator expressions, instead we iterate over an iterable with `for`. -This iterable is constructed from a `lambda` that returns `display_value`, with the [sentinel value][sentinel-value] set to `0`. -This means that [`iter()`][iter-built-in] returns an iterable that calls the `lambda` until the returned `display_value` equals `0`. - -For each iteration of the generator expression, we assign `value` to the return value of the `lambda`. -Then we construct a `tuple` with two elements, using `[0]` to get its first element and feed it to `sum()`. -That element is the least significant bit of `value`, which can be calculated via `value % 2` or `value & 1`, as shown in the previous variations. - -The second element is more complicated. -Here, we update `display_value`, cutting off the least significant bit (via `// 2` or `>> 1`) by using the walrus operator (`:=`). -The walrus operator acts like a simple assignment statement, except that it returns the right-hand value and it can be used anywhere that an expression can be used. -(See the [Python docs][assignment-expression-docs] for more details.) -Thus we can use walrus operator here to update `display_value` in the generator expression, then simply ignore the return value by only feeding the first element of the `tuple` to `sum()`. - - -[assignment-expression-docs]: https://docs.python.org/3/reference/expressions.html#assignment-expressions -[bitwise-operators]: https://www.w3schools.com/programming/prog_operators_bitwise.php -[concept-tuples]: https://exercism.org/tracks/python/concepts/tuples -[concept-unpacking-and-multiple-assignment]: https://exercism.org/tracks/python/concepts/unpacking-and-multiple-assignment -[divmod-built-in]: https://docs.python.org/3/library/functions.html#divmod -[generator-expression]: https://dbader.org/blog/python-generator-expressions -[iter-built-in]: https://docs.python.org/3/library/functions.html#iter -[lambda-expression]: https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions -[right-shift-operator]: https://www.geeksforgeeks.org/software-engineering/right-shift-operator-in-programming/ -[sentinel-value]: https://python-patterns.guide/python/sentinel-object/ -[sequence-count]: https://docs.python.org/3/library/stdtypes.html#sequence.count -[sum-built-in]: https://docs.python.org/3/library/functions.html#sum -[walrus-operator]: https://mathspp.com/blog/pydonts/assignment-expressions-and-the-walrus-operator diff --git a/exercises/practice/eliuds-eggs/.approaches/parameter-modification/snippet.txt b/exercises/practice/eliuds-eggs/.approaches/parameter-modification/snippet.txt deleted file mode 100644 index c3d5eeb7bf4..00000000000 --- a/exercises/practice/eliuds-eggs/.approaches/parameter-modification/snippet.txt +++ /dev/null @@ -1,6 +0,0 @@ -def egg_count(display_value): - eggs = 0 - while display_value: - eggs += display_value % 2 - display_value //= 2 - return eggs \ No newline at end of file From f8109898e137cb18b4f879e4ba3f61699e0b64d7 Mon Sep 17 00:00:00 2001 From: Yrahcaz7 <74512479+Yrahcaz7@users.noreply.github.com> Date: Thu, 18 Jun 2026 21:26:33 -0400 Subject: [PATCH 17/17] minor spelling, grammar, and formatting fixes also revert most additions to `convert-to-binary-string` variation 3, as agreed upon --- .../argument-modification/content.md | 4 ++- .../.approaches/built-in-bit-count/content.md | 17 ++++++------ .../eliuds-eggs/.approaches/config.json | 6 ++--- .../convert-to-binary-string/content.md | 26 +++++++------------ .../.approaches/helper-functions/content.md | 6 +++-- .../eliuds-eggs/.approaches/introduction.md | 19 +++++++------- .../no-argument-modification/content.md | 2 -- 7 files changed, 39 insertions(+), 41 deletions(-) diff --git a/exercises/practice/eliuds-eggs/.approaches/argument-modification/content.md b/exercises/practice/eliuds-eggs/.approaches/argument-modification/content.md index 58876690a78..812dee0306f 100644 --- a/exercises/practice/eliuds-eggs/.approaches/argument-modification/content.md +++ b/exercises/practice/eliuds-eggs/.approaches/argument-modification/content.md @@ -109,10 +109,12 @@ This variant uses the [`divmod()`][divmod-built-in] built-in instead of `%` and Within the loop, `divmod(display_value, 2)` is used to get both the quotient and the remainder of the division. The `tuple` returned by `divmod()` is [unpacked][concept-unpacking-and-multiple-assignment] into `display_value` and `remainder` using [multiple assignment][concept-unpacking-and-multiple-assignment]. -`eggs` is then incremented by `remainder`. +Then, `eggs` is incremented by `remainder`. As `display_value` is updated in the multiple assignment expression, we don't need to do anything else inside the loop. Just like the previous variations, the loop will continue until `display_value` reaches 0, and then we return `eggs`. + + ## Variation #5: Overcomplicated One-Liner ~~~~exercism/caution diff --git a/exercises/practice/eliuds-eggs/.approaches/built-in-bit-count/content.md b/exercises/practice/eliuds-eggs/.approaches/built-in-bit-count/content.md index 64584e894a4..5f5ba0dc5de 100644 --- a/exercises/practice/eliuds-eggs/.approaches/built-in-bit-count/content.md +++ b/exercises/practice/eliuds-eggs/.approaches/built-in-bit-count/content.md @@ -17,14 +17,14 @@ Instead, all of these are considered _representations_ or display formats of `in Even if a binary literal is declared with the `0b` prefix, Python stores it internally as type `int`: ```python ->>> 0b00110101 #<- 53 in binary +>>> 0b110101 # <- 53 in binary 53 ->>> type(0b00110101) +>>> type(0b110101) ->>> 0O65 #<- 53 in octal +>>> 0o65 # <- 53 in octal 53 ->>> type(0O65) +>>> type(0o65) ``` @@ -50,8 +50,8 @@ Though one could argue that this _technically_ doesn't use the built-in bit-coun egg_count = int.bit_count ``` -This solution is the shortest of them all, but it can also be rather confusing (_and does not follow the instructions_). -It also can throw what appears to be a non-related error: +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: ```python >>> egg_count(3.5) @@ -63,12 +63,13 @@ TypeError: descriptor 'bit_count' for 'int' objects doesn't apply to a 'float' o ``` This variant makes clever use of [function/method aliasing][function-aliasing], which creates a new name that refers to the existing `int.bit_count()` method. -This means when `egg_count(display_value)` is called, `int.bit_count(display_value)` is being used. +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()` becomes just another way of saying `.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!_). +This solution works because `int.bit_count()` is just another way of saying `.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][concept-classes: methods] or the [Official Python Classes Tutorial][class-method-objects-tutorial] for more detail on how `self` works. + [approach-convert-to-binary-string]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/convert-to-binary-string [bin-built-in]: https://docs.python.org/3/library/functions.html#bin [class-method-objects-tutorial]: https://docs.python.org/3/tutorial/classes.html#method-objects diff --git a/exercises/practice/eliuds-eggs/.approaches/config.json b/exercises/practice/eliuds-eggs/.approaches/config.json index 5e6072e4095..e0af7d64653 100644 --- a/exercises/practice/eliuds-eggs/.approaches/config.json +++ b/exercises/practice/eliuds-eggs/.approaches/config.json @@ -8,21 +8,21 @@ "uuid": "27fb20ed-a4c2-4f73-a8fc-86ba384c7b35", "slug": "argument-modification", "title": "Modify the Argument in a Loop", - "blurb": "Modify the parameter in a while-loop to determine the number of eggs.", + "blurb": "Modify the argument in a while-loop to determine the number of eggs.", "authors": ["yrahcaz7"] }, { "uuid": "65fd717c-0e50-444b-a4b2-b51862f1f810", "slug": "no-argument-modification", "title": "Loop Without Modifying the Argument", - "blurb": "Loop over the bits without modifying the parameter to calculate the number of eggs.", + "blurb": "Loop over the bits without modifying the argument to calculate the number of eggs.", "authors": ["yrahcaz7"] }, { "uuid": "df202fa9-3757-4808-a416-7ec3ee1e9680", "slug": "convert-to-binary-string", "title": "Convert to a Binary String", - "blurb": "Convert the parameter to a binary string and count its ones to determine the number of eggs.", + "blurb": "Convert the argument to a binary string and count its ones to determine the number of eggs.", "authors": ["yrahcaz7"], "contributors": ["BethanyG"] }, diff --git a/exercises/practice/eliuds-eggs/.approaches/convert-to-binary-string/content.md b/exercises/practice/eliuds-eggs/.approaches/convert-to-binary-string/content.md index 9f4b11c67ea..120c84c4ae6 100644 --- a/exercises/practice/eliuds-eggs/.approaches/convert-to-binary-string/content.md +++ b/exercises/practice/eliuds-eggs/.approaches/convert-to-binary-string/content.md @@ -2,7 +2,7 @@ ```python def egg_count(display_value): - binary_value = bin(display_value)[2:] #<- Slice off the first two characters. + binary_value = bin(display_value)[2:] # <- Slice off the first two characters. eggs = 0 for digit in binary_value: eggs += int(digit) @@ -10,7 +10,7 @@ def egg_count(display_value): ``` This approach uses [`bin()`][bin-built-in] to convert `display_value` to a binary string. -Next, the first two characters of the binary string are removed via slice, as the string has "0b" as a prefix before the binary digits. +Next, the first two characters of the binary string are removed via slicing, as the string has "0b" as a prefix before the binary digits. After the binary digits are obtained, this solution loops across all of them, turning each one into an `int` and adding it to `eggs`. This counts up all of the instances of "1" in the binary string, as 0 and 1 are the only valid binary digits. @@ -22,13 +22,13 @@ However, it does have the added overhead of converting to and from a string. ~~~~exercism/note There are three other Pythonic ways of obtaining a binary string. These strategies use the [string format specification][string-format-spec] in different ways. - -The first is to use an [`f-string`][f-string] + +The first is to use an [`f-string`][f-string]: ```python # This uses the 'binary' format code. binary_value = f"{display_value:b}" -``` +``` Another is to use [`str.format()`][str-format]: @@ -73,7 +73,7 @@ def egg_count(display_value): ``` Similar to the previous variant, this one uses `sum()` with a generator expression. -The main difference is that it avoids slicing & copying the binary string by using an `if` clause in the generator expression. +The main difference is that it avoids slicing and copying the binary string by using an `if` clause in the generator expression. This also avoids the overhead of calling `int()` on each digit. @@ -85,15 +85,9 @@ def egg_count(display_value): ``` This variant replaces the generator expression with a [list comprehension][list-comprehension]. -This way, it can use `len()` to get the number of ones (_which evaluate to True_), after the comprehension filters the other digits (_which evaluate to False_) out. - -Here, `True` is used for the list elements, but we could use any other value as well, as we only care about the length of the "1"s list. -`bool()` could also be used here, but would require that each digit be converted via `int()` before evaluating: +This way, it can use `len()` to get the number of ones after the comprehension filters out the other digits using an `if` clause. -```python -def egg_count(display_value): - return len([bool(int(digit)) for digit in bin(display_value)[2:]]) -``` +Here, `True` is used for the list elements, but we could use any other value as well, as we only care about the length of the list. ## Variation #4: Using `map()` Instead of a Generator Expression or List Comprehension @@ -106,7 +100,7 @@ def egg_count(display_value): Here, we directly [`map`][map-built-in] the elements of the binary string to `int()` without using a generator expression or a list comprehension. This variant is the most concise, but it may be not very comprehensible to those unfamiliar with functional programming. -It also somewhat hides the overhead that is incurred calling `int()` on every digit. +It also somewhat hides the overhead that is incurred by calling `int()` on every digit. ## Variation #5: Using `filter()` with a `lambda` @@ -117,7 +111,7 @@ def egg_count(display_value): ``` Another alternative to a generator expression (or list comprehension) is to use the [`filter()` built-in][filter-built-in] along with a [`lambda` expression][lambda-expression]. -However, the creation and repeated calling of the `lambda` adds unnecessary overhead to the solution and `filter()` typically runs slower than the equivalent list comprehension. +However, the creation and repeated calling of the `lambda` adds unnecessary overhead to the solution, and `filter()` typically runs slower than the equivalent list comprehension. ## Variation #6: Using `functools.reduce()` with a `lambda` diff --git a/exercises/practice/eliuds-eggs/.approaches/helper-functions/content.md b/exercises/practice/eliuds-eggs/.approaches/helper-functions/content.md index b9e7ef08f2e..7bc996007c4 100644 --- a/exercises/practice/eliuds-eggs/.approaches/helper-functions/content.md +++ b/exercises/practice/eliuds-eggs/.approaches/helper-functions/content.md @@ -30,7 +30,8 @@ First, `convert_to_binary()` is used to convert `display_value` to a binary stri Then, `count_ones()` is called to count the number of ones in that string. In this specific version of the approach, `convert_to_binary()` is implemented similarly to the [modify the argument in a loop][approach-argument-modification] approach. -The main differences are that the bits are converted to strings and concatenated (_rather being added together_), and that a [conditional expression][conditional-expression] (_also called a ternary operator_) is used to handle the edge case of a `0`. +The main differences are that the bits are converted to strings and concatenated (_rather than being added together_), and that a [conditional expression][conditional-expression] (_also called a ternary operator_) is used to handle the edge case of a `0`. + ~~~~exercism/note Here, the [`or` operator][boolean-operations-default-or] could be used instead of a conditional expression: @@ -50,7 +51,7 @@ The only difference is that it takes the binary string as an argument rather tha Though breaking a problem up into helper functions may facilitate code reuse, here it adds unnecessary overhead to the solution. This approach is also complicated by additional edge cases, such as making `convert_to_binary()` return "0" instead of an empty string when given the number `0`. -The edge case of negative numbers is also not handled, and doing so would complicate the solution even further: +Additionally, the edge case of negative numbers is not handled, and doing so would complicate the solution even further: ```python def convert_to_binary(decimal_value): @@ -69,6 +70,7 @@ def convert_to_binary(decimal_value): Due to these scenarios, one may decide to forego handling all the edge cases. However, when your future self (_or someone else_) tries to reuse the function, edge cases could produce errors or unexpected results. + [approach-argument-modification]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/argument-modification [approach-convert-to-binary-string]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/convert-to-binary-string [conditional-expression]: https://docs.python.org/3/reference/expressions.html#conditional-expressions diff --git a/exercises/practice/eliuds-eggs/.approaches/introduction.md b/exercises/practice/eliuds-eggs/.approaches/introduction.md index 4ed44aa2076..120b34cb33a 100644 --- a/exercises/practice/eliuds-eggs/.approaches/introduction.md +++ b/exercises/practice/eliuds-eggs/.approaches/introduction.md @@ -1,20 +1,21 @@ # Introduction -There are many different approaches to solving the Eliud's Eggs exercise, among them are: +There are many different approaches to solving the Eliud's Eggs exercise. +Among them are: - Using a `while-loop` and modifying the function argument on each iteration - Looping over every binary digit _without_ modifying the function argument -- Converting the `int` argument into a binary string and counting the "ones" in it +- Converting the `int` argument into a binary string and counting the ones in it There are also some approaches that aren't recommended: -- Using the bit-count functionality from the Python standard library, as the instructions ask this challenge be solved "manually". +- Using the bit-count functionality from the Python standard library, as the instructions ask that this challenge be solved "manually". - Breaking up the counting process into many small functions, which can overcomplicate or slow the solution. ## General guidance -The goal of the Eliud's Eggs exercise is to count the number of ones in a [binary representation of a number][concept-numbers] (_e.g. the "filled gg slots" a chicken coop_). +The goal of the Eliud's Eggs exercise is to count the number of ones in a [binary representation of a number][concept-numbers] (_e.g. the "filled egg slots" a chicken coop_). In essence, this requires you to iterate through each "slot" or bit (binary digit) of the binary number in some way. The approaches below represent categories of the most common ways of accomplishing this. @@ -31,7 +32,7 @@ def egg_count(display_value): return eggs ``` -This approach uses a `while-loop` to count up the ones in the calculated binary equivalent of `display value`. +This approach uses a `while-loop` to count up the ones in the calculated binary equivalent of `display_value`. In the loop, we increment `eggs` by `display_value % 2`. This adds the least significant bit (_the rightmost digit in the binary representation_) of `display_value` to `eggs`. @@ -59,7 +60,7 @@ This solution uses a `for-loop` with `range()` to iterate over all of the bits i To determine how many bits `display_value` has, this solution imports `ceil` and `log2` from the `math` module. It then feeds this number into `range()` to make the `for-loop` iterate over all the `bit_position`s. -For each `bit_position`, we determine the value of the bit at that position by using the [right-shift operator][right-shift-operator] and the [bitwise AND][bit-AND] operator. +For each `bit_position`, we determine the value of the bit at that position by using the [right-shift operator][right-shift-operator] and the [bitwise AND][bitwise-operations] operator. Once we determine the bit's value, we increment `eggs` by that number. After the loop ends, we know that we have processed all bits in `display_value`, so we return `eggs`. @@ -79,7 +80,7 @@ def egg_count(display_value): ``` This approach uses [`bin()`][bin-built-in] (or some other means, such as an [`f-string`][f-string]) to convert `display_value` to a binary string. -The first two characters of the binary string are removed as "0b" is used as a prefix to the binary digits. +The first two characters of the binary string are removed, as "0b" is used as a prefix to the binary digits. After the binary digits are obtained, this solution loops through them, turning each one into an integer and adding it to `eggs`. This effectively counts up all of the instances of "1" in the binary string, as 0 and 1 are the only valid binary digits. @@ -139,7 +140,7 @@ The actual implementations of `convert_to_binary()` and `count_ones()` could use Though breaking the problem up into helper functions may facilitate code reuse, it also adds unnecessary overhead to the solution. It can also overcomplicate things, as you may need to consider additional edge cases, such as making `convert_to_binary()` return "0" instead of an empty string when given the number `0`. -If you do not handle all of these cases, when you (_or someone else_) tries to reuse the function later, they may get unexpected results, such as "0" being returned when a negative number in input. +If you do not handle all of these cases, when your future self (_or someone else_) tries to reuse the function, they may get unexpected results, such as "0" being returned when a negative number is input. For more details, check out the [helper functions][approach-helper-functions] approach. @@ -150,7 +151,7 @@ For more details, check out the [helper functions][approach-helper-functions] ap [approach-no-argument-modification]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/no-argument-modification [approach-argument-modification]: https://exercism.org/tracks/python/exercises/eliuds-eggs/approaches/argument-modification [bin-built-in]: https://docs.python.org/3/library/functions.html#bin -[bit-AND]: https://docs.python.org/3/library/stdtypes.html#bitwise-operations-on-integer-types +[bitwise-operations]: https://docs.python.org/3/library/stdtypes.html#bitwise-operations-on-integer-types [concept-numbers]: https://exercism.org/tracks/python/concepts/numbers [f-string]: https://docs.python.org/3/reference/lexical_analysis.html#f-strings [int-bit_count]: https://docs.python.org/3/library/stdtypes.html#int.bit_count diff --git a/exercises/practice/eliuds-eggs/.approaches/no-argument-modification/content.md b/exercises/practice/eliuds-eggs/.approaches/no-argument-modification/content.md index 03dd6e8a54a..410e15596d0 100644 --- a/exercises/practice/eliuds-eggs/.approaches/no-argument-modification/content.md +++ b/exercises/practice/eliuds-eggs/.approaches/no-argument-modification/content.md @@ -1,6 +1,5 @@ # Loop Without Modifying the Argument - ```python from math import ceil, log2 @@ -41,7 +40,6 @@ After the loop ends, we know that we have checked all bits in `display_value`, t ## Variation #1: Using an `if` Statement - ```python from math import ceil, log2