简体   繁体   English

在Python中计算10位数字中的零,几率和偶数的数量?

[英]Counting the number of zeroes, odds, and evens in a 10-digit number in Python?

integer = int(raw_input("Enter a ten-digit number please: "))

zero_count = 0
even_count = 0
odd_count = 0

def digit_count(x):
    while x > 0:
        if x % 10 == 0:
            zero_count += 1
        elif x % 2 == 0:
            even_count += 1
        else:
            odd_count += 1
        x / 10

    print zero_count
    print even_count
    print odd_count

print digit_count(integer)

The user inputs a ten-digit integer and then the output should be the number of odd, even, and zero digits are in it. 用户输入一个十位数的整数,然后输出应为其中的奇数,偶数和零位数。 When I run this, currently it just has me input an integer and then does nothing else. 当我运行它时,当前它只是让我输入一个整数,然后什么也不做。

As others mentioned, it should be x = x / 10 , but you also need to make your counter variables global . 就像其他人提到的那样,它应该是x = x / 10 ,但是您还需要使计数器变量成为global

Also, 也,

print digit_count(integer)

Will display None . 将显示None Since printing of the zero, odd and even counts is performed in digit_count() , you don't need the additional print . 由于零,奇数和偶数计数的打印是在digit_count()执行的, digit_count()您不需要额外的print

Another way to do this is to apply a Counter to mapped input: 另一种方法是将Counter应用于映射的输入:

from collections import Counter

s = raw_input("Enter a ten-digit number please: ")
c = Counter('zero' if d == '0' else ('odd' if int(d)%2 else 'even') for d in s)
print "zeros {}, odd {}, even {}".format(c['zero'], c['odd'], c['even'])

there are some flaw in your code: 您的代码中存在一些缺陷:

integer = int(raw_input("Enter a ten-digit number please: "))

zero_count = 0
even_count = 0
odd_count = 0


def digit_count(x):
    global zero_count,even_count,odd_count
    while x > 0:
        num = x%10  # store the last digit of x
        if  num % 10 == 0:
            zero_count += 1
        elif num % 2 == 0:
            even_count += 1
        else:
           odd_count += 1
        x /= 10

digit_count(integer)       # you need to call the function 1st
print zero_count
print even_count
print odd_count

That's because you are not re-assigning the x value after each iteration of 'while'. 这是因为您不会在每次“ while”迭代之后重新分配x值。

Simply change x/10 , which does nothing, to x = x/10 只需将不执行任何操作的x/10更改为x = x/10

ALSO

Your declarations: 您的声明:

zero_count = 0
even_count = 0
odd_count = 0

are outside of your function. 不在您的功能范围内。 Therefore, you will get a 'referenced before assignment' error unless you: 因此,除非出现以下情况,否则将出现“分配前被引用”错误。

  1. declare them as nonlocal inside your digit_count function. digit_count函数digit_count它们声明digit_count nonlocal by 通过
nonlocal zero_count
nonlocal even_count
nonlocal odd_count

If you are using Python 2, will you need to use 'global' instead of nonlocal. 如果您使用的是Python 2,是否需要使用“全局”而不是非本地。

Or 要么

  1. initialize them inside your function. 您的函数中初始化它们。

For your specific purpose, I'd say the second option of declaring and initializing them inside your function makes more sense. 对于您的特定目的,我想说在您的函数中声明和初始化它们的第二种选择更有意义。 You only need to use them inside the function. 您只需要在函数内部使用它们。

There are scoping issues in your code. 您的代码中存在范围问题。 The zero, even and odd counts are global variables and they're modified within the function. 零,偶数和奇数计数是全局变量,它们在函数中进行了修改。 And, you're missing an assignment in the statement x = x / 10. 而且,您在语句x = x / 10中缺少分配。

Instead of processing the big integer through division by 10, I'd like to highlight an alternative method. 我想强调一种替代方法,而不是通过10除以处理大整数。 First convert your string to a list of single digits, and then process the list through the digit_count function: 首先将您的字符串转换为一个数字列表,然后通过digit_count函数处理该列表:

def digit_count(digits):
    """ Takes a list of single digits and returns the 
        count of zeros, evens and odds
    """
    zero_count = 0
    even_count = 0
    odd_count = 0
    for i in digits:
        if i == 0:
            zero_count += 1
        elif i % 2 == 0:
            even_count += 1
        else:
            odd_count += 1
    return zero_count, even_count, odd_count

inp = raw_input("Enter a ten-digit number please: ")
digits = [int(i) for i in inp] # see comment at the bottom of the answer

zero_count, even_count, odd_count = digit_count(digits)

print('zero_count: %d' % zero_count)
print('even_count: %d' % even_count)
print('odd_count: %d' % odd_count)

The caveat with my code is that it will count leading zeros. 我的代码的警告是它将计入前导零。 While your method would not count leading zeros. 虽然您的方法不会计算前导零。 To get the exact behavior as your code, replace the line 要获得与代码完全相同的行为,请替换该行

digits = [int(i) for i in inp]

with

digits = [int(i) for i in  str(int(inp))]

By collections.Counter 按集合数

  1. Created Counter dictionary from the user input. 根据用户输入创建了Counter字典。
  2. As we know 2,4,6,8 are even digit and 3,5,7,9 are odd digit. 众所周知,2、4、6、8是偶数,3、5、7、9是奇数。 So add value of all even digit to get even count and all Odd digit to get odd count. 因此,将所有偶数的值相加可获得偶数,而所有奇数的值相加可获得奇数。

Code: 码:

from collections import Counter
digit_counter = Counter(map(lambda x: int(x), raw_input("Enter a ten-digit number please: ")))

print "Zero count",  digit_counter[0]
print "Even count", digit_counter[2]+digit_counter[4]+digit_counter[6]+digit_counter[8]
print "Odd count", digit_counter[1]+digit_counter[3]+digit_counter[5]+digit_counter[7]+digit_counter[9]

Output: 输出:

python test.py 
Enter a ten-digit number please: 0112203344
Zero count 2
Even count 4
Odd count 4

With Python 3 you can do in a better way. 使用Python 3,您可以做的更好。

from collections import Counter
#s = '03246'
s = str(input ("Enter number --> "))
c = Counter('zero' if d == '0' else ('odd' if int(d)%2 else 'even') for d in s)
print("Zero --> " ,c['zero'], "Odd--> ", c['odd'],"Even-->", c['even'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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