-1

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.

Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
Jun
  • 91
  • 1
  • 10

4 Answers4

4

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:

Community
  • 1
  • 1
Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
  • Thank you for your help! Although not as easy to understand as Gordon's answer, I appreciate another point of view. This lets me learn more about what loops can do! – Jun Oct 10 '16 at 03:02
  • Sorry to bother you again, the one thing I dont understand is what is "n_string and int(n_string)" nesscessary. How come if I removed n_String it doesnt work? – Jun Oct 10 '16 at 03:33
  • @Jeffrey Edited the answer. Take a look. – Sнаđошƒаӽ Oct 10 '16 at 03:59
1

Not going to write any code for you because doing it the way you have specified is just boring. Also since you have not indicated what version of python you are using, I will just assume version 2.

Here are a few things you will need:

  • str.isspace() Use this to determine when you have reached a space
  • str.isdigit() Use this to determine when you have read a number
  • int() Use this to convert a string number to integer

The algorithm goes like this:

  1. First initialize a variable called num to the empty string

  2. Read digits until you either reach the end of the string or reach a non digit. Each digit read should be appended to num

  3. If you reach a space or end of the string and neg is not empty, use int to convert num to an integer otherwise skip to step 5
  4. Compare this value to your current max and replace max with the value if it is larger
  5. Repeat from step 1 if you have not reached the end of the string
  6. Finally print your current max

Special case to handle negative numbers

  1. Initialize a variable called num to the empty string and a variable called neg to 1
  2. If the first thing read is not a digit and is not space but is the - character, set neg to -1 otherwise read digits until you either reach the end of the string or reach a non digit. Each digit read should be appended to num
  3. If you reach a space or end of the string and num is not empty, use int to convert num to an integer; otherwise skip to step 6
  4. Multiply this integer by neg
  5. Compare this value to your current max and replace max with the value if it is larger
  6. Repeat from step 1 if you have not reached the end of the string
  7. Finally print your current max

The non boring version:

print (max(map(int, my_str.split())))
smac89
  • 39,374
  • 15
  • 132
  • 179
1
def max_numbers(s):
    # biggest number we've seen so far.  init to a very small number so
    # it will get replaced immediately by real input data
    biggest = -999

    # accumulate digit characters from input
    n_string = ''

    # loop through each input character
    for char in s:

        # is it a digit 0-9?
        if char.isdigit():

            # add it onto the end of n_string
            n_string += char

        # not a digit
        else:

           # if n_string has some digits in it
           if n_string:

                # calculate integer value of n_string, and if it's bigger
                # than the previous biggest, save it as the new biggest
                biggest = max(biggest, int(n_string))

                # reset n_string back to empty
                n_string = ''

    return biggest
John Gordon
  • 29,573
  • 7
  • 33
  • 58
  • A better initial value for `biggest` will be `float('-inf')` or set it to `None` and immediately replace it with the first integer in the string – smac89 Oct 10 '16 at 02:53
  • THANK YOU! It was a good explanation-easy to understand. It seems that I have to study more on loops! I did not know about the reset method. – Jun Oct 10 '16 at 03:01
-2

If @IvanCai's answer is too advanced try:

def max_numbers(s):
    top=0
    curr=0
    for char in s:
        if char.isdigit():
            curr*=10
            curr+=int(char)
            if curr>top:
                top=curr
        elif char==' ' or char=='\n':
            curr=0
    return top
print(max_numbers('22 53 123 54 243'))
boboquack
  • 249
  • 5
  • 15