简体   繁体   English

如何在特定条件下打印数字?

[英]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.

相关问题 您如何根据数据框中的某些数字计算总和? - How do you calculate the sum based on certain numbers in the dataframe? 如何从文件中打印出符合特定条件但有许多列要检查的行? - How do you print out lines from a file that match a certain condition, but you have many columns to check? 如何找到一定范围内的所有素数并打印出来? - How do i find all the prime numbers in a certain range and print them out? 如何打印 if else 语句中某个参数被满足的次数? - How do you print how many times a certain parameter was met in an if else statement? 如何从python中具有一定条件的句子中提取数字? - How to extract numbers from sentences with certain conditions in python? 如何使用 python 通过用户输入在范围内打印一定数量的结果? - How do you print certain amount of results in range by user input using python? 如何打印具有特定状态码的最常用的客户端 IP。 - How do you print the top most used clients IP with a certain status code.? 您如何阅读文本文件并只打印列出的某些行? - How do you read a text file and only print certain lines listed together? 如何在python中从多行用户输入中打印最大和最小数字? - How do you print the maximum and minimum numbers from multiple lines of user input in python? 如何在python的for循环中仅打印某些条件 - How to print only certain conditions inside my for loop in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM