---
# System prepended metadata

title: CS 1358 Introduction to Programming in Python SC13
tags: [pythonSC]

---

# CS 1358 Introduction to Programming in Python SC13

###### tags: `pythonSC`

Answer the following questions to check your understanding of your material.  Expect the same kind of questions to show up on your tests.
This self check is for Python Standard Library part 1.

# 1. Definitions and Short Answers - functions

1. If a function is built-in, do you have to import it first, or can you just call it without importing?
    > You can 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?
    > You have to import it first before you call it 

3. Which of the following are valid calls to the eval() function, and what are their return values?
    - [ ] eval(2 + 3)
    - [x] eval('2 + 3')
    - [ ] eval(len("hello"))
    - [x] eval('len("hello")')
    - [ ] eval('hello world')
    - [x] eval('"hello world"')

4. Which of the following are valid calls to the eval() function, and what are their return values?
    ```shell
    > a = 5
    > eval('a + 3')
    8
    
    > a = 5
    > eval('a + 3', {'a': 7})
    10
    
    > a = 5
    > eval('a + 3', {})
    NameError: name 'a' is not defined
    ```
5. Is the  following a valid call to exec() function and what is the results?
    ```shell
    > exec('def hello(s):\n    print(f"hello {s}")\n')
    > hello('Mike')
    hello Mike
    ```
6. When your Python program first starts,
    ```shell
    > 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,
    ```shell
    > 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?
    - [ ] max is a keyword in Python
    - [ ] max is defined in the global name space but is just hidden
    - [x] max is defined in the \_\_builtins__ name space, which is searched after the global name space
    - [ ] max is defined in a package in the standard library and must be imported before it can be called.

7. If you do the following
    ```shell
    > max, min = min, max
    > L = [1, 7, 3, 4, 6]
    > max(L), min(L)
    ```
    What do you get?
    ```python
    (1, 7)
    ```

8. If you do the following
    ```shell
    > L = [1, 7, 3, 4, 6]
    > len = 'a'
    > len(L)
    ```
    a. What do you get by len(L)?  or do you get an error?
    > TypeError: 'str' object is not callable
    
    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, it still can get the original definition back.
    ```python
    len = __builtins__.len  #restore the built-in 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? 
    > You need to do an import statement before you can use four classes above.
     
    b. If you see the statement
    ```python
    import datetime 
    ```
    Does datetime refer to the module or class?
    > Module

    c. if you see the statement
    ```python
    from datetime import *
    ```
    What is the meaning of * ?
    > import all of the classes in datatime
    
    After the import statement, does datetime refer to the module or class?
    > refer to 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?
    ```python
    from datatime 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.
    ```python
    from datetime import datetime
    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?  If x is an instance of datetime from the previous question, are you allowed to call x.now()?
    ```python
    from datetime import datetime
    datetime.now()
    x.now()#allow
    ```

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     | op  | class     | result class  |
    | --------- | --- | --------- | ------------- |
    | timedelta | +   | timedelta | timedelta     |
    | timedelta | -   | timedelta | timedelta     |
    | timedelta | *   | int       | timedelta     |
    | datetime  | +   | datetime  | Not supported |
    | 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?
    > TextCalendar can be used to generate plain text calendars.
    > HTMLCalendar can be used to generate HTML calendars.

    b. in the TextCalendar class, what is the difference between the prmonth() and formatmonth() methods?
    > prmonth() Print a month’s calendar as returned by formatmonth().
    > formatmonth() Return a month’s calendar in a multi-line string

12. In the namedtuple class in the collections module,
    ```python
    from collections import namedtuple
    Point = namedtuple('Point', ['x', 'y'])
    ```
    a. hat is the type of Point?  Is it an instance of namedtuple class, or is a class?
    > Class
    
    b. To continue with the example above, the next line is 
    ```python
    p = Point(2, 3)
    ```
    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?
    > It is an instance of Point and tuple. It is immutable.

13. In the Counter class in the collections module,
    ```python
    from collections import Counter
    c = Counter(['dog','cat','dog','cow','dog','cat'])
    c
    ```
    a. What do you expect to see?
    ```python
    Counter({'dog': 3, 'cat': 2, 'cow': 1})
    ```
    b. How do you find the value with the most occurrences?
    ```python
    c.most_common(1)
    ```
    c. How do you find the value with the least occurrences?
    ```python
    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,
    ```python
    from collections import abc
    x = abc.Iterable()
    ```
    
    ```python
    TypeError: Can't instantiate abstract class Iterable with abstract methods
    __iter__
    ```
    
    b. Can you test if an object is an instance of one of these abc's?  for example,
    ```python
    x = 'hello'
    if isinstance(x, abc.Iterable):
        print('str is iterable')
    else:
        print('str is not iterable')
    ```
    ```shell
    str is iterable
    ```

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? 
    > False

    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
    ```python
    import types
    f = types.FunctionType()
    ```
    ```python
    TypeError: function() missing required argument 'code' (pos 1)
    ```

17. What is the purpose of an enumerated type as in the Enum class in the enum module?  Consider the code
    ```python=
    from enum import Enum
    Animal = Enum('Animal', ['ANT', 'BEE', 'CAT', 'DOG'])
    ```
    a. What is the value of Animal(1)?  Animal(3)?
    ```python
    <Animal.ANT: 1>
    <Animal.CAT: 3>
    ```
    b. What is the value of Animal.BEE?
    ```python
    <Animal.BEE: 2>
    ```
    c. What is the value of str(Animal['CAT'])
    ```python
    'Animal.CAT'
    ```
    d. What is the value of Animal.DOG > Animal.ANT?
    ```python
    TypeError: '>' not supported between instances of 'Animal' and 'Animal'
    ```

18. What is the difference between the built-in float type and Decimal class in the decimal module?
    a. What is the value of 
    ```python
    1.1 + 2.2 == 3.3
    ```
    ```python
    False
    ```
    
    b. Assuming you have from decimal import Decimal, what is the value of
    ```python
    Decimal('1.1') + Decimal('2.2') == Decimal('3.3')
    ```
    ```python
    True
    ```
19. Assume you have from fractions import Fraction, what is the value of
    ```python
    Fraction(16, -10)
    ```
    ```python
    Fraction(-8, 5)
    ```
20. In the random module,
    a. What are the possible values of 
    ```python
    random.randrange(10)
    ```
    > [1, 10)

    b. What are possible values of 
    ```python
    random.choice(['win', 'lose', 'draw'])
    ```
    > 'win', 'lose', 'draw'
    
    c. What is the purpose of a random seed?  If you have
    ```python
    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?
    > Yes

21. In the itertools module, 
    a. there is a class named count, and you can use it like
    ```python
    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()?
    > range() 是iterable的data structure, 必須有開始與結束
    > count 是iterator, 可以無限地產生下去

    b. There is another class named cycle, and you can use it like
    ```python
    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()?
    > same as the last question


    c. There is another class named zip_longest.  Example use is
    ```python
    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.
    > It will automatically fill 0 to the shorter polynomial's coefficient.




