JamCoders

💾 Download

Lecture 2, Part 2

Note: This lab is to brush up on loops using animation!

In [2]:
# You only need to run this code once.

%pip install ipython
%pip install termcolor
Requirement already satisfied: ipython in /opt/conda/lib/python3.10/site-packages (8.4.0)
Requirement already satisfied: pygments>=2.4.0 in /opt/conda/lib/python3.10/site-packages (from ipython) (2.12.0)
Requirement already satisfied: traitlets>=5 in /opt/conda/lib/python3.10/site-packages (from ipython) (5.3.0)
Requirement already satisfied: setuptools>=18.5 in /opt/conda/lib/python3.10/site-packages (from ipython) (62.6.0)
Requirement already satisfied: stack-data in /opt/conda/lib/python3.10/site-packages (from ipython) (0.3.0)
Requirement already satisfied: backcall in /opt/conda/lib/python3.10/site-packages (from ipython) (0.2.0)
Requirement already satisfied: decorator in /opt/conda/lib/python3.10/site-packages (from ipython) (5.1.1)
Requirement already satisfied: prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0 in /opt/conda/lib/python3.10/site-packages (from ipython) (3.0.29)
Requirement already satisfied: jedi>=0.16 in /opt/conda/lib/python3.10/site-packages (from ipython) (0.18.1)
Requirement already satisfied: matplotlib-inline in /opt/conda/lib/python3.10/site-packages (from ipython) (0.1.3)
Requirement already satisfied: pickleshare in /opt/conda/lib/python3.10/site-packages (from ipython) (0.7.5)
Requirement already satisfied: pexpect>4.3 in /opt/conda/lib/python3.10/site-packages (from ipython) (4.8.0)
Requirement already satisfied: parso<0.9.0,>=0.8.0 in /opt/conda/lib/python3.10/site-packages (from jedi>=0.16->ipython) (0.8.3)
Requirement already satisfied: ptyprocess>=0.5 in /opt/conda/lib/python3.10/site-packages (from pexpect>4.3->ipython) (0.7.0)
Requirement already satisfied: wcwidth in /opt/conda/lib/python3.10/site-packages (from prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0->ipython) (0.2.5)
Requirement already satisfied: pure-eval in /opt/conda/lib/python3.10/site-packages (from stack-data->ipython) (0.2.2)
Requirement already satisfied: executing in /opt/conda/lib/python3.10/site-packages (from stack-data->ipython) (0.8.3)
Requirement already satisfied: asttokens in /opt/conda/lib/python3.10/site-packages (from stack-data->ipython) (2.0.5)
Requirement already satisfied: six in /opt/conda/lib/python3.10/site-packages (from asttokens->stack-data->ipython) (1.16.0)
Note: you may need to restart the kernel to use updated packages.
Requirement already satisfied: termcolor in /opt/conda/lib/python3.10/site-packages (1.1.0)
Note: you may need to restart the kernel to use updated packages.

Question 1: Warm Up

1.1

Create a string called my_string with value "jamcoders".

In [ ]:

1.2

Print the length of my_string.

In [ ]:

1.3

Given the list of strings below, use a for loop to print each string in the list.

In [ ]:
my_strings = ["comp", "ute", "rz", "!"]

# Your code here:

1.4

Use a for loop to print the length of each string in my_strings.

In [ ]:

1.5

Create a function that takes a list of strings and prints the length of the longest string in the list.

In [ ]:
my_strings = ["comp", "ute", "rz", "!"]

def longest_string(lst):
    # Your code goes here


longest_string(my_strings)
# answer: 6

Question 2: Build a square

2.1

Write a function that takes an integer x and prints an x by x checkerboard of hashes.

Ex:

build_checkerboard(4)  
# # # #
# # # #
# # # #
# # # #
In [ ]:
def build_checkerboard(x):
    # Your code goes here


build_checkerboard(4)

Question 3: Build a pyramid

Write a function that takes an integer x and prints a pyramid with height x.

Ex:

build_pyramid(4)  
   #
  # #
 # # #
# # # #
In [ ]:
def build_pyramid(x):
    # Your code goes here


build_pyramid(4)

Question 4: Some cool Animations!

4.1

Run the code in the cell below. Here, we are using a function called sleep (that someone else wrote) from a module called time.

What does sleep() seem to do?

In [ ]:
from time import sleep

# Experiment and answer here!

print('print1')
sleep(1)
print('print2')
sleep(2)
print('print3')
sleep(5)
print1
print2
print3
In [ ]:
# Answer here!

4.2

Another function is a function called clear_output from IPython. What does clear_output() seem to do?

In [ ]:
from time import sleep
from IPython.display import clear_output

print('print1')
sleep(1)
clear_output()

print('print2')
sleep(2)
clear_output()

print('print3')
sleep(5)
clear_output()
In [ ]:
# Answer here!

4.3

Using sleep and clear_output, we can build animations! Together, in the function show, the two functions allow us to pause to show the current 'frame', then clear the frame after some amount of time.

Fix the code below so that there is a count-down animation, and finally at the end we print 'Ding!'

# Code your edits in this cell!

from IPython.display import clear_output
from time import sleep

def show():
  sleep(0.25)
  clear_output(wait=True)


def chime(time):
    # Your code here! We recommend:

    # 1. Do a for loop to count down
    # Hint: There are many ways to count down, some of which we may not have learned. 
    # One way is: if you are able to loop from 0 to n - 1, 
    # how can you use subtraction to count down from n to 1?

    # 2. In the loop, we want to first print the time

    # 3. Also in the loop, we want to show() the frame

  # Outside the loop, at the very end, we print 'Ding!'
  print('Ding!')

# Then we call the function to run it
chime(10)

The above is for reference only. Please code below

In [ ]:
# Code your edits in this cell!

from IPython.display import clear_output
from time import sleep

def show():
  sleep(0.25)
  clear_output(wait=True)


def chime(time):
    # Your code here! We recommend:

    # 1. Do a for loop and range() to count up, and use this to calculate a count down

    # 2. We want to first print the time

    # 3. Then we want to show() the frame

  # At the very end, we print Ding!
  print('Ding!')

# Then we call the function to run it
chime(10)

4.4

This code draws grids increasing sized grids. However, we'd like to alter the code. Instead of printing grids, can you make pyramids? And instead of increasing sizes of pyramids, can you make the size decrease? You can use your code from Question 3.

from IPython.display import clear_output
from time import sleep

def show():
  sleep(0.25)
  clear_output(wait=True)

# This function prints a solid grid of some size
def print_grid(size):
    for i in range(1, size + 1):
      print('#' * (size + 1) * 2)

# This function shows grids of increasing sizes, starting from size 0 to n-1!
def increasing_grid(n):
  # For loop, incrementing a variable called size
  for size in range(n):
    # Printing a new grid for a certain size
    print_grid(size)
    # Then showing the grid
    show(1)

increasing_grid(20)

The above is for reference only. Please code below

In [ ]:
from IPython.display import clear_output
from time import sleep

def show():
  sleep(0.25)
  clear_output(wait=True)

# Make your edits here!

# This function prints a solid grid of some size
# You may want to replace this with your print pyramid function
def print_grid(size):
    for i in range(size + 1):
      print('#' * (i + 1) * 2)

# This function shows grids of increasing sizes, starting from size 0 to n-1!
def increasing_grid(n):
  # For loop, incrementing a variable called size
  # You may want to change the loop so that it decreases in size instead
  for size in range(n):
    # Printing a new grid for a certain size
    print_grid(size)
    # Then showing the grid
    show(1)

increasing_grid(20)

Question 5: Colors!

5.1

Recall from lecture that you can print colors, like Professor Boaz demonstrated with the Jamaican flag! To do so, we will use some code the someone else has written. (We will use the function called colored from a module called termcolor)

  • colored is a function
  • colored(text, color) returns the same string as text except in a certain color
  • note that color is also a string that can have certain values:
    • "grey"
    • "red"
    • "green"
    • "yellow"
    • "blue"
    • "magenta"
    • "cyan"
    • "white"

Try running the code sample below:

In [ ]:
from termcolor import colored 

block = '█'
circle = 'o'
cross = 'x'
plus = '+'

print(f"The return value of colored has type: {type(colored(block, 'green'))}")

# print a red block 
print(colored(block, 'red'))

# print a green circle
print(colored(circle, 'green'))

# print a magenta plus
print(colored(plus, 'magenta'))

5.1

Can you print a blue cross?

In [ ]:
from termcolor import colored 
# Code here!

5.2

Can you print a cyan hashtag?

In [ ]:
from termcolor import colored 
# Code here!

5.3

Anakai wants to make a rainbow animation that does the following:

  • Takes in some text and a list of colors.
  • For each color, it prints() the text, then shows() the text
  • When we reach the end of the list, we finally print() the string text in the first color.

For example, rainbow_print('hi', ['red', 'green', 'blue']) would first print 'hi' in red, then in green, then in blue. Finally, at the end, it finishes by printing 'hi' in the first color, 'red'.

In [ ]:
from IPython.display import clear_output
from time import sleep
from termcolor import colored 

def show():
  sleep(1)
  clear_output(wait=True)

def rainbow_print(text, colors):
  # Your code here!
  pass

# Test here!
all_colors = ["grey", "red", "green", "yellow", "blue", "magenta", "cyan", "white"]
rainbow_print('███<<<HELLO!>>███', all_colors)

5.4: Arrow

Jabari wants to draw an arrow going to the right. The grid should be 40 blocks across, and 5 blocks tall. The arrow should be 3 blocks and 5 blocks tall.

  • He has written some code to draw the first arrow that starts at the first column. Try running this code!
  • Can you turn this in a function called print_arrow(column), that prints the white arrow where the top left square is on certain column?
  • For example, print_arrow(0) should print out the same as Jabari's current code, and print_arrow(1) should print out Jabari's arrow shifted one square to the right.
  • (The function should work when column is between [0-37], inclusive. In other words, don't worry about the arrow going off the screen).
In [ ]:
from termcolor import colored 

# Jabari's code!
block = '█'
board = ''
for row in range(5):
  for column in range(40):
    
    # The coordinates (row=0, column=0), (row=4, column=0) should be white
    if (row == 0 or row == 4) and column == 0:
      board += colored(block, 'white')

    # The coordinates (row=1, column=1), (row=3, column=1) should be white
    elif (row == 1 or row == 3) and column == 1:
      board += colored(block, 'white')

    # The coordinates (row=2, col=1), should be white
    elif (row == 2) and column == 2:
      board += colored(block, 'white')

    # This coordinate is not on the arrow, just add a green tile
    else:
      board += colored(block, 'green')

  board += '\n' # '\n' means a new line!
print(board)
In [ ]:
from termcolor import colored 

def print_arrow():
  # Your code here!
  pass

# print_arrow(5)

5.5 -optional

Can you use print_arrow() to animate moving the arrow to the right?

In [ ]:
from termcolor import colored 
from IPython.display import clear_output
from time import sleep

def show():
  sleep(0.25)
  clear_output(wait=True)

# Your code to animate here!

Question 6: Make your own animation

Now, try making your own animation. It can be anything, so it is a chance to be creative!

Below is an example that the staff made. You can try running it if you'd like! You can show us or your friends who have finished when you are done!

In [2]:
# Example, but we encourage you to do something completely different!
from IPython.display import clear_output
from time import sleep

def show():
  sleep(0.25)
  clear_output(wait=True)

def metaprint(text, pretext=''):
  code_text = 'print(\''+ text +'\')'
  output_text = '>>> ' + text

  for i in range(len(code_text)):
    print(pretext, end='')
    print(code_text[:i] + '_')
    show()
  
  print(pretext, end='')
  print(code_text)
  print(output_text)
  show()

  return pretext + code_text + '\n' + output_text + '\n'

res = metaprint('I')
res = metaprint('love', res)
res = metaprint('Jamcoders', res)
res = metaprint('2022', res)
print('I')
>>> I
print('love')
>>> love
print('Jamcoders')
>>> Jamcoders
print('2022')
>>> 2022
In [ ]:
# Your amazing animation here!