Issue
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?
Solution
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)
Answered By - Will Da Silva
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.