python - 在 Python 中显示包含 4 和 5 最多 10 000 的 2 个奇数的数字

标签 python python-3.x count

我正在尝试制作一个程序,它只会显示包含 2 个奇数的数字,其中还包含一个 4 和一个 5,直到 10000。

我做了这个,但我无法让它检查奇数,它只显示包含 4 和 5 的那些。

n = 9999
def countNumbersWith4(n) : 
    result = 0
    for x in range(1, n + 1) : 
        if((has4(x) == True) & (has5(x) == True)) :
            def countEvenOdd(x):
                odd_count = 0
                while (x > 0):
                    rem = x % 10
                    if (rem % 2 != 0):
                        odd_count += 1             
                    x = int(x / 10)
            t = countEvenOdd(x);
            result = result + 1 
            print(x)
    return result 
def has4(x) : 
    while (x != 0) : 
        if (x%10 == 4) : 
            return True 
        x = x //10
def has5(x) :
    while (x != 0) :
        if (x%10 == 5) :
            return True
        x = x //10 

    return False
print ("0 to ", n," is ",countNumbersWith4(n))

最佳答案

也许不是最好的风格,但很管用,希望也适合你 ;-)

def two_odd_numbers(n):
    cnt = 0

    for i in n:
        if int(i) % 2 == 0:
            cnt += 1

    return cnt == 2

def containing_two_odd_numbers_4_and_5(n):
    l = []
    for i in range(1000, n):
        number = str(i)
        if '4' in number and '5' in number and two_odd_numbers(number):
            l.append(i)
    return l


if __name__ == '__main__':
    n = 9999
    l = containing_two_odd_numbers_4_and_5(n)
    print('0 to {} is {}'.format(n, len(l)))
    print(l)

关于python - 在 Python 中显示包含 4 和 5 最多 10 000 的 2 个奇数的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51119253/

相关文章:

python - 从python中的JSON字符串中提取特定值

python - 创建奇怪的边矩阵

python - 如何在 Django 1.7 中导出到 excel 日期时间

python - 循环http客户端python,扭曲

python - 通过Python脚本查看Azure中虚拟机的故障和更新域

php - MySQL 查询 w/COUNT() 和 HAVING 基于日期比较

r - 计算字符串中出现在 R 字符串中特定位置的单词

Python 基础 - 为什么我的文件内容不打印?

python - 简单的 Python 服务器设置