Transcript Wednesday 24 October
| categories: Transcripts
After answering several questions about assignment 4 we looked at programming factorial.
Write a function named fact that takes an integer and returns the factorial of it. You may assume the number is 1 or greater.
One person suggested using arange and np.prod.
def fact(N):
return np.prod(np.arange(1, N+1))
Yes, that works but we're learning about loops. We could do it with a while loop.
def fact(N):
r = 1
while N > 1:
r = r * N
N = N - 1
return r
The while repeats the statements as long as the contional expression is True.
We could do it going forward with a for.
def fact(N):
r = 1
for i in range(2, N+1):
r = r * 1
return r
Or we can do it going backward with a for.
def fact(N):
r = 1
for i in range(N, 1, -1):
r = r * 1
return r
Nathaniel noticied that he got different results for the first version than for the later ones for big factorials. The numpy arrays limit the precision of integers and the python ints do not.
Notice that pattern again. We initialize our result variable, loop doing something to it on each interation, and then we return it.
Then we talked about sum.
def mysum(A):
r = 0
for v in A:
r = r + v
return r
Again that simple pattern. We can easily transform it into taking the product.
def myprod(A):
r = 1 # multiplicative identity
for v in A:
r = r * v
return r