Reputation: 55
question is:
Write a program, which will find all such numbers between m and n (both included) such that each digit of the number is an even number.
Input Format:
The first line contains value m and n separated by a comma.Output Format:
The numbers obtained should be printed in a comma-separated sequence on a single line.Constraints:
1000<=m<=9000
1000<=n<=9000
However my code only works when no odd number is present at hundreds and thousands place. Where am I going wrong? Test cases and expected results:
Test Case 1
Test Case 2
Test Case 3
Test case 3 is failing in my case. Why is it so?
num=list(map(int,input().split(",")))
length=len(num)
list=[]
first=num[0]
last=num[length-1]
for i in range(first,last+1):
count=0
num1 = i
k=i
for j in range(4):
last_digit=k%10
k=i//10
if(last_digit%2==0):
count=count+1
if(count==4):
list.append(num1)
length2=len(list)
for i in range(length2):
if(i<length2-1):
print(list[i],end=',')
else:
print(list[i])
Upvotes: 2
Views: 274
Reputation: 1122102
Your error lies here:
k=i
for j in range(4):
last_digit=k%10
k=i//10
You are assigning i // 10
to k
each iteration, and i
never changes, so you always only look at the last two digits, never anything else. If i
starts at 1234
, then k
starts at 1234
, last_digit
becomes 4
and k
becomes 123
. From there on out, you only look at 123
(last_digit
will be 3
and k = i // 10
so 123
again, each iteration).
You need to divide k
:
k=i
for j in range(4):
last_digit=k%10
k=k//10
A simpler method would be to compare the digits (string values) to the set of even digits:
even = set('02468')
results = []
for i in range(first, last + 1):
if set(str(i)) <= even: # only even digits used
results.append(i)
Upvotes: 1
Reputation: 28447
For readability's sake, I'd write something like so:
nums = list(map(int, input().split(",")))
all_even = []
for num in range(nums[0], nums[1]+1):
# Skips the num if it's not even
if num % 2 != 0:
continue
# Skips the num if any of its digits is not even
# Note that it'll skip on the first item that is not even
# so it is rather efficient as it does not necessarily
# need to iterate over *all* digits
if any(int(digit) % 2 != 0 for digit in str(num)):
continue
# Appends the num to the final list
all_even.append(str(num))
print(','.join(all_even))
Upvotes: 0