[Tutor] Question
Alan Gauld
alan.gauld at btinternet.com
Sat Dec 3 10:29:37 CET 2011
On 03/12/11 08:31, Michael Hall wrote:
> # a) write a function, getDivisors(), that returns a list of all
> # of the positive divisors of a given number.
This is a very clear statement of what you need to do.
> def getDivisors(num):
> my_list = []
> sum = 0
> for number in range(1, num, 10000):
>
> if num % number == 0:
> print([1, 2, 3])
> sum += num
>
> print('The sum is ', sum)
> if sum == num:
> print(num, 'is a perfect number')
> else:
> print(num, 'is not a perfect number')
> problem. If you enter the number 6 the program is just what the teacher
> wants. My problem is if you enter any other number it is wrong.
Even for 6 it is NOT what the teacher wants.
Your function PRINTS the answer the teacher asked for a function that
RETURNS the answer. These are different things.
Do you understand the difference?
Also the reason it works for 6 is because you hard coded the answer for 6:
> if num % number == 0:
> print([1, 2, 3])
You only ever print [1,2,3]. You are not finding the divisors you are
just printing [1,2,3].
Similarly the teacher did not ask you to test/report whether the number
was perfect in the function, only to get the list of divisors. You need
to strip the function back to the minimum to do what you were asked to do.
def getDivisors(num):
my_list = []
for x in range (1,num):
# if is x a divisor of num
# add x to my_list
return my_list
I've left the commented lines for you to complete.
But that is ALL you need for part (a) of the assignment.
You might need a main() function to test it, but it will simply print
the result. Something like:
def main():
print getDivisors(24)
As it is you are trying to do way too much and making your function more
complicated than it needs to be. You can tweak it to make it more
efficient later, but for now stick to the simplest thing that can
possibly work and solve the problem you were asked to solve.
Once you have part (a) working part (b) of the assignment becomes easy.
But get (a) working before attempting (b). At the moment you are mixing
the two together and making it more difficult. And that is one of the
lessons from the homework. In programming, if you split a task down into
smaller chunks it becomes easier. If you try to solve everything in one
place it is much harder.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list