Search code examples
python-3.xfor-loopaccumulator

Python - how to accumulate comma using a for loop


community - this is my first post, so please forgive me if I failed to properly display this message. I am trying to add commas as depicted below in the test cases. It appears there are more efficient ways than what I have coded below; however, I would like to solve the problem using my code below. What in the world am I missing?

def get_country_codes(prices):
    country_prices = prices
    p = ""
    for i in country_prices:
        if i.isalpha() and i == ",": 
            p = p + i[0] + ","
    return (p)

My code is returning:

Test Failed: expected NZ, KR, DK but got 
Test Failed: expected US, AU, JP but got 
Test Failed: expected AU, NG, MX, BG, ES but got 
Test Failed: expected CA but got 

from test import testEqual

testEqual(get_country_codes("NZ$300, KR$1200, DK$5"), "NZ, KR, DK")
testEqual(get_country_codes("US$40, AU$89, JP$200"), "US, AU, JP")
testEqual(get_country_codes("AU$23, NG$900, MX$200, BG$790, ES$2"), "AU, NG, MX, BG, ES")
testEqual(get_country_codes("CA$40"), "CA")

Solution

  • It would be better to accept a list instead of a string type as a parameter for get_country_codes. This will prevent you from having to worry about parsing the string and ignoring the comma. I'd recommend Joining Lists and Splitting Strings by diveintopython.net.

    This code accepts a list, iterates through it, splits each value on the $, grabs the first token, and checks if this passes isalpha(). If it does, it appends the returned list.

    def get_country_codes(prices):
        """Get country codes given a list of prices.
    
        :param prices: list of prices
        :return: list of alphabetical country codes
        """
        countries = []
        for price in prices:
            country = price.split('$')[0]
            if country.isalpha():
                countries.append(country)
        return countries
    
    # As a proof, this line will concatenate the returned country codes
    # with a comma and a space:
    print(', '.join(get_country_codes(["NZ$300", "KR$1200", "DK$5"])))
    # As another proof, if your input has to be a string:
    print(get_country_codes("US$40, AU$89, JP$200".split(", ")))
    print(get_country_codes(["AU$23", "NG$900", "MX$200", "BG$790", "ES$2"]))
    print(get_country_codes(["CA$40"]))
    

    The code returns

    NZ, KR, DK
    ['US', 'AU', 'JP']
    ['AU', 'NG', 'MX', 'BG', 'ES']
    ['CA']
    

    Finally, to make an assertion:

    testEqual(get_country_codes(["NZ$300", "KR$1200", "DK$5"]), ["NZ", "KR", "DK"])