Skip to content

Instantly share code, notes, and snippets.

@watersb
Created June 16, 2015 18:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save watersb/4cc5b56065115dc7f345 to your computer and use it in GitHub Desktop.
Save watersb/4cc5b56065115dc7f345 to your computer and use it in GitHub Desktop.
year with most alive.py
from collections import defaultdict
CENTURY = 1900
demographic_data = '''
James 1954 1977
Linda 1922 1928
Robert 1912 1924
Mary 1965 1993
John 1915 1915
Patty 1946 2014
Michael 1939 2004
Barbara 1961 1991
David 1949 1962
Susan 1967 2014
William 1919 1967
Nancy 1939 2002
Richard 1944 1953
Deborah 1967 2034
Thomas 1923 1973
Sandra 1945 1965
Charles 1918 1986
Carol 1913 1921
Gary 1934 1980
Kate 1917 1929
Larry 1964 2014
Sharon 1959 1964
Ronald 1909 1936
Karen 1916 1981
Joseph 1925 1941
Donna 1905 1908
Donald 1969 1996
Brenda 1941 1967
Kenneth 1954 1961
Magie 1909 1933
Steven 1955 1967
Diane 1961 2023
Dennis 1920 1933
Pamela 1939 1976
Paul 1914 1982
Janet 1945 1971
Stephen 1900 1917
Shirley 1937 2003
George 1943 1992
Carolyn 1958 2005
'''
max_year = 0
alive = defaultdict(int)
for data in demographic_data.splitlines():
if len(data):
birth, death = (int(x)-CENTURY for x in data.split()[1:])
for year in range(birth , death):
alive[year] += 1
######
for year in alive:
max_year = max( max_year, alive[year] )
print "In %i, the maximum of %i people were alive." % \
((max_year+CENTURY), alive[max_year])
@watersb
Copy link
Author

watersb commented Jun 16, 2015

Given a list of people, with their year of birth and year or death, find the year that has the most people.

A toy job-interview sort of programming exercise. I used it as a goal for my first Python programming on my iPad. Pythonista and Editorial by OMZ Software. I sketched out the Perl solution in about ten minutes, but learning enough Python took me about three hours.

So now I can see that since I'm using a Dictionary instead of a simple numeric array, the add/subtract of CENTURY should go away.

List comprehensions suggest that this could be done in about two or three lines of code, but I'm not sure that would improve anything. Likely to be worse.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment