-1

I was asked to write a function to arrange a given number to get its maximum number. The output is correct, but I keep getting None beside the rearranged number. Obs: I don't want a new code. I want this one fixed.

def max(s):
    l=[]
    for i in str(s):
        l.append(int(i))
    l.sort()
    l.reverse()
    for i in l:
        print(i,end="")

print(max(812309))
Franz Kurt
  • 1,020
  • 2
  • 14
  • 14
IXZLY
  • 7
  • 2
  • 1
    How could you possibly get anything *other* than None as the result of this function? It contains no `return` statement! – jasonharper Jan 03 '22 at 16:19
  • Output aside, this is a really inefficient way to get the maximum value of a list. Sorting takes O(n lg n), while you only need O(n) time to find a maximum. Just iterate over the digits, check if each is greater than the largest digit found so far. – chepner Jan 03 '22 at 20:12
  • Does this answer your question? [Why is the output of my function printing out "None"?](https://stackoverflow.com/questions/7053652/function-returns-none-without-return-statement) – Gino Mempin Jan 05 '22 at 09:27

3 Answers3

1

It prints None because the function does not return anything. So instead just don't print the function output and simply call the function like so:

def max(s):
    l=[]
    for i in str(s):
        l.append(int(i))
    l.sort()
    l.reverse()
    for i in l:
        print(i,end="")

max(812309)
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Eli Harold
  • 2,280
  • 1
  • 3
  • 22
0

The way you have set up the call to your method/function, you are actually calling print on the method itself i.e. print(max(812309)).

This is incorrect, as the way the compiler reads it is that it will attempt to print the method rather than a given input (which is the usual practice -- e.g. a string, int, etc).
EDIT: As @kindall mentioned, my explanation here is inaccurate. The compiler is not printing the method, but rather the return value of the method (in this case, no value is being returned so None is printed. My mistake!)

Judging by your description, you want to print out your numbers after having been sorted from your method. However, your method is ALREADY doing the printing; so just call the method by itself and you'll get your expected result.

lawgik
  • 87
  • 3
  • 10
  • 2
    This explanation is incorrect. You're not printing the function, you're printing the result of the function. Which is `None` because the function doesn't return anything. – kindall Jan 03 '22 at 20:10
  • Instead of keeping the inaccurate explanation and having an "EDIT:" block, just remove the inaccurate explanation because it's not useful to keep it here (especially since it's the 1st thing people read). – Gino Mempin Jan 05 '22 at 09:34
0

Because you doesn't implement a return statement inside your function.

So the python interpreter adds a "return None" at the end of your function.

Reference read this article

Franz Kurt
  • 1,020
  • 2
  • 14
  • 14