8. A BIT of This OR That - Alternative Solution!


#1


https://www.codecademy.com/en/courses/python-intermediate-en-KE1UJ/1/3?curriculum_id=4f89dab3d788890003000096

Nothing wrong with my code (that i know of), but the instructions sort of offers you the challenge of doing this operation outside of the built in bitwise function OR. I wanted to test what I had learned, so I spent the better part of an hour figuring out how to make this work. I would love to hear feedback on how I could have done this better.

Also, Hi All! This website is awesome!

EDIT:: so i apparently misunderstood the instructions when it said "try to do this on your own". Lol, i had fun doing it anyways.


#print bin(14 | 5) # commented out for the following code to be able to fail if i get it wrong

fourteen = "1110"
five  = "101"


combined = [fourteen, five]

def bitwise_OR(fourteen, five):
    one = "1"
    together = []
    different_length = abs(len(five) - len(fourteen))
    final = ""
    
    if len(fourteen) > len(five):
        for i in fourteen:
            together.append("0")
        five = ("0" * different_length) + five
    elif len(five) > len(fourteen):
        for i in five:
            together.append("0")
        fourteen = ("0" * different_length) + fourteen
    
    for i, c in enumerate(five):
        if c == one:
            together[i] = c
    for i, c in enumerate(fourteen):
        if c == one:
            together[i] = c        
    final = "0b" + final.join(together)
    return final
    
print bitwise_OR(fourteen, five)


#2

I interpreted those instructions to mean "Do it in your head" or "Use a pen and paper to figure it out". The purpose being to get your head fully wrapped around the concept of bitwise operations.


#3

Hey! I am trying to understand this. Here is my interpretation:

For the given pair of numbers, you will (1) check to see which is larger in length; (2) for the larger number, you will create a list of "0" for each digit of the number. (3) then you will add "0" before the shorter number, as many times as the difference between the two lengths.
Next, (4) for every digit in both numbers, if a digit is to equal "1", then change the equivalent digit in the created list to 1. (5) Lastly, convert the final list into binary by adding "0b" followed by each number in the list.

Great stuff! Writing out each step helped me understand it too :slight_smile: Let me know if I was off the mark at all.


#4

Hey all! I think you can just build the final list as you compare the values of the two binary numbers rather than building the final list with 0's first and then replacing them with 1's as you do the comparison. Here is how I did it with a bit less of code and for any two binary numbers input by the user, but it's essentially the same.

@samsara330 Your interpretation looks correct!

def bitwise_or(num1, num2):

    final_list = []
    difference = abs(len(num1)-len(num2))

    if len(num1) >= len(num2):
        num2 = '0' * difference + num2
    else:
        num1 = '0' * difference + num1

    num2_list = list(num2)
    num1_list = list(num1)

    for i in range(len(num1_list)):
        if num1_list[i] == '1' or num2_list[i] == '1':
            final_list.append('1')
        else:
            final_list.append('0')

    print '0b' + ''.join(final_list)

bitwise_or(raw_input('Please enter the first binary # here: '), raw_input('Please enter the second binary # here: '))

#5

Hi I am pretty new here! Been on codecademy less than 2 weeks, and this is my first post in a forum. Hoping to revive this old conversation...

My solution seems pretty similar in approach to the above. I just wondered how it compares.

Mine takes in num1 and num2 as strings with the prefix "0b".

Is it better to build the result as you go (like in the final_list of @kenfucius) than to have a working result whose digits you change as you compare the two inputs?

def thisorthat(num1, num2):
a = list(num1)[2:]
b = list(num2)[2:]

if len(b) <= len(a):
    shorter = list(b)
    longer = list(a)
else:
    shorter = a
    longer = b
    
s = len(shorter)
l = len(longer)

aorb = longer

for i in range(s):
    if shorter[s-1-i] == "1":
        aorb[l-1-i] = "1"
return "0b" + "".join(aorb)

#6

My solution seems a little comlex to the above but similar
Here's it:

def bitor(a,b):
    stra = str(a)[2:]
    strb = str(b)[2:]
    if len(stra) > len(strb):
        strb = '0'*(len(stra)-len(strb))+strb
    elif len(strb) > len(stra):
        stra = '0'*(len(strb)-len(stra))+stra
    aorb = ''
    for i in range(len(stra)):
        if stra[i] == '0' and strb[i] == '0':
            aorb += '0'
        else:
            aorb += '1'
    return bin(int(aorb,2))

a = bin(int(raw_input("First number:")))
b = bin(int(raw_input("Second number:")))
print bitor(a, b)

#7

this is my solution: it's probably not optimal, but it works. what do you think? It's actually printing a binary, not just a string that looks like one. some of the solutions above are doing that. not sure if that counts or not.

def counting_bits(a,b):
    a = '{:b}'.format(a)
    b = '{:b}'.format(b)
    a = a.zfill(len(b))
    b = b.zfill(len(a))
    ans = ['1' if a[i] != b[i] else '0' for i in range(len(a))]
    ans = '0b' + ''.join(ans)
    ans = int(ans, 2)
    return bin(ans)
print counting_bits(0b1110,0b101)

edit: made some corrections


#8

This is my alternative solution:

def bitwise_or(num1, num2):
    str_bits = ""
    while (num1 != 0 or num2 != 0):
        value = 0x1 if (num1 & 0x1) == 0x1 or (num2 & 0x1) == 0x1 else 0x0
        str_bits = str(value) + str_bits
        num1 >>= 1
        num2 >>= 1
    return "0b" + str_bits

print bitwise_or(0b1110, 0b101)