i'm new to python and programming at all Was trying to make a code to give me all the factors of a number, but can't see where i'm lacking
def divisores(numero):
divisor = 0
while divisor < numero :
divisor = 1
if numero % divisor == 0:
return(divisor)
divisores(50)
all it shows is "1", that is the first factor. If i use "print", it indeed gives all the factors,but i wanted it to be all in a single line
CodePudding user response:
Return a list:
def divisores(numero):
divisor = 0
divs = [] # empty list
while divisor <= numero :
divisor = 1
if numero % divisor == 0:
divs.append(divisor)
return divs
Also, since you are counting 1
as an divisor, you likely want numero
counting as a valid divisor as well. Hence, while divisor <= numero
.
CodePudding user response:
If you want your output on a single line then you can achieve this conveniently by writing a generator which you unpack as follows:
def factors(n):
def y(f):
nonlocal neg
yield f
if neg:
yield -f
if n == 0:
raise ValueError('Cannot factor zero')
if neg := n < 0:
n = -n
yield from y(1)
for factor in range(2, n // 2 1):
if n % factor == 0:
yield from y(factor)
yield from y(n)
print(*factors(50))
Output:
1 2 5 10 25