Not logged in. Login

Exercise 5

Mostly Spaces

In a file spaces.py, write a function named mostly_spaces that takes one argument: a string. The function should return True if the string is more than half spaces, and False otherwise. (Note: The boolean values True and False are not the same as the strings "True" and "False".)

Include this as the main part of the program:

print(mostly_spaces("a  c  d"))
print(mostly_spaces("ac d"))
print(mostly_spaces("x x x "))
if mostly_spaces("1 2 3 4"):
    print "yes"
else:
    print "no"
if mostly_spaces("1  2  3  4"):
    print "yes"
else:
    print "no"

The result if you run this program with your function should be:

True
False
False
no
yes

Again, but as functions.

In this question, you will recreate older lab exercises as functions in a file functions.py. You are welcome to use the code from your older lab solutions. You don't have to worry about error checking (numbers out of bounds, etc.) as before.

Write a function area that calculates the area of a circle, as in lab 2. It should take a number as it argument (the radius) and return the area. So, the function call area(10) should return 314.16.

Write a function feedback that gives feedback on a mark, as in lab 3. It should take a number as it argument (the grade) and return a string with English feedback on the grade. So, the function call feedback(55) should return "needs improvement" and feedback(85) should return "very good".

Running Time

Create a text file running-time.txt. Give the running time of these algorithms (which have been expressed in Python). Assume the value of n has already been set; express the running time in terms of n. For each of them, the number of “steps” is the number of times the calculation in the loop is repeated.

(a)

x = 0
for i in range(2*n):
    x = x + i
print(x)

(b)

x = 0
for i in range(n):
    for j in range(n-1):
        x = x + i*j
print(x)

(c)

x = 1
while x < n:
    x = x * 2
print(x)

Remember to eliminate lower-order terms and leading constants.

Submitting

Submit all of your work through CourSys.

Updated Tue June 04 2024, 15:45 by ggbaker.