Mar-05-2018, 04:57 PM
Small change:
Sets are very useful:
Lesser code, only one different statement and more flexibility.
visited_cities = ["New York", "Shanghai", "Munich", "Toyko", "Dubai", "Mexico City", "São Paulo", "Hyderabad"] unique_visited_cities = set(visited_cities) sorted_cities = sorted(unique_visited_cities) print('All sorted cities:',sorted_cities) cities_till_q = [] for city in sorted_cities: if city[0].lower() > 'q': break cities_till_q.append(city) print('Sorted cities till q (inclusive):', cities_till_q)The function set comes from set theory. A set has only unordered unique elements.
Sets are very useful:
set(['A', 'B', 'C']) & set(['X', 'Y', 'A', 'Z', 'U'])We get only elements, which are in both sets.
Output:{'A'}
Instead of running the loop on module level, make a function to be more flexible.def get_cities(unsorted_cities, letter) ret = [] for city in unsorted_cities: if city[0].lower() > letter.lower(): continue ret.append(city) return retNext iteration should be a docstring.
def get_cities(unsorted_cities, letter) """ Returns a new list of unsorted cities. Cities which letter is bigger than the given letter are filtered. """ ret = [] for city in unsorted_cities: if city[0].lower() > letter.lower(): continue ret.append(city) return retInstead of creating inside the function a new list, you can also make a generator.
Lesser code, only one different statement and more flexibility.
def get_cities(unsorted_cities, letter): """ Iterates over unsorted cities and yield cities, where the first letter is bigger than letter. """ for city in unsorted_cities: if city[0].lower() > letter.lower(): continue yield city # you have to call the function to get the generator (lazy) # Then you need to consume the generator. # You can use the generator in a for-loop # or you use functions where the constructor # iterates over the argument list(get_cities(sorted_cities, 'q')) list(get_cities(sorted_cities, 'h')) list(get_cities(unsorted_cities, 'h')) list(get_cities(unique_visited_cities, 'h'))
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!