Skip to content

Instantly share code, notes, and snippets.

@yasyf
Created May 30, 2013 02:10
Show Gist options
  • Save yasyf/5675347 to your computer and use it in GitHub Desktop.
Save yasyf/5675347 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import math,os,sys
def clear():
os.system('cls' if os.name=='nt' else 'clear')
def init():
clear()
print "Pascale's Triangle\n"
def get_int(prompt):
print prompt
result = 0
while result == 0:
try:
result = input("> ")
except NameError:
pass
return result
def get_str(prompt):
print prompt
result = raw_input("> ")
return result
def nCr(n,r):
f = math.factorial
return f(n)/(f(n-r)*f(r))
def gen_triangle(rows,delim=" "):
ncr_triangle = ""
int_triangle = ""
for x in range(0,rows):
ncr = ""
result = ""
for y in range(0,x+1):
ncr = "%s%sC%s%s" % (ncr,x,y,delim)
result = "%s%s%s" % (result,nCr(x,y),delim)
ncr_triangle = "%s%s\n" % (ncr_triangle,ncr)
int_triangle = "%s%s\n" % (int_triangle,result)
return ncr_triangle, int_triangle
def print_formatted_triangle(triangle):
rows = triangle.splitlines()
formatted = []
width = len(rows[len(rows)-1])
for row in rows:
if len(row) < width:
spacing = " "*int((width-len(row))/2)
else:
spacing = ""
row = "%s%s%s" % (spacing,row,spacing)
formatted.append(row)
print "%s%d Rows\n" % (" "*int((width-len(str(len(rows)))-5)/2),len(rows))
print "\n".join(formatted)
print "\n"
def main():
init()
if len(sys.argv) > 1:
rows = int(sys.argv[1])
else:
rows = get_int("Enter Number Of Rows")
ncr_triangle, int_triangle = gen_triangle(rows)
#print_formatted_triangle(ncr_triangle)
print_formatted_triangle(int_triangle)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment