Skip to content

Instantly share code, notes, and snippets.

@adusak
Last active August 29, 2015 14:17
Show Gist options
  • Save adusak/eb13cc4c7ed6f7d99ff7 to your computer and use it in GitHub Desktop.
Save adusak/eb13cc4c7ed6f7d99ff7 to your computer and use it in GitHub Desktop.
Generates pascal triangle image
import random
from PIL import Image
import matplotlib.colors as colors
from python.less2.combinatorics import vartiations
'''
' Calculates combination number using cache (doesn't recalculate already calculated values)
'''
def comb_number(n, k, cache=None):
if k == 0 or k == n:
return 1
if cache is None:
cache = [[0 for _ in range(k)] for _ in range(n)]
if cache[n - 1][k - 1] == 0:
cache[n - 1][k - 1] = comb_number(n - 1, k - 1, cache) + comb_number(n - 1, k, cache)
return cache[n - 1][k - 1]
'''
' Calculates combination number inefficiently
'''
def comb_number2(n, k):
if k == 0 or k == n:
return 1
else:
return comb_number2(n - 1, k - 1) + comb_number2(n - 1, k)
'''
' Calculates the numbers in pascal triangle
' Returns list of list with numbers each list represents one row in the pascal triangle
'''
def hex_to_rgb(value):
value = value.lstrip('#')
lv = len(value)
return tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))
def rgb_to_hex(rgb):
return '#%02x%02x%02x' % rgb
def pascal(n):
cache = [[0 for _ in range(n)] for _ in range(n)]
numbers = []
for i in range(0, n):
line = []
for j in range(0, i + 1):
line.insert(0, comb_number(i, j, cache))
numbers.insert(0, line)
return numbers
def draw_pascal(n, d, input_scale=1):
pascal_list = pascal(n)
if input_scale % 2 == 1:
direction_base = range(0, input_scale)
else:
direction_base = range(0, input_scale + 1)
# [0, 2], [2, 2], [2, 0], [2, 1], [1,2]]
directions = vartiations(direction_base, 2, True)
scale = len(direction_base)
width = n * scale
height = n * scale
im = Image.new("RGB", (width + 1, height + 2))
color_map = []
list_colors = list(colors.cnames.items())
random.shuffle(list_colors)
for i in range(d):
color_map.insert(i, list_colors[431 * i * d % len(colors.cnames)])
for i in range(len(pascal_list)):
offset = int((n - len(pascal_list[i])) * scale / 2)
for j in range(len(pascal_list[i])):
for pix in directions:
(x, y) = (
(offset + j * scale + pix[0]), height - (scale * i + pix[1]))
im.putpixel(
(x, y), hex_to_rgb(color_map[pascal_list[i][j] % d][1]))
im.show()
draw_pascal(30, 5, 20)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment