0

I want to define a function umklappen that takes in the dual representation of a number base 10 as a list and flip the bit 1->0 and 0->1. I ran into the problem that the type ntobasetwo(n,c) is of the class NoneType. I'm not sure why this is the case and how to get around this in my case.

# Funktion, die ganze Zahlen im Dezimalsystem als Zahlen im Dualsystem darstellt
import numpy as np
import math

# Decimal number is converted into binary by dividing the number successively by 2
# and printing the remainder in reverse order
def  ntobasetwo(n,c):
    binary = []
    while n!= 0:
        bit = n%2
        binary.insert(0, bit)
        n = n//2
    if len(binary)>c:
        binary = binary[0:c]
    print(binary)

bin_1248 = ntobasetwo(1248,5)

def umklappen(binList):
    for i in range(len(binList)):
        if binList[i] == 0:
            binList[i] = 1
        else:
            binList[i] = 0
    print(binList)

umklappen_bin_1248 = umklappen(bin_1248)
umklappen_bin_1248
Jung
  • 139
  • 6
  • 1
    You are using `print()`, not `return`; printing to the console is *not the same as returning a value*. Because `ntobasetwo()` never uses `return`, the default return value is `None`. – Martijn Pieters Oct 29 '19 at 11:02
  • The second parameter `c` to `ntobasetwo` results in dropping low-order bits. But I don't understand why you have that. – Booboo Oct 29 '19 at 11:18
  • @RonaldAaronson: most likely because they misunderstood in what order the bits are stored in `binary`; it should probably be `binary[-c:]`. – Martijn Pieters Oct 29 '19 at 11:30
  • And even so, `1248` is `0000010011100000` in binary, well beyond the maximum of 31 you can represent in 5 bits.. – Martijn Pieters Oct 29 '19 at 11:32
  • @MartijnPieters Even so, I don't believe the algorithm produces extra high-order 0 bits and there is ever a need for this. – Booboo Oct 29 '19 at 11:35
  • This function should check for negative values of `n` because `-1 // 2` -> -1` and you loop forever. – Booboo Oct 29 '19 at 11:38
  • @RonaldAaronson: well, you could argue that you might want to mask the input to a smaller range. But then I'd just pass in the masked value instead, don't make that function responsible for creating a list of bits *and* masking. – Martijn Pieters Oct 29 '19 at 11:40
  • But between that and pointing out that negative values are not handled we are just nitpicking here. The OP can learn all those things at a later time once they have mastered functions and return values. :-) – Martijn Pieters Oct 29 '19 at 11:41

0 Answers0