CS21 Lab 2: Numbers, Strings, and For Loops

Due Saturday, February 10, by 11:59pm

Goals

The goals for this lab assignment are:

  • Manipulate Python numeric and string data types (int, float, str).

  • Practice with string data types and sring operations.

  • Practice with numeric data types and numeric operations.

  • Learn to iterate over sequences using for loops.

  • Practice using the range function.

  • Practice using the accumulator pattern.

Getting and Working on Lab02 Code

Make sure you are working in the correct directory when you edit and run lab 02 files.

Run update21 to get the starting point code of the next lab assignment. This will create a new ~/cs21/labs/02 directory for your lab work. Edit and run Lab 02 programs from within your cs21/labs/02 directory.

Make sure all programs are saved to your cs21/labs/02 directory! Files outside that directory will not be graded.

$ update21
$ cd ~/cs21/labs/02
$ pwd
/home/username/cs21/labs/02
$ ls
(should see your program files here)

Then edit and run program files in your ~/cs21/labs/02 directory:

$ code filename.py
$ python3 filename.py

Unix Filesystem Practice (Optional Warmup)

This is not a required part of the assignment, but we encourage you to try the Pokémon Scavenger Hunt to get some more practice using Unix commands.

If you solve the scavenger hunt, we will award you 1 extra credit point on Lab 02.

1. Points

Write a program called points.py that asks the user for two points in the Cartesian plane, and computes the distance between the points and the slope of the line between them.

The formulas for slope and distance are:

  • distance between points (x1,y1) and (x2,y2):

    \[\sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2}\]
  • slope of line between points (x1,y1) and (x2,y2):

    \[\frac{(y_2 - y_1)}{(x_2 - x_1)}\]

1.1. Example Output

Some examples of running the program are shown below. User input is shown in bold.

$ python3 points.py
Given two points, this program computes the slope of
the line between them and the distance between them
Enter the x-coordinate of the 1st point: 1
Enter the y-coordinate of the 1st point: 1
Enter the x-coordinate of the 2nd point: 2
Enter the y-coordinate of the 2nd point: 2

Point 1: (1.0,1.0)
Point 2: (2.0,2.0)
Distance between them is: 1.4142135623730951
Slope is: 1.0

$ python3 points.py
Given two points, this program computes the slope of
the line between them and the distance between them
Enter the x-coordinate of the 1st point: -5.6
Enter the y-coordinate of the 1st point: 11
Enter the x-coordinate of the 2nd point: 8.4
Enter the y-coordinate of the 2nd point: -4

Point 1: (-5.6,11.0)
Point 2: (8.4,-4.0)
Distance between them is: 20.518284528683193
Slope is: -1.0714285714285714

1.2. Required Features

Your program should have the following features:

  • Print a message saying what the program does

  • Prompt the user to enter x and y values for the two points. You can assume the user enters a valid integer value for each point.

  • Print out the two points as (x,y)

  • Print out the distance value between the two points with string describing what the value is (e.g. "Distance between them is: ")

  • Print out the slope of the line between the two points with a string describing what the value is (e.g., "Slope is: ")

1.3. Hints/Tips

  • You may assume that the user enters valid integer values for each point.

  • The math library contains a sqrt function that you can use to compute the square root.

  • Add some debug information to print out partial terms in slope or distance if your values are not correct. Be sure to remove your debug output before submitting

  • Remember the precedence rules for numeric operators in your formulas. Note that using parens, ( and ), around subparts makes your code more readable even if your formula is correct based on the precedence rules of Python numeric operators without them.

  • You can check if your program is producing the correct answers comparing it to an on-line tool like this one: slope calculator.

2. Approximating PI

Scientists love \(\pi\), and since ancient times mathematicians have been developing ways to approximate \(\pi\).

One type of approximation uses an infinite series of terms added together, where each subsequent term added into the summation so far yeilds a closer approximation of \(\pi\). Infinite series approximations are typically represented by a formula that contains a sequence variable, \(i\), that iterates over an infinite set of values. For example \(i\) could go from \(1\) to \(\infty\).

Although computers are not able to perform an infinite number of operations and produce an answer, they can add thousands, even millions, of values together very quickly. Thus, we can use computers to compute very accurate approximations of \(\pi\) by computing the first thousands (or millions) of terms of an infinite series.

You will write a program named approxpi.py that computes some number of terms of the Leibniz infinite series summation that approximates \(\pi\).

A note on mathematical notation for summation of a series

A summation of a series of values is represented using a capital sigma and specifying the range of values for \(i\) and the formula for each term. For example, the following is an infinite series associated with Zeno’s Paradox:

\[\sum_{i=1}^{\infty} \frac{1}{2^i}\]

This expands to an infinite sum of terms, each term created from a different value of \(i\) starting from \(1\) and going to \(\infty\):

\[\frac{1}{2^1} + \frac{1}{2^2} + \frac{1}{2^3} + \frac{1}{2^4} + \ldots\]

In your approxpi.py program, after getting the input value for \(n\) from the user, compute the first \(n\) terms of the Leibniz approximation of \(\pi\) defined as:

\[\frac{\pi}{4} \hspace{0.5cm} = \hspace{0.5cm} \sum_{i=1}^{\infty} \frac{(-1)^{i+1}}{2i - 1}\]

In practice, we cannot sum an infinite number of terms, and instead we will sum the first n terms of the series for some large integer n. If we look at the first three terms i=1,2,3 of the series, we get the following expansion. Note how we replaced the i in the formula with the actual value of i for each term:

\[\frac{(-1)^{1+1}}{2(1)-1} + \frac{(-1)^{2+1}}{2(2)-1} + \frac{(-1)^{3+1}}{2(3)-1} + \ldots\]

After some simplification, the first few terms looks like:

\[\frac{\pi}{4} \hspace{0.5cm} = \hspace{0.5cm} \frac{1}{1} + \frac{-1}{3} + \frac{1}{5} + \ldots\]

Use an accumulator pattern to add up the first n terms of this sum. Remember that this series approximates \(\frac{\pi}{4}\). You will need to multiply by 4 to approximate \(\pi\).

2.1. Example Output

Here are a few runs of a working program:

$ python3 approxpi.py

This program approximates PI, computing the first n terms
of the Leibniz Summation infinite series
Enter the number of terms, n, to compute in the series: 1

Leibniz approx of pi for 1 terms is 4.0


$ python3 approxpi.py

This program approximates PI, computing the first n terms
of the Leibniz Summation infinite series
Enter the number of terms, n, to compute in the series: 2

Leibniz approx of pi for 2 terms is 2.666666666666667


$ python3 approxpi.py

This program approximates PI, computing the first n terms
of the Leibniz Summation infinite series
Enter the number of terms, n, to compute in the series: 1000

Leibniz approx of pi for 1000 terms is 3.140592653839794


$ python3 approxpi.py

This program approximates PI, computing the first n terms
of the Leibniz Summation infinite series
Enter the number of terms, n, to compute in the series: 1000000

Leibniz approx of pi for 1000000 terms is 3.1415916535897743

2.2. Required Features

Your program should have the following features:

  • Print a message saying what the program does.

  • Prompt the user to enter a value for the number of terms of each series to compute.

  • Compute the Leibniz series for n terms (from 1 to n inclusive) and print out its estimation of \(\pi\).

  • You should also print out the number of terms of each series that were computed (see example output for one example).

2.3. Hints/Tips

  • You may assume that the user enters a valid integer value for n.

  • Look at some of the in class numeric accumulator pattern examples.

  • Note that the sumation starts with i of 1 and not 0, and it includes the `n`th term.

  • The range fuction can be passed two integer values specifying the start and the end of the sequence to generate. For example, range(5,10) generates the sequence starting at 5 and up to but not including 10: [5,6,7,8,9].

  • Remember that the Leibniz series approximates \(\pi\)/4, so you need to adjust the results of the summation when you print the approximations of \(\pi\).

  • Try computing just part of each term first. For example, you could write code to sum the first \(n\) terms of just the numerator part of Leibniz (\(1 + -1 + 1 + -1 + \ldots \)) and test it for correctness for different values of \(n\). You could also try this for summing just the denominator part as well (\(1 + 3 + 5 + \dots \)). Once those are tested for correctness, put them together to create the correct next term of the Leibniz sequence.

  • Try just computing the first term and compare it to the sample output (when n is 1) to see if you are computing the right term in the sequence.

  • Add some debug print statements inside the for loop to print out the next term for each series (If you do this be sure to remove or comment these out in your submitted solution).

3. Strings!

Write a program named stringmanip.py that takes as input as string and a positive integer value, and manipulates the string in different ways, some of which use the integer value, and all of which requiring using loops.

Given a string and an integer value, n, both entered by the user, your program will:

  • Print an increasing number of characters (chars) in string.

  • Print a decreasing pattern of n star (*) characters

  • Print an increasing number of chars in string followed by a decreasing number of stars (* characters).

  • Print increasing number of characters in the string, each repeated n times.

See the Example Output for some examples of each of these for different string and integer input values.

3.1. Example Output

Three examples runs of the program are shown below. Note how the values of the string and the integer are used in the different patterns, and also note the example with space characters in the string (space is a valid character just like any other). User input is shown in bold (and here is some information about Grace Hopper whose name we use in some of these examples).

$ python3 stringmanip.py

This program produces some patterns from a string and an integer n.
Enter string: GraceHopper
Enter a (small positive) integer for n: 5

print increasing number of chars in string
G
Gr
Gra
Grac
Grace
GraceH
GraceHo
GraceHop
GraceHopp
GraceHoppe
GraceHopper

print decreasing pattern of n stars (the character *)
*****
****
***
**
*

print increasing number of chars in string and decreasing stars (*)
G***********
Gr**********
Gra*********
Grac********
Grace*******
GraceH******
GraceHo*****
GraceHop****
GraceHopp***
GraceHoppe**
GraceHopper*

print increasing number of char, each repeated n times
GGGGG
GGGGGrrrrr
GGGGGrrrrraaaaa
GGGGGrrrrraaaaaccccc
GGGGGrrrrraaaaaccccceeeee
GGGGGrrrrraaaaaccccceeeeeHHHHH
GGGGGrrrrraaaaaccccceeeeeHHHHHooooo
GGGGGrrrrraaaaaccccceeeeeHHHHHoooooppppp
GGGGGrrrrraaaaaccccceeeeeHHHHHooooopppppppppp
GGGGGrrrrraaaaaccccceeeeeHHHHHoooooppppppppppeeeee
GGGGGrrrrraaaaaccccceeeeeHHHHHoooooppppppppppeeeeerrrrr
$ python3 stringmanip.py

This program produces some patterns from a string and an integer n.
Enter string: Grace Hopper
Enter a (small positive) integer for n: 3

print increasing number of chars in string
G
Gr
Gra
Grac
Grace
Grace
Grace H
Grace Ho
Grace Hop
Grace Hopp
Grace Hoppe
Grace Hopper

print decreasing pattern of n * chars
***
**
*

print increasing number of chars in string and decreasing stars (*)
G************
Gr***********
Gra**********
Grac*********
Grace********
Grace *******
Grace H******
Grace Ho*****
Grace Hop****
Grace Hopp***
Grace Hoppe**
Grace Hopper*

print increasing number of chars, each repeated n times
GGG
GGGrrr
GGGrrraaa
GGGrrraaaccc
GGGrrraaaccceee
GGGrrraaaccceee
GGGrrraaaccceee   HHH
GGGrrraaaccceee   HHHooo
GGGrrraaaccceee   HHHoooppp
GGGrrraaaccceee   HHHooopppppp
GGGrrraaaccceee   HHHoooppppppeee
GGGrrraaaccceee   HHHoooppppppeeerrr
$ python3 stringmanip.py

This program produces some patterns from a string and an integer n.
Enter string: Strings in Python Rock!
Enter a (small positive) integer for n: 2

print increasing number of chars in string
S
St
Str
Stri
Strin
String
Strings
Strings
Strings i
Strings in
Strings in
Strings in P
Strings in Py
Strings in Pyt
Strings in Pyth
Strings in Pytho
Strings in Python
Strings in Python
Strings in Python R
Strings in Python Ro
Strings in Python Roc
Strings in Python Rock
Strings in Python Rock!

print decreasing pattern of n stars (* characters)
**
*

print increasing number of chars in string and decreasing stars (*)
S***********************
St**********************
Str*********************
Stri********************
Strin*******************
String******************
Strings*****************
Strings ****************
Strings i***************
Strings in**************
Strings in *************
Strings in P************
Strings in Py***********
Strings in Pyt**********
Strings in Pyth*********
Strings in Pytho********
Strings in Python*******
Strings in Python ******
Strings in Python R*****
Strings in Python Ro****
Strings in Python Roc***
Strings in Python Rock**
Strings in Python Rock!*

print increasing number of chars, each repeated n times
SS
SStt
SSttrr
SSttrrii
SSttrriinn
SSttrriinngg
SSttrriinnggss
SSttrriinnggss
SSttrriinnggss  ii
SSttrriinnggss  iinn
SSttrriinnggss  iinn
SSttrriinnggss  iinn  PP
SSttrriinnggss  iinn  PPyy
SSttrriinnggss  iinn  PPyytt
SSttrriinnggss  iinn  PPyytthh
SSttrriinnggss  iinn  PPyytthhoo
SSttrriinnggss  iinn  PPyytthhoonn
SSttrriinnggss  iinn  PPyytthhoonn
SSttrriinnggss  iinn  PPyytthhoonn  RR
SSttrriinnggss  iinn  PPyytthhoonn  RRoo
SSttrriinnggss  iinn  PPyytthhoonn  RRoocc
SSttrriinnggss  iinn  PPyytthhoonn  RRoocckk
SSttrriinnggss  iinn  PPyytthhoonn  RRoocckk!!

3.2. Required Features

Your program should have the following features:

  • Print a message saying what the program does

  • Prompt the user to enter a string and a (small) positive integer value. You can assume the user enters a valid integer value for each point.

  • For each of the four patterns, print out a short description of the pattern pattern is followed by the pattern.

3.3. Hints/Tips

  • Implement and test each one incrementally. Each loop is in increasing order of complexity, so start with the first one. However, if you get stuck on one (like the 3rd one), skip ahead and try another one come back to the one you are stuck on. You may want to look at your inclass/w02-loops/loop.py for a sample program with multiple loops.

  • Look at the sample output often to make sure you are implementing the correct pattern (note how the value n and the length of the string are used in different patterns by looking how each pattern differs across the three example runs).

  • Look at in-class sting operator and string accumulator example code to help you. Try running the in-class code again, and you can modify it to see how it changes too.

  • Try implementing and testing partial (simplified) version of each one and then change them to implement the full pattern. For example, for the first one, you could just print the full string for the correct number of lines. Once that works, then modify what you print to print out an increasing number of characters each line.

  • There may be more than one way to implement a given pattern, but all require using a for loop.

  • Keep in mind that everything on one line has to be printed out before moving on to print the next line (you can’t go back and add to a previously printed line of output).

4. Extra Challenge

Do not attempt this until after you have fully completed the required parts of this assignment, and run handin21 to submit them.

This is not worth extra credit points, but is an extra challenge to try out if you’d like.

First, copy your stringmanip.py to a file named extra.py:

$ cp stringmanip.py extra.py

Open extra.py in the code editor, delete most of the main code except the parts that reads in the string and the integer value.

code extra.py

Then try adding one or more of the following:

  • print out a pyramid of * characters of size n.

  • print out a diamond of * characters of size n.

  • print out a mirror image pyramid of the input string (look at the example for how to interpret this…​this one is extra tricky).

No Hints on extra challenges, but it may be helpful to remember that space is a valid charater that can be part of a string. You can represent a string consisting of a single space character as double quotes with space between them: " " (just like a string with a single a character would be represented as "a").

Here is some example output from a couple runs:

$ python3 extra.py

This program produces some extra challange patterns from a string
and an integer n.
Enter string: Grace Hopper
Enter a (small positive) integer for n: 8

Extra challenge: print a pyramid of n * chars:
                *
              * * *
            * * * * *
          * * * * * * *
        * * * * * * * * *
      * * * * * * * * * * *
    * * * * * * * * * * * * *
  * * * * * * * * * * * * * * *

Extra challenge: print a diamond of n * chars:
                *
              * * *
            * * * * *
          * * * * * * *
        * * * * * * * * *
      * * * * * * * * * * *
    * * * * * * * * * * * * *
  * * * * * * * * * * * * * * *
    * * * * * * * * * * * * *
      * * * * * * * * * * *
        * * * * * * * * *
          * * * * * * *
            * * * * *
              * * *
                *


Extra challenge: print mirror image string pyramid
                        G
                      G r G
                    G r a r G
                  G r a c a r G
                G r a c e c a r G
              G r a c e   e c a r G
            G r a c e   H   e c a r G
          G r a c e   H o H   e c a r G
        G r a c e   H o p o H   e c a r G
      G r a c e   H o p p p o H   e c a r G
    G r a c e   H o p p e p p o H   e c a r G
  G r a c e   H o p p e r e p p o H   e c a r G


$ python3 extra.py

This program produces some extra challange patterns from a string
and an integer n.
Enter string: Python Strings Rock!
Enter a (small positive) integer for n: 5

Extra challenge: print a pyramid of n * chars:
          *
        * * *
      * * * * *
    * * * * * * *
  * * * * * * * * *

Extra challenge: print a diamond of n * chars:
          *
        * * *
      * * * * *
    * * * * * * *
  * * * * * * * * *
    * * * * * * *
      * * * * *
        * * *
          *


Extra challenge: print mirror image string pyramid
                                        P
                                      P y P
                                    P y t y P
                                  P y t h t y P
                                P y t h o h t y P
                              P y t h o n o h t y P
                            P y t h o n   n o h t y P
                          P y t h o n   S   n o h t y P
                        P y t h o n   S t S   n o h t y P
                      P y t h o n   S t r t S   n o h t y P
                    P y t h o n   S t r i r t S   n o h t y P
                  P y t h o n   S t r i n i r t S   n o h t y P
                P y t h o n   S t r i n g n i r t S   n o h t y P
              P y t h o n   S t r i n g s g n i r t S   n o h t y P
            P y t h o n   S t r i n g s   s g n i r t S   n o h t y P
          P y t h o n   S t r i n g s   R   s g n i r t S   n o h t y P
        P y t h o n   S t r i n g s   R o R   s g n i r t S   n o h t y P
      P y t h o n   S t r i n g s   R o c o R   s g n i r t S   n o h t y P
    P y t h o n   S t r i n g s   R o c k c o R   s g n i r t S   n o h t y P
  P y t h o n   S t r i n g s   R o c k ! k c o R   s g n i r t S   n o h t y P

Programming Tips

As you write programs, use good programming practices:

  • Use a comment at the top of the file to describe the purpose of the program (see example).

  • All programs should have a main() function (see example).

  • Use variable names that describe the contents of the variables.

  • Write your programs incrementally and test them as you go. This is really crucial to success: don’t write lots of code and then test it all at once! Write a little code, make sure it works, then add some more and test it again.

  • Don’t assume that if your program passes the sample tests we provide that it is completely correct. Come up with your own test cases and verify that the program is producing the right output on them.

  • Avoid writing any lines of code that exceed 80 columns.

    • Always work in a terminal window that is 80 characters wide (resize it to be this wide)

    • In vscode, at the bottom right in the window, there is an indication of both the line and the column of the cursor.

Function Comments

All functions should have a top-level comment! Please see our function example page if you are confused about writing function comments.

Answer the Questionnaire

After each lab, please complete the short Google Forms questionnaire. Please select the right lab number (Lab 02) from the dropdown menu on the first question.

Once you’re done with that, you should run handin21 again.

Submitting lab assignments

Remember to run handin21 to turn in your lab files! You may run handin21 as many times as you want. Each time it will turn in any new work. We recommend running handin21 after you complete each program or after you complete significant work on any one program.

Logging out

When you’re done working in the lab, you should log out of the computer you’re using.

First quit any applications you are running, including your vscode editor, the browser and the terminal. Then click on the logout icon (logout icon or other logout icon) and choose "log out".

If you plan to leave the lab for just a few minutes, you do not need to log out. It is, however, a good idea to lock your machine while you are gone. You can lock your screen by clicking on the lock xlock icon. PLEASE do not leave a session locked for a long period of time. Power may go out, someone might reboot the machine, etc. You don’t want to lose any work!