python - 代码不适用于十位和百位的奇数

标签 python python-3.x math

问题是:

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

但是,我的代码仅在百位和千位不存在奇数时才有效。我哪里错了?测试用例和预期结果:

测试用例 1

  • 输入:2000,2020
  • 产量:2000,2002,2004,2006,2008,2020

测试用例 2

  • 输入:2000,2050
  • 输出:2000,2002,2004,2006,2008,2020,2022,2024,2026,2028,2040,2042,2044,2046,2048

测试用例 3

  • 输入:1000,2000
  • 输出:2000

测试用例 3 在我的案例中失败了。为什么会这样?

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

最佳答案

你的错误在于:

k=i
for j in range(4):
    last_digit=k%10
    k=i//10

您在每次迭代中将 i//10 分配给 k,并且 i 永远不会改变,因此您总是只查看最后两个数字,别无其他。如果i1234开始,那么k1234开始,last_digit变为4k 变为 123。从那里开始,您只看 123(last_digit 将是 3k = i//10所以再次 123,每次迭代)。

你需要划分k:

k=i
for j in range(4):
    last_digit=k%10
    k=k//10

一个更简单的方法是将数字(字符串值)与偶数集进行比较:

even = set('02468')

results = []
for i in range(first, last + 1):
    if set(str(i)) <= even:  # only even digits used
        results.append(i)

关于python - 代码不适用于十位和百位的奇数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52835933/

相关文章:

具有字符串和第二类的 __new__ 和 __init__ 的 Python 多重继承

python - Pip 在 Windows 7 中挂起

python - 我不明白如何在游戏 FallDown 中的 pygame 中生成多个平台

math - 获取要在 Sphinx 中显示的多行文档字符串方程。 Sphinx 中的潜在错误?

Python 在运行时意外执行命令

python - 为什么在 python 字典中添加多个 'nan' 给出多个条目?

python - 导入错误 : No module named foxhound. utils.vis

django - 如何在 Django 2 中将事件电子邮件请求从 gmail 发送到 Outlook

algorithm - 连续数的总和性质

algorithm - 比较两个点数组