python - What is wrong with this alternative bitwise operator function? -
n1 = "0b1110" n2 = "0b101" def bitwise_or(num1, num2): diff1 = "" new_num1 = [] new_num2 = [] new_num = [] c in num1: new_num1.append(c) c in num2: new_num2.append(c) if len(num1) != len(num2): if len(num1) > len(num2): diff1 = "0" * (len(num1) - len(num2)) c in diff1: new_num2.append(c) if len(num1) < len(num2): diff1 = "0" * (len(num2) - len(num1)) c in diff1: new_num1.append(c) in range(len(new_num1)): if new_num1[i] == "1" or new_num2[i] == "1": new_num.append("1") else: new_num.append(new_num1[i]) final = "".join(new_num) return final print(bitwise_or(n1,n2))
i made function should replicate | operation, it's not working correctly. correct answer suppose print out 0b1111, don't understand how gets that.
when pad zeros should insert them before bits of number.
0b1
means number 1
. if try or 0b11101
cannot change 0b10000
have pad 0b00001
.
also handling of 0b
works isn't clear not readable. "happen" work because when loop through 0b11101
, 0b00001
first character 0
in both , end in new_num.append(new_num1[0])
, b != '1'
, hence if
test fails , b
gets inserted in new_num
.
i suggest remove prefix @ beginning , add @ end. simplifies correct padding.
by way: convert string list of characters can call list
on it:
new_num1 = list(num1)
moreover add number of elements list can use extend
method, or use slice assignment:
>>> my_list = list('hello') >>> my_list ['h', 'e', 'l', 'l', 'o'] >>> my_list.extend('world') >>> my_list ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']
so code become this:
def bitwise_or(num1, num2): new_num1 =list(num1) new_num2 = list(num2) if len(num1) > len(num2): new_num2[2:2] = '0' * (len(num1) - len(num2)) elif len(num1) < len(num2): new_num1[2:2] = '0' * (len(num2) - len(num1)) new_num = [] c1, c2 in zip(new_num1, new_num2): if c1 == "1" or c2 == "1": new_num.append("1") else: new_num.append(c1) return ''.join(new_num)
however i'd rather make explicit handling of prefix:
def bitwise_or(num1, num2): new_num1 =list(num1[2:]) new_num2 = list(num2[2:]) if len(num1) > len(num2): new_num2[:0] = '0' * (len(num1) - len(num2)) elif len(num1) < len(num2): new_num1[:0] = '0' * (len(num2) - len(num1)) new_num = [] c1, c2 in zip(new_num1, new_num2): if c1 == "1" or c2 == "1": new_num.append("1") else: new_num.append(c1) return '0b' + ''.join(new_num)
Comments
Post a Comment