Comp 150-001, MWF 12:35, Crown 105

Week 2



TA: Robert Kania

Homework 1: If you turned it in by yesterday, you're done.
If you turn it in later, I may ask you to resubmit parts.


Homework 2

Due Friday, Feb 1

Each of these should be written as a python function. Each function will have one or more parameters.

1. Write a function boxprint(str, margin) that prints the given string in a five-line box formed of '*' characters (or other character, your choice). The string is to be centered in the box, with margin many spaces between the edge of the box and the string. For example, here is the output from boxprint("hello, world", 4):

**********************
*                    *
*    hello, world    *
*                    *
**********************

To create a string consisting of the character c repeated n times, you can use c * n. Also, to get the length of the string str you use len(str).


2.  Define a function numtriangle(rows) that should print a triangle like this:

  1
  2   3
  4   5   6
  7   8   9  10

That is, the pattern follows the triangle from the first homework, with the ith row (starting with i=1) having i numbers on it. However, the numbers replace the '*' character, and should be incremented steadily throughout.

Here is how you can print the number n in four spaces total, whether n is one, two or three digits (if you don't do this, the triangle columns will not line up!):

    print('{0: >4}'.format(n), end='')

I recommend this basic loop outline:

for row in range(1, rows+1):
    for col in range(row):

You will start with theNumber = 1 and then print it at each row,col position and then increment it.


3. Write a function sumbythrees(n) that returns the sum of those numbers less than or equal to n that leave a remainder of 1 after division by 3. In other words, these are the numbers in the sequence 1, 4, 7, 10, 13, ...

sumbythrees(15) should return 1+4+7+10+13 = 35.

This is a lot like oddsum(), which we discussed in class. Perhaps the easiest way to do this is to start with range(1, n+1, 3), which includes exactly the desired numbers.


4. Write a function collatz(n) that returns the stopping time of the Collatz sequence beginning with n. This sequence is generated as follows: if x is the value at step k, then the next value is

    3*x+1   if x is odd  (x // 2 == 1)
    x//2       if x is even (I've used the Python integer-division symbol // here)

The stopping time is the number of steps needed to reach 1. Starting from N=7, the sequence is as follows; its stopping time is 16.

7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1

You will need a while loop, because you don't know at the start how long the sequence will be.

Can you find a number n for which the stopping time is 200 or more? Hint: there's one between 2000 and 3000.

More information about the sequence itself is at en.wikipedia.org/wiki/Collatz_conjecture. See also 3.3.3.4 in the tutorial.



Python intro, from anh.cs.luc.edu/python/hands-on/3.1/handsonHtml.

Write add3 as a function:

def add3():
    x = int(input('enter x: '))
    y = int(input('enter y: '))
    z = int(input('enter z: '))
    print('The sum of {}, {} and {} is {}'.format(x, y, z, x+y+z))

In general, almost everything will be in functions from now on. (Why?)

Here is the function from last week that calculates the sum of the numbers from 1 to n. Generally we will be using parameters rather than input() values for data, and return rather than print for results.

def sum(n):
    sum = 0
    for i in range(n+1):
         sum += i
    return sum

Demo: Start Idle. Create a new file. Type in sum(). Note the automatic indentation. Save, and select Run module. Run both functions.

We can also write this with a while loop (though we haven't "officially" covered that yet):

def sum2(n):
    sum = 0
    i=1
    while i <= n:
        sum += i
        i += 1
    return sum

Not everything has to be in functions. We can just type this at the top level:

for i in range(5):
    print(i)

But let's go back to the basics of 1.13:


Friday: homework 2, while loops,

def sqrt(x):
    guess = x/3
    while abs(guess * guess - x) > 0.000001:
        guess = (x/guess + guess)/2
        print(guess)
    return guess

3.3: interactive while

Monday: 1.14

Dictionaries

The Python example collection is available at anh.cs.luc.edu/python/hands-on/3.1/examples.zip

d = dict()

d['one'] = 1
d['three'] = 3
d['two'] = 2

d

for i in d:
    print(i)

What can you do with a dictionary?