8. A BIT of This OR That - Improvement Suggestions


#1



https://www.codecademy.com/pt-BR/courses/python-intermediate-pt-BR-h8rkb/1/3?curriculum_id=53594ed4fed2a85327000001#


I wrote this code based on the values that the exercise gave and I passed, but I'd like to improve it to become useful with another values.
Any suggestions to do this without using advanced tools? I'd like to do it with only the knowledge that I have now.

b1 = list(raw_input('First number:'))
b2 = list(raw_input('Second number:'))
def or_function(x, y):
    for n in x:
        if n == '0':
            x.remove(n)
    for n in y:
        if n == '0':    
            y.remove(n)
    xtotal = x.count('1')
    ytotal = y.count('1')
    xy = x + y
    result = ''.join(xy)
    result = int(result, 2)
    while xtotal != ytotal:
        result >>= 1
        if xtotal > ytotal:
            ytotal += 1
        elif xtotal < ytotal:
            xtotal += 1
        else:
            break
    print bin(result)
or_function(b1, b2)


#2

It's very odd for a bitwise OR to accept a list and produce a string.
I suggest making it accept and return the same types, whether that's a list, string, or a number.
If you use a string then decide on whether you want to prefix it with 0b, or not.
It would also be far more useful to return the value instead of printing it, if you want to print the result, then call it and print the returned value.

To debug it, I suggest first testing your algorithm manually, for example with the input: 11110000 00001111 which should result in 11111111. And if you do get that result (your code doesn't) then you can start adding print statements after each action to see if it had the desired effect. Also note that you have a lot of code at the end of the function that has no effect on the final outcome - was that meant to do something important?

If you know how to carry out a bitwise OR-operation, then refer to that when considering what to change. Your program should probably be doing the same thing.


#3

Thanks for your answer.
The codes at the end of the function are to make x and y have the same size, but now I understand how to do it in a better way. Doing the XOR exercise I wrote the code below, I just changed some things to do the OR function.

x = raw_input('First number:')
y = raw_input('Second number:')
def or_function(x, y):
    x = str(x)[2:]
    y = str(y)[2:]
    result_list = []
    result = ''
    dif = (len(x)) - len(y)
    if len(x) > len(y) or len(x) < len(y):
        if dif > 0:
            y = ('0' * dif) + y
        else:
            x = ('0' * abs(dif)) + x
    for n in range(len(x)):
        if x[n] == '0' and y[n] == '0':
            result_list.append('0')
        else:
            result_list.append('1')
    result = '0b' + ''.join(result_list)
    return result
print or_function(x, y)

#4