---
tags: Python
---
# Python Self-Check 13
CS 1358 Introduction to Programming in Python
Fall Semester 2022
Prof. Pai H. Chou
Self-Check 1
Due Date: --
Answer the following questions to check your understanding of your material. Expect the
same kind of questions to show up on your tests. For this course, we use vi and vim
interchangeably.
## 1. Definitions and Short Answers
1. If a function is built-in, do you have to import it first, or can you just call it without importing?
```
call it without importing
```
2. If a function is in the standard library, do you have to import it first, or can you just call it without importing?
```
have to import
```
3. Which of the following are valid calls to the eval() function, and what are their return values?
```
a. eval(2 + 3)
//invalid
b. eval('2 + 3')
//valid '5'
c. eval(len("hello"))
//invalid
d. eval('len("hello")')
//valid 5
e. eval('hello world')
//invalid
f. eval('"hello world"')
//valid 'hello world'
```
4. Which of the following are valid calls to the eval() function, and what are their return values?
```
a. a = 5
eval('a + 3')
//valid 8
b. a = 5
eval('a + 3', {'a': 7})
//valid 10
c. a = 5
eval('a + 3', {})
//invalid
```
5. Is the following a valid call to exec() function and what is the results?
```
exec('def hello(s):\n print(f"hello {s}")\n')
hello('Mike')
```
```
valid hello Mike
```
6. When your Python program first starts,
```
>>> x = 3
>>> dir()
```
['\_\_annotations\_\_', '\_\_builtins\_\_', '\_\_doc\_\_', '\_\_loader\_\_', '\_\_name\_\_', '\_\_package\_\_', '\_\_spec\_\_', 'x']
which shows that the name 'x' has been added to the global name space. However,
```
>>> max(x, 5)
5
>>>
```
However, the name max is not in the global name space as shown in dir(). Which of the following is a correct explanation of how Python knows max is the name of a function that you can call?
```
a. max is a keyword in Python
//no, max is a bulit-in function
b. max is defined in the global name space but is just hidden
//no, max is in __builtins__ name space
c. max is defined in the __builtins__ name space, which is searched after the global name space
//Yes
d. max is defined in a package in the standard library and must be imported before it can be called.
//no, max don't have to import
```
7. If you do the following
```
>>> max, min = min, max
>>> L = [1, 7, 3, 4, 6]
>>> max(L), min(L)
```
What do you get?
```
1, 7
```
8. If you do the following
```
>>> L = [1, 7, 3, 4, 6]
>>> len = 'a'
>>> len(L)
```
```
a. What do you get by len(L)? or do you get an error?
//get an error
b. if the built-in len() function has been redefined to 'a', can you still get the original definition back? If so, how? can the original len() be called?
//Yes, len = __builtins__.len
```
9. The datetime module contains the following classes
datetime
date
time
timedelta
```
a. Do you need to do an import statement before you can use any of the four classes above?
//need
b. If you see the statement
import datetime
Does datetime refer to the module or class?
//module
c. if you see the statement
from datetime import *
What is the meaning of * ?
After the import statement, does datetime refer to the module or class?
//imports all the functions and classes into your own namespace
class
d. If you want to import the "datetime class within the datetime module" without importing the other classes (date, time, deltatime), what import statement should you use?
//from datetime import datetime
e. The constructor for the datetime class takes three required parameters: year, day, and hour.
What is the Python code for instantiating an object of datetime class with year=2019, month=12, day=10, and assign it to the identifier x?
Include also the statement for import.
//
from datetime import *
x = datetime(2019, 12, 10)
f. The documentation says datetime.now is a class method that takes no parameter.
How do you call it on the datetime class?
//x = datetime.now()
g. If x is an instance of datetime from the previous question, are you allowed to call x.now()?
//Yes
```
10. Operator overloading is supported on datetime and deltatime classes. Indicate the combinations supported by filling in the result type; or indicate if the combination is not supported.
|class|operator|class|result class|
|-|-|-|-|
|timedelta|+|timedelta|timedelta|
|timedelta|-|timedelta|timedelta|
|timedelta|\*|int|timedelta|
|datetime|+|datetime|not suppout|
|datetime|-|datetime|timedelta|
|datetime|+|timedelta|datetime|
|datetime|-|timedelta|datetime|
11. In the calendar module,
```
a. what is the difference between the TextCalendar and the HTMLCalendar class?
//HTMLCalendar express by html type
b. in the TextCalendar class, what is the difference between the prmonth() and formatmonth() methods?
//
prmonth print the Calendar
formatmonth() return a string literal
```
12. In the namedtuple class in the collections module
```
>>> from collections import namedtuple
>>> Point = namedtuple('Point', ['x', 'y'])
```
```
a. What is the type of Point? Is it an instance of namedtuple class, or is a class?
//namedtuple, class
To continue with the example above, the next line is
>>> p = Point(2, 3)
b. What kind of object is p?
Is it an instance of namedtuple class? an instance of Point class? an instance of tuple?
Is it mutable?
//instance of Point class, immutable
```
13. In the Counter class in the collections module,
```
>>> from collections import Counter
>>> c = Counter(['dog','cat','dog','cow','dog','cat'])
>>> c
```
```
a. What do you expect to see?
//Counter({'dog':2, 'cat':2, 'cow':1})
b. How do you find the value with the most occurrences?
//c.most_common(1)
c. How do you find the value with the least occurrences?
//c.most_common()[-1]
```
14. Consider the overloaded operators defined by Counter class in the collections module, what is the value you expect from the expressions?
|a|op|b|value|
|-|-|-|-|
|Counter('abacus')|+|Counter('aba')|Counter({'a': 4, 'b': 2, 'c': 1, 'u': 1, 's': 1})|
|Counter('abacus')|-|Counter('ada')|Counter({'b': 1, 'c': 1, 'u': 1, 's': 1})|
|Counter('ada')|-|Counter('abacus')|Counter({'d':1})|
|Counter('dust')|&|Counter('rust')|Counter({'u':1, 's':1, 't':1})|
|Counter('dust')|\||Counter('rust')|Counter({'d':1, 'u':1, 's':1, 't':1, 'r':1})|
15. In the collections.abc module for abstract base classes, some such base classes include Container, Hashable, Iterable, Iterator, …, Sequence, MutableSequence, etc.
```
a. Can you instantiate an object from one of these abc's? for example,
from collections import abc
x = abc.Iterable()?
//no
b. Can you test if an object is an instance of one of these abc's? for example,
x = 'hello'
if isinstance(x, abc.Iterable):
print('str is iterable')
else:
print('str is not iterable')
//yes
```
16. In the types module, a number of classes are also defined, including FunctionType, LambdaType, GeneratorType, MethodType, BuiltinFunctionType, ModuleType, etc.
```
a. Are these classes in types module also abstract base classes like those defined in collections.abc module?
//no
b. Are you expected to use these classes for instantiation by calling their constructors? If not, why not? For example, is the following the expected usage
>>> import types
>>> f = types.FunctionType()
//no,
```
17. What is the purpose of an enumerated type as in the Enum class in the enum module? Consider the code
```
from enum import Enum
Animal = Enum('Animal', ['ANT', 'BEE', 'CAT', 'DOG'])
```
```
a. What is the value of Animal(1)? Animal(3)?
//<Animal.ANT: 1>, <Animal.CAT: 3>
b. What is the value of Animal.BEE?
//<Animal.BEE: 2>
c. What is the value of str(Animal['CAT'])
//'Animal.CAT'
d. What is the value of Animal.DOG > Animal.ANT?
//not supported
```
18. What is the difference between the built-in float type and Decimal class in the decimal module?
```
a. What is the value of
1.1 + 2.2 == 3.3?
//false
b. Assuming you have from decimal import Decimal, what is the value of
Decimal('1.1') + Decimal('2.2') == Decimal('3.3')
//True
```
19. Assume you have from fractions import Fraction, what is the value of
Fraction(16, -10)?
```
Fraction(-8, 5)
```
20. In the random module
```
a. What are the possible values of
random.randrange(10)?
//0~9
b. What are possible values of
random.choice(['win', 'lose', 'draw'])?
//'win', 'lose', 'draw'
c. What is the purpose of a random seed? If you have
import random
r = random.Random()
s = random.Random()
r.seed(100)
x = r.randint(1, 100)
s.seed(100)
y = s.randint(1, 100)
is x == y?
//same seed => same sequence, yes
```
21. In the itertools module,
```
a. there is a class named count, and you can use it like
>>> c = itertools.count(10)
>>> next(c)
10
>>> next(c)
11
>>> next(c)
12
Why is this class useful, and why can't it be done with the built-in range()?
//count can create a inf list, but range() cat't to inf
b. There is another class named cycle, and you can use it like
>>> cy = itertools.cycle(['a', 'b', 'c'])
>>> next(cy)
'a'
>>> next(cy)
'b'
>>> next(cy)
'c'
>>> next(cy)
'a'
>>> next(cy)
'b'
Why is this class useful, and why can't it be done with the built-in range()?
//cycle can create a inf cycle, but range() cat't to inf
reduce the memory use
c. There is another class named zip_longest. Example use is
>>> list(itertools.zip_longest('ABCD', 'WXY', '12', fillvalue='-'))
[('A', 'W', '1'), ('B', 'X', '2'), ('C', 'Y', '-'), ('D', '-', '-')]
Explain how this can be useful for adding two polynomial functions.
//when adding two polynomial functions, it will have many term and lenght of them can be different, if use zip_longest we can make a tuple without if-else
```