|
| 1 | +from data import us_state_abbrev, states_list |
| 2 | + |
| 3 | +NOT_FOUND = 'N/A' |
| 4 | + |
| 5 | +def get_every_nth_state(states=states_list, n=10): |
| 6 | + """Return a list with every nth item (default argument n=10, so every |
| 7 | + 10th item) of the states list above (remember: lists keep order)""" |
| 8 | + return [states[i] for i in range(n-1,50,n)] |
| 9 | + |
| 10 | + |
| 11 | +def get_state_abbrev(state_name, us_state_abbrev=us_state_abbrev): |
| 12 | + """Look up a state abbreviation by querying the us_state_abbrev |
| 13 | + dict by full state name, for instance 'Alabama' returns 'AL', |
| 14 | + 'Illinois' returns 'IL'. |
| 15 | + If the state is not in the dict, return 'N/A' which we stored |
| 16 | + in the NOT_FOUND constant (takeaway: dicts are great for lookups)""" |
| 17 | + try: |
| 18 | + return us_state_abbrev.pop(state_name) |
| 19 | + except KeyError: |
| 20 | + return NOT_FOUND |
| 21 | + |
| 22 | + |
| 23 | +def get_longest_state(data): |
| 24 | + """Receives data, which can be the us_state_abbrev dict or the states |
| 25 | + list (see above). It returns the longest state measured by the length |
| 26 | + of the string""" |
| 27 | + return sorted(data, key=len,reverse=True)[0] |
| 28 | + |
| 29 | + |
| 30 | + |
| 31 | +def combine_state_names_and_abbreviations(us_state_abbrev=us_state_abbrev, |
| 32 | + states=states_list): |
| 33 | + """Get the first 10 state abbreviations ('AL', 'AK', 'AZ', ...) from |
| 34 | + the us_state_abbrev dict, and the last 10 states from the states |
| 35 | + list (see above) and combine them into a new list without losing |
| 36 | + alphabetical order""" |
| 37 | + return sorted(us_state_abbrev.values())[:10]+(sorted(states)[-10:]) |
| 38 | + |
| 39 | +if __name__ == "__main__": |
| 40 | + |
| 41 | + print([(k,v) for k,v in us_state_abbrev.items()][9]) |
| 42 | + print(states_list[9]) |
| 43 | + print([k for k in us_state_abbrev.keys()][44]) |
| 44 | + print([v for v in us_state_abbrev.values()][26]) |
| 45 | + |
0 commit comments