0

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".

7
  • What exactly is the purpose of the pairs variable here? You always set it to either 1 or 0 (and it is never returned from the function either) Commented Sep 25, 2020 at 22:19
  • You want +=, not =+. I don't know if that's your problem, but that will cause improper behavior. Also, the pairs += 0 does nothing and should be removed. Commented Sep 25, 2020 at 22:20
  • 1
    And ya, pairs is 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. Commented Sep 25, 2020 at 22:21
  • @UnholySheep the pairs variable is the variable that will store the number of pairs of consecutive letters found in the string. Commented Sep 25, 2020 at 22:24
  • 1
    This assignment clearly wants to teach you about functional programming, meaning your function should not be doing any state keeping. In functional programming your functions are "pure", meaning they do not modify anything outside of the function and only return a value Commented Sep 25, 2020 at 22:26

5 Answers 5

1

You need to wrap your head a little around what the recursion will do: it will call the function recursively to count the pairs from that point on, then (it should) add the pair, if any, found by this instance.

So your function needs to do something with the result of the recursive call, not just return it unchanged. For example, instead of this

elif s[0].lower() == s[1].lower():
    pairs = +1
    return countpairs(s[1:])

you might write this:

elif s[0].lower() == s[1].lower():
    return countpairs(s[1:]) + 1

Something along these lines. You'll need to do a bit more work to get it just right, but I hope you get the idea.

Sign up to request clarification or add additional context in comments.

Comments

1

The problems is that the variable pairs resets every recursive call... When using counting recursive algorithms you don't need a variable that counts, that's the beauty Instead, try to think how to recursive call can help you count.

def countpairs(s):
    if len(s)<2:
       return 0                       
    elif s[0].lower() == s[1].lower():      
        return countpairs(s[1:])+1
    else:                                
        return countpairs(s[1:])
print(countpairs('Hello Salaam'))

There you go, in the recursive call the "counter" gets bigger every time it should be, think of the counter as a part of the function stack (or something like that).

2 Comments

sorry about the answer layout
@ggorlen Thank! pls vote for good answer, it's my first one :)
0

You need to fix the syntax: pairs=+1 should be pairs+=1, same for pairs=+0. And you can pass the total into the next level.

def countpairs(s, pairs=0):
    if len(s)<2:
        return pairs                            #base case
    elif s[0].lower() == s[1].lower():       #recursion
        pairs+=1
        return countpairs(s[1:], pairs)
    else:                                   #recursion
        pairs+=0
        return countpairs(s[1:], pairs) 
print(countpairs('Hello Salaam'))  # 2

Comments

0

You can do it by creating a recursive nested function and defining pairs in the outer function. Here's what I mean (with fixes for other issues encountered):

def countpairs(s):
    pairs = 0
    def _countpairs(s):
        nonlocal pairs  # Since it's not local nor global.

        if len(s) < 2:  # base case
            return pairs
        elif s[0].lower() == s[1].lower():
            pairs += 1
            return _countpairs(s[1:])  # recursion
        else:
            return _countpairs(s[1:])  # recursion

    return _countpairs(s)

print(countpairs('Hello Salaam'))  # -> 2

Comments

0

The code will always evaluate to zero because the last recursion will always have the length of s being less than 2. Instead use the global keyword to be able to grab the value of pairs.

numberOfPairs = 0
pairsList = []
def countpairs(s):
    global numberOfPairs
    if len(s)<2:
        print("doing nothing")
        return 0                            #base case
    elif s[0].lower() == s[1].lower():       #recursion
        numberOfPairs+=1
        newString = f"{s[0]} is equal to {s[1]}"
        print(newString)
        pairsList.append(newString)
        return countpairs(s[1:])
    else:
        print(f"nothing happened: {s[0]}")                                   #recursion
        return countpairs(s[1:])

print(f"\nThe returned value of countpairs is: {countpairs('Hello Salaam')}")
print(f"Number of pairs: {numberOfPairs}")
print(pairsList)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.