Reputation: 22634
I'm trying to get all possible permutations of dice rolls. Below is my code.
def PrintAllPerms(n, arr, str_):
if (n == 0):
print str_
arr.append(str_)
return arr
else:
for i in ["1","2","3","4","5","6"]:
str_ = str_ + i
arr = PrintAllPerms(n-1,arr,str_)
str_ = str_[:-1]
PrintAllPerms(2,[],"")
But I got following error after printing only this much.
PrintAllPerms(2,[],"")
11
12
13
14
15
16
21
<ipython-input-7-d03e70079ce2> in PrintAllPerms(n, arr, str_)
2 if (n == 0):
3 print str_
----> 4 arr.append(str_)
5 return arr
6 else:
AttributeError: 'NoneType' object has no attribute 'append'
Why does it print until 2,1 then?
And what is the correct to way to deal with this?
Upvotes: 1
Views: 789
Reputation: 7040
You need to return arr
in the else branch.
def PrintAllPerms(n, arr = [], str_ = ''):
if n == 0:
print(str_)
arr.append(str_)
return arr
else:
for i in ['1','2','3','4','5','6']:
str_ = str_ + i
arr = PrintAllPerms(n-1,arr,str_)
str_ = str_[:-1]
return arr
PrintAllPerms(2)
Upvotes: 2
Reputation: 526593
This is due to the following line:
arr = PrintAllPerms(n-1,arr,str_)
Your PrintAllPerms
function doesn't return anything if it takes the else
path, and thus is treated as if it's returning None
. So arr
gets set to None
.
Upvotes: 3