简体   繁体   中英

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

My teacher solved this question "Write a function which takes an 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)

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.

You can condense the code to a single line:

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

尝试:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM