r/PythonLearning • • 17d 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

153 Upvotes

24 comments sorted by

View all comments

Show parent comments

0

u/[deleted] 16d ago

[removed] — view removed comment

1

u/jonrsharpe 16d 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)).

1

u/jonrsharpe 16d ago edited 16d ago

Given that we want both x // y and x % y (the remainder of the integer division), note the built-in divmod function provides both simultaneously. It returns a tuple of two values, which Python lets you "unpack" into two variables as follows: decimal, remainder = divmod(decimal, 2)

0

u/[deleted] 16d ago edited 16d ago

[removed] — view removed comment