问:写一个函数safe(n),它取一个非负整数n作为输入,其中n最多有2位数。该函数确定n是否为安全数字。如果数字包含9作为数字,或者它可以除以9,则该数字是不安全的。该函数应测试n是否安全并返回表示测试结果的字符串,“数字是安全的”,或“数字不安全”。(解决下面的问题没有循环,if和其他分支声明,列表) 到目前为止,我有:
def safe(n):
0<n<100
n%9!=0
return 'The number is safe'
return 'The number is not safe'
我知道这是错误的/不完整的,但我不确定该怎么做?
答案 0 :(得分:2)
您需要检查三种不同的条件:
def safe(n):
not_divisible = n % 9 != 0
not_9x = n // 10 != 9
not_x9 = n % 10 != 9
return not_divisible and not_9x and not_x9
要在不使用if
语句的情况下返回字符串,可以使用三元运算符:
def safe(n):
not_divisible = n % 9 != 0
not_9x = n // 10 != 9
not_x9 = n % 10 != 9
is_safe = not_divisible and not_9x and not_x9
return 'The number is safe' if is_safe else 'The number is not safe'
可以说,这仍然使用分支,所以你可能很聪明:
def safe(n):
not_divisible = n % 9 != 0
not_9x = n // 10 != 9
not_x9 = n % 10 != 9
is_safe = not_divisible and not_9x and not_x9
lookup = ['The number is not safe', 'The number is safe']
return lookup[int(is_safe)]
这当然是荒谬的,但是,说明也是如此。
编辑:该解决方案使用不允许的列表。这是一本带字典:
def safe(n):
not_divisible = n % 9 != 0
not_9x = n // 10 != 9
not_x9 = n % 10 != 9
is_safe = not_divisible and not_9x and not_x9
lookup = {
False: 'The number is not safe',
True: 'The number is safe'
}
return lookup[is_safe]
答案 1 :(得分:0)
def safe(n):
if n>0 and n<100:
if n%9==0 or '9' in str(n):
print('The number is not safe')
else:
print('The number is safe')
else:
print('Not acceptable number')