Related
The 3 parameters: list of integers (n), integer number (n1), and another integer number (n2), not including 0
I have:
def hw(n, n1, n2):
multiples = []
for i in n:
if i % n1 == 0 and i % n2 == 0:
return multiples
which is wrong and not even returning anything. I'm not sure where I went wrong, though?
the test script:
sol= hw(np.arange(20), 3, 4)
assert sol==[3, 4, 6, 8, 9, 12, 15, 16, 18]
With return you just return from the function in the very first iteration, you need to append to the list and return the list outside of the loop.
def hw(n, n1, n2):
multiples = []
for i in n:
if i % n1 == 0 or i % n2 == 0:
multiples.append(i)
return multiples
Also, use or instead of and if you need multiples of 3 or 4.
This is how you can do it using list comprehension:
def fun(n, n1, n2):
multiples = [i for i in n if i % n1 == 0 and i % n2 == 0]
return multiples
res = fun([18, 23, 21, 42, 3], 3, 7)
print(res)
I want to iterate through a list in python, detect prime numbers and then add them to another list.
primes = []
nprimes = []
for j in range(0, len(arr)):
num = arr[j] #my list with numbers to check
if num > 1:
for k in range(2, num):
if (num % k) == 0:
nprimes.append(num)
break
else:
primes.append(num)
else:
print(num, " can't be checked, because its smaller than 1")
I have the problem that numbers are always added which are not prime numbers. Also in general the code does not seem to work properly.
If num % k == 0 is false you can't say it's prime directly you have to wait the whole loop, so move the else with the for loop, it'll be executed of no break has been encountered which means it's prime
you may iterate directly on the values for num in arr
you can stop your loop at sqrt(num) you won't find a new divisor after that
for num in arr:
if num > 1:
for k in range(2, int(num ** 0.5) + 1):
if num % k == 0:
nprimes.append(num)
break
else:
primes.append(num)
else:
print(num, " can't be checked, because its smaller than 1")
For learning purposes, let's play with a different approach. First, I recommend you move your trial division code into its own predicate function is_prime(), that returns True or False, so it can be optimized independently of the rest of your code.
Then, I'm going to have itertools.groupby divide the list into prime and non-prime sequences that we splice onto the appropriate lists:
def is_prime(number):
if number < 2:
return False
if number % 2 == 0:
return number == 2
for divisor in range(3, int(number ** 0.5) + 1, 2):
if number % divisor == 0:
return False
return True
if __name__ == "__main__":
from random import sample
from itertools import groupby
array = sample(range(1, 100), 15)
primes = []
composites = []
for are_prime, numbers in groupby(array, is_prime):
if are_prime:
primes.extend(numbers)
else:
composites.extend(numbers)
print("Numbers:", array)
print("Primes:", primes)
print("Composites:", composites)
OUTPUT
% python3 test.py
Numbers: [91, 87, 10, 2, 11, 24, 21, 12, 46, 61, 15, 32, 57, 22, 5]
Primes: [2, 11, 61, 5]
Composites: [91, 87, 10, 24, 21, 12, 46, 15, 32, 57, 22]
%
There are lots of ways to go about this problem, many of them educational!
i have a task:
got a range on input
[x;y]
then i should check every number from that range and check every numeral in number. if its odd, i should print it
for example: 3, 20
i should print 4,6,8,20
def check(num):
if int(num) % 2 == 0:
return True
x, y = int(input()), int(input())
numbers = []
if x <= y:
while x != y:
for i in str(x):
if check(i):
numbers.append(x)
x += 1
else:
while y != x:
for i in str(y):
i = int(i)
if check(i):
numbers.append(y)
y += 1
if y == x:
for i in str(x):
if check(i):
numbers.append(x)
print(numbers)
it prints
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 20, 21, 22, 22, 23, 24, 24, 25, 26, 26, 27, 28, 28, 29]
instead of 2,4,6,8,20,22,24,26,28
You are checking and approving based on a single digit for each number. You should check all of them before appending the entire number. That's why you get 22 twice: once for the first 2 and once for the second. You get 10, because even though 1 is odd, 0 is even and so you append it to your list.
Move the check for the entire number into the function check and have it return True only if all digits are even. This shortens your code. Also note that you can trivially swap x and y if the user entered them in the wrong order.
The function check immediately returns False as soon as it finds a digit i is odd, and you can see it can only return True if the loop ended and all digits were even.
def check(num):
for i in str(num):
if int(i) % 2 != 0:
return False
return True
x, y = int(input()), int(input())
if x > y:
x,y = y,x
numbers = []
while x <= y:
if check(x):
numbers.append(x)
x += 1
print (numbers)
Result, with 3 and 20 entered (but 20 and 3 would also work):
[4, 6, 8, 20]
Am new to python and I have been trying to solve this problem but it does not seem to work as intended. your help is highly appreciated:
Given two numbers X and Y, write a function that:
returns even numbers between X and Y, if X is greater than Y
else returns odd numbers between x and y
.
def number(x,y):
if x > y:
for i in range(x,y):
if i%2 == 0:
list = []
return list.append[i]
else:
for i in range(x,y):
if i%2 == 1:
list = []
return list.append[i]
print(number(10,2))
Try this code it's working as per your need.
def number(x,y):
num= []
if x > y:
for i in range(y,x):
if i%2 == 0:
num.append(i)
else:
for i in range(x,y):
if i%2 == 1:
num.append(i)
return num
print(number(2,10))
print(number(10,2))
The outputs are:
[3, 5, 7, 9]
[2, 4, 6, 8]
Let me know if this doesn't serve your purpose.
And it is done. Basically if x > y, you need to switch the first range. You append the items normally(using () instead of []), and then return the full list, got it?
def number(x,y):
list = []
if x > y:
for i in range(y,x):
if i%2 == 0:
list.append(i)
else:
for i in range(x,y):
if i%2 == 1:
list.append(i)
return list
print(number(10,2))
Working sample: https://py3.codeskulptor.org/#user302_nwBq00w56n_1.py
Instead of testing for oddness/evenness all the time, use range(start,stop[,step]) with a step of 2 starting with a (corrected, known) odd/even number:
def number(x,y):
if x > y:
if y%2 == 1: # y is smaller && odd
y += 1 # make even
return list(range(y,x,2)) # x is > y - start from y to x
else: # this is strictly not needed - but more verbose intention-wise
if x%2 == 0: # is even
x += 1 # make odd
return list(range(x,y,2))
print(number(10,32))
print(number(10,2))
You need to also switch x and y if x > y
you do not need to iterate a range and add its element to a list iteratively - simply stuff the range-sequence into the list(sequence) constructor and return it
Output:
[11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31]
[2, 4, 6, 8]
It's so easy to do, and there are several ways to do what do you want, so i show you two ways to do that, first an understandable way and second an easy way ok let's start:-
First example
def number(x,y):
list = [] #firstly create a list
if x > y: #if x was greater than y
for num in range(y, x): # a loop for searching between them
if(num % 2 == 0): # if the number was even add it to list
list.append(num)
elif y > x: #if y was greater than x
for num in range(x, y): # a loop for searching between them
if(num % 2 != 0): # if the number was not even add it to list
list.append(num)
return list
print(number(10, 20))
print(number(20, 10))
#[11, 13, 15, 17, 19]
#[10, 12, 14, 16, 18]
Second example
number = lambda x, y : [n for n in range(y, x) if n%2 == 0] if x > y else [n for n in range(x, y) if n%2 != 0]
print(number(10, 20))
print(number(20, 10))
#[11, 13, 15, 17, 19]
#[10, 12, 14, 16, 18]
Note : But be sure that in both of my answers the x number is inclusive(exists in searching function) and the y number is exclusive, so if you wanted to make both of them inclusive so make loops ...(x, y+1)... and if you wanted to make both of them exclusive just change loops to ...(x+1, y)....
Knowing that 2 % 2 == 0 we then can just use if not 2 % 2 for evens since not 0 will evaluate to true, here it is with comprehension and in extended form
def something(x, y):
if x > y:
l = [i for i in range(y, x) if not i % 2]
else:
l = [i for i in range(x, y) if i % 2]
return l
print(something(10, 2))
print(something(2, 10))
~/python/stack$ python3.7 sum.py
[2, 4, 6, 8]
[3, 5, 7, 9]
Full loop:
def something(x, y):
l = []
if x > y:
for i in range(y, x):
if not i % 2:
l.append(i)
else:
for i in range(x, y):
if i %2:
l.append(i)
return l
Here in this i use the list comprehensions.list comprehension is a easy and readable technique in python.In this i include both x and y
def fun(x,y):
if x>y:
l=[i for i in range(y,x-1) if i%2==0]
return l.reverse()
else:
l=[i for i in range(x,y+1) if i%2!=0]
return l
I've been trying to complete this assignment but I couldn't get what is asked, which is: in Python 3, Ask a user to enter an integer (1, 1000). Out of the list of the first prime numbers 2,3,5,7, print those prime numbers that are factors of the received integer.
I hope could help me to get this.
def get_primes(n):
out = list()
sieve = [True] * (n+1)
for p in range(2, n+1):
if (sieve[p]):
out.append(p)
for i in range(p, n+1, p):
sieve[i] = False
return out
def get_factors(n):
output = list()
for i in range(1, n + 1):
if n % i == 0:
output.append(i)
return output
# input_number = input('Enter a number')
# input_number = int(input_number)
input_number = 30
primes = get_primes(input_number+1) # [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
factors = get_factors(input_number) # [1, 2, 3, 5, 6, 10, 15, 30]
prime_factors = list()
for i in factors:
if i in primes:
prime_factors.append(i)
print(prime_factors)
Output:
[2, 3, 5]
Code for getting prime numbers:
Print series of prime numbers in python