Saturday, September 30, 2023
HomeSoftware EngineeringThe way to create a Nickname Generator in Python

The way to create a Nickname Generator in Python


The problem

Write a nickname generator operate, nicknameGenerator that takes a string identify 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 quick”.

Notes:

  • Vowels are “aeiou”, so low cost the letter “y”.
  • Enter will at all times be a string.
  • Enter will at all times have the primary letter capitalised and the remaining lowercase (e.g. Sam).
  • The enter will be modified

The answer in Python code

Choice 1:

def nickname_generator(identify):
    if len(identify)<4:
        return "Error: Title too quick"
    if identify[2] not in ['a','e','i','o','u']:
        return identify[:3]
    else:
        return identify[:4]

Choice 2:

def nickname_generator(identify):
    if len(identify) < 4:
        return 'Error: Title too quick'
    return identify[: 4 if name[2] in 'aeiou' else 3]

Choice 3:

def nickname_generator(identify):
    return "Error: Title too quick" if len(identify) < 4 else identify[:3+(name[2] in "aeiou")]

Take a look at instances to validate our resolution

check.describe("Instance Take a look at Instances")
check.assert_equals(nickname_generator("Jimmy"), "Jim");
check.assert_equals(nickname_generator("Samantha"), "Sam");
check.assert_equals(nickname_generator("Sam"), "Error: Title too quick");
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");
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments