bang21
bang21

Reputation: 21

How do you print numbers with certain conditions?

The question asks 4 digit numbers within a range that has been imputed. The conditions are that there should be no number 4, no multiples of 4, and has to include number 7 at least once.

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]

Upvotes: 0

Views: 724

Answers (2)

DarrylG
DarrylG

Reputation: 17166

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

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)))))

Upvotes: 2

Huchsle
Huchsle

Reputation: 58

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

Upvotes: 0

Related Questions