Как найти количество нулей в числе python

Eсть вот такой кусок кода
надо чтобы он при вводе числа в котором есть ноль, выдавал это кол-во нулей

def zero(value):
    x = 0
    if  value == '0':
        print(x)
        x = x + 1

F = input()

zero(F)

Не могу понять, что надо исправить

motpfofs's user avatar

motpfofs

1,2842 золотых знака9 серебряных знаков24 бронзовых знака

задан 1 дек 2020 в 10:49

Никита Пупкин's user avatar

3

def count_zeroes(n):
    return str(n).count('0')

ответ дан 1 дек 2020 в 10:53

USERNAME GOES HERE's user avatar

USERNAME GOES HEREUSERNAME GOES HERE

10.3k21 золотой знак25 серебряных знаков51 бронзовый знак

0

если надо работать только с числом:

num = -10203040506070809

count = 0
value = abs(num)

while value != 0:
    count += int(value % 10 == 0)
    value //= 10

print(count)

абсолютное значение берется, потому что -1 // 10 = -1 и цикл будет бесконечным для отрицательных чисел

если можно работать со строкой:

num = -10203040506070809

count = str(num).count('0')

print(count)

ответ дан 1 дек 2020 в 11:32

Zhihar's user avatar

ZhiharZhihar

36.9k4 золотых знака25 серебряных знаков67 бронзовых знаков

Если по честному работать с числом, то нужно делить:

def foo(n):
    if n < 0: 
        return foo(-n)
    i = 0
    while n:
        i += n % 10 == 0
        n //= 10
    return i

assert 3 == foo(10230240)

Для строки можно так:

def sfoo(sn):
    # if sn[0] == '-': return sfoo(sn[1:])
    # return sn.count('0')
    # len([*filterfalse(int, sn)])
    # return len([1 for d in sn if d == '0'])
    # return sum(d == '0' for d in sn)

    i = 0
    for d in sn:
        i += d == '0'

    return i

assert 3 == sfoo('10230240')

USERNAME GOES HERE's user avatar

ответ дан 1 дек 2020 в 11:03

vp_arth's user avatar

vp_arthvp_arth

27.1k2 золотых знака45 серебряных знаков76 бронзовых знаков

def f(n):
    return len(list(filter(lambda x: x == "0", str(n)))) 

ответ дан 1 дек 2020 в 11:11

Danis's user avatar

DanisDanis

19.1k5 золотых знаков20 серебряных знаков55 бронзовых знаков

1

Infeeqs

8 / 8 / 0

Регистрация: 15.02.2020

Сообщений: 195

1

Вывести количество нулей в числе

27.02.2020, 23:55. Показов 41691. Ответов 13

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Нужно вывести кол-во нулей в числе.

Вот что я написал, но не понимаю, почему не работает, может кто подсказать?

Python
1
2
3
4
5
6
a = str(input())
k = 0
for i in range(len(a)):
  if a[i] == 0:
    k = k + 1
print(k)



0



iSmokeJC

Am I evil? Yes, I am!

Эксперт PythonЭксперт Java

16118 / 9004 / 2605

Регистрация: 21.10.2017

Сообщений: 20,705

28.02.2020, 00:01

2

Лучший ответ Сообщение было отмечено Infeeqs как решение

Решение

Python
1
if a[i] == '0':

Добавлено через 2 минуты
Infeeqs,

Python
1
2
a = input()
print(a.count('0'))



2



8 / 8 / 0

Регистрация: 15.02.2020

Сообщений: 195

28.02.2020, 00:07

 [ТС]

3

Спасибо



0



Модератор

Эксперт функциональных языков программированияЭксперт Python

35427 / 19452 / 4071

Регистрация: 12.02.2012

Сообщений: 32,488

Записей в блоге: 13

28.02.2020, 12:41

4

Цитата
Сообщение от Infeeqs
Посмотреть сообщение

Вот что я написал

— и где тут число? Я бы это решение (даже с поправкой iSmokeJC) не зачел бы.



0



ioprst

1303 / 843 / 409

Регистрация: 12.03.2018

Сообщений: 2,305

28.02.2020, 13:26

5

Python
1
2
3
4
5
6
7
8
9
num = int(input('>> '))
cnt_zero = 0
 
while num > 0:
    num, tmp = divmod(num, 10)
    if tmp == 0:
        cnt_zero += 1
 
print(cnt_zero)



1



8 / 8 / 0

Регистрация: 15.02.2020

Сообщений: 195

29.02.2020, 17:52

 [ТС]

6

В каком смысле где тут число? Его должен человек ввести.



0



Am I evil? Yes, I am!

Эксперт PythonЭксперт Java

16118 / 9004 / 2605

Регистрация: 21.10.2017

Сообщений: 20,705

29.02.2020, 17:54

7

Infeeqs, имеется ввиду, что тут

Цитата
Сообщение от Infeeqs
Посмотреть сообщение

a = str(input())

получается строка, а не число.



1



8 / 8 / 0

Регистрация: 15.02.2020

Сообщений: 195

29.02.2020, 18:08

 [ТС]

8

Ясно, ну ведь человек вводит число



0



Am I evil? Yes, I am!

Эксперт PythonЭксперт Java

16118 / 9004 / 2605

Регистрация: 21.10.2017

Сообщений: 20,705

29.02.2020, 18:10

9

Я надеюсь, ты понимаешь разницу между 1234 и «1234»?
Так вот input() возвращает строку «1234»!



0



easybudda

Модератор

Эксперт PythonЭксперт JavaЭксперт CЭксперт С++

11758 / 7258 / 1720

Регистрация: 25.07.2009

Сообщений: 13,273

29.02.2020, 19:27

10

Цитата
Сообщение от Infeeqs
Посмотреть сообщение

ну ведь человек вводит число

Человек может ввести к примеру 001, или 0001, и в соответствующих строках будет 2 и 3 нуля, но в числе 1 с нулями как-то не задалось…

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
>>> def zcount(n):
...   c = 0
...   while n:
...     if n % 10 == 0:
...       c += 1
...     n //= 10
...   return c
... 
>>> zcount(102)
1
>>> zcount(int('0001'))
0
>>>



1



Эксперт Python

5407 / 3831 / 1214

Регистрация: 28.10.2013

Сообщений: 9,554

Записей в блоге: 1

29.02.2020, 19:48

11

Цитата
Сообщение от Infeeqs
Посмотреть сообщение

ведь человек вводит число

Как думаешь сколько нулей в числе 1e12?
Не поверишь — 12.



1



4200 / 2487 / 525

Регистрация: 07.11.2019

Сообщений: 4,133

01.03.2020, 15:38

12

Garry Galler, думаю согласно стандарту IEEE754 Double precision 64-bit число нулей в 1e12 будет побольше..
А вообще задача неоднозначная.. с одной стороны в числе 5 по крайней мере один ноль, с другой стороны нет нулей..



0



Эксперт Python

5407 / 3831 / 1214

Регистрация: 28.10.2013

Сообщений: 9,554

Записей в блоге: 1

01.03.2020, 15:46

13

Почему больше то? Я имел ввиду MEp to intfloat.

Вывести количество нулей в числе



0



4200 / 2487 / 525

Регистрация: 07.11.2019

Сообщений: 4,133

01.03.2020, 16:11

14

А в бинарном представлении?
1e12=01000010 01101101 00011010 10010100 10100010 00000000 00000000 00000000
Вот в этом то и неоднозначность…

Добавлено через 2 минуты
Причем впередистоящие нули тоже имеют значение..



0



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.

asked Jan 2, 2015 at 4:33

literatechild's user avatar

0

As others mentioned, it should be x = x / 10, but you also need to make your counter variables global.

Also,

print digit_count(integer)

Will display None. Since printing of the zero, odd and even counts is performed in digit_count(), you don’t need the additional print.

Another way to do this is to apply a Counter to mapped input:

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'])

answered Jan 2, 2015 at 4:56

mhawke's user avatar

mhawkemhawke

83.9k9 gold badges115 silver badges136 bronze badges

That’s because you are not re-assigning the x value after each iteration of ‘while’.

Simply change x/10, which does nothing, to 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 nonlocalinside your digit_count function. 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.

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.

answered Jan 2, 2015 at 4:43

Jobs's user avatar

JobsJobs

3,2876 gold badges25 silver badges51 bronze badges

4

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

answered Jan 2, 2015 at 4:40

Hackaholic's user avatar

HackaholicHackaholic

18.9k4 gold badges54 silver badges71 bronze badges

3

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.

Instead of processing the big integer through division by 10, I’d like to highlight an alternative method. First convert your string to a list of single digits, and then process the list through the digit_count function:

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))]

answered Jan 2, 2015 at 5:05

Haleemur Ali's user avatar

Haleemur AliHaleemur Ali

26.3k5 gold badges59 silver badges84 bronze badges

By collections.Counter

  1. Created Counter dictionary from the user input.
  2. As we know 2,4,6,8 are even digit and 3,5,7,9 are odd digit. 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

answered Jan 2, 2015 at 7:11

Vivek Sable's user avatar

Vivek SableVivek Sable

9,8103 gold badges38 silver badges55 bronze badges

With Python 3 you can do in a better way.

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'])

answered Apr 28, 2019 at 8:44

Mohammad Javed's user avatar

Skip to content

Задача «Количество нулей»

Условие

Дано N чисел: сначала вводится число N, затем вводится ровно N целых чисел.

Подсчитайте количество нулей среди введенных чисел и выведите это количество. Вам нужно подсчитать количество чисел, равных нулю, а не количество цифр.

Решение задачи от разработчиков на Python:

Другие интересные реализации задачи:

Смотреть видео — Задача «Количество нулей» решение на Python

Делитесь с друзьями ссылкой на ответ и задавайте вопросы в комментариях! 👇

Related Posts

Посмотреть все комментарии
Marchello

В обоих решениях есть ошибка, либо показана неполная их часть. Нужно определить переменную num_zeroes

wpDiscuz

1

Оставьте комментарий! Напишите, что думаете по поводу статьи.x

Eсть вот такой кусок кода
надо чтобы он при вводе числа в котором есть ноль, выдавал это кол-во нулей

def zero(value):
    x = 0
    if  value == '0':
        print(x)
        x = x + 1

F = input()

zero(F)

Не могу понять, что надо исправить

Ответы (4 шт):

def count_zeroes(n):
    return str(n).count('0')

→ Ссылка

Автор решения: vp_arth

Если по честному работать с числом, то нужно делить:

def foo(n):
    if n < 0: 
        return foo(-n)
    i = 0
    while n:
        i += n % 10 == 0
        n //= 10
    return i

assert 3 == foo(10230240)

Для строки можно так:

def sfoo(sn):
    # if sn[0] == '-': return sfoo(sn[1:])
    # return sn.count('0')
    # len([*filterfalse(int, sn)])
    # return len([1 for d in sn if d == '0'])
    # return sum(d == '0' for d in sn)

    i = 0
    for d in sn:
        i += d == '0'

    return i

assert 3 == sfoo('10230240')

→ Ссылка

Автор решения: Zhihar

если надо работать только с числом:

num = -10203040506070809

count = 0
value = abs(num)

while value != 0:
    count += int(value % 10 == 0)
    value //= 10

print(count)

абсолютное значение берется, потому что -1 // 10 = -1 и цикл будет бесконечным для отрицательных чисел

если можно работать со строкой:

num = -10203040506070809

count = str(num).count('0')

print(count)

→ Ссылка

Понравилась статья? Поделить с друзьями:
  • Как найти главную страницу компьютера
  • Как составить декларацию по прибыли для начинающих
  • Как установить найти телефон по хлопку
  • Как молиться чтобы найти друзей
  • Как составить налоговый вычет на лечение детей