def divisors(n):
ans =0
for i in range(n):
i += 1
k=n%i
if k!=1:
ans=i
return ans
print(20)
I have a function that's not working properly when I run it prints the n value instead of printing out the divisors.
Yu Hao
123k50 gold badges253 silver badges306 bronze badges
4 Answers 4
Three key issues are:
k=n%ireturns the remainder - if the remainder != 1 it doesn't mean thatiis a divisor!- in the for-loop you keep overriding
ansand at the end of the function you return the value that was found on the last iteration that satisfied theifcondition. What you want to do instead is to accumulate all theanss into a list and return that list. - The
printat the end is not calling the function - it simply prints the number 20.
I'm not posting a corrected solution because I think that it will be a good exercise for you to fix these bugs by yourself, good luck!
answered Oct 10, 2015 at 15:49
Nir Alfasi
53.6k12 gold badges94 silver badges138 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
user4574134
def divisors(n): ans = [] for i in range(n): i += 1 if n % i == 0: ans.append(i) return ans
Nir Alfasi
@user4574134 you got it :)
user4574134
def divisors(n): ans = [] for i in range(n): i += 1 if n % i == 0: ans.append(i) return ans print(divisors([30])) this is not working when i enter 30 as a list value
Nir Alfasi
@user4574134 the function receives an integer as an argument, why would you pass a list ?
I saved the result in a list:
def divisors(n):
ans = []
for i in range(n):
i += 1
k=n%i
if k==0:
ans.append(i)
return ans
print divisors(20)
answered Oct 10, 2015 at 15:50
Shapi
5,6334 gold badges31 silver badges40 bronze badges
1 Comment
Fernando Matsumoto
You missed something when cleaning your code. The function should
return ans.If you what a more elegant way you can use lists-comprehension, also you reduce it in one line.
def divisors(n):
return [i+1 for i in range(n) if n%(i+1) == 0]
answered Oct 10, 2015 at 16:11
Shapi
5,6334 gold badges31 silver badges40 bronze badges
Comments
Try to use generator function with yield for that purpose:
def divisors(n):
iterable = xrange(1, n + 1)
for i in iterable:
k = n % i
if k == 0:
ans = i
yield ans
print list(divisors(20))
answered Oct 10, 2015 at 16:00
xiº
4,7173 gold badges31 silver badges43 bronze badges
1 Comment
Shapi
i think that is an advanced approach for the OP level, but its a good answer indeed.
lang-py
print(divisors(20)), but that will only print the lastansvalue sincedivisors()does not return a list.