0

I am working on a function that would take an input of a single string and capitalize all names in the string while leaving any number and words that begin with numbers intact.

So far I have created this, which looks to me like it should do the job. But for some reason it is not passing the hackerank checker. Any ideas for what is going wrong?

def solve(s):
    cap = True
    name_new = ""
    for char in s:
        if cap == True and char.isalpha() == True:
            name_new += char.capitalize()
            cap = False
        elif char.isspace() == True:
            name_new += str(char)
            cap = True
        elif char.isnumeric() == True:
            name_new += str(char)
            cap = False
        else:
            name_new += str(char)
    
    print(name_new)

s = "aa bb cc"
solve(s)

This seems to work when I try it in python, but it gives me an error on hackerank.

Traceback (most recent call last):
  File "Solution.py", line 36, in <module>
    fptr.write(result + '\n')
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'

If it helps, the checking code in hackerank for this challenge looks like this, which does not tell me a lot:

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    s = input()

    result = solve(s)

    fptr.write(result + '\n')

    fptr.close()
Alexius
  • 47
  • 3
  • 2
    `result = solve(s)` tells you that solve should return a string. Yours does not. Hence it returns `None` - wich is then used in `fptr.write(result + '\n')` – Patrick Artner Feb 23 '21 at 06:46
  • 1
    Beside that - you are probably looking for something like `def solve(s): return ' '.join( (term.capitalize() for term in s.split()) )`. At least you should use a list to collect all the single characters and join that before returning - string concattenation to build up a result is wasteful in python as string are immuteable and you essentially build and discard len(s) strings while doing what you do. Lists do not have that drawback and are much faster. – Patrick Artner Feb 23 '21 at 06:48
  • Thanks, changing print to return solved the problem. Your second commend is really helpful, I am going to need to work on making my code a lot more efficient in general. – Alexius Feb 23 '21 at 07:09

0 Answers0