I wanted to improve my python so I decided to implement some math functions. I implemented the integer factorization as follows:
def integer_factorization(x):
if isprime(x):
return [x]
factors = []
for i in sieve_eratosthenes(x):
while x % i == 0:
int_fact.append(i)
x /= i
return factors
I want to return all the factors of x
in a list.
Now I wonder if I can do it with list comprehension as I return a list in any case, whether it adds readability to the function or not (the use of such syntactic sugar is what I meant with when I said I want to improve my python).
I noticed that it is not possible (or I just don't know how) to use a while-loop in list-comprehension as you would use a for-loop in it.
For example:
#filling l with items of lst with a for loop
def foo1(lst):
l = []
for i in list:
l.append(i)
return l
#filling l with items of lst with a while loop
def foo2(lst):
l = []
i = 0
while i < len(lst):
l.append(lst[i])
return l
foo1()
can be "transformed" into
def foo1(list):
return [x for x in list]
But is it possible to use this list-comprehension as I did with foo1()
also with foo2()
?
If yes how can I rewrite integer_factorization()
into something like:
def integer_factorization(x):
return [x if isprime(x) else for i in sieve_eratosthenes(x) #while x%i==0 ...]
If this is not possible, why is it like that? In what way does a for-loop differ from a while-loop that it can not be used in list-comprehension?