CSci 150: Foundations of computer science I
Home Syllabus Assignments Tests

Recursion, continued

Anagrams

def print_anagrams(prefix, letters):
    if len(letters) <= 1:
        print prefix + letters
    else:
        for i in range(len(letters)):
            letter = letters[i]
            remaining = letters[:i] + letters[i + 1:]
            print_anagrams(prefix + letter, remaining)

to_anagram = raw_input('Input string to anagram: ')
print_anagrams('', to_anagram)

Tree

from graphics import *
import math

def draw_tree(window, x0, y0, len, angle):
    if len > 2:
        x1 = x0 + len * math.cos(math.radians(angle))
        y1 = y0 - len * math.sin(math.radians(angle))

        trunk = Line(Point(x0, y0), Point(x1, y1))
        trunk.draw(window)

        draw_tree(window, x1, y1, len * 0.75, angle + 30)
        draw_tree(window, x1, y1, len * 0.66, angle - 50)

win = GraphWin('Tree', 200200)
draw_tree(win, 1102005090)