!PC

533 days ago by mpaul

Here are some ways we defined n! using just Python:

def fact(n): product = 1 while n>1: product *= n n -= 1 return product 
       
fact(10) 
       
def fact(n): product = 1 for f in range(2, n+1): product *= f return product 
       
fact(10) 
       
def fact(n): if n<2: return 1 return n*fact(n-1) 
       
fact(10) 
       
 
       

It's good to understand how these definitions work.

If you understand a little programming, you will be able to use Sage much more effectively.

However, Sage also has stuff like ! built in:

factorial(10) 
       

Same for _nP_r and _nC_r.

Here are some ways we expressed them using pure Python:

 

def P(n,r): return fact(n)/fact(n-r) 
       
P(10, 3) 
       
def P(n,r): if r == 0: return 1 return n*P(n-1,r-1) 
       
P(10,3) 
       
def C(n,r): return fact(n)/(fact(r)*fact(n-r)) 
       
C(10,3) 
       
def C(n,r): if r == 0: return 1 return P(n,r)/fact(r) 
       
C(10,3) 
       

However, Sage already contains a function binomial that returns a binomial coefficient:

binomial(10, 3) 
       

We can easily tell Sage that we'd like to substitute C for binomial:

C = binomial 
       
C(10,3) 
       

And now we can define P in terms of C using the fact that _nP_r =  _nC_r \cdot r!  :

def P(n,r): return C(n,r)*factorial(r) 
       
P(10,3) 
       

Pascal's Triangle

def row(n): return [C(n,r) for r in [0..n]] 
       
row(10) 
       
for n in range(13): row(n) 
       

Here's another cool way to create Pascal's triangle using pure Python:

row = [1] def expand(row): return [a+b for (a,b) in zip([0]+row, row+[0])] 
       
for n in range(13): row row = expand(row) 
       

Sage also has the functions Permutations and Combinations that are worth exploring:

Permutations('abc') 
       
list(_) 
       
list(Permutations('abc',2)) 
       
Combinations('abcde') 
       
list(_) 
       
list(Combinations('abcde', 2)) 
       
list(Permutations([1..6], 2)) 
       
[[1, 2], [1, 3], [1, 4], [1, 5], [1, 6], [2, 1], [2, 3], [2, 4], [2, 5],
[2, 6], [3, 1], [3, 2], [3, 4], [3, 5], [3, 6], [4, 1], [4, 2], [4, 3],
[4, 5], [4, 6], [5, 1], [5, 2], [5, 3], [5, 4], [5, 6], [6, 1], [6, 2],
[6, 3], [6, 4], [6, 5]]
[[1, 2], [1, 3], [1, 4], [1, 5], [1, 6], [2, 1], [2, 3], [2, 4], [2, 5], [2, 6], [3, 1], [3, 2], [3, 4], [3, 5], [3, 6], [4, 1], [4, 2], [4, 3], [4, 5], [4, 6], [5, 1], [5, 2], [5, 3], [5, 4], [5, 6], [6, 1], [6, 2], [6, 3], [6, 4], [6, 5]]
len(_) 
       
30
30
[a+b for (a,b) in list(Permutations([1..6],2))] 
       
[3, 4, 5, 6, 7, 3, 5, 6, 7, 8, 4, 5, 7, 8, 9, 5, 6, 7, 9, 10, 6, 7, 8,
9, 11, 7, 8, 9, 10, 11]
[3, 4, 5, 6, 7, 3, 5, 6, 7, 8, 4, 5, 7, 8, 9, 5, 6, 7, 9, 10, 6, 7, 8, 9, 11, 7, 8, 9, 10, 11]