2
\$\begingroup\$

A very simple problem here (I'm learning Python) - given a list of tuples which represent (year of birth, year of death) for a group of people, I want to find the minimum "year of birth" and the maximum "year of death". Here's how I did it:

def testmax():
    years = [(1804, 1884), (1885,1997), (1902,1975), (1900,1989)] # sample data

    endyr = max([deathyr for (birthyr,deathyr) in years])
    startyr = min([birthyr for (birthyr,deathyr) in years])
    print(startyr, endyr) # correctly returns 1804 1997

As you can see, I use list comprehensions to go through the years list twice. Time complexity O(2N) = O(N).

I can improve this with a simple function that is longer but does it through one iteration of the years list — I simply track (min, max) as my return variables that I keep checking on every iteration to get the min and max years that I need, in one iteration. Time complexity = O(N). What I don't like here is writing longer code (perhaps in a test/interview where time is limited).

My question: is there a better/cleaner/more Pythonic way you would do this? Would a lambda function work here, if so how? Even if you still do it in 2 iterations, I'd appreciate it if you could demo/explain any variations of the code (perhaps using lambda) that you would have used.

\$\endgroup\$
4
\$\begingroup\$

What you really want to do is transpose the separate tuples into 2 tuples - one containing all the birth dates, and the other death dates.

Fortunately, python's zip function can do this easily for you, using the *x syntax:

years = [(1804, 1884), (1885,1997), (1902,1975), (1900,1989)]
births, deaths = zip(*years)
# births = (1804, 1885, 1902, 1900)
# deaths = (1884, 1997, 1975, 1989)
print(min(births), max(deaths))
# 1804 1997
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ what's relative performance? I'm guessing slightly worse \$\endgroup\$ – Oscar Smith Apr 4 '18 at 3:56
  • \$\begingroup\$ Its definitely better than iterating over years twice. Not the most memory efficient method though. \$\endgroup\$ – match Apr 4 '18 at 6:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.