Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
startswith() function
#3
Small change:
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 ret
Next 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 ret
Instead 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!
Reply


Messages In This Thread
startswith() function - by milo204 - Mar-05-2018, 03:57 PM
RE: startswith() function - by mpd - Mar-05-2018, 04:48 PM
RE: startswith() function - by DeaD_EyE - Mar-05-2018, 04:57 PM
RE: startswith() function - by milo204 - Mar-06-2018, 10:07 AM
RE: startswith() function - by DeaD_EyE - Mar-06-2018, 10:38 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020