The idea is to separate out the integers from the string (as you are already doing, but a bit wrongly), and keep track of the max so far. When a character is not digit, you convert the n_string
to int
and compare with max_
which keeps track of maximum int found so far, and then set n_string
empty for next number.
The final checking is for the last number, since at the end of the string there may not always be a non-digit, so the last iteration will not be in the else
part.
def max_numbers(s):
n_string = ''
max_ = 0
for char in s:
if char.isdigit():
n_string += char
else:
if n_string and int(n_string) > max_:
max_ = int(n_string)
n_string = ''
if n_string and int(n_string) > max_:
max_ = int(n_string)
return max_
print(max_numbers('22 53 123 54 243'))
Output:
243
Edit:
If n_string
is empty, int(n_string)
fails with an error
ValueError: invalid literal for int() with base 10: ' '
So in order to avoid that, a check to see if n_string
is empty or not is required before doing int(n_string)
. In python, empty string evaluates to False
, and non-empty string to True
. So, simply writing
if n_string and int(n_string) > max_:
checks if n_string
is non-empty and n_string
as integer is greater than max_
. When n_string
is empty, the second part of the if
is not evaluated due to short-circuiting behaviour of if
, thus the error is avoided.
Some related links: