0

I gave this string to my python code from which I wanted to find the maximum.

>>> a = ("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6")
>>> a = a.split(" ")
>>> max(a)
>>> 6

Can someone please explain me why it is not returning 542? At last, I found the correct code:

>>> a = a.split(" ");
>>> a = [int(i) for i in a];
>>> return str(max(a))

But could someone please teel me my foolishness in the former code.

3 Answers3

2

You can also find the maximum string as if interpreted as an integer by passing a key

max(a.split(), key=int)

'542'

And make it an int afterwards

int(max(a.split(), key=int))

542
piRSquared
  • 285,575
  • 57
  • 475
  • 624
1
max([int(x) for x in a.split()])

This will convert a into a list of ints and find the correct max. Strings are compared char by char, comparing charcodes.

max(int(x) for x in a.split())

The above works too, without creating a list, as a generator variant.

Attersson
  • 4,755
  • 1
  • 15
  • 29
  • 3
    You don't need the list comprehension with `[` and `]`. `max` can directly take a generator expression – sshashank124 May 17 '18 at 14:39
  • Alternatively, `max(map(int, a))` works for Python 3.x & 2.7, and is lazy in 3.x. – jpp May 17 '18 at 14:40
  • @sshashank124 Thanks for the comment, I edited my answer – Attersson May 17 '18 at 14:41
  • `max` does not do double generation. could you please provide a source on that? – sshashank124 May 17 '18 at 14:45
  • @sshashank124 Apparently I can't find any. I had in mind a similar case where I read that generators indeed double up the number of generations. There was a popular StackOverflow entry about that. However this might have been a similar case. In the meantime I will definitely amend this answer. – Attersson May 17 '18 at 14:55
  • I'm not claiming that it definitely doesn't but I tried searching it and skimming the src code and I couldn't find it. I think it would be safer to keep it out of the discussion in the answer itself haha. – sshashank124 May 17 '18 at 14:58
  • @sshashank124 the gen expr is very slightly slower. `test_list = list(np.random.randint(0, 500, 100000).astype(str))`. From `timeit` - list: `29.7 ms ± 375 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)`, gen expr: `32.7 ms ± 593 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)` – roganjosh May 17 '18 at 15:01
  • @Cleb added a.split(). roganjosh thanks for the benchmark (anyway OP already wrote `a= a.split()` but it is ok to specify) – Attersson May 17 '18 at 15:03
0
max(map(int, a.split(" ")))
# 542
Amitkumar Karnik
  • 912
  • 13
  • 23