Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download
Project: Math 367-17S
Views: 143
#This code produces Pascal's triangle up to row nrows. #Note that it is a list of lists nrows=10 pascal=[[1],[1,1]] for r in [2..nrows]: nextrow=[1] prevrow=pascal[-1] lenPre=len(prevrow) for k in [0..lenPre-2]: nextrow.append(prevrow[k]+prevrow[k+1]) nextrow.append(1) pascal.append(nextrow)
#here is a printout to test it for r in pascal: print r
[1] [1, 1] [1, 2, 1] [1, 3, 3, 1] [1, 4, 6, 4, 1] [1, 5, 10, 10, 5, 1] [1, 6, 15, 20, 15, 6, 1] [1, 7, 21, 35, 35, 21, 7, 1] [1, 8, 28, 56, 70, 56, 28, 8, 1] [1, 9, 36, 84, 126, 126, 84, 36, 9, 1] [1, 10, 45, 120, 210, 252, 210, 120, 45, 10, 1]
#Now we do the same thing, but mod m m=3 nrows=10 pascal=[[1],[1,1]] for r in [2..nrows]: nextrow=[1] prevrow=pascal[-1] lenPre=len(prevrow) for k in [0..lenPre-2]: nextrow.append(mod(prevrow[k]+prevrow[k+1],m)) nextrow.append(1) pascal.append(nextrow)
#test it for r in pascal: print r
[1] [1, 1] [1, 2, 1] [1, 0, 0, 1] [1, 1, 0, 1, 1] [1, 2, 1, 1, 2, 1] [1, 0, 0, 2, 0, 0, 1] [1, 1, 0, 2, 2, 0, 1, 1] [1, 2, 1, 2, 1, 2, 1, 2, 1] [1, 0, 0, 0, 0, 0, 0, 0, 0, 1] [1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1]
#the next lines of code count the number of odd numbers in each row. You cannot just sum the elements in each row, because #the elements are NOT integers but instead are integers modulo 2, so they only sum to 0 (even) or 1 (odd) #So we use a boolean expression. rowNum =0 #keep track of the row for output for r in pascal: #here "r" is the actual row, with numerous elements if rowNum is large nOdd=0 #begin a sum for a in r: nOdd += a==1 #increment the value only if a equals 1, i.e. a is odd print rowNum, nOdd rowNum += 1 #increment the row number
0 1 1 2 2 2 3 2 4 4 5 4 6 2 7 4 8 5 9 2 10 4
#incidentally, you may want to use binary, etc. n=2018 n.digits() n.digits(base=2)
[8, 1, 0, 2] [0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1]
rowNum.digits(2)
[1, 1, 0, 1]