Вы находитесь на странице: 1из 11

CSC807: Advanced programming.

Study Guide

Module 1: Basics
Module 2: Built-in function and operators
Module 3: Modules, functions and built-in modules
Module 4: Decision structures
Module 5: Strings, lists and tuples
Module 6: Dictionaries and sets
Module 7: File processing
Module 8: Exceptions and Pickling
Module 9: Classes ad inheritance
Module 10: Iterators, recursions, and data structures
``

Module 1: Basics

1. What is the meaning of an algorithm in computing? Give two examples


2. What distinguishes low-level programming languages from high-level programming
languages. Give examples of both low-level and high-level programming languages.
3. Why is Python described as scripting language?
4. Which of the following identifier names are valid in Python? employee_01, 1_radius,
abiola’s age, MusaID, metric-no, diameter9, temp-centigrade, employee_wt,
EMPLOYEE_HT, course-no-1.
5. Represent the following numbers in hexadecimal: 1000101010, 110111, 98, 129, 255
6. Represent the following numbers in binary: 0xFCB0A, 0x89AD
7. Find the two’s complement representation of the following numbers using an 8-bit
pattern: 128, -89, 75, 34
8. What is will displayed from the following statements:
print(9//5 + 17%3 + 3**2)
print(9>5 and 4<=3)
print(19%4, 25//4, 3**3, sep =“**”)
print(9%4==1, 89%2==0, 78//2>15, sep =“$”)
print(list(range(4,34, 6)))
print(bin(0b111101))
print(hex(56))
print(oct(89))
print(int(0o56))
Write the following expressions in Python:
x(x-y) +y(y-x)
a
a3 + |a|+ y b
Module 2: Built-in functions and operators
1. Write a program that will accept the dimensions of 3 rooms in a house and display the
total areas. The program should involve the following operations :
a) For each room, accept from the user the length and breadth
b) Compute the area using the formula area = length*breadth and add to total area
c) Compute and display the total areas (square metres).
d) The program should display using the example format below:
Size of room Room 1: 2m x 4m
Size of room 2: 2.34m x 6.2m
Size of room 3: 3.4m x 5.1m
Total area of house is 39.848 sq. m. (format using 3 decimal places)
2. Write a program the value of s=v+0.5 ∗g∗t 2 for given values of v and t and g =
9.8067. The program should involve the following:
a) Accept from user the values of v and t.
b) Compute s
c) Display the values of v, t and s using the example format below:
Value of v = 2.45
Value of t = 10.0
Value of s = 492.78 (format using 2 decimal places)
3. Write a program that execute the following operations:
a) Prompt the user to enter a string and assign to variable employee
b) Prompt the user to enter an integer and assign to variable ID
c) Prompt the user to enter a floating point number and assign to variable hrlyRate
d) Prompt the user to enter a floating point number and assign to variable hrs
e) Compute hrlyRate*hrs and assign to variable pay
f) Print employee, ID, hrlyRate, hrs and pay using the example format below:
Employee: Adamu
Employee ID: 221133
Hourly Rate: 1000
Hours: 100
Total Pay: N100,000.00 (format using 2 decimal places)

Module 3: Modules, functions and built-in modules

1. Define a function (name it displacement) that accepts the 2 floating point numbers
(name them velocity and t_travel), computes and returns the value of
velocity + 0.5*g*t_travel2 , where g = 9.8067.
2. Define a function (name it swap) that will accept 2 values, swap their values and return
the swapped values.
3. Define a function (name it threeRandoms) that will return the three random integers
between 25 and 85.
4. Define a function (name it employeeInfo) that will accept from user a string
representing name, an integer representing the refno and a string representing the
dept. The function to return values of name, refno and dept.
5. Define a function (name it circlePoint) that will accept 2 values representing radius and
arcangle (a) of a circle and uses xCoord = radius*cos(arcangle) and yCoord =
radius*sin(arcangle) to compute and return the x and y coordinates of a point on the
circle.
6. Define a function (name it amort) that will accept 3 values, representing the principal
(p), annual percentage rate (r%) and number of years (n) of a investment, compute
and return the total investment amount after n years using the formula
12∗n
a= p∗(1+r /1200) .

Module 4: Decision Structures


1. Define a function (name it funcRands) that will accept an integer (n) that is less than 20
and display the n random integers between 5 and 10.
2. Define a function (name it funcFloatRands) that will accept an integer (n) and display n
floating point numbers between 0 and 1.
3. Define a function (name it echoFun) that will continue to prompt to use to enter a string
and display the string entered, until the user enters a string “quit”.
4. Write a program that will find the smallest n such that n 3 is less than or equal to 12000.
5. Write a program that will find the largest n such that n 3 is less than or equal to 12000.
6. Write a program that will display the following output:
1
121
12421
1248421
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
7. Write a program that ask the user to enter and integer n, compute and display the
following series:
1 1 1 1
1+ + + +⋯+ , n !=n(n−1)( n−2)⋯(2)(1).
1! 2! 3! n!
8. Describe the following
a) modular programming
b) structured programming
c) variable scope; distinguish between global and local variables

Module 5: Strings, lists and tuples


1. Answer the following questions
a) Write a statement defining a string object named strObj that references the phrase
below:
FSU's Bronco Square
b) Write a statement defining a string object named strObj that references the phrase
below:
Your time to bed is "now"
c) Write a single print statement that will display the following phrase:
Your time
to bed
is "now"
d) Let
strObj="Your time to bed is now"
Write a print statements that will display the substring "time" and “now” in strObj.
e) Suppose s1 = "Hello Daniel." and s2 = " How are you?".
Write a print statement that will display using the two string objects the following:
Hello Daniel. How are you?
f) Suppose
strObj="Patricia\nCynthia\nDaniel\nWilliams\Latasha"
Write a statement that will create a list using the escape character \n as the
delimiter from strObj and store the result in another variable lstObj.
g) Write a statement that will remove the character & from the string
strObj="&&&&&&Hello Pauline&&&&&&&&&&&&"
and store the store in another string object strObjnew.
2. Define a function named countVowels that will take as an argument a string object,
find and return the number of vowel characters in the string object. For example,
countVowels("Daniel Okunbor")
will return
6
3. Define a function named replaceVowels that will take as an argument a string object,
return another string object that will contain the argument string object after capitalizing
(changing to uppercase) all vowel characters. For example,
replaceVowels("Daniel Okunbor")
will return
"DAnIEl OkUnbOr"
4. Answer the following questions:
a) Suppose
obj1 = [3, 4, 6]
Write a print statement that will display
[3, 4, 6, 3, 4, 6, 3, 4, 6, 3, 4, 6, 3, 4, 6]
b) Write a statement that will add "Andrea" to the end of the following list object.
lst_obj = ["John", "Patricia", "Daryl"]
c) Write a statement that will delete the item stored at index 3 of the list object.
lst_obj=["Gina", "Erika", "McNeill", "Kristine", "Wilma"]
d) Write a statement that will define a tuple object tObj with the value 9 assigned to it.
e) Let
aObj = [[4,5], [-1,0,2], [6], [10,15,28,-5]]
Write a print statement that will display the value 10 in the list.
f) Let
aObj = [[4,5], [-1,0,2], [6], [10,15,28,-5]]
Write a print statement that will display [-1,0,2] in the list.
g) Write a print statement that will display the size of the following list object.
AObj = [[4,5], [-1,0,2], [6], [10,15,28,-5]]
5. Define a function named addValue that will take a list object and an integer object as
arguments, add the integer argument to every element in the list object. Assume every
element is a number to avoid raising an exception if the list element is not a number.
6. Define a function named removeOdds that will take a list object as an argument,
remove all elements with odd indices.

Module 6: Dictionaries and Sets


1. Answer the following questions
a) Let
aDict = {0:"Math", 1:"Biology", 2:"Physics"}
Write a single statement that would display all the keys.
b) Let
aDict = {0:"Math", 1:"Biology". 2:"Physics}
Write a single statement that would display all the values.
c) What are the characteristics distinguishing a dictionary object from a set object?
d) What statements are used to define empty dictionary or set object?
e) How many elements are in {9,}?
f) Let
aDict = {'MTH':"Mathematics", 'CHM':"Chemistry", 'BIO':"Biology"}
Write a statement that would add the element 'PHY':"Physics" to aDict.
g) Let
aDict = {'MTH':"Mathematics", 'CHM':"Chemistry", 'BIO':"Biology"}
Write a statement that would add elements in bDict = {'PHY':"Physics", 'CSC':"Computer
Science"} to aDict.
h) Define a function, name it keyValue that would accept a dictionary object as an
argument, and displays all elements using the format below.
aDict = {'MTH':"Mathematics", 'CHM':"Chemistry", 'BIO':"Biology"}
keyValue(aDict)
will display
MTH:Mathematics
CHM:Chemistry
BIO:Biology
2. Define a function, name it cumValues, that will accept a dictionary
object that has its values as list objects and does the following:
1. Computes the sum of items in each list object.
2. Adds each computed sum to a list, name it cumList
3. Returns cumList.
For example
cumValues({0:[1,0,1], 2:[0,3,4,5], 3:[-1,2,-4]})
will display
[2, 12, -3]
obtained form 2= 1+0+1, 12 = 0+3+4+5, -3=-1 +2 + (-4)
3. Answer the following questions
a) Using the get method, write a print statement that will display the values having
keys 4,9 and 6 of A so that the display is
45?23?89
A = {0:89, 4:45, 3:67, 6:89, 9:23}
b) What set method is used to add element to a set object.
4. Define a function, name it aMod2 that will accept a set object, computes and returns
another set object containing remainders of all elements in the set when divided by 2.
For example,
aMod2({0,1,2,3,4,5,6})
will return
{0,1,0,1,0,1,0}
5. Answer the following questions
a) Let
a be a set object containing 3,-1,4,10,34,-15,8,9 and
b be a set object containing 3,5,7,10,8,-18.
What is displayed when the statement below is executed?
print(a & b)
b) Let
a be a set object containing 3,-1,4,10,34,-15,8 and
b be a set object containing 3,5,7,10,8,-18.
What is displayed when the statement below is executed?
print(a – b)
c) Let
a = {3,-1,4,10,-15,8,9}
b = {3,5,7,10,8,-18}
What is displayed when the statement below is executed?
print(a ^ b)
6. Define a function, name it dictToSet, that will accept a dictionary object as an argument
and does the following:
1. creates two sets (name them, keys and values), one containing the keys and the other
containing the values.
2. returns the two sets, keys and values
For example,
dictToSet({0:45, 1:67, 2:89})
will return
{0,1,2}
{45,67,89}
7. Answer the following questions.
a) Write a statement that will define a set object (name it aSet) directly using the list
[3,4,6,8].
b) Write a statement that will remove all items in the dictionary object:
aDict = {0:"FSU", 1:"UNCP", 2:"NCA&T"}
c) Let
a be a set object containing 3,-1,4,10,34,-15,8,9 and
b be a set object containing 3,5,7,10,8,-18.
What is displayed when the statement below is executed? (Avoid use of spaces)
print(a & b <= b, a & b >= b, sep="?")
d) Write a statement the will define a set object (name it aSet) directly using a tuple
(0,4,9,4,8,9,10).
e) Suppose we define a set object (named aSet) directly using the tuple (0,4,9,4,9,10).
What are the elements of aSet?
8. Define a function, name it factorial, that will accept an integer (n) as an argument and
does the following:
1. computes factorials of integers between 1 and n, inclusive of 1 and n; saves the factorials
in a set, name it factSet. Note that factorial of 1 is 1, factorial of 2 is 1*2, factorial of 3 is 1*2*3,
factorial of 4 is 1*2*3*4, factorial of n is 1*2*3*4*...*(n-1)*n.
2. returns factSet

Module 7: File Processing and pickling


1. Answer the following questions
a) What is an output file?
b) What is an input file?
c) What three steps must be taken by a program when it uses a file?
d) In general, what are the two types of files? What is the difference between these
two types of files?
e) What are the two types of file access? What is the difference between these
two?
f) When writing a program that performs an operation on a file, what two file-
associated names do you have to work with in your code?
g) If a file already exists what happens to it if you try to open it as an output file
(using the 'w' mode)?
h) What is the purpose of opening a file?
i) What is the purpose of closing a file?
j) What is a file’s read position? Initially, where is the read position when an input
file is opened?
k) In what mode do you open a file if you want to write data to it, but you do not
want to erase the file’s existing contents? When you write data to such a file, to
what part of the file is the data written?
2. Answer the following questions
a) What is a record? What is a field?
b) Describe the way that you use a temporary file in a program that modifies a
record in a sequential access file.
c) Describe the way that you use a temporary file in a program that deletes a
record from a sequential file.
17. Write a program that opens an output file with the filename my_name.txt, writes
your name to the file, and then closes the file.
1. Write a program that takes an input from the user and asks to enter filename. It then
opens the file for reading it. If the file is not found, catch the exception and give a
suitable message.
2. Write a program to open a file and ask the user to input the filename. If the file exists,
display the content of the file, else create a file and write the line “File is opened in
write mode”.
3. Write code that does the following: opens the number_list.txt file that was created by
the code you wrote in question 5, reads all of the numbers from the file and displays
them, and then closes the file.
4. Modify the code that you wrote in question 6 so it adds all of the numbers read from the
file and displays their total.
5. Assume that a file containing a series of integers is named numbers.txt and exists on
the computer’s disk. Write a program that displays all of the numbers in the file.
6. Write a program that asks the user for the name of a file. The program should display
only the first five lines of the file’s contents. If the file contains less than five lines, it
should display the file’s entire contents.

Module 8: Exceptions and pickling

1. Briefly describe what an exception is.


2. If an exception is raised and the program does not handle it with a try/except
statement, what happens?
3. What type of exception does a program raise when it tries to open a nonexistent file?
4. What type of exception does a program raise when it uses the float function to convert
a non-numeric string to a number?
5. When you open a file for the purpose of saving a pickled object to it, what file access
mode do you use?
6. When you open a file for the purpose of retrieving a pickled object from it, what file
access mode do you use?
7. What module do you import if you want to pickle objects?
8. What function do you call to pickle an object?
9. What function do you call to retrieve and unpickle an object?

Module 9: Classes and Inheritance


1. Suppose my_car is the name of a variable that references an object, and go is the
name of a method. Write a statement that uses the my_car variable to call the go
method. (You do not have to pass any arguments to the go method.)
2. Write a class definition named Book. The Book class should have data attributes for a
book’s title, the author’s name, and the publisher’s name. The class should also have
the following:
a) An _ _init_ _ method for the class. The method should accept an argument for each
of the data attributes.
b) Accessor and mutator methods for each data attribute.
c) An _ _str_ _ method that returns a string indicating the state of the object.
3. Look at the following description of a problem domain:
The bank offers the following types of accounts to its customers: savings accounts,
checking accounts, and money market accounts. Customers are allowed to deposit
money into an account (thereby increasing its balance), withdraw money from an
account (thereby decreasing its balance), and earn interest on the account. Each
account has an interest rate.
Assume that you are writing a program that will calculate the amount of interest earned
for a bank account.
a) Identify the potential classes in this problem domain.
b) Refine the list to include only the necessary class or classes for this problem.
c) Identify the responsibilities of the class or classes.
4. Design a class that holds the following personal data: name, address, age, and phone
num- ber. Write appropriate accessor and mutator methods. Also, write a program that
creates three instances of the class. One instance should hold your information, and
the other two should hold your friends’ or family members’ information.
5. Look at the following class definitions:
class Vegetable:
def _ _init_ _(self, vegtype):
self._ _vegtype = vegtype
def message(self):
print("I'm a vegetable.")
class Potato(Vegetable):
def _ _init_ _(self):
Vegetable._ _init_ _(self, 'potato')
def message(self):
print("I'm a potato.")
Given these class definitions, what will the following statements display?
v = Vegetable('veggie')
p = Potato()
v.message()
p.message()
6. Answer the following questions
a) We discussed superclasses and subclasses. Which is the general class, and which
is the specialized class?
b) What does it mean to say there is an “is a” relationship between two objects?
c) What does a subclass inherit from its superclass?
d) Look at the following code, which is the first line of a class definition. What is the
name of the superclass? What is the name of the subclass?
class Canary(Bird):
7. Look at the following class definition:
class Beverage:
def _ _init_ _(self, bev_name):
self._ _bev_name = bev_name
Write the code for a class named Cola that is a subclass of the Beverage class. The
Cola class’s __init__ method should call the Beverage class’s __init__ method,
passing ‘cola’ as an argument.

Module 10: Iterators, recursions, and data structures


1. It is said that a recursive algorithm has more overhead than an iterative algorithm.
What does this mean
2. What is a base case?
3. What is a recursive case?
4. What causes a recursive algorithm to stop calling itself?
5. What is direct recursion? What is indirect recursion?
6. Design a recursive function that accepts an integer argument, n, and prints the
numbers 1 up through n.
7. Design a recursive function that accepts two arguments into the parameters x and y.
The function should return the value of x times y. Remember, multiplication can be
performed as repeated addition as follows:
73454141414141414 (To keep the function simple, assume that x and y will always
hold positive nonzero integers.)
8. Write a recursive function that accepts an integer argument, n. The function should
display n lines of asterisks on the screen, with the first line showing 1 asterisk, the
second line showing 2 asterisks, up to the nth line which shows n asterisks.
9. Design a function that accepts a list as an argument and returns the largest value in
the list. The function should use recursion to find the largest item.
10. Design a function that accepts a list of numbers as an argument. The function should
recursively calculate the sum of all the numbers in the list and return that value.
11. Design a function that accepts an integer argument and returns the sum of all the
integers from 1 up to the number passed as an argument. For example, if 50 is passed
as an argu- ment, the function will return the sum of 1, 2, 3, 4, . . . 50. Use recursion to
calculate the sum.
12. Design a function that uses recursion to raise a number to a power. The function
should accept two arguments: the number to be raised and the exponent. Assume that
the exponent is a nonnegative integer.
13. Answer the following questions:
14. Write a statement that will define an iterator (name it iterObj) from the string
“UNIABUJA”.
15. Write a statement that will define an iterator (name it iterObj) from the dictionary object
empDict. Write a program that will display the items in the iterator using a for loop or
while loop.
16. Define a function that would take an integer n as an argument and return a list of first n
factorials
17. Define a function that would take an integer n as an argument and return a list of the
first n Fibonacci numbers.
18. Write a class that will define an iterable/iterator object that will iterate through a
triangular sequence given by
f(1) = 1, f(n) = f(n-1) + n, for n = 2,3,4,…,
19. Write a class that will define an iterable/iterator object that will
calculate the sum of first the n integers using the formula
f(1) = 1, f(n) = f(n-1) + n*n.
For examples, f(2) = f(1) + 2^2 = 1+ 2^2,
f(3) = f(2) + 3^2 =1+ 2^2 + 3^2
f(4) = f(3) + 4^2 = 1+2^2 +3^2 +4^
20. Write a class that will define an iterable/iterator object that will
iterate through a tetrahedral sequence given by:
f(1) = 1, f(n) = 1+2^2 + 3^2 + … + n^2 - f(n-1), n=2,3,…,n
21. Write a generator function what will generate the first n triangular numbers.
22. Write a generator function that will generate the first n tetrahedral numbers.
23. Read the sections on generators, itertools and data structures.

Вам также может понравиться