The problem
Write a nickname generator operate, nicknameGenerator
that takes a string title as an argument and returns the primary 3 or 4 letters as a nickname.
The nickname generator ought to carry out the next duties.
If the third letter is a consonant, return the primary 3 letters.
nickname("Robert") # "Rob"
nickname("Kimberly") # "Kim"
nickname("Samantha") # "Sam"
If the third letter is a vowel, return the primary 4 letters.
nickname("Jeannie") # "Jean"
nickname("Douglas") # "Doug"
nickname("Gregory") # "Greg"
If the string is lower than 4 characters, return “Error: Title too brief”.
Notes:
- Vowels are “aeiou”, so low cost the letter “y”.
- Enter will all the time be a string.
- Enter will all the time have the primary letter capitalised and the remainder lowercase (e.g. Sam).
- The enter will be modified
The answer in Python code
Choice 1:
def nickname_generator(title):
if len(title)<4:
return "Error: Title too brief"
if title[2] not in ['a','e','i','o','u']:
return title[:3]
else:
return title[:4]
Choice 2:
def nickname_generator(title):
if len(title) < 4:
return 'Error: Title too brief'
return title[: 4 if name[2] in 'aeiou' else 3]
Choice 3:
def nickname_generator(title):
return "Error: Title too brief" if len(title) < 4 else title[:3+(name[2] in "aeiou")]
Take a look at instances to validate our answer
check.describe("Instance Take a look at Circumstances")
check.assert_equals(nickname_generator("Jimmy"), "Jim");
check.assert_equals(nickname_generator("Samantha"), "Sam");
check.assert_equals(nickname_generator("Sam"), "Error: Title too brief");
check.assert_equals(nickname_generator("Kayne"), "Kay", "'y' shouldn't be a vowel");
check.assert_equals(nickname_generator("Melissa"), "Mel");
check.assert_equals(nickname_generator("James"), "Jam");