[英]How do you print numbers with certain conditions?
The question asks 4 digit numbers within a range that has been imputed.该问题询问已估算范围内的 4 位数字。 The conditions are that there should be no number 4, no multiples of 4, and has to include number 7 at least once.
条件是不能有数字 4,不能是 4 的倍数,并且必须至少包含一次数字 7。
An example would be:一个例子是:
start: 1069
end : 1074
1070, 1071, 1073
So far I only have this:到目前为止,我只有这个:
start = int(input("start: ")
end = int(input("end: ")
num_list = [i for i in range(start, end) if i % 4 != 0]
Code代码
def satisfy(n):
" Conditions "
if n % 4 == 0:
return False # no multiples of 4
s = str(n)
if len(s) != 4:
return False # lenght is not 4
if '4' in s:
return False # can't have a 4 in number
if not '7' in s:
return False # must have a 7 in number
return True
start = int(input("start: "))
end = int(input("end: "))
num_list = [i for i in range(start, end+1) if satisfy(i)]
print(num_list)
Test Input测试输入
start: 1069
end: 1074
[1070, 1071, 1073]
Alternative One-liner from @Matthias in comment来自@Matthias 的另类 One-liner 在评论中
print(', '.join(map(str, (n for n in range(start, end+1) if n%4 and '4' not in str(n) and '7' in str(n)))))
def liste (start,end):
num_list = []
for i in range(start,end):
if (i % 4 != 0) and ('4' not in str(i)):
num_list.append(i)
else :
return False
if '7' in str(i):
num_list.append(True)
if True in num_list:
return True
else:
return False
testlist = liste(int(input('start:')),int(input('end:')))
print(testlist)
Input: 1077,1078 Output: True输入:1077,1078 Output:真
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.