热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何获得一个程序以对所有奇数位整数返回True?

该问题要求编写一个程序,如果给定的整数内所有数字均为奇数,则返回true,否则为

该问题要求编写一个程序,如果给定的整数内所有数字均为奇数,则返回true,否则为false。

我得到了一些简单的方法,但是仅当数字在列表中时才起作用,而不仅仅是当它们以整数形式给出时。

输入:

def test3(n):
for x in n:
print (x%2 != 0)
test3([13579])

输出:

True

输入:

def test3(n):
for x in n:
print (x%2 != 0)
test3(13579)

输出:

Traceback (most recent call last):
File "main.py",line 86,in
test3(13579)
File "main.py",line 83,in test3
for x in n:
TypeError: 'int' object is not iterable

预期输出:

True

这个问题也有一个提示:
提示:

To extract the lowest digit of a positive integer n,use the expression n % 10. To extract all other digits except the lowest one,use the expression n // 10. Or,if you don't want to be this fancy,first convert the number into a string and work there. (There is a more general and fundamental idea hidden in plain sight in this technique.)```



您正在弄乱整数和字符串类型。为了遍历数字,我们必须先将整数转换为字符串,然后将每个数字重新转换为整数以检查其是奇数还是偶数。这有点忽略了给出的提示,但是我认为它比提示所提示的方式更加优雅:)(但这值得商。)

def odd_digits_only(number: int) -> bool: # this is equal to
# def odd_digits_only(number):
for digit in str(number):
if int(digit) % 2 == 0:
return False
return True

可以使用列表理解和all来缩短此时间:

def odd_digits_only(number: int) -> bool:
return all([int(digit) % 2 != 0 for digit in str(number)])


推荐阅读
author-avatar
Nedo_zou
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有