Pyschool Answers – Topic 5: While loops

1. Add Numbers
Create a function addNumbers(x) that takes a number as an argument and adds all the integers between 1 and the number (inclusive) and returns the total number.

def addNumbers(num):
    total = 0
    i = 1
    while i<=num:
    return total

2. Add Numbers II
Create a function addNumbers(start, end) that adds all the integers between the start and end value (inclusive) and returns the total sum.

def addNumbers(start, end):
    total =0
    while start<=end:
    return total

3. Using ‘break’ in ‘while’ loop.[MCQ]
The ‘break’ statement can be used to terminate the ‘while’ loop.

[MCQ] What will be the maximum value of ‘cnt’?

      cnt = 0
      while True:
           while cnt<10:
                if cnt>10:

** 0
** 9
** Infinity, because it goes into endless loop.
** 10
** None of the above

4. Count Pages In A Book
Create a function countPages(x) that takes the number of pages of a book as an argument and counts the number of times the digit ’1′ appears in the page number.

def countPages(num):
    total = 0
    i = 1
    while i<=num:
        page_no = str(i)
        total += page_no.count('1')
    return total

5. Using ‘Break’ In ‘While’ Loop.[MCQ]
The ‘break’ statement can be used to terminate the ‘while’ loop.

[MCQ] Which of the following does not produce the same output?


cnt = 0
while True:
    print cnt
    if cnt&gt;5:


cnt = 0
while cnt&lt;6:
    while cnt&lt;6:
        print cnt


cnt = 0
while cnt&lt;6:
    print cnt


cnt = 0
while cnt&lt;6:
    print cnt
    if cnt==6:

** All give the same output.

6. Factorial(N)
Create a function factorial(x) that takes an integer and returns the product of all the positive integers less than or equal to n.

def factorial(num):
    product =1
    i = num
    while i > 0:
       product *=i
    return product

7. Double Factorial(N)
Create a function doubleFactorial(n) that takes an odd integer and returns the product of all odd values up to the value n (where n=2k-1).

def doubleFactorial(num):
    product = 1
    i = 0
    k = 0
    while k <num:
       k = 2*i+1
       product *= k
       i += 1
    return product

8. Prime Numbers
Create a function that takes in a positive integer and return a list of prime numbers.
A prime number is only divisible by 1 and itself.

def primeNumbers(num):
    primes = []
    i = 2
    # iterates through range from 2 to num(inclusive)
    while i<=num:     # add 'while' condition
        k = 2
        isPrime = True
        # check if prime number
        while k<i :      # add 'while' condition
            if i%k==0:
                isPrime = False
            k+=1           # update k
        if isPrime==True:
        i+=1              # update i
    return primes

9. Square Root Approximation
Create a function that takes in a positive number and return 2 integers such that the number is between the squares of the 2 integers. It returns the same integer twice if the number is a square of an integer.

import math
def sqApprox(num):
    i = 0
    minsq =0                         # set lower bound
    maxsq =math.ceil(num*num)                         # set upper bound
    while i<maxsq :                       # set 'while' termination condition
        if i*i<=num and i>minsq:  # complete inequality condition
            minsq = i
        if i*i>=num and i<maxsq:  # complete inequality condition
            maxsq = i
        i+=1                         # update i so that 'while' will terminate
    return (minsq, maxsq)

10. Pi Approximation
Create a function that computes the approximation of pi, based on the number of iterations specified.
pi can be computed by 4*(1-1/3+1/5-1/7+1/9- …).

def piApprox(num):
    i = 1
    pi = 0
    while i<=num:                # set 'while' termination condition
        pi +=((4/float(2*i-1))*(-1)**(i+1))             # compute the ith term of the series
        i+=1                      # update i
    return pi

11. Estimate Pi
Write a function estimatePi() to estimate and return the value of pi based on the formula found by an Indian Mathematician Srinivasa Ramanujan. It should use a while loop to compute the terms of the summation until the last term is smaller than 1e-15. The formula for estimating pi is given below:

import math
def factorial(n):
    if n == 0:
        return 1
        return n * factorial(n-1)

def series_term(k):
    return float(a*b)/(d*e)

def estimatePi():
    while True:
        term = series_term(k)
        final += term
        if term < 1.0e-15:
    pi = 1.0/(final * f)
    return pi

12. Prime Factorization
Given a positive integer, write a function that computes the prime factors that can be multplied together to get back the same integer.

def primeFactorization(num):
    factors = []
    lastresult = num
    # 1 is a special case
    if num == 1:
        return []
    while True:
        if lastresult == 1:
        c = 2
        while True:
            if lastresult % c == 0:
            c += 1
        lastresult /= c
    return factors

13. Lowest Common Multiple
The smallest common multiple of two or more numbers is called the lowest common multiple (LCM). Given a list of integers, find the lowest common multiple.

def LCM(nums):
    while sum([(multiplier*biggest)%num for num in nums])!=0:
    return biggest*multiplier

Leave a Reply