Comp 150, Dordal
In this lab we will write two functions, each
using a while loop.
1. Factorial loop
Here is a definition of the factorial function using a for loop:
def fact(n):Recall that the for loop runs the variable factor through each member of the list [1,2,3....,n-1], which is created by the range(1,n) call. While the creation of simple lists is pretty fast, it is fundamentally unnecessary here and in some cases can degrade performance.
prod = 1
for factor in range(1,n):
prod = prod * factor
return prod
You are to rewrite this using a while loop;
that is, without using for or range.
2. Base-2 conversion
You are to write a function binary(n) containing a loop to convert a base-10 number to base 2. The output should be either printed or else returned as a list of digits.
Start with n. To get one binary digit, use n % 2 (this is the remainder upon dividing n by 2). Then set n = n/2, and continue (this is where the while comes in). Stop when n=0 (that is, the while loop will be while n > 0:)
Alas, if you print the digits n%2 as you go, you get them in the reverse order; the digit you get with n%2 is the last digit. A fix is to put the digits into a list or string as you go. If the list is to be called digits, then you start with digits = '' (the empty string) or digits = [] (the empty list), and then add each successive digit to the front:
digits = num2dig(n%2) + digits # string version; see below for num2dig
digits = [n%2] + digits # list version
If you use the list version, then at the end you have to convert to a string: "".join(digits) (this joins all the characters of digits to the end of the empty string ""). If you use the string version, you need to write num2dig, which takes the number 0 or 1 and returns the character (string) '0' or '1'. Here's one approach:
def num2dig(num):
if num = 0:
return '0'
else:
return '1'
An even simpler method is to use indexing on the string "01": "01"[0]
is '0' and "01"[1] is '1'. You can use this as the body of num2dig, or
you can just put it "in-line" in the body of binary().
Another simple method is chr(48+n%2): chr(x) is the ascii character
with numeric value x, n%2 is either 0 or 1, and chr(48) == '0',
chr(49)=='1'.
You will need a separate case to handle n==0; you can test for this with an if statement. Do not worry about negative n.
Here are a few examples of numeric while loops. Do not forget the i=i+1 increment!
To find the sum of the numbers from 1 to N:
N = 100The value of 1+2+...+N is now in variable sum.
i= 1
sum = 0
while i<=N:
sum = sum + i
i = i+1
To find the sum of the numbers in a list L:
L=[2,3,5,7,11,13,17,19]
i=0
sum = 0
while i<len(L):
sum = sum + L[i]
i = i+1
To reverse a string S. The reversed string will be in the variable revS,
at the end of the loop.
S = "hello, world"
i = len(S)-1; # last position of S
revS = ""
while i>=0:
revS = revS + S[i]
i = i-1 # this time i is DECREMENTED