Как найти количество четных чисел питон

Given a list of numbers, write a Python program to count Even and Odd numbers in a List.

Example:

Input: list1 = [2, 7, 5, 64, 14]
Output: Even = 3, odd = 2

Input: list2 = [12, 14, 95, 3]
Output: Even = 2, odd = 2

Example 1: 

Count Even and Odd numbers from the given list using for loop Iterate each element in the list using for loop and check if num % 2 == 0, the condition to check even numbers. If the condition satisfies, then increase the even count else increase odd count. 

Python3

list1 = [10, 21, 4, 45, 66, 93, 1]

even_count, odd_count = 0, 0

for num in list1:

    if num % 2 == 0:

        even_count += 1

    else:

        odd_count += 1

print("Even numbers in the list: ", even_count)

print("Odd numbers in the list: ", odd_count)

Output:

Even numbers in the list:  3
Odd numbers in the list:  4

Time Complexity: O(N), Here N is the number of elements in the list.
Auxiliary Space: O(1), As constant extra space is used.

Example 2: Using while loop 

Python3

list1 = [10, 21, 4, 45, 66, 93, 11]

even_count, odd_count = 0, 0

num = 0

while(num < len(list1)):

    if list1[num] % 2 == 0:

        even_count += 1

    else:

        odd_count += 1

    num += 1

print("Even numbers in the list: ", even_count)

print("Odd numbers in the list: ", odd_count)

Output:

Even numbers in the list:  3
Odd numbers in the list:  4

Time Complexity: O(N), Here N is the number of elements in the list.
Auxiliary Space: O(1), As constant extra space is used.

Example 3: Using Python Lambda Expressions 

Python3

list1 = [10, 21, 4, 45, 66, 93, 11]

odd_count = len(list(filter(lambda x: (x%2 != 0) , list1)))

even_count = len(list(filter(lambda x: (x%2 == 0) , list1)))

print("Even numbers in the list: ", even_count)

print("Odd numbers in the list: ", odd_count)

Output:

Even numbers in the list:  3
Odd numbers in the list:  4

Time Complexity: O(n)
Space Complexity: O(1)

Example 4: Using List Comprehension 

Python3

list1 = [10, 21, 4, 45, 66, 93, 11]

only_odd = [num for num in list1 if num % 2 == 1]

odd_count = len(only_odd)

print("Even numbers in the list: ", len(list1) - odd_count)

print("Odd numbers in the list: ", odd_count)

Output:

Even numbers in the list:  3
Odd numbers in the list:  4

Time Complexity: O(N), Here N is the number of elements in the list.
Auxiliary Space: O(1), As constant extra space is used.

Example 5: Using Recursion

Python3

even_count = 0 

i = 0 

odd_count = 0 

def evenoddcount(lst):

    global even_count

    global odd_count

    global i

    if lst[i] % 2 == 0

        even_count += 1

    else

        odd_count += 1

    if i in range(len(lst)-1):

        i += 1 

        evenoddcount(lst) 

    else:

        print("Even numbers in the list: ", even_count)

        print("Odd numbers in the list: ", odd_count)

list1 = [10, 21, 4, 45, 66, 93, 1]

evenoddcount(list1)

Output

Even numbers in the list:  3
Odd numbers in the list:  4

Time Complexity: O(N), Here N is the number of elements in the list.
Auxiliary Space: O(1), As constant extra space is used.

Example 6: Using Bitwise XOR operator

The idea is to check whether the last bit of the number is set or not. If the last bit is set then the number is odd, otherwise even. As we know bitwise XOR Operation of the Number by 1 increments the value of the number by 1 if the number is even otherwise it decrements the value of the number by 1 if the value is odd.

CHECK IF NUMBER IS EVEN OR ODD USING XOR OPERATOR

Python3

list1 = [10, 21, 4, 45, 66, 93, 1]

even_count, odd_count = 0, 0

for num in list1:

    if num ^ 1 == num + 1:

        even_count += 1

    else:

        odd_count += 1

print("Even numbers in the list: ", even_count)

print("Odd numbers in the list: ", odd_count)

Output

Even numbers in the list:  3
Odd numbers in the list:  4

Time Complexity: O(N), Here N is the number of elements in the list.
Auxiliary Space: O(1), As constant extra space is used.

Example 7: Using Bitwise AND operator

The idea is to check whether the last bit of the number is set or not. If the last bit is set then the number is odd, otherwise even.
As we know bitwise AND Operation of the Number by 1 will be 1, If it is odd because the last bit will be already set. Otherwise, it will give 0 as output. 

Python3

list1 = [10, 21, 4, 45, 66, 93, 1]

even_count, odd_count = 0, 0

for num in list1:

    if not num & 1:

        even_count += 1

    else:

        odd_count += 1

print("Even numbers in the list: ", even_count)

print("Odd numbers in the list: ", odd_count)

Output

Even numbers in the list:  3
Odd numbers in the list:  4

Time Complexity: O(N), Here N is the number of elements in the list.
Auxiliary Space: O(1), As constant extra space is used.

Example 8: Using Bitwise OR operator

The idea is to check whether the last bit of the number is set or not. If the last bit is set then the number is odd, otherwise even. As we know bitwise OR Operation of the Number by 1 increment the value of the number by 1 if the number is even otherwise it will remain unchanged. So, if after OR operation of number with 1 gives a result which is greater than the number then it is even and we will return true otherwise it is odd and we will return false.

Python3

list1 = [10, 21, 4, 45, 66, 93, 1]

even_count, odd_count = 0, 0

for num in list1:

    if num | 1 > num:

        even_count += 1

    else:

        odd_count += 1

print("Even numbers in the list: ", even_count)

print("Odd numbers in the list: ", odd_count)

Output

Even numbers in the list:  3
Odd numbers in the list:  4

Time Complexity: O(N), Here N is the number of elements in the list.
Auxiliary Space: O(1), As constant extra space is used.

Method: Using the enumerate function 

Python3

lst = [12, 14, 95, 3];c=0;c1=0

for i,a in enumerate(lst):

    if a%2==0:

        c+=1

    else:

        c1+=1

print("even number count",c,"odd number count",c1)

Output

even number count 2 odd number count 2

Time Complexity: O(N), Here N is the number of elements in the list.
Auxiliary Space: O(1), As constant extra space is used.

Method: Using Numpy.Array : 

Python

import numpy as np

List = [10, 21, 4, 45, 66, 93, 11]

list1 = np.array(List)

Even_list = list1[list1 % 2 == 0]

print("Even numbers in the list: ", len(Even_list))

print("Odd numbers in the list: ", len(list1)-len(Even_list))

Output:

Even numbers in the list:  3
Odd numbers in the list:  4

Time Complexity: O(N), Here N is the number of elements in the list.
Auxiliary Space: O(1), As constant extra space is used.

Method: Using Numpy.where() function : 

note: install numpy module using command “pip install numpy”

Algorithm:

Convert the given list to a numpy array.
Use numpy.where() function to find the indices of even and odd numbers in the array.
Count the number of indices using the len() function.
Print the counts.

Here’s the Python program to count Even and Odd numbers in a List using numpy.where() function:

Python3

import numpy as np

list1 = [2, 7, 5, 64, 14]

arr = np.array(list1)

even_count = len(np.where(arr % 2 == 0)[0])

odd_count = len(np.where(arr % 2 == 1)[0])

print("Even numbers in the list: ", even_count)

print("Odd numbers in the list: ", odd_count)

Output:

Even numbers in the list:  3
Odd numbers in the list:  2

Time Complexity: O(N), where N is the number of elements in the list.
Space Complexity: O(N), as we create a numpy array of size N.

Method: Using Sum and len function  

Approach: 

  • Initialize list. 
  • Initialize even_count and odd_count variables to store numbers. 
  • Use Sum method which counts 1 if the number in the list is odd and store the result in odd_count. 
  • Subtract the total length list to odd_count and store the value in even_count. 
  • Print event_count and odd_count. 

Python3

list1 = [10, 21, 4, 45, 66, 93, 1]

even_count, odd_count = 0, 0

odd_count = sum(1 for i in list1 if i&1)

even_count = len(list1) - odd_count

print("Even numbers in the list: ", even_count)

print("Odd numbers in the list: ", odd_count)

Output:

Even numbers in the list:  3
Odd numbers in the list:  4

Time Complexity: O(n), where n is the length of the list.
Space Complexity: O(1), Because no extra space is used.

Посчитать четные и нечетные цифры числа

Определить, сколько в числе четных цифр, а сколько нечетных. Число вводится с клавиатуры.

Решение задачи на языке программирования Python

Если число делится без остатка на 2, его последняя цифра четная. Увеличиваем на 1 счетчик четных цифр even. Иначе последняя цифра числа нечетная, увеличиваем счетчик нечетных цифр odd.

В Python операцию нахождения остатка от деления выполняет знак %.

Чтобы избавиться от младшего уже учтенного разряда, число следует разделить нацело на 10. Деление нацело обозначается двумя слэшами //.

a = int(input())
 
even = 0
odd = 0
 
while a > 0:
    if a % 2 == 0:
        even += 1
    else:
        odd += 1
    a = a // 10
 
print(f'Even: {even}, odd: {odd}')

Пример выполнения:

Кроме чисто математического подхода в Python можно решить задачу “через строку”. Мы не будем переводить введенное строковое представление числа к целочисленному типу, вместо этого переберем символы строки в цикле for. Каждый символ преобразуем к числу и проверим на четность.

a = input()
 
even = 0
odd = 0
 
for i in a:
    if int(i) % 2 == 0:
        even += 1
    else:
        odd += 1
 
print("Even: %d, odd: %d" % (even, odd))

Поскольку количество четных (как и нечетных) цифр ограничено, в программу можно включить что-то типа “базы данных” и проверять каждый символ на вхождение в нее.

a = input()
 
digits = "02468"
 
even = 0
odd = 0
 
for i in a:
    if i in digits:
        even += 1
    else:
        odd += 1
 
print("Even: %d, odd: %d" % (even, odd))

Обратим внимание, что оператор in языка Python в заголовке цикла for обозначает иное, чем в заголовке условного оператора. Логическое выражение i in digits возвращает истину если i входит в состав digits. В иных случаях – ложь.

Больше задач в PDF

Перейти к содержанию

На чтение 2 мин Просмотров 1.7к. Опубликовано 27.01.2023

Содержание

  1. Введение
  2. Написание кода программы для подсчёта чётных и нечётных цифр числа
  3. Заключение

Введение

В ходе статьи напишем программу для подсчёта чётных и нечётных цифр в числе на языке программирования Python.

Написание кода программы для подсчёта чётных и нечётных цифр числа

Для начала дадим пользователю возможность ввода числа и создадим две переменные, одна для чётных цифр, вторая для нечётных:

number = int(input('Введите число: '))
# Для чётных цифр
even = 0
# Для нечётных цифр
odd = 0

Создадим цикл while, который не закончится пока number > 0:

number = int(input('Введите число: '))

even = 0
odd = 0

while number > 0:

Внутри цикла зададим условие, если number делится на 2 без остатка, то цифра чётная и прибавляем к even единицу, если условие не сработало, то цифра нечётная и прибавляем единицу к odd:

number = int(input('Введите число: '))

even = 0
odd = 0

while number > 0:
    if number % 2 == 0:
        even += 1
    else:
        odd += 1

После условия делим number целочисленно на 10, чтобы избавиться от цифры, которая уже была проверена:

number = int(input('Введите число: '))

even = 0
odd = 0

while number > 0:
    if number % 2 == 0:
        even += 1
    else:
        odd += 1
    number = number // 10

Выведем результат используя форматирование f-string:

number = int(input('Введите число: '))

even = 0
odd = 0

while number > 0:
    if number % 2 == 0:
        even += 1
    else:
        odd += 1
    number = number // 10

print(f'Количество чётных цифр: {even}')
print(f'Количество нечётных цифр: {odd}')

Проверка программы:

Введите число: 9876124
Количество чётных цифр: 4
Количество нечётных цифр: 3

Заключение

В ходе статьи мы с Вами написали программу для подсчёта чётных и нечётных цифр в числе на языке программирования Python. Надеюсь Вам понравилась статья, желаю удачи и успехов! 🙂

Admin

lower = int(input())
upper = int(input())
odd = 0
even = 0
prima = 0
for i in range(lower, upper+1):
    if i % 2 == 0:
        even += 1
    else:
        odd += 1

    if i > 1:
        for j in range(2, i):
            if (i % j) == 0:
                break
            else:
                prima += 1

print(prima, even, odd)

Я написала вот такой код. Что касается нечётных и чётных чисел – всё работает. А вот с простыми числами выдаёт неправильный ответ. Подскажите в чём проблема. Спасибо.

задан 8 авг 2021 в 15:38

python_prog's user avatar

python_progpython_prog

651 золотой знак2 серебряных знака12 бронзовых знаков

Вам нужно изменить условие для проверки на простоту числа. Раньше вы считали число правильным сразу, если оно не делилось на 2.

По сути надо написать блок else для цикла, то есть удалить по знаку табуляции на 2 строках. Так будет работать:

upper = int(input())
odd = 0
even = 0
prima = 0
for i in range(lower, upper+1):
    if i % 2 == 0:
        even += 1
    else:
        odd += 1

    if i > 1:
        for j in range(2, i):
            if (i % j) == 0:
                break
        else:
            prima += 1

print(prima, even, odd)

P.S. Для проверки числа на простоту достаточно перебирать только от 2 до квадратного корня этого числа

ответ дан 8 авг 2021 в 15:54

Elusha's user avatar

Отфильтруй и посчитай длину, например.

 a = [1, 2, 3, 4, 5, 6, 7]
print(len(list(filter(lambda i: i % 2 == 0, a))))

Выведет 3.
Чуть более короткий вариант:

 print(len([x for x in a if x % 2 == 0])) 

А учитывая, что там ещё и цикл, можно заменить его.
Было:

 for i in a:
if i%2==0:
print(i)

Стало:

 e = [x for x in a if x % 2 == 0]
print(*e, len(e), sep = 'n')

Принт выведет сами чётные числа, по одному на строке, и отдельной строкой – их количество.

И вообще, я бы рекомендовал методом Чака Норриса переписать весь алгоритм:

 import random

a = [random.randint(5, 15) for i in range(10)]
print(*a, '', sep = 'n')

a.insert(1,25)
print(a[1], 'n')

e = [x for x in a if x % 2 == 0]
print(*e, '', len(e), sep = 'n')

Добавил в вывод пустые строки для ясности, где какие числа выводятся.

Добавить комментарий