作者:Nedo_zou | 来源:互联网 | 2023-08-13 21:40
该问题要求编写一个程序,如果给定的整数内所有数字均为奇数,则返回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)])