【问题标题】:python get amount of odd and even digitspython获取奇数和偶数的数量
【发布时间】:2017-09-07 12:31:10
【问题描述】:

我需要一个 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

【问题讨论】:

  • 好的。是什么阻止你写一篇文章?
  • 你能告诉我们你的尝试吗?如果您遇到困难,我们可以提供帮助,但不会为您编写整个代码。
  • 请参阅有关如何创建minimal reproducible example的教程。
  • 错误是你必须从:if digit % 2 == 0:改为if int(digit) % 2 == 0:,因为“arr”是一个字符串列表

标签: python python-2.7 function dictionary


【解决方案1】:

另一种方法是使用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})

【讨论】:

    【解决方案2】:

    您的代码中的digit 引用的是字符串而不是整数,您不应该这样做digit % 2,但是,您可以使用int(digit)%2。而当int(digit)%2==0,则表示digiteven不是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}
    

    【讨论】:

      猜你喜欢
      • 2021-05-12
      • 2017-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多