I solved the following question
You are asked to ensure that the first and last names of people begin with a capital letter in their passports. For example, alison heck should be capitalised correctly as Alison Heck.
Given a full name, your task is to capitalize the name appropriately.
A single line of input containing the full name, S.
- 0 < len(S) < 1000
- The string consists of alphanumeric characters and spaces.
Note: in a word only the first character is capitalized.
Example 12abc when capitalized remains 12abc.
Print the capitalized string, S.
Here's my code:
#!/bin/python import math import os import random import re import sys # Complete the solve function below. def solve(s): ls = s.split(" ") new_word = "" new_name = "" for word in ls: if len(word) > 1: new_word = new_word + word.title() + word[1:] + " " else: new_word = new_word + word.title() + " " new_name = new_name.join(new_word) return new_name if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') s = raw_input() result = solve(s) fptr.write(result + '\n') fptr.close()
I think I used a very long approach and would appreciate more efficient techniques to do the same.
The primary problem which I faced is handling arbitrary spaces and hence I went with this approach but the code smells bad. One things I can think of is reducing variables but that wouldn't be very helpful and make it less readable I think
EDIT : The question is this question from HackerRank however the solution to this problem on the website does not include test cases where capitalize() and title() fail. The failing of these and more methods have also been discussed here