Bummer! You have been redirected as the page you requested could not be found.

Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

binary converter in python3

I have a problem i think that my algorithm for converting is good but after input program is just doing nothing i dont know where is a problem.

def converter():

start = True
while start:
    number_sys = input()
    x = number_sys.split(" ")
    try:
        number = int(x[0])
        system = int(x[1])
    except ValueError:
        break

    if system == 2:
        Num2 = 0
        power = 0
        sys = 10
        while number > 0:

            Num2 += 2 ** power * (number % sys)
            number //= sys
            power += 1
            return Num2, sys
    elif system == 10:
        Num2 = 0
        power = 0
        sys = 2
        while x[0] > 0:

            Num2 += 10 ** power * (x[0] % sys)
            x[0] //= sys
            power += 1
            return Num2, sys
    else:
        start = False

converter()

3 Answers

EDIT SOLUTION

Igor Bochenek

def converter(number, base):
    def convert_to_base_10(val):
        target_base = 10  # Target number base
        output_sum = 0  # Initial value for output sum
        expo = 0  # Initial exponent
        digits = [int(x) for x in str(val)] # Convert the base 2 number to an array of integer
        digits.reverse()  # Reverse the array.

        for d in digits:  # For each bit...
            if d != 0:  # If it's not 0, we will get the value relative to the position
                output_sum += pow(2, expo)  # Add it to the output
            expo += 1  # Move to the next bit

        return output_sum, target_base

    def convert_to_base_2(val):
        target_base = 2  # Target number base
        binary = []
        while True:
            reminder = val % target_base
            val = int(val / target_base)  # Force int truncation
            binary.append(reminder)  # Put the digit in the list

            if val > 0:
                continue  # We still need to divide
            else:
                break  # Nothing else to do

        binary.reverse()

        binary = list(map(lambda x: str(x), binary))  # Transform the int to an array of str

        return int(''.join(binary)), target_base

    if base == 2:
        return convert_to_base_10(number)
    elif base == 10:
        return convert_to_base_2(number)

if __name__ == '__main__':
    print("Converting from binary to decimal")
    print(converter(101110011, 2))

    print("Converting from decimal to binary")
    print(converter(708, 10))

This is how I would implement it. I wrote some comments, let me know if you have questions.

-Dan

in this program in input first number is (decimal or binary) and second number is current system for this number(2 = binary, 10 = decimal) in output there shuld be depending of the first number (if in input decimal > output binary and viceversa) also system output shoul change in output but something is not working still even if function is now working

So what you want to do is convert numbers from base 10 to base 2 or base 2 to base 10?

It took me some time before a I get that but now its clear thank you soo much now I have to add input and some changes but most important is that now its working thanks again, Cheers!

I have one more question im not quit sure how is that lambda function working could you explain how it works ?

Igor Bochenek of course! So lambdas have different names: lambdas/closures/anonymous functions. They all mean the same. A lambda it's just a function without an identifier, that is a name. Although you can bind names to a lambda, at it's heart it doesn't have a name. That's why the name of "anonymous". In Python functions are first class citizens and what that all means it that you can treat them as types. With that being said, you can pass functions are arguments to other functions or a function from another function. Are you following? It might be confusing, if not keep reading.

def do_something_unknown(elements, op):
    new_list = []
    for e in elements:
        new_list.append(
            op(e)
        )
    return new_list

Here you can see that do_something_unkown takes two arguments, a list of elements and callable object, that it's a function.

Now we can use it like this:

numbers = [2, 3, 4]

def multi_by_two(n):
    return n * 2

new_numbers = do_something_unkown(numbers, multi_by_two)
print(new_numbers)
#  Output [4, 6, 8]

Here you can see that we define multi_by_two that takes an argument and just return the argument times 2. Then because function can be passed as arguments we just pass multi_by_two to do_something_unknown and as you might figure do_something_unkown calls multi_by_two inside. Are you following? If so keep reading. Let's get into lambdas:

numbers = [2, 3, 4]

new_numbers = do_something_unkown(numbers, lambda n: n * 2)
print(new_numbers)
#  Same output: [4, 6, 8]

As you see the lambda takes n as argument and multiply it by two. Same thing that multi_by_two is doing. The lambda will be bind to op inside do_something_unkown and it will be called inside the for loop. This is the concept, but if you want to learn the semantics of Python's lambdas check this link http://www.secnetix.de/olli/Python/lambda_functions.hawk

By the way, the implementation of do_something_unkown its basically what the map function is doing.

I know it's a lot, but I hope this helped. If you want to learn more check this Kenneth Love's workshop https://teamtreehouse.com/library/functional-programming-with-python or this Pro course https://teamtreehouse.com/library/functional-python

-Dan

So tell me if i am wrong, lambda is diong same as multi_by_2 but we dont have to define an function we just can use lambda whaen we are calling main function yes ?

Okay i het it now thanks a lot Dan !

yes

In reality you are defining a function, because lambda is a function. They only thing that you are not doing is binding it to a identifier, that is a variable with a name. When you do:

def mult_by_2(n):
    return n * 2

and

mult_by_2 = lambda n: n *2

Then for both cases, you can do

mult_by_2(6)
# Output: 12

Input:

1010 2 Output:

10 10 Input:

4583 10 Output:

000100011110011 2

i wish output should be something like that