+ 1
Trouble returning values from my factor finder function
I am trying to code a factor finder function to find the factor of a user input, when printing the values proven to be factors in the for loop it works but, returning the values only returns the first factor, 1. Any help is much appreciated! code: num = int(input()) def factor_call(num): for i in range(1, num + 1): if num % i == 0: return i print(factor_call(num))
7 Respuestas
+ 7
coprime takes an integer but you're giving it range and 'num % i != 0' means i is not factor of num so you should use '=='
def coprime(z): #returns True if z is coprime to num
for i in factors(z):
if i in num_factors:
return False
return True
for i in range(1, num + 1):
if coprime(i):
print(i)
def coprime2(rn): #returns generator containing numbers coprime to num
for z in rn:
for i in factors(z):
if i in num_factors:
break
else:
yield z
print(list(coprime2(range(1, num + 1))))
+ 7
generator == generator always returns False so you should use a loop to check if num and z have common factors like this:
num_factors = list(factors(num))
for i in factors(z):
if i in num_factors:
break
else:
yield z
and you should use range(2, num + 1) in 'factors'
+ 2
Thanks
+ 2
This keeps returning unsupported operant types, I'm not used to generators apart from the fact that they are similar to lists but do not hold values
num = int(input())
def factors(num):
for i in range(2, num + 1):
if num % i != 0:
yield i
num_factors = list(factors(num))
def coprime(z):
for i in factors(z):
if i in num_factors:
break
else:
yield z
print(list(coprime(range(2, num + 1))))
+ 2
Aah! Thanks for helping me through this
+ 1
num = int(input())
rg = range(num + 1)
def factors(num):
for i in rg:
if num % i == 0:
yield i
def coprime():
for z in rg:
if factors(z) != factors(num):
yield z
print(*coprime())
Here is the updated code, would the generator work as a variable?