if i == N-1: return ['bisque'] else: for j in range(N): sol[i+1] = j Queen(sol, i+1) return ['lightgrey'] # Return True if a solution is found. Annotate with a color. @viz def queen(sol, i): if promising(sol,i): if i == N-1: return [sol, 'cyan'] else: for j in range(N): sol[i+1] = j found, _ = queen(sol, i+1) if found: return [found, 'lightgrey'] return [None, 'lightgrey'] if __name__ == '__main__': # Queen([-1]*N, -1) # callgraph.render("queens.png", annotate=True) queen([-1]*N, -1) callgraph.render("queens.svg",annotate=True)
from rcviz import callgraph, viz @viz def quicksort(items): if len(items) <= 1: return items else: pivot = items[0] lesser = quicksort([x for x in items[1:] if x < pivot]) greater = quicksort([x for x in items[1:] if x >= pivot]) return lesser + [pivot] + greater print quicksort( list("helloworld") ) callgraph.render("sort.png") ########NEW FILE######## __FILENAME__ = rcviz # rcviz : a small recursion call graph vizualization decorator # Copyright (c) Ran Dugal 2014 # Licensed under the GPLv2, which is available at # http://www.gnu.org/licenses/gpl-2.0.html import inspect import pygraphviz as gviz import logging import copy
# For example: # If n = 10 and coins = [1,5,10]. Then there are 4 possible ways to make change: # # 1+1+1+1+1+1+1+1+1+1 # 5 + 1+1+1+1+1 # 5+5 # 10 # # With 1 coin being the minimum amount. from rcviz import callgraph, viz @viz def coin_change(target, coins): min_coins = target if target in coins: return 1 else: for val in [coin for coin in coins if coin <= target]: total_coins = 1 + coin_change(target - val, coins) if min_coins > total_coins: min_coins = total_coins return min_coins print(coin_change(10,[1,5])) callgraph.render("coin_change_DP.png")
return res @viz def fib2(num): assert num >= 0 return num if num <= 1 else fib2(num - 1) + fib2(num - 2) def gcd(a, b): print "a = %d, b = %d" % (a, b) if a == 0 or b == 0: return max(a, b) res = gcd(b % a, a) return res def main(): a, b = 24, 9 d = gcd(a, b) print(d) if __name__ == "__main__": # main() print fib1(6) # callgraph.reset() callgraph.render("test.png")
merge_sort.track(right=right, left=left) merge_sort(left) merge_sort(right) i, j, k = 0, 0, 0 while i < len(left) and j < len(right): if left[i] < right[j]: items[k] = left[i] i += 1 else: items[k] = right[j] j+=1 k+=1 if i< len(left): items[k:] = left[i:] if j< len(right): items[k:] = right[j:] return items print random_items, '\n' print merge_sort(random_items) callgraph.render("pic/sort.svg")
self.data = v self.left = None self.right = None @viz def print_tree(tree): if tree.left: print_tree(tree.left) print(tree.data) if tree.right: print_tree(tree.right) return tree.data if __name__ == "__main__": root = TreeNode(2) l1 = TreeNode(0) l0 = TreeNode(-1) l2 = TreeNode(1) r1 = TreeNode(5) l1.left = l0 l1.right = l2 root.left = l1 root.right = r1 print_tree(root) callgraph.render("tree.png")
from rcviz import callgraph from TreeNode import TreeNode, print_tree def create_tree(arr, l, r): if l > r or l < 0 or l > len(arr): return TreeNode(None) if l == r: return TreeNode(arr[l]) middle = (l + r) // 2 tree = TreeNode(arr[middle]) tree.left = create_tree(arr, l, middle - 1) tree.right = create_tree(arr, middle + 1, r) return tree def create_tree_main(arr): length = len(arr) return create_tree(arr, 0, length - 1) if __name__ == "__main__": vals = [11, 12, 13, 14, 15] t = create_tree_main(vals) print_tree(t) callgraph.render("img/tree.png")
# -*- coding: utf-8 -*- from rcviz import callgraph, viz # turn [1, [2, [3,4]], 5] to [1,2,3,4,5] flat = list() @viz def flatten_in(arr, flat): for i in arr: flatten_in.track(i=i) flatten_in(i, flat) if isinstance(i, list) else flat.append(i) return flat nested = [1, [2, [3,4]], 5] flatten_in(nested, flat) callgraph.render("pic/flatten.svg")
from rcviz import callgraph, viz Table = {} @viz def fib2(n): if n not in Table: if n<2: Table[n] = n else: Table[n] = fib2(n-1) + fib2(n-2) return Table[n] @viz def fib(n): if n<2: return n else: return fib(n-1) + fib(n-2) @viz def fact(n): if n==0: return 1 return n * fact(n-1) fib(11) callgraph.render()
from rcviz import callgraph, viz import copy def merge(y, z): result = [] while (len(y) > 0) and (len(z) > 0): if y[0] > z[0]: result.append(z.pop(0)) else: result.append(y.pop(0)) return result + y + z @viz def msort(x): if len(x) < 2: return x mid = int(len(x)/2) y = msort(x[:mid]) z = msort(x[mid:]) return merge(y,z) msort([4,8,3,10,5,1,2,15,7,6]) callgraph.render("ms.png")
def begin_viz(self): # Disable the button once pushed self.begin_viz.config(state='disabled') # Get our current problem information problem_index = self.tabContainer.index('current') problem = problems[problem_index] problem_info = functions[problem] # Input parsing if (problem_info[0] == 'list'): args = [x.get() for x in self.inputs[problem_index]] args = [x.split(',') for x in args] args = [[int(x) for x in y] for y in args] else: args = [x.get() for x in self.inputs[problem_index]] # Recursive visualization if type(problem_info[2][0]) == tuple: func = problem_info[2][0][0] else: func = problem_info[2][0] try: t0 = time.perf_counter_ns() rec_res = func(*args) t1 = time.perf_counter_ns() tRec = (t1 - t0) / (10**6) except: pass else: img_data = callgraph.render('png') self.rec_display_label = CanvasImage(self.master, BytesIO(img_data)) self.rec_display_label.grid(row=4, column=0, rowspan=4, sticky='nsew') self.rec_time_label = tk.Label(self.master, text="Time Elapsed: " + str(tRec) + 'ms', width=40) self.rec_time_label.grid(row=3, column=0, sticky='new') self.result_label = tk.Label(self.outframe, text=str(rec_res), font=('Courier', 20)) self.result_label.grid(row=1, sticky='new') # DP visualization func = problem_info[2][1] try: t0 = time.perf_counter_ns() dp_res = func(*args) t1 = time.perf_counter_ns() tDP = (t1 - t0) / (10**6) except: pass else: self.reset = False self.dp_display_loop = threading.Thread( target=self.loop_tables, args=(problem_info[2][1].tables, ), daemon=True) self.dp_display_loop.start() self.dp_time_label = tk.Label(self.master, text="Time Elapsed: " + str(tDP) + 'ms', width=40) self.dp_time_label.grid(row=3, column=2, sticky='new')
# -*- coding: utf-8 -*- from rcviz import callgraph, viz @viz def hanoi(n, a='A', b='B', c='C'): if n == 1: print('move', a, '-->', c) return hanoi(n-1, a, c, b) # print('move', a, '-->', c) hanoi(1, a, b, c) hanoi(n-1, b, a, c) hanoi(4) callgraph.render("pic/hanoi.svg") def fact(n): res = 1 for i in xrange(1, n+1): res *= i return res # print fact(5) def fact2(n): return fact_rec(n, 1) def fact_rec(n, product): # 尾递归形式
@author: suresh """ from rcviz import callgraph, viz @viz def ssum(lis, sum, prev): if sum == 0: return True elif len(lis) == 0: return False elif lis[len(lis) - 1] > sum: a = ssum(lis[: len(lis) - 1], sum, sum) if a == True and sum != prev: print prev - sum return a else: a = ssum(lis[: len(lis) - 1], sum, sum) b = ssum(lis[: len(lis) - 1], sum - lis[len(lis) - 1], sum) if a == True: if sum != prev: print prev - sum elif b == True: if sum - lis[len(lis) - 1] != prev: print lis[len(lis) - 1] return a or b print ssum([1, 2, 3, 4], 5, 5) callgraph.render("subsetsum.png")
cur = head res = '' while cur: output = str(cur.val) + ' ->' if cur.next else str(cur.val) res += output print output, cur = cur.next print '' res += '' return res @viz def recursively_reverse_list( head): if head is None or head.next is None: # 当head从头,通过递归调用一步步走到,倒数第二个元素时停止 return head tmp = print_list(head) recursively_reverse_list.track( tmp=tmp) tmp = recursively_reverse_list(head.next) head.next.next = head head.next = None return tmp h = recursively_reverse_list(ll.head) ll.print_list(h) callgraph.render("pic/rr.svg")
Created on Jun 16, 2014 @author: suresh ''' from rcviz import callgraph, viz @viz def coinchange(lis,sum,prev): if(sum==0): #print prev return True elif(len(lis)==0): return False elif lis[len(lis)-1]>sum: a=coinchange(lis[:len(lis)-1],sum,sum) return a else: a=coinchange(lis[:len(lis)-1],sum,sum) b=coinchange(lis[:len(lis)],sum-lis[len(lis)-1],sum) if(a==True): if(prev != sum): print prev-sum if( b==True): if(sum-lis[len(lis)-1]!=sum): print lis[len(lis)-1] return a or b print coinchange([1,2,3,4],4,4) callgraph.render("coinchange.png")
@viz def quicksort(items): if len(items) <= 1: return items else: pivot = items[0] lesser = quicksort([x for x in items[1:] if x < pivot]) greater = quicksort([x for x in items[1:] if x >= pivot]) return lesser + [pivot] + greater print quicksort(list("helloworld")) callgraph.render("sort.png") ########NEW FILE######## __FILENAME__ = rcviz # rcviz : a small recursion call graph vizualization decorator # Copyright (c) Ran Dugal 2014 # Licensed under the GPLv2, which is available at # http://www.gnu.org/licenses/gpl-2.0.html import inspect import pygraphviz as gviz import logging import copy class callgraph(object):
@viz def quicksort(items): if len(items) <= 1: return items else: pivot = items[0] quicksort.track(pivot=pivot) lesser = quicksort([x for x in items[1:] if x < pivot]) greater = quicksort([x for x in items[1:] if x >= pivot]) return lesser + [pivot] + greater # print quicksort( list("helloworld") ) print quicksort( [5, 1, 9, 7, 3, 0, 2] ) callgraph.render("pic/quick_sort.svg") @viz def fib(n): if n == 1 or n == 2: # 斐波那契数列,递归形式,很好的显示了递推公式表达形式;a1,a2初始数值,加上递推公式 return n - 1 else: return fib(n-2) + fib(n-1) # print fib(6) # callgraph.render("pic/fib.svg") def fib_itr(n): a = 0