I am trying to reverse the order of bits using divide and conquer. Here is my approach
def reverseBits(n, p, q):
if len(n) <= 1:
return
mid = (p+q)//2
return reverseBits(n[mid+1:q+1], mid, q) + reverseBits(n[p:mid+1], p, mid)
Here is the data I used to call the function:
n = list(str(10110))
print(reverseBits(n, 0, len(n)-1))
But this always gives me the following error:
TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'
How can I fix this problem?
In the reverseBits(n, p, q) method, the base condition returns nothing, that is, "None", which results. Your base condition should return a list with reversed value.
if len(n) <= 1:
return
You also send the new smaller list in each recursive call but the mid value varies based on the original list. Sending the entire list in each recursive call should help fix that. I have also changed the base condition to "p >= q" to end the recursive call when the left sub list overlaps the right sub list This should work
def reverseBits(n, p, q):
if p >= q:
return n[p]
mid = (p+q)//2
return reverseBits(n, mid+1, q) + reverseBits(n, p, mid)
n = list(str(10110))
print(reverseBits(n, 0, len(n)-1))