You are on page 1of 8

COMP1021 (2013) Examples Bank

EG.1 STRING STRIP, RSTIP, LSTRIP


1232asd12321 1232asd1232 1232asd12321 #str not saved automatically 232asd12321 #Remove leading 1 232asd1232 #Remove trailing 1 str = '1232asd12321' print(str.rstrip('2')) print(str.rstrip('1')) print(str. rstrip ('2')) print(str. lstrip ('1')) print(str. strip ('1'))

EG.2

BREAK AND CONTINUE


0 Skipped 1 Skipped 2 Skipped 3 Skipped 4 Four to 5 Four to 6 Six 6 Six after "continue" is run after "continue" is run after "continue" is run after "continue" is run Ten Ten

i = 0 for _ in range(2): while i < 10: print(i) if i == 6: print('Six') break if i in range(4, 10): print('Four to Ten') i += 1 continue else: print('Skipped after \ "continue" is run') i += 1

EG.3

3D STRUCTURE
[[[0, 1, 2], [0, 1, 2], [0, 1, 2]], [[0, 1, 2], [0, 1, 2], [0, 1, 2]], [[0, 1, 2], [0, 1, 2], [0, 1, 2]]] 1

x_axis = [] for i in range(3): j_axis = [] for j in range(3): k_axis = [] for k in range(3): k_axis.append(k) j_axis.append(k_axis) x_axis.append(j_axis) print(list(x_axis)) print(x_axis[1][0][1])

EG.4

CLASS AND OBJECTS


The area is 25 The area now is 10000 #By using [self] #The self.<var> can be used in other obj in the same class

class SimpleSquare: def __init__(self, length): self.len = length def area(self): return(self.len * self.len) mysquare = SimpleSquare(5) print('The area is', mysquare.area()) mysquare.len = 100 print('The area now is', mysquare.area())

EG.5

RECURSIVE FUNCTION (SIMPLE)

sec = 0 def timer(): global sec turtle.clear() turtle.write(sec) sec += 1 turtle.ontimer(timer, 1000) timer()

# A timer in seconds counting

EG.6

RECURSIVE FUNCTION (SIERPINSKI)

import turtle max_depth = 3 height = 500 width = 500 turtle.setup(height, width) def fillTriangle(vertices): turtle.up() turtle.goto(vertices[0]) turtle.begin_fill() turtle.goto(vertices[1]) turtle.goto(vertices[2]) turtle.end_fill() def clearScreenAndDrawTriangles(): global max_depth turtle.clear() vertices = [ (0, height/2), (-width/2, -height*.4), (width/2, -height*.4) ] turtle.color("black") fillTriangle(vertices) Sierpinski(vertices, 0) turtle.color("black") turtle.update() def Sierpinski(vertices, depth): global max_depth x1 = (vertices[0][0] vertices[1][0]) / 2.0 y1 = (vertices[0][1] vertices[1][1]) / 2.0 midPoint1 = [x1, y1] x2 = (vertices[1][0] vertices[2][0]) / 2.0 y2 = (vertices[1][1] vertices[2][1]) / 2.0 midPoint2 = [x2, y2] x3 = (vertices[0][0] vertices[2][0]) / 2.0 y3 = (vertices[0][1] vertices[2][1]) / 2.0 midPoint3 = [x3, y3] + \ + \ + \ + \ + \ + \ # # # # Define 3 points of starting triangle top point left point right point

# First point # Second point # Third point

# Start with 1 large black triangle # Begin the recursion process. The parameters are: the list of triangle vertices, the current depth (0) #Show the maximum depth value and some instructions in the bottom left corner of the screen ### The recursive function ### # To make it easier to understand what's happening, here's an example of a triangle stored in a list: [[0,250], [250,-200], [-250,-200]] # Calculate the middle point of each of the three sides of the triangle

turtle.color("white") fillTriangle( [midPoint1, midPoint2, midPoint3] ) 2

# The background is a black triangle, so we always draw white triangles # Draw the middle white triangle

if depth < max_depth: Sierpinski( [vertices[0], midPoint1, midPoint3], depth+1 ) Sierpinski( [midPoint1, vertices[1], midPoint2], depth+1 ) Sierpinski( [midPoint3, midPoint2, vertices[2]], depth+1 ) def setMaxDepth0(): global max_depth max_depth = 0 clearScreenAndDrawTriangles() turtle.onkeypress(setMaxDepth0, "0") turtle.tracer(False) turtle.hideturtle() clearScreenAndDrawTriangles() turtle.listen() turtle.done()

# If we haven't yet reached the maximum depth of recursion, call this function three times, once for the top triangle, once for the left triangle, once for the right triangle # When we recursively call this function, we give the function a new triangle list and [depty]+=1 so the next function knows what depth it is. Recursively call Sierpinski() to draw the top triangle

EG.7

FILES READING (STAR WAR ANIMATION)


#Assign a <file_var> #Read all lines in the file into a list

ani_file = open('scene2.ani', 'r') lines = ani_file.readlines() ani_file.close() frames = [] while True: frame_pic = [] line = lines.pop(0) if line.strip().isdigit(): frame_dur = line else: break for _ in range(13): frame_pic.append(lines.pop(0)) frame = {'duration' : frame_dur, \ 'content' : frame_pic} frames.append(frame)

#Current line is taken over by [line] #Check if the line is a number

#Append all lines to a single frame list #Append all frames into frames list

EG.8

FILES WRITING (TURTLE ASSIGNMENT - RANKING)


#Set the <file_var> in write mode

ranking_file = open('ranking.txt', 'w') for i in range(len(rank)): score_lin = str(rank[i]) + '\t' + \ '\n' ranking_file.write(score_lin) ranking_file.close()

#Write the <string_type> to <file_var>

EG.9

L-SYSTEM (BAREBONES MODULE)


#Generate resultant string #Provide the initial value

import turtle def generate_1string(start, rules, \ iteration): result = start for _ in range(iteration): new_result = '' for s in result: if s in rules: new_result += (rules[s]) else: new_result += \ (rules.get(s, s)) result = new_result return result def draw(commands, step, angle, \ start_position, start_angle): turtle.up() turtle.goto(start_position) turtle.setheading(start_angle) for c in commands: turtle.down() if c == 'F' or c == 'A': turtle.forward(step) if c == '+': turtle.left(angle) if c == '-': turtle.right(angle)

#Search for the <key> in <dict_type> #Add the replacement value to a tmp var #If no rule is found, use <dict_type>.get to avoid error #Update the result with rules replaced #commands are generated using generate_lstring()

#If any char matches with the commands #Run the predefined commands

EG.10 L-SYSTEM (EXAMPLES)


start = 'F++F++F' rules = {'F' : 'F-F++F-F'} iteration = 4 step = 4 angle = 60 start_position = (0, 0) start_angle = 0 koch_curve_commands = \ LSystem.generate_lstring(start, rules, \ iteration) LSystem.draw(koch_curve_commands, step, \ angle, start_position, start_angle) #Starting string #Replacement rules #Number of iterations #The step of movement of the turtle #The angle for rotation

# Generate the commands by calling LSystem.generate_commands() # Start drawing using LSystem

EG.11 DICTIONARY
heads = {"a": (588,104,48,57), "b": (474,102,44,58), "c": (438,146,45,60), "d": (522,162,55,68)} print("All the information in the dictionary:") for key, value in heads.items(): print(key, value) print("The people are:") for key in heads.keys(): print(key) print("The positions and dimensions are:") for value in heads.values(): print(value) print("Is \'a\' in the picture?") if "a" in heads.keys(): print("\'a\' is there!") All the information in the dictionary: b (474, 102, 44, 58) c (438, 146, 45, 60) a (588, 104, 48, 57) d (522, 162, 55, 68) The people are: b c a d The positions and dimensions are: (474, 102, 44, 58) (438, 146, 45, 60) (588, 104, 48, 57) (522, 162, 55, 68) Is 'a' in the picture? 'a' is there!

EG.12 ELIZA AI RESPONSE SYSTEM


def getResponse(sentence): words=sentence.split() if len(words) == 0: return "You have to talk to me." if sentence[-1]=='?': return "Why do you want to know?" if "mum" in words: return "Tell me more about your \ mother." if "dad" in words: return "Tell me more about your \ father." if "sister" in words: return "Tell me more about your \ sister." if "brother" in words: return "Tell me more about your \ brother." if "rossiter" in words: return "Tell me more about that \ remarkable man." if words[0] == "i" and words[1] == \ "feel": return "Why do you feel that \ way?" if words[0] == "i" and words[1] == \ "think": return "Do you really think so?" return "Tell me more." #Divide the sentence into list of words #Predefine responses

EG.13 {APPENDIX} L-SYSTEM (ALL SAMPLES)


Name Koch Triangle Parameters Variables: Constants: Starting String: Rule: Angle: Sierpinsk i Triangle Variables: Constants: Starting String: {F} {+, -} F F F+FF-F+F 90 {A, B} {+, -} A A B-AB B A+B+A 60 5 iterations 7 iterations 3 iterations A Few Iterations A Medium Amount of Iterations A Lot of Iterations

3 iterations

4 iterations

6 iterations

Rules:

Angle:

Koch Snowflake

Variables: Constants: Starting String: Rule: Angle:

{F} {+, -} F++F++F F FF++F-F 60

2 iterations 3 iterations PeanoGosper Curve Variables {F, X, Y} : Constants {+, -} : Starting String: X X X+YF++YFFX--FXFX-YF+ Y FX+YFYF++YF+F X--FX-Y 60 3 iterations 4 iterations 6 iterations 5 iterations

Rules:

Angle:

Rings

Variables: Constants: Starting String: Rule: Angle:

{F} {+, -} F-F-F-F F FF-FF-F-F-F+F 90 2 iterations

3 iterations Dragon Curve Variables: Constants: Starting String: {F, X, Y} {+, -} FX X X+YF+ Y -FXY 90

5 iterations

5 iterations

Rules:

Angle:

15 iterations

9 iterations

You might also like