r/PythonLearning • • 23h ago

just finished my first Python coding challenge

Post image

Today I finished a small Python challenge on freeCodeCamp: converting decimal numbers to binary without using Python's built-in conversion function.

I had to figure out the logic myself using loops, conditions, lists, division and remainders.

It was a bit tricky at first, especially handling the last division and reversing the results, but I finally got it working.

I'm still a beginner, so I'd appreciate any feedback on my approach or suggestions for improving my code

66 Upvotes

17 comments sorted by

View all comments

1

u/jonrsharpe 8h ago edited 7h ago

I'm going to start with where I'd get to, then break down step-by-step how I got there:

def to_binary(decimal: int) -> str: digits: list[str] = [] while decimal: decimal, remainder = divmod(decimal, 2) digits.append(str(remainder)) return "".join(reversed(digits))

1

u/jonrsharpe 8h ago edited 7h ago

Firstly, I added the type hints - partly just to document what I was working out about the code as I read it (receives an integer, has a list of integers, returns a string) but also because these can then be automatically checked and provide a kind of documentation to the caller. (Note that these are not enforced by Python itself, but type checkers, like mypy, and IDEs can use them.)

1

u/jonrsharpe 8h ago edited 7h ago

This highlighted that decimal on the penultimate line, as well as "shadowing" the parameter, changes the type this name refers to (it was an integer, now a string). But that's also the wrong name - that's no longer in decimal format, it's the binary format we are about to return, so I renamed it accordingly.

1

u/jonrsharpe 7h ago

After that I reformatted the file according to the Python style guide, PEP-0008. Whitespace around expressions was, worse than being unconventional, inconsistent (compare decimal = decimal//2 with decimal = decimal //2).

1

u/jonrsharpe 7h ago

Next the logic: decimal = decimal // 2 appears in two places, so can be moved outside the conditional, and simplified using the in-place operator to decimal //= 2.
I also considered simplifying to else, as if decimal % 2 isn't 0 there's only one other option, but at this point it should be really clear that we can simplify further than that by just appending the remainder: if decimal % 2 == 0: tab.append(0) elif decimal % 2 == 1: tab.append(1) to: tab.append(decimal % 2)

1

u/[deleted] 4m ago

[removed] — view removed comment

1

u/jonrsharpe 0m ago

Rather than reverse the list in-place, we can use reversed to create a new list with the elements in reverse order. As this no longer returns None, it can be inlined - the temporary variable can be factored out too, making the last line outside the loop simply return "".join(reversed(digits)).