# CS 1358 Introduction to Programming in Python SC14
###### tags: `pythonSC`
# 1. Definitions and Short Answers - functions
1. Assuming you have
```python
import string
```
What is the value of
```python
string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
string.whitespace
' \t\n\r\x0b\x0c'
```
2. Why is it more preferable to check if a character c is a white space by
```python
if c in string.whitespace:
#instead of
if c in {' ', '\n', '\t'}:
```
> \r\x0b\x0c are also represent whitespace
3. Assuming you have
```python
from string import Template
s = Template('$x and $y')
```
What is the value of the following expressions?
```python
s.substitute(x='hello', y='world')
'hello and world'
s.substitute(x=0x20, y=20)
'32 and 20'
s.substitute(x=2., y=.2)
'2.0 and 0.2'
```
4. In vim,
a. what do you type to search for the string "or"?
> /or
b. what do you type to find string "or" at the beginning of the line?
> /^or
c. what do you type to find string "or" at the end of the line?
> /or$
d. what do you type to find string "or" as the only string on the entire line?
> /^or$
e. what do you type to find words that end with "or"?
> /or\\>
f. what do you type to find words that begin with "or"?
> /\\<or
g. what do you type to find strings "or" that are not part of another word?
> /\\<or\\>
5. In vim, what is the meaning of
:%s
> % 是全域
> s 是置換的指令
:%s/abc/xyz/
> 把每一行中的第一個abc置換成xyz
:%s/abc/xyz/g
> 把每一行中所有的abc置換成xyz
6. In python, you can import a module named re. What does it stand for?
> regular expression
7. Given the following functions in the re module
```python
re.search(pattern, source) #returns matched object for first found
re.findall(pattern, source) #returns list of found strings
```
Assume
```python
import re
```
What are the values of the following expressions?
```python
re.findall('Gary', 'Mary had a little lamb')
#[]
re.findall('Mary', 'Mary had a little lamb')
#['Mary']
re.findall('Mary', 'Mary and Gary had a little lamb')
#['Mary']
re.findall('lamb', 'Mary had a little lamb little lamb')
#['lamb', 'lamb']
re.findall('a', 'Mary had a little lamb')
#['a', 'a', 'a', 'a']
```
8. Assume the following
```python
import re
s = re.findall(pat, 'Mary, Gary, and Cary had a scary lamb')
```
What is the value of pattern `pat` that will yield the following values for s?
```python
['Mary', 'Gary', 'Cary']
#pat = r'[A-Z]ary'
ans = ['Mary', 'Gary']
#pat = r'[G-Z]ary'
['Mary', 'Gary', 'Cary', 'cary']
#pat = r'.ary'
['Cary', 'cary']
#pat = r'[C, c]ary'
['Mary', 'Gary', 'Cary', 'scary']
#pat = r'[a-zA-Z]+?ary'
```
9. Assume
```python
import re
```
What are the values of the following expressions?
```python
re.findall('[a-z]*are', 'We scare because we care')
#['scare', 'care']
re.findall('[a-z]+are', 'We scare because we care')
#['scare', 'care']
re.findall('[a-z]*are', 'We are here to scare and care')
#['are', 'scare', 'care']
re.findall('[a-z]+are', 'We scare because we care')
#['scare', 'care']
re.findall('[a-z]*are', 'He cares that we are scared')
#['care', 'are', scare']
re.findall('[a-z]+are', 'He cares that we are scared')
#['care', 'scare']
re.findall('[a-z]*are[sd]', 'He cares that we are scared')
#['cares', 'scared']
re.findall('[a-z]*are[sd]?', 'He cares that we are scared')
#['cares', 'are', 'scared']
re.findall('[a-z]+are[sd]', 'He cares that we are scared')
#['cares', 'scared']
re.findall('[a-z]+are[sd]?', 'He cares that we are scared')
#['cares','scared']
```
10. Assume
```python
import re
```
What are the values of the following expressions? Explain the difference between c and d.
```python
re.findall('[a-z]*','He cares that we are scared')
#['', 'e', '', 'cares', '', 'that', '', 'we', '', 'are', '', 'scared', '']
re.findall(r'\w*','He cares that we are scared')
#['He', '', 'cares', '', 'that', '', 'we', '', 'are', '', 'scared', '']
re.findall(r'\bare\b','He cares that we are scared')
#['are']
re.findall('\bare\b','He cares that we are scared')
#[]
#Because for the string in python '\b' didn't mean the word boundary
```
11. Assume
```python
import re
```
What are the values of the following expressions?
```python
re.findall('Mary',"Mary and Mary's lamb like Mary")
#['Mary', 'Mary', 'Mary']
re.findall('^Mary',"Mary and Mary's lamb like Mary")
#['Mary']
re.findall('Mary$',"Mary and Mary's lamb like Mary")
#['Mary']
re.search('^Mary',"Mary and Mary's lamb like Mary")
#<re.Match object; span=(0, 4), match='Mary'>
re.search('Mary$',"Mary and Mary's lamb like Mary")
#<re.Match object; span=(26, 30), match='Mary'>
re.findall('Mary\S+',"Mary and Mary's lamb like Mary")
#["Mary's"]
```
12. Fill in the following blanks
|meaning|backslash notation|equivalent ASCII set|
|-------|------------------|--------------------|
|word boundary|\b|n/a|
|not beginning or end of word|\B|n/a|
|decimal digit|\d|[0-9]|
|not decimal digit|\D|[^0-9]|
|white space|\s|[ \t\n\r\f\v]|
|not whitespace|\S|[^ \t\n\r\f\v]|
|alphanumeric|\w|[a-zA-Z0-9_]|
|not alphanumeric|\W|[^a-zA-Z0-9_]|
|beginning of string|\A|n/a|
|end of string|\Z|n/a|
13. Assume
```python
import re
```
What are the values of the following expressions? Explain the difference between '*' and '*?' as regular expressions
```python
re.findall(r'\b.are', 'He cares that we are scared')
#['care', ' are']
re.findall(r'\b.*are', 'He cares that we are scared')
#['He cares that we are scare']
re.findall(r'\b.*?are', 'He cares that we are scared')
#['He care', ' that we are', ' scare']
```
14. What are the values of the following expressions? assume
```python
import re
```
```python
'To be, or not to be--that is the question!'.split()
#['To', 'be,', 'or', 'not', 'to', 'be--that', 'is', 'the', 'question!']
'To be, or not to be--that is the question!'.split('-')
#['To be, or not to be', '', 'that is the question!']
'To be, or not to be--that is the question!'.split('--')
#['To be, or not to be', 'that is the question!']
re.split(' ', 'To be or not--that is the question!')
#['To', 'be', 'or', 'not--that', 'is', 'the', 'question!']
re.split(r'\W', 'To be or not--that is the question!')
#['To', 'be', 'or', 'not', '', 'that', 'is', 'the', 'question', '']
re.split(r'\W+', 'To be or not--that is the question!')
#['To', 'be', 'or', 'not', 'that', 'is', 'the', 'question', '']
re.split(r'-+', 'To be or not--that is the question!')
#['To be or not', 'that is the question!']
re.split(r'\s*/+\s*','To/be/// or //not/that//question')
#['To', 'be', 'or', 'not', 'that', 'question']
```
15.
|reguar expresison|explanation|
|-----------------|-----------|
|[A-Z][a-z]{2}|one capital letter followed by two lower-case letters|
|0?[1-9]\|[12]\d\|3[01]|1-9,10-29, 0-31|
|\d\d:\d\d:\d\d|2-digits hh:mm:ss|
|\d{1,4}|1-4 digits|
16. Assume
```python
import re
```
Does the following result in match?
```python
m = re.fullmatch(r'^.*(\d\d):(\d\d):(\d\d).*(\d{4})$', 'Thu Jul 18 14:33:28 PDT 2019')
```
If so, what are the values of
```python
m.group(1) #'14'
m.group(2) #'33'
m.group(3) #'28'
m.group(4) #'2019'
```
17. Assume
```python
import re
```
What is the value of
```python
re.sub('-', '/', 'today 5-20-2019, tomorrow 5-21-2019')
#'today 5/20/2019, tomorrow 5/21/2019'
re.sub('.', '/', 'today 5.20.2019, tomorrow 5-21-2019')
#'///////////////////////////////////'
re.sub(r'\.', '/', 'today 5.20.2019, tomorrow 5-21-2019')
#'today 5/20/2019, tomorrow 5-21-2019'
```
18. Assume
```python
import re
```
What is the value of
```python
re.sub(r'(\d+)/(\d+)/(\d+)', r'\3/\2/\1', 'today 5/20/2019, tomorrow 5/21/2019')
#'today 2019/20/5, tomorrow 2019/21/5'
```
19. 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
#false
```
b. Assuming you have from decimal import Decimal, what is the value of
```python
Decimal('1.1') + Decimal('2.2') == Decimal('3.3')
#true
```
20. Assume you have from fractions import Fraction, what is the value of
```python
Fraction(16, -10)
```
```python
Fraction(-8, 5)
```
21. Consider the first Tkinter program
```python=
import tkinter
root = tkinter.Tk()
f = tkinter.Frame(root)
f.pack()
l = tkinter.Label(f, text='Hello world')
l.pack()
b = tkinter.Button(f, text='Quit', command=root.destroy)
b.pack()
tkinter.mainloop()
```
a. What kind of user interface object is tkinter.Label on line 5?
> widget
b. What kind of object is root.destroy on line 7?
> a method to Destroy this and all descendants widgets
c. Does line 9 run forever? Or in what condition does line 9 finish?
> when the button is beem pressed
22. The second version of the Tkinter program is as follows, where the difference is highlighted in pink:
```python=
import tkinter
root = tkinter.Tk()
f = tkinter.Frame(root, width=200, height=150)
f.pack_propagate(0)
f.pack()
l = tkinter.Label(f, text='Hello world')
l.pack(side=tkinter.TOP)
b = tkinter.Button(f, text='Quit', command=root.destroy)
b.pack(side=tkinter.BOTTOM)
tkinter.mainloop()
```
a. What is the purpose of line 4?
> Don't shrink
b. What is the purpose of line 7 and line 9?
> Put the label on the top of the frame and put the button to the bottom of the frame.
23. In the Calendar v2 example, the first page of the source code looks like this:
```python=
import tkinter
root = tkinter.Tk()
f = tkinter.Frame(root, width=250, height=200)
f.pack_propagate(0)
f.pack()
import datetime
today = datetime.date.today()
current_year, current_month = today.year, today.month
import calendar
cal = calendar.TextCalendar(6)
calstr = tkinter.StringVar()
calstr.set(cal.formatmonth(current_year, current_month))
l = tkinter.Label(f, textvariable=calstr,justify=tkinter.LEFT, font=('Courier', 12))
l.pack(side=tkinter.TOP)
b = tkinter.Button(f, text='Quit',command=root.destroy)
b.pack(side=tkinter.BOTTOM)
```
a. On line 13, why does it pass parameter textvariable=calstr (created and set on lines 11-12) instead of parameter text= some string value as before?
> the text may change during the program executing.
24. Continuing with the same example, consider part of the second page of the source code, (abridged)
```python=18
def prev_month():
global current_year, current_month
current_month -= 1
if current_month == 0:
current_month = 12
current_year -= 1
calstr.set(cal.formatmonth(current_year,current_month))
pm = tkinter.Button(f, text='Prev', command=prev_month)
pm.pack(side=tkinter.LEFT)
tkinter.mainloop()
```
a. How is the prev_month function (line 18) called? Can any parameters be passed to it?
> Called by tkinter.Button, No
b. Why is line 19 necessary?
> else it will create a same name variable in it's namespace
c. What is the effect of line 24 on the user interface?
> To update the calstr.
25. Continuing with the same example, one improvement is to replace the prev_month and next_month functions with the following:
```python=32
def shift_month(add_or_sub):
global current_year, current_month
current_month = add_or_sub(current_month, 1)
if current_month == 0:
current_month = 12
current_year -= 1
elif current_month == 13:
current_month = 1
current_year += 1
calstr.set(cal.formatmonth(current_year,
current_month))
import operator
next_month = lambda : shift_month(operator.add)
prev_month = lambda : shift_month(operator.sub)
```
a. Why is it better to combine the functionality of next_month and prev_month functions into one function?
> Decrease the redundent code.
b. Can this new function shift_month be passed as callback to (line 52 in the previous problem), i.e.,
```python
pm = tkinter.Button(f, text='Prev',command=shift_month)
```
Why or why not?
> No, it needs to pass a parameter.
c. Can line 52 be written as
```python
pm = tkinter.Button(f, text='Prev',command=shift_month(operator.sub))
```
instead? Why or why not?
> No! 'lambda' is necessary.
d. What is the difference between part c and the following:
```python
pm = tkinter.Button(f, text='Prev',command=lambda:shift_month(operator.sub))
```
which one is correct?
> d. is correct.
26. In calendar v3, the grid layout manager is used instead of pack. What is the difference?
> pack - simplest, but may not be aligned
> grid - expandable table, good for most purpose
27. What is the meaning of
```python
f.grid(row=0, column=0) # f is an instance of tkinter.Frame
#Put frame in root's grid
l.grid(row=0, column=0, columnspan=3) # l is a tkinter.Label
#Label takes entire row 0, column span = 3
```
28. What is the inlined equivalent code to
```python
[w.grid(row=1,column=i) for i,w in enumerate([pm, b, nm])]
```
```python
pm.grid(row=1, column=0)
b.grid(row=1, column=1)
nm.grid(row=1, column=2)
```
where pm, b, nm are all instances of tkinter.Button?
29. In the `word finder` example, the text to search is entered into the Entry widget that is set up using the following code
```python
pat_str = tkinter.StringVar()
pat_entry = tkinter.Entry(f, textvariable=pat_str)
pat_entry.grid(row=0, column=1)
```
What is the purpose of the text typed into the Entry? Does it need to be processed first before being passed to re.search?
> The string we want to search in dict. No
30. Continuing with the word finder example, a ListBox instance named result_box is used to display the matched results. Explain the purpose of the following three lines of code that invoke methods on the list box:
```python
result_box.delete(0, tkinter.END)
for i, w in enumerate(matched_words):
result_box.insert(i, w)
```
> delete the old result in result_box and insert the new result from matched_words
31. Continuing with the word finder example,
a. Explain what the second line does when reading the list of words from the file:
```python
fh = open('/usr/share/dict/words')
words = list(map(lambda x: x[:-1] if x[-1]=='\n' else x,fh.readlines()))
fh.close()
```
> if the element from fh.readlines() have '\n' remove '\n'
b. Give an alternative code that uses str split() method in conjunction with fh.read() to achieve the same as the second line.
```python
fh = open('/usr/share/dict/words')
words = fh.read().split('\n')
print(words)
```
32. Give the regular expressions and the corresponding description
|strings containing six (or more) o's|(.*?o){6}|
|------------------------------------|---------|
|string containing exactly six o's|.*?o{6}.*?|
|words that contain at least a 3-character sequence twice|??|
|8-character palindrome|\(.\)\(.\)\(.\)\(.\)\4\3\2\1|
|word (of any length) in the form of the same substring twice (e.g., soso)|??|
33. In the clock example, can the time be updated every second if you don't use a thread? Why or why not?
> No, it will stuck in mainloop
34. Continuing with the clock example, does the following code do?
```python
import threading
th = threading.Thread(target=update_clock)
th.start()
```
> make a new thread to run update_clock
35. In the clock example, why is it necessary to have the line quit = True after f.mainloop()?
```python
f.mainloop()
quit = True
```
considering that the update_clock() function looks like
```python
import threading, time
def update_clock():
while not quit:
now = datetime.datetime.now()
clockstr.set(f'''Date: {now.year}/{now.month}/{now.day} Time: {now.hour:02d}:{now.minute:02d}:{now.second:02d}''')
time.sleep(1)
```
> or the update_clock will not stop in some situation.