Python,计算偶数位数

时间:2015-10-07 20:49:38

标签: python

对于介绍性python类中的作业,其中一个问题是计算n中​​偶数的数量。这是我目前的代码:

def num_even_digits(n):
    i=0
    count = 0
    while i < n:
        i+=1
        if n%2==0:
            count += 1
    return count

print(num_even_digits(123456))

2 个答案:

答案 0 :(得分:0)

你每次都在比较整数。你需要将它转换为一个字符串然后循环遍历该数字串中的每个数字,将其强制转换为整数并查看其余数是否为0

def num_even_digits(numbers):
    count = 0
    numbers = str(numbers)
    for number in numbers:
        try:
            number = int(number)
        except ValueError:
            continue

        if number % 2 == 0:
            count += 1
    return count

print(num_even_digits(123456))

如果你想实际遍历0到大数字范围内的每个可能的数字,你可以这样做。

def num_even_digits(numbers):
    count = 0
    for number in range(0, numbers):
        if number % 2 == 0:
            count += 1
    return count

print(num_even_digits(10))

当前功能的问题:

def num_even_digits(n): # n is not descriptive, try to make your variable names understandable
    i=0
    count = 0
    while i < n: # looping over every number from 0 to one hundred twenty three thousand four hundred and fifty six.
        i+=1
        if n%2==0: # n hasn't changed so this is always going to be true
            count += 1
    return count

print(num_even_digits(123456))

答案 1 :(得分:0)

Pythonic回答:

def num_even_digits(x):
    return len([ y for y in str(x) if int(y) % 2 == 0])

print(num_even_digits(123456))

免责声明:我认识到,对于介绍 Python类,我的答案可能不合适。