Jeffrey - 1 month ago 6
Python Question

# How do I find the max integer of a string of integer without using a list?

I must use a for loop, no list allowed. May assume string is non-empty. What I have:

def max_numbers(s):
n_string = ''
for char in s:
if char.isdigit():
n_string += char
return max(n_string)

max_numbers('22 53 123 54 243')
5
expected 243

Please don't use any advance methods, I am still a beginner. I wanted 243 to show up but ended up with 5 instead.

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