Home > Enterprise >  python code to find number of integers with only even digits and with only odd digits
python code to find number of integers with only even digits and with only odd digits

Time:04-11

I'm writing a python program that returns the number of integers in a list that have only even digits and number of integers that have only odd digits for example if the list values are 222,333,456,789 then number of integers with only even digits is 1 and only odd digits is 1, the code works fine if single digit inputs are given but takes infinite inputs when 2 or more digit inputs are given... please help.. here's the code

count_p=0
count_n=0
lst=[]
n=int(input())
for i in range(0, n):
    ele = int(input())
    lst.append(ele)
for i in range(len(lst)):
    if lst[i]>10:
        a=lst[i]
        if a%2==0:
            count_p=count_p 1
        else:
            count_n=count_n 1
        
        while lst[i]/10>0:
            b=lst[i]/10
            if b%2==0:
                count_p=count_p 1
            else:
                count_n=count_n 1
    else:
        if lst[i]%2==0:
            count_p=count_p 1
        else:
            count_n=count_n 1
print("even arre",count_p)
print("odd arre",count_n)

CodePudding user response:

while lst[i]/10>0:
    b=lst[i]/10
    if b%2==0:
        count_p=count_p 1
    else:
        count_n=count_n 1

This while loop is iterating. In the code lst is the list of input numbers. If your input is [123, 222, 234] this loop should iterate over a number for every digit in that number.

But you are iterating through the list again.

Why it is going to be infinite?: Because you haven't incremented i. This loop should be implemented for every digit.

Assigin current_number = lit[i]. Now use this variable for to check other digits in the number.

CodePudding user response:

count_p=0
count_n=0
lst=[]
n=int(input())
for i in range(0, n):
    ele = input()
    lst.append(ele)
for i in range(len(lst)):
    for j in lst[i]:
        if int(j)%2==0:
            count_p=count_p 1
        else:
            count_n=count_n 1
print("even arre",count_p)
print("odd arre",count_n)

I believe this method is closest to your code, more simple and more readable. Simply take each number from the string of the numbers, turn it into an int and check if its even or odd. Also, you could put the range of the 2nd for loop as n not sure why you put len(lst).

On the other hand, as pointed by other, the problemtic part was mainly but not limited to this part

while lst[i]/10>0:
            b=lst[i]/10
            if b%2==0:
                count_p=count_p 1
            else:
                count_n=count_n 1
  • Related