Home > OS >  Please review my Python recursion snippet
Please review my Python recursion snippet

Time:06-02

The problem:

Given a string S, compute recursively a new string where identical characters that are adjacent in the original string are separated from each other by a "*".

Example:

Input = hello

Output = hel*lo

My code:

def pairStar(s):
    if len(s)<=1:
        return s
    if s[0]==s[1]:
        return s[0] "*" pairStar(s[1:])

string=input()
print(pairStar(string))

My input: hello

My output: None

Please help! The output shows "None" instead of "hel*lo".

CodePudding user response:

You're missing another return call in case the string is longer than 1 and the first 2 characters aren't a matching pair:

def pairStar(s):
    if len(s)<=1:
        return s
    if s[0]==s[1]:
        return s[0] "*" pairStar(s[1:])
    return s[0]   pairStar(s[1:])

string=input()
print(pairStar(string))

CodePudding user response:

Here is your Answer

def pairStar(s,start):
    if len(s)<=1:
        return s
    if start 1 >= len(s):
        return s
    if s[start] == s[start 1]:
        s = s[:start 1] "*" s[start 1:]
        return pairStar(s,start 2)
    else:
        return pairStar(s,start 1)

string=str(input("Enter the string:"))
start = 0
print(pairStar(string,start))
  • Related