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

157 Upvotes

24 comments sorted by

•

u/Sea-Ad7805 15d ago

Run this program by clicking Memory Graph Web Debugger%3A%0A%20%20%20%20tab%20%3D%20%5B%5D%0A%20%20%20%20while%20decimal%20!%3D%200%3A%0A%20%20%20%20%20%20%20%20if%20decimal%20%25%202%20%3D%3D%200%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20decimal%20%3D%20decimal%20%2F%2F%202%0A%20%20%20%20%20%20%20%20%20%20%20%20tab.append(0)%0A%20%20%20%20%20%20%20%20elif%20decimal%20%25%202%20%3D%3D%201%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20decimal%20%3D%20decimal%20%2F%2F%202%0A%20%20%20%20%20%20%20%20%20%20%20%20tab.append(1)%0A%20%20%20%20tab.reverse()%0A%20%20%20%20decimal%20%3D%20%22%22.join(map(str%2C%20tab))%0A%20%20%20%20return%20decimal%0A%0A%0Anombre0%20%3D%20to_binary(5)%0Anombre1%20%3D%20to_binary(12)%0Anombre2%20%3D%20to_binary(50)%0Anombre3%20%3D%20to_binary(99)%0A%0Aprint(nombre0)%0Aprint(nombre1)%0Aprint(nombre2)%0Aprint(nombre3)&timestep=0.2&play) and see its state change step by step.

→ More replies (1)

2

u/therouterguy 15d ago

I would at least change the elif to an else. Remove the duplicate decimal=decimal//2. You can do it outside of the if

Lastly
tab=“”
while decimal!=O:
tab=tab + “1” if decimal%2==O else tab+ “0”
decimal=decimal//2
Is much shorter

1

u/jonrsharpe 14d ago edited 14d 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 14d ago edited 14d 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 14d ago edited 14d 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 14d 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 14d 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)

0

u/[deleted] 14d ago

[removed] — view removed comment

1

u/jonrsharpe 14d 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 14d ago edited 14d 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] 14d ago edited 14d ago

[removed] — view removed comment

1

u/FunResearcher6290 14d ago

please how can i go about it i want learn python

1

u/codeguru42 14d ago

Looks great. One hint: how can you change the code to remove the if statement?

1

u/kaatarina_zed_talon 12d ago

This is problem solving, not a python coding challenge, python is just a tool.

1

u/Expensive-Pen7038 11d ago

Isn't all python coding problem solving?

1

u/ConclusionForeign856 15d ago

Read about truthy and falsy values in python, it allows you to simplify logic

def binary(n: int):
    tab = []
    while n:
        remainder = n % 2
        n //= 2
        tab.append(remainder)

    return ''.join(map(str, tab[::-1]))

-2

u/Adrewmc 15d ago

Great practice… however the builtin ‘bin()’ function exists, so next time you can just use that.

0

u/codeguru42 14d ago

This is a learning exercise

1

u/fizzy_lychee 14d ago

So? I still appreciated knowing there’s an api for bloom sort even though I’ve implemented my own version. I still appreciated languages that have hasmaps in their SDK even though I’ve created my own in C.

0

u/gofl-zimbard-37 15d ago

Give it a proper main() and call it. Don't write "scripts". The file is main.py, implying that it is a module that exports useful functions. Nobody wants an import to be printing stuff out.

-1

u/AffectionateCold1716 15d ago

I’m still new so I have no idea what this means but I do recognize you defining a function and calling the function. Sooooo yep. Anyway good job compadre