(Emergency!)Easy Python from CMPT 140 Objectives Students will be able to design
ID: 3571255 • Letter: #
Question
(Emergency!)Easy Python from CMPT 140
Objectives Students will be able to design solution with recursive methods Specification Part A (50%): Write a recursive function sumA11Digits. This function will take an integer parameter as input and return the sum of the digits in the input integer. You must design a recursive solution for this assignment, do not use loops. For example, if the input is 423511, then the function should return 16. Part B (50%): Using the turtle graphics library (http://docs.pvthon.Org/3/librarv/turtle.html) to draw the following graphics. A Sierpinski triangle of order 0 is an equilateral triangle. An order 1 triangle can be drawn by drawing 3 smaller triangles (shown slightly disconnected here, just to help our understanding). Higher order 2 and 3 triangles are also shown. Create a program where it draws Sierpinski triangles of any order input by the user. You must design a recursive solution for this assignment, do not use loops.Explanation / Answer
from turtle import *
def Triangle(t, length):
for angle in [120, 120, 120]:
t.forward(length)
t.left(angle)
def sierpinski_triangle(turtle, order, length):
"""
3. A Sierpinski triangle of order 0 is an equilateral triangle. An order 1 triangle can be drawn by drawing 3
smaller triangles (shown slightly disconnected here, just to help our understanding).
Higher order 2 and 3 triangles are also shown.
Draw Sierpinski triangles of any order input by the user..
:return:
"""
if order == 0: # The base case is just a straight line
Triangle(turtle, length)
else:
for i in range(3):
turtle.forward(length)
turtle.left(120)
sierpinski_triangle(turtle, order - 1, length / 2)
wn = Screen()
wn.title("Exercise 18.7.3 Sierpinski triangle Fractal!")
wn.bgcolor("white")
fract_turtle = Turtle()
fract_turtle.pencolor("#0000FF")
fract_turtle.fillcolor("black")
fract_turtle.pensize(1)
# setup initial location
# delay(0)
fract_turtle.speed(0)
fract_turtle.up()
fract_turtle.goto(-450, -200)
fract_turtle.down()
fract_turtle.pendown()
fract_turtle.hideturtle()
size = 200
sierpinski_triangle(fract_turtle, 4, size)
exitonclick()
1.
def sum_digits_recursion(A):
'''
Takes a list A, and returns
the sum of all the digits in the
list e.g. [10, 30, 45] should return
1 + 0 + 3 + 0 + 4 + 5 = 13
'''
def sub(n):
if n < 10:
return n
return sub(n % 10) + sub(n / 10)
total = 0
for i in A:
total += sub(i)
return total
# test your code
print sum_digits([10, 30, 45])
def sum_digits(A):
total = 0
for x in "".join([str(i) for i in a]):
total += int(x)
return total
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.