The function is supposed to print out all the bit vetcors that are n bits long and contain k 1's. The problem is that I can not give an empty list as an input to the function.
I am working on Ubuntu and using Python 3.6. I have also tried to use a non empty list like [1], but this throws the same error. When trying to find a length of an empty list outside of the function, it works as it should: len([]) returns 0.
Here is my code:
def bitvector(n, k, vektor):
if len(vektor) == n:
if vektor.count(1) == k:
print(vektor)
bitvector(n, k, vektor.append(0))
bitvector(n, k, vektor.append(1))
bitvector(1, 2 , [])
EDIT:
def bitvector(n, k, vektor):
if len(vektor) > n:
return
if len(vektor) == n:
print("test")
if vektor.count(1) == k:
print(vektor)
return
bitvector(n, k, vektor.append(1))
bitvector(n, k, vektor.append(0))
bitvector(1, 2 , [])
It is supposed to get the length of the list, but instead it throws the following error:
TypeError: object of type 'NoneType' has no len()
Since I was not limited to use a certain Type, the I chose to use a string instead of the list.
def bitvector(n, k, vektor):
vektor_list = list(vektor)
if len(vektor) > n:
return
if len(vektor) == n:
if vektor_list.count("1") == k:
print(vektor)
return
bitvector(n, k, vektor + "0")
bitvector(n, k, vektor + "1")
EDIT, optimized my code:
def bitvector(n, k, vektor):
vektor_list = list(vektor)
if vektor_list.count("1") > k:
return
if len(vektor) == n:
if vektor_list.count("1") == k:
print(vektor)
return
else:
return
bitvector(n, k, vektor + "0")
bitvector(n, k, vektor + "1")