我需要一个Python 2.7函数,它将一个整数作为输入,并返回带有奇数和偶数位数的字典,如下所示:
count_digits(34567)
应该返回{'odd': 3, 'even': 2}
这是我的代码:
def count_digits(num):
if type(num) == int:
arr = list(str(num))
result = {
'odd': 0,
'even': 0
}
for digit in arr:
if digit % 2 == 0:
result['odd'] += 1
else:
result['even'] += 1
return result
else:
return False
print count_digits(123)
我得到TypeError: not all arguments converted during string formatting
答案 0 :(得分:3)
另一种方法是使用collections.Counter
,它是dict
from collections import Counter
def count_digits(num):
return Counter('odd' if int(d) % 2 else 'even' for d in str(num))
print count_digits(123)
print count_digits(34567)
>>> Counter({'odd': 2, 'even': 1})
>>> Counter({'odd': 3, 'even': 2})
答案 1 :(得分:1)
digit
引用的字符串不是整数,您不应该digit % 2
,但是,您可以使用int(digit)%2
。如果int(digit)%2==0
,则表示digit
为even
而非odd
,否则为odd
:
def count_digits(num):
if type(num) == int:
arr = str(num)
result = {
'odd': 0,
'even': 0
}
for digit in arr:
if int(digit) % 2 == 0:
result['even'] += 1
else:
result['odd'] += 1
return result
else:
return False
print count_digits(123) # => {'odd': 2, 'even': 1}
print count_digits(34567) # => {'odd': 3, 'even': 2}