Asim Okby
Asim Okby

Reputation: 80

I am using `max()` to get the highest value from n digits?

My teacher solved this question "Write a function which takes a n digits number as an input and return True if the biggest digit in this number is divisible by 3" like this:

def is_divisable(n):
    a = str(n)
    b = 0
    for i in a:
        if int(i)>b:
            b = int(i)

    if b % 3 == 0:
        return "True"
print is_divisable(67479)

I have thought of it in another way but my code is not working and I am getting an error says:

"TypeError: 'int' object is not iterable"

def is_dvo(n):


    if max(n) % 3 == 0:
        return True

print is_dvo(67479)

Upvotes: 0

Views: 607

Answers (3)

Fomalhaut
Fomalhaut

Reputation: 9747

Try:

max(str(n), key=int) in {'3', '6', '9'}

Upvotes: 0

Rory Daulton
Rory Daulton

Reputation: 22544

You don't quite say what your question is, but if you want another way to solve the problem,

def is_divisable(n):
    return int(max(str(n))) % 3 == 0

This code converts the number to its decimal string representation, finds the largest digit (as a character), changes that digit to an integer, checks if that is divisible by 3, then returns that answer.

If your question is why you are getting that error, your parameter n is an integer, and you try to apply the max() function to that integer. However, max() is supposed to be used on iterable objects such as strings, lists, tuples, generators, and so on. My code changes the integer to a string before using max() so it does not have that problem, and it iterates over the digits in the string.

Upvotes: 2

Ajax1234
Ajax1234

Reputation: 71451

You can condense the code to a single line:

def is_divisable(n):
  return max(map(int, str(n)))%3 == 0

Upvotes: 0

Related Questions