Reputation:
Im trying to write a function named find_numbers that will find all numbers divisible by 7 and not by 5.
My issue is the actual function this is what I have so far:
def find_numbers(lower_bound, upper_bound):
for i in range(lower_bound,upper_bound):
if (i % 7 == 0 and i % 5 !=0):
print(i)
return ()
do i have the correct parameters? what exactly am i returning? I feel that i'm close to the correct solution, but I really am stuck :( It's printing out what I want, sort of, but not correctly. Any help is really appreciated!! Thank you all.
lower_bound = int( input("Lower bound to search for numbers: ") )
upper_bound = int( input("Upper bound to search for numbers: ") )
found_numbers = find_numbers(lower_bound, upper_bound)
print("The numbers that are divisible by 7 but not by 5
are:\n{}".format(found_numbers))
Upvotes: 0
Views: 3930
Reputation: 2004
You can think of it like pattern, offset, instead of lower and upper bounds.
7 * 5 = 35 => you’ll have a harmonic pattern of length 35, where 7, 14, 21, 28 are your numbers of interest, 35 is the one you skip. Add n * 35 as offset and you have the infinity at the reach of your hands 😏
Sorry to use java. On the go with my cell it’s what I have on the top of my mind easier.
List<Integer> pattern = Arrays.asList(7, 14, 21, 28);
Stream.iterate(0, offset -> offset + 1)
.forEach(offset -> pattern.stream()
.forEach(p -> print(35 * offset + p))
);
Upvotes: 0
Reputation: 11927
You can use a simple list comprehension for this purpose.
result = [x for x in range(lower_bound, upper_bound) if x % 7 == 0 and x % 5 != 0]
You can wrap it in a function if you want to make more elegant and re-usable like this.
def find_numbers(lower_bound, upper_bound):
return [x for x in range(lower_bound, upper_bound) if x % 7 == 0 and x % 5 != 0]
lower_bound = int( input("Lower bound to search for numbers: ") )
upper_bound = int( input("Upper bound to search for numbers: ") )
found_numbers = find_numbers(lower_bound, upper_bound)
print("The numbers that are divisible by 7 but not by 5 are:\n{}".format(found_numbers))
It can be seen that this method of list comprehension will run a little faster than conventional looping solution.
Upvotes: 3
Reputation: 2882
There are several things wrong in the logic:
I'd modify it like this:
In [1]: def find_numbers(L, U):
...: r = []
...: for i in range(L, U):
...: if i % 7 == 0 and i % 5 != 0:
...: r.append(i)
...: if not r:
...: return None
...: else:
...: return r
...:
Upvotes: 1
Reputation: 807
def find_numbers(lower_bound, upper_bound):
results=[]
for i in range(lower_bound,upper_bound):
if (i % 7 == 0 and i % 5 !=0):
results.append(i)
return results
lower_bound = int( input("Lower bound to search for numbers: ") )
upper_bound = int( input("Upper bound to search for numbers: ") )
found_numbers = find_numbers(lower_bound, upper_bound)
print("The numbers that are divisible by 7 but not by 5
are:\n{}".format(found_numbers))
Upvotes: 5