开发者

Suggestions for improving my method for finding the max value

开发者 https://www.devze.com 2023-02-08 10:50 出处:网络
I have a set called ISET; with a long list of 3-letter elements like: USA, BRA, CHN, .... I also have a dictionary called heights. The keys for this dictionary are the elements of SET combined with a

I have a set called ISET; with a long list of 3-letter elements like: USA, BRA, CHN, ....

I also have a dictionary called heights. The keys for this dictionary are the elements of SET combined with a certain YEAR string. For example: USA1991, USA1992, ..., BRA1991, ... ...

What is the best way of finding the max height-value across all countries for a given year?

开发者_如何学C

This is what I have been using:

YEAR = getuserselection()
for i in ISET:
    z = heights.get(i + YEAR, None)
    if z is None: continue
    if z > Max: Max = z

Any suggestions for improving it?

Thank you.


Suggestion, not actually measured: use a mapping heights_per_year from years to dicts mapping country codes to heights.

year = getuserselection()
heights = heights_per_year[int(year)]
max_height = max(a.itervalues())

Note the conversion to int for some extra speed (no need to compare strings).

Better yet, let height_per_year map to descending sorted lists of (country code, height) pairs.

max_height = heights[0][1]


If height doesn't change much, cache the statistics you need, when you create or update the data.


What is just a rewording of your algorithm could be:

YRNormalizer = max(heights.get(z+YEAR, -99999) for z in ISET)

If you can you should have python doing the loops itself...

0

精彩评论

暂无评论...
验证码 换一张
取 消