Hello people, in this article we will solve the below python problem.

You receive the name of a city as a string, and you need to return a string that shows how many times each letter shows up in the string by using an asterisk (*).

For example:

“Chicago” –> “c:*,h:,i:,a:,g:,o:

As you can see, the letter c is shown only once, but with 2 asterisks.

The return string should include only the letters (not the dashes, spaces, apostrophes, etc). There should be no spaces in the output, and the different letters are separated by a comma (,) as seen in the example above.

Note that the return string must list the letters in order of their first appearance in the original string.

I will solve the above problem using just a pure/core python module without importing any extra module.

def get_strings(city):

    city = "".join(city.lower().split()) # get rid of all spaces and turn all characters into lower case characters

    city_list = list(city) # next turn the city string into a list

    already = [] # this is used to hold the character which has already counted before

    city_string = '' # this is the city string which will be returned

    for word in city_list:

        if word not in already:

            count = city_list.count(word)
            city_string += word + ":"

            for i in range(0, count):
                city_string += "*"

            city_string+= ","
            already.append(word)

    return city_string[:-1] # don't forget to get rid of the last comma
Save Up to 88% Off + Free Gift. Limited Time Offer

Do you like the above solution or do you have a better one? Let me know in the comment box below this post!

Click to rate this post!
[Total: 0 Average: 0]
Please follow and like us:

2 Comments

  1. Strip is the method that removes blank characters, not split.
    In your implementation you should be using sets instead of lists for already seen.
    You can count everything in one pass, instead of doing a pass for each letter.
    Strings are immutable so python will make a new string every time you use +=.
    It would be better to use a dictionary and join the result at the end.
    Here are some of the possible solutions:
    https://imgur.com/uQxEAXV

    Test with:
    python city_string.py Ouagadougou

Leave a Reply

Your email address will not be published. Required fields are marked *