Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Python Exercise 11.4: At the beginning of the chapter, we discussed a pyramid as

ID: 3720160 • Letter: P

Question

Python

Exercise 11.4: At the beginning of the chapter, we discussed a pyramid as another natural example of a recursive structure. Implement a Pyramid class recursively, using an approach similar to that used for the Bullseye class. Allow the user to specify the number of levels and the overall width (which can be the same as the height). The main difference in techniques involves the positioning of the components. For the bullseye, the outer circle and inner bullseye were concentric. For the pyramid, you will need to relocate the bottom rectangle and the upper pyramid to achieve the desired effect. Move the components so that the completed pyramid sits with its bottom edge centered on the origin (the default reference point).

from cs1graphics import *

class Bullseye(Drawable):

"""Represent a bullseye with an arbitrary number of bands."""

def __init__(self, numBands, radius, primary='black', secondary='white'):

    """Create a bullseye object with alternating colors.

   The reference point for the bullseye will be its center.

    numBands         the number of desired bands (must be at least 1)

    radius           the total radius for the bullseye (must be positive)

    primary          the color of the outermost band (default black)

    secondary        the color of the secondary band (default white)

    """

    if numBands <= 0:

      raise ValueError('Number of bands must be positive')

    if radius <= 0:

      raise ValueError('radius must be positive')

    Drawable.__init__(self)                            # must call parent constructor

    self._outer = Circle(radius)

    self._outer.setFillColor(primary)

    if numBands == 1:

      self._rest = None

    else: # create new bullseye with one less band, reduced radius, and inverted colors

      innerR = float(radius) * (numBands-1) / numBands

      self._rest = Bullseye(numBands-1, innerR, secondary, primary)

def _draw(self):

    self._beginDraw()                                  # required protocol for Drawable

    self._outer._draw()                                # draw the circle

    if self._rest:

      self._rest._draw()                               # recursively draw the rest

    self._completeDraw()                               # required protocol for Drawable

Explanation / Answer

Answer::

def pypart(n):

for i in range(0, n):

for j in range(0, i+1):

print("* ",end="")

print(" ")

# Driver Code

n = 5

pypart(n)