COMP1021 HKUST (Examples)
COMP1021 HKUST (Examples)
EG.2
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 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
sec = 0 def timer(): global sec turtle.clear() turtle.write(sec) sec += 1 turtle.ontimer(timer, 1000) timer()
EG.6
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
# 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
# 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
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)
#Append all lines to a single frame list #Append all frames into frames list
EG.8
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()
EG.9
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.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!
3 iterations
4 iterations
6 iterations
Rules:
Angle:
Koch Snowflake
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
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