Trouble returning values from my factor finder function | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 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))

22nd Dec 2018, 5:44 PM
David Shayne
David Shayne - avatar
7 Antworten
+ 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))))
23rd Dec 2018, 9:43 AM
Mert Yazıcı
Mert Yazıcı - avatar
+ 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'
22nd Dec 2018, 8:55 PM
Mert Yazıcı
Mert Yazıcı - avatar
22nd Dec 2018, 5:57 PM
Mert Yazıcı
Mert Yazıcı - avatar
+ 2
Thanks
22nd Dec 2018, 5:57 PM
David Shayne
David Shayne - avatar
+ 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))))
23rd Dec 2018, 8:11 AM
David Shayne
David Shayne - avatar
+ 2
Aah! Thanks for helping me through this
23rd Dec 2018, 5:53 PM
David Shayne
David Shayne - avatar
+ 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?
22nd Dec 2018, 8:27 PM
David Shayne
David Shayne - avatar