Reputation: 13
I want to copy a list to another recursively in python. For that purpose, i have taken string as input, defined an empty list and send them to recursive function as lists, so that i can copy the list to another list. However, the error displays "NoneType" object has no attribute "append". What am i missing ? i have defined "S" as list in main(). If there are other recursive methods, they are welcomed.
Error shown:
line 35, in string_copy
return string_copy(k,s.append(k[i]),i+1)
AttributeError: 'NoneType' object has no attribute 'append'
The code is :
def string_copy(k,s,i):
if (i == len(k)):
return s;
else:
return string_copy(k,s.append(k[i]),i+1)
def main():
print("enter the string you want to copy:");
k = input();
s = [None];
i = 0;
print("the type of k and s is:", type(k),type(s));
res = string_copy(list(k),list(s),i);
print("the desired results are:","\n", res);
if __name__ == "__main__": main() `
Upvotes: 0
Views: 2208
Reputation: 13
The final solution is:
def string_copy(k,s,i):
if (i == len(k)):
return s
else:
s.append(k[i])
return string_copy(k,s,i+1)
def main():
print("enter the string you want to copy:")
k = input()
s = ""
i = 0;
print("the type of k is:", type(k))
res = string_copy(list(k),list(s),i)
print("the desired results are:","\n", "".join(res))
if __name__ == "__main__": main()
Better way of approaching this problem:
def string_copy(k):
if (len(k) == 0):
return k
else:
return k[0] + string_copy(k[1:])
def main():
print("enter the string you want to copy:")
k = input()
print("the type of k is:", type(k))
res = string_copy(k)
print("the copied string is:","\n",res)
if __name__ == "__main__": main()
Upvotes: 0
Reputation: 33335
return string_copy(k,s.append(k[i]),i+1)
The list append()
method does not return the updated list; it adds the new item in-place and returns None
.
Therefore the next call to string_copy()
will have None
as the value for s
.
Upvotes: 1