如何获取先前输入的整数并在数字中找到赔率均衡和零

时间:2017-10-13 16:51:43

标签: python python-3.x

我的一个模块要求我取一个先前输入的整数并找到evens,odds和zero。但我的代码给了我一些有缺陷的结果。一点帮助将不胜感激

def oez(num):
        s = 0
        count_odd = int (0)
        count_even = int (0)
        count_zero= int (0)
        while (num > 0):
            r = num % 10
            s= s+r
            num = num //10
            if num % 2 == 0:
                count_even=+1
            elif num % 10 == 0:
                count_zero=+1
            else:
                count_odd=+ 1
        print("Number of even numbers :",count_even)
        print("Number of odd numbers :",count_odd)
        print("Number of Zeroes:", count_zero)

3 个答案:

答案 0 :(得分:1)

因为我今天早上感觉很邪恶,这是一个很酷的解决方案(目标号码为551240

odd,even,zed = map(len,map(''.join,zip(*re.findall("([13579])|([2468])|(0)","551240"))))
print(odd,even,zed)
粗略的,更理智的解决方案可能只是检查每个数字

odd=even=zed=0
for digit in "551240":
   if digit in "2468": even += 1
   elif digit in "13579": odd += 1
   elif digit == "0": zed += 1

答案 1 :(得分:0)

def oez(num):
        count_odd = 0
        count_even = 0
        count_zero = 0
        for letter in str(num): # Cast the input as a string
            digit = int(letter) # Cast the character as an int (0-9)
            if digit == 0:
                count_zero += 1
            elif digit % 2 == 0:
                count_even += 1
            elif digit == 0:
                count_odd += 1
            else:
                print("Invalid character")
        print("Number of even numbers :",count_even)
        print("Number of odd numbers :",count_odd)
        print("Number of Zeroes:", count_zero)

答案 2 :(得分:0)

def oez(num):
    num_repr = str(int(num))
    zeroes = len([digit for digit in num_repr if digit == "0"])
    evens = len([digit for digit in num_repr if int(digit) % 2 == 0])
    odds = len([digit for digit in num_repr if int(digit) % 2 == 1])
    print("evens: %d" % evens)
    print("zeroes: %d" % zeroes)
    print("odds: %d" % odds)