I need to get an input from the user, and I need to print out each character in the input with a space, but using a recursion. How would I go about this?
inputNum = input("Enter a number: ")
def extractDigits(n):
lastNum = n[-1]
if n == lastNum:
return ''
else:
return n '' extractDigits(n[0])
print(extractDigits(inputNum))
My hope was that if I were to input "12345" with this function it would output "1 2 3 4 5 " but it still outputs as "12345". I'm trying to do this without for loops as well.
CodePudding user response:
If you want a recursive function, you can do:
def extractDigits(n):
if len(n) == 1:
return n[-1]
else:
return n[0] ' ' extractDigits(n[1:])
Output:
extractDigits("12345")
# '1 2 3 4 5'
However, while pretty, recursive functions don't perform that well.
For example,
def extractDigits(n):
return ' '.join(n)
performs much much faster.
CodePudding user response:
simple use join method.
inputNum=input("enter a number:")
num=" ".join(inputNum)
#look there is a space bitween double qoutes
print(num)
#input: 123456
#output:1 2 3 4 5 6