Jump to content

User:Kithira/Course Pages/CSCI 12/Assignment 2/Group 3/Homework 2

From Wikipedia, the free encyclopedia

Making the Program 'Factors'

[edit]

This program takes an integer as an input and returns a list of all of the factors of that integer. The numbers in the parentheses next to each code of line are not part of the actual code, rather they are there so that each line of code is easier to refer to.

Code

[edit]
   (1) def factors(x):
   (2)     list = []
   (3)     count = 1
   (4)     while x >=count:
   (5)         if x%count == 0:
   (6)             list.append(count)
   (7)         count = count + 1
   (8)     return list
   (9) def _test():
   (10)     assert(factors(5) ==[1, 5])
   (11)     assert(factors(10) == [1, 2, 5, 10])
   (12)     assert(factors(1) == [1])
   (13) if _name__=='__main__':
   (14)     _test()



Explanation

[edit]

This program works because when an integer is the input of our function, then the function takes every number beginning with one through the integer itself. It divides our original integer by each number and if the remainder is zero (the number divides nicely into our original integer) then this number is a factor of our original integer and is added to our list. Once, the loop gets through every number leading up to the original input, our function returns the modified list with all of the factors. A step by step explanation of our program follows:

In line 1) we define our function by the name factors and give it a single input. In line 2) we created a variable called list where we stored an empty list. In line 3) we created a variable called count where we stored the integer value of one. In line 4) we created a while loop that keeps executing as long as the following condition is met: the input of our function factors is greater than or equal to our variable count. In this while loop, we have an if statement (line 5) that only executes if the following condition is met: the input of our function divided by our variable count is equivalent to the integer value of zero. If the previous condition is met then line 6) executes and the value stored in the variable count at that time is stored in our variable list by being added to our the list stored within that variable. At the end of the while loop (line 7) our integer value stored in count increases by one. Line 8) simply returns our modified variable list at the end of our function. Lines 9) through 14) simply test our function by testing it out for three known lists corresponding to three inputs that we calculated without the help of our program. If the program recognizes these input/list correspondences as correct then the program executes without a problem (as it does now). However if this were not the case, then our program would not execute successfully.