Created
December 4, 2018 16:33
-
-
Save ty-shaikh/d8c66d502eed65a8fa7fa7e57fe3965d to your computer and use it in GitHub Desktop.
Programming Paradigm -- Functional
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Functional | |
def normalize_state(s): | |
return s.strip().lower().replace(’.’,’’) | |
def mean(nums): | |
return sum(nums) / len(nums) | |
def extract_state_age(l): | |
pieces = l.split(’,’) | |
return normalize_state(state), float(age) | |
def get_state_mean(pairs): | |
ages_by_state = {} | |
for age, state in pairs: | |
ages_by_state[state] = ages_by_state.setdefault(state,[]) + [age] | |
state_mean_pairs = [(state, mean(ages)) for state, ages in ages_by_state.items()] | |
return sorted(state_mean_pairs, key=lambda p: p[1]) | |
def format_output(state_age_pairs): | |
out_lines = [state + ’,’ + str(age) for state, age in state_age_pairs] | |
return '\n'.join(out_lines) | |
lines = open('data.txt') | |
state_age_pairs = [extract_state_age(l) for l in lines] | |
output = format_output(state_age_pairs) | |
open('output.txt','w').write(output) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment