2

If i have a list and a function to calculate score, I could calculate argmax as such:

maxscore = 0; argmax = None
x = [3.49, 0.122, 293, 0.98] # Imagine a LARGE list.
for i in x:
    # Maybe there're some other func() to calculate score
    # For now just sum the digits in i.
    score = sum([int(j) for j in str(i) if j.isdigit()])
    print i, score
    if maxscore < score:
        maxscore = score
        argmax = i

Is there any other way to achieve argmax? What is the pythonic way to do so?

alvas
  • 115,346
  • 109
  • 446
  • 738

2 Answers2

8
def score(i):
    return sum([int(j) for j in str(i) if j.isdigit()])

max(x, key=score)
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
0

If you're going to do this a lot for large lists of non-Unicode strings, it might be worth the one-time overhead of setting things up so as much of the process as possible can be done via relatively simple table-lookups and built-in methods written in C (asstring_translate()is in CPython):

x = [3.49, 0.122, 293, 0.98]

digits = set(range(ord('0'), ord('9')+1))
transtable = ''.join(chr(i-ord('0')) if i in digits else chr(0)
                        for i in range(256))
deletechars = ''.join(chr(i) for i in range(256) if i not in digits)

def sum_digit_chars(i):
    return sum(bytearray(str(i).translate(transtable, deletechars)))

print max(x, key=sum_digit_chars)
martineau
  • 119,623
  • 25
  • 170
  • 301