A BIT of This OR That Alternative

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

Any better way to solve it ?



print bin(0b1110 | 0b101)
m = int(raw_input("any no. pls: "))
n = int(raw_input("other no. pls: "))
m = str(bin(m))
n = str(bin(n))
m = m[2:] 
n = n[2:]
if len(m) < len(n):
    m = ("0" * (len(n) - len(m))) + m[::-1]
    
    
elif len(n) < len(m):
    n = ("0" * (len(m) - len(n))) + n[::-1]
    
    
k = ""
j = 0
for i in m:
    if (i == "0" and n[j] == "1") or (i == "1" and n[j] == "0") or (i == "1" and n[j] == "1"):
        k += "1"
    else:
        k += "0"
    j += 1
        
print "".join(k)  



print bin(0b1111)

@gigawhiz67659, above is enough to solve it!

quit impressive to do it without the | bitwise operator. Great challenge by the exercise, don’t you think?

personally i would change this:

if (i == "0" and n[j] == "1") or (i == "1" and n[j] == "0") or (i == "1" and n[j] == "1"):

there are 4 possible cases, you written 3 of them here, you could reverse it? check if i and n[j] both equal zero, if so, add 0 to k, else add one

you could also use zip:

for i, j in zip(m,n): 
   print i, j

this allows you to loop over two list/strings at the same time.

you can take the slice at string conversion:

m = str(bin(m))[2:]

the purpose of the slice is to cut off 0b but i would add it at the end again:

print "0b" + "".join(k)

if you then enter 14 and 5, the exercise will approve.

@karray, this was an additional challenge from the exercise:

Try to do it on your own without using the | operator if you can help it.

of course you can do it with |, but writing the program without is a great challenge for your coding skill

1 Like

i did not use this… |

no, you are right, you did not. But this code gigawhiz wrote, will work for any number, it is cool and it emulates the | bit-wise operator.

your solution is just enter a fixed number to pass the exercise, not helping gigawhiz

gigawhiz is asking if there’s a shorter alternate code… :expressionless:

yes, a shorter way to emulate the | bit-wise operator, not on how to pass the exercise.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.