Previous topic

CS 2120: Class #16

Next topic

CS 2120: Practice Final Exam

This Page

Extra practice with while loopsΒΆ

  1. Write a function oddsum(n) that will return the sum of all odd numbers from 1 to n.
  2. Modify oddsum so that it takes two parameters: oddsum(n,m) and returns the sum of all odd numbers from n to m.
  3. Write a function that will return the sum of all even numbers from 1 to n plus the product of all odd numbers from 1 to n. (viz., add up all the even numbers between 1 and n, multiply together all the odd numbers between 1 and then add those two values).
  4. Write a function that computes the value of the following mathematical expression \sum_{i=1}^n x \cdot \frac{1-x^n}{1-x}. The function will take two parameters: n and x.
  5. Write a function that computes the value of the following mathematical expression \sum_{i=0}^n \frac{x^i}{i!}. Remember that ! denotes the _factorial_ function (which you’ve already seen as the dostuff function in Lecture #6).
  6. Write a function isprime(n) that returns True if n is prime and False otherwise. Remember that a number is prime if it is divisible by 1 and itself and nothing else.
  7. Write a function primes_less_than(p) that will print out all of the prime numbers (greater than 1 and) less than p.
  8. Write a function rand_loop(cutoff) that will return a count of how many times the interpreter makes it through a special loop. The loop condition will be the following expression numpy.random.rand() < cutoff. You will need to import numpy in your code. The random.rand() function generates a random number between 0 and 1, so the function parameter cutoff should be a floating point value between 0 and 1. In short: your function will generate a random number. If it’s less than the cutoff you’ll increment a counter and go through the loop again. If it’s equal to, or bigger than, the cutoff, you stop looping and return the count. Play with the function a bit to find a relationship between your choice of cutoff and the number of times your function makes it through the loop.
  9. Write a function mult_table(n) that will print out an n \times n multiplication table for the values 1 to n. Hint: you can nest if statements... can you nest while loops?