The problem is my code keeps reflecting a variable as zero and this is caused by the fact that the variable is assigned at the start of my function, so each time I call the function the value evaluates to zero. However I need this variable assignment for the code to work and placing it within the elif statements still evaluates to zero and placing the the variable outside the function causes the function not work.
The aim of the program is to count pairs of consecutive letters in a string using recursion with no for/while loops in the code.
def countpairs(s):
pairs=0
if len(s)<2:
return 0 #base case
elif s[0].lower() == s[1].lower(): #recursion
pairs=+1
return countpairs(s[1:])
else: #recursion
pairs=+0
return countpairs(s[1:])
print(countpairs('Hello Salaam'))
This code is supposed to evaluate to 2 because of "ll" and "aa".
pairsvariable here? You always set it to either 1 or 0 (and it is never returned from the function either)+=, not=+. I don't know if that's your problem, but that will cause improper behavior. Also, thepairs += 0does nothing and should be removed.pairsis local to each recursive call. You need to rethink how you're approaching this. You'd need to do something like... elif s[0].lower() == s[1].lower(): return countpairs(s[1:]) + 1 else: return countpairs(s[1:]); although that can be cleaned up. Return a modified value; don't try to have some state (pairs) that you're mutating in each call. That's useful in some cases, but not here.