--- tags: Python --- # Python Self-Check 14 CS 1358 Introduction to Programming in Python Fall Semester 2022 Prof. Pai H. Chou Self-Check 14 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. Assuming you have import string What is the value of ``` a. string.ascii_letters //'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' b. string.ascii_lowercase //'abcdefghijklmnopqrstuvwxyz' c. string.punctuation //'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' d. string.whitespace //' \t\n\r\x0b\x0c' ``` 2. Why is it more preferable to check if a character c is a white space by ``` if c in string.whitespace: instead of if c in {' ', '\n', '\t'}:? ``` ``` more readable ``` 3. Assuming you have ``` from string import Template s = Template('$x and $y') ``` What is the value of the following expressions? ``` a. s.substitute(x='hello', y='world') //'hello and world' b. s.substitute(x=0x20, y=20) //'32 and 20' c. 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 ``` a. :%s // search and replace throughout the file b. :%s/abc/xyz/ // search abc and replace by xyz(once per line) c. :%s/abc/xyz/g // search abc and replace by xyz ``` 6. In python, you can import a module named re. What does it stand for? ``` 1. pattern matching 2. split 3. subtitute ``` 7. Given the following functions in the re module re.search(pattern, source) returns matched object for first found re.findall(pattern, source) returns list of found strings Assume import re What are the values of the following expressions? ``` a. re.findall('Gary', 'Mary had a little lamb') //[] b. re.findall('Mary', 'Mary had a little lamb') //['Mary'] c. re.findall('Mary', 'Mary and Gary had a little lamb') //['Mary'] d. re.findall('lamb', 'Mary had a little lamb little lamb') //['lamb', 'lamb'] e. re.findall('a', 'Mary had a little lamb') //['a', 'a', 'a', 'a'] ``` 8. Assume the following ``` 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? ``` a. ['Mary', 'Gary', 'Cary'] //'[A-Z]ary' b. ['Mary, 'Gary'] //'[^Cc]ary' c. ['Mary', 'Gary', 'Cary', 'cary'] //'.ary' d. ['Cary', 'cary'] //'[Cc]ary' e. ['Mary', 'Gary', 'Cary', 'scary'] //'[A-Za-z]*ary' ``` 9. Assume import re What are the values of the following expressions? ``` a. re.findall('[a-z]*are', 'We scare because we care') //['scare', 'care'] b. re.findall('[a-z]+are', 'We scare because we care') //['scare', 'care'] c. re.findall('[a-z]*are', 'We are here to scare and care') //['are', scare', 'care'] d. re.findall('[a-z]+are', 'We scare because we care') //['scare', 'care'] e. re.findall('[a-z]*are', 'He cares that we are scared') //['care, 'are', 'scare'] f. re.findall('[a-z]+are', 'He cares that we are scared') //['care', 'scare'] g. re.findall('[a-z]*are[sd]','He cares that we are scared') //['cares, 'scared'] h. re.findall('[a-z]*are[sd]?','He cares that we are scared') //['cares, 'are', 'scared'] i. re.findall('[a-z]+are[sd]','He cares that we are scared') //['cares', 'scared'] j. re.findall('[a-z]+are[sd]?','He cares that we are scared') //['cares', 'scared'] ``` 10. Assume import re What are the values of the following expressions? Explain the differ in between c and d. ``` a. re.findall('[a-z]*','He cares that we are scared') //['', 'e', '', 'cares', '', 'that', '', 'we', '', 'are', '', 'scared', ''] b. re.findall(r'\w*','He cares that we are scared') //['He', '', 'cares', '', 'that', '', 'we', '', 'are', '', 'scared', ''] c. re.findall(r'\bare\b','He cares that we are scared') //['are'] d. re.findall('\bare\b','He cares that we are scared') //[] //c, d differ in r (means raw string), ``` 11. Assume import re What are the values of the following expressions? ``` a. re.findall('Mary','Mary and Mary's lamb like Mary') //['Mary', 'Mary', 'Mary'] b. re.findall('^Mary','Mary and Mary's lamb like Mary') //['Mary'] c. re.findall('Mary$','Mary and Mary's lamb like Mary') //['Mary'] d. re.search('^Mary','Mary and Mary's lamb like Mary') //<re.Match object; span=(0, 4), match='Mary'> e. re.search('Mary$','Mary and Mary's lamb like Mary') //<re.Match object; span=(26, 30), match='Mary'> f. 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 import re What are the values of the following expressions? Explain the difference between '*' and '*?' as regular expressions ``` a. re.findall(r'\b.are', 'He cares that we are scared') //['care', 'are'] b. re.findall(r'\b.*are', 'He cares that we are scared') //['He cares that we are scared'] c. re.findall(r'\b.*?are', 'He cares that we are scared') //['He care', ' that we are', ' scare'] //'*':greedy match the max length //'*?': match one and return ``` 14. What are the values of the following expressions? assume import re ``` a. 'To be, or not to be--that is the question!'.split() //['To', 'be,', 'or', 'not', 'to', 'be--that', 'is', 'the', 'question!'] b. 'To be, or not to be--that is the question!'.split('-') //['To be, or not to be', '', 'that is the question!'] c. 'To be, or not to be--that is the question!'.split('--') //['To be, or not to be', 'that is the question!'] d. re.split(' ', 'To be or not--that is the question!') //['To', 'be,', 'or', 'not--that', 'is', 'the', 'question!'] e. re.split(r'\W', 'To be or not--that is the question!') //['To', 'be,', 'or', 'not', '', 'that', 'is', 'the', 'question', ''] f. re.split(r'\W+', 'To be or not--that is the question!') //['To', 'be,', 'or', 'not', 'that', 'is', 'the', 'question', ''] g. re.split(r'-+', 'To be or not--that is the question!') //['To be or not', 'that is the question!'] h. 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 30-31| |\d\d:\d\d:\d\d|2 digit:2 digit:2 digit| |\d{1,4}|1 to 4 digit| 16. Assume import re Does the following result in match? ``` 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 ``` a. m.group(1) //'14' b. m.group(2) //'33' c. m.group(3) //'28' d. m.group(4) //'2019' ``` 17. Assume import re What is the value of ``` a. re.sub('-', '/', 'today 5-20-2019, tomorrow 5-21-2019') //'today 5/20/2019, tomorrow 5/21/2019' b. re.sub('.', '/', 'today 5.20.2019, tomorrow 5-21-2019') //'///////////////////////////////////' c. re.sub(r'\.', '/', 'today 5.20.2019, tomorrow 5-21-2019') //'today 5/20/2019, tomorrow 5-21-2019' ``` 18. Assume import re What is the value of ``` re.sub('(\d+)/(\d+)/(\d+)', '\3/\2/\1', 'today 5/20/2019, tomorrow 5/21/2019') //'today \x03/\x02/\x01, tomorrow \x03/\x02/\x01' **if r'\3/\2/\1' then 'today 2019/5/20, tomorrow 2019/5/21' ``` 19. Consider the first Tkinter program ``` 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? //Label b. What kind of object is root.destroy on line 7? //Button c. Does line 9 run forever? Or in what condition does line 9 finish? //no, if b click ``` 20. The second version of the Tkinter program is as follows, where the difference is highlighted in pink: ``` 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? let button in bottom, label in top ``` 21. In the Calendar v2 example, the first page of the source code looks like this: ``` 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? //don't need to find the label and call its method ``` 22. Continuing with the same example, consider part of the second page of the source code, (abridged) ``` 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? //when button click, No b. Why is line 19 necessary? //because current_year, current_month is initial no value, and we want to get the value in main function c. What is the effect of line 24 on the user interface? //get the new calendar ``` 23. Continuing with the same example, one improvement is to replace the prev_month and next_month functions with the following: ``` 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? //they are similar b. Can this new function shift_month be passed as callback to (line 52 in the previous problem), i.e., pm = tkinter.Button(f, text='Prev', command=shift_month) ? Why or why not? //no, shift_month need a parameter c. Can line 52 be written as pm = tkinter.Button(f, text='Prev', command=shift_month(operator.sub)) instead? Why or why not? //no, need to use lambda d. What is the difference between part c and the following: pm = tkinter.Button(f, text='Prev', command=lambda shift_month(operator.sub)) which one is correct? //d ``` 24. In calendar v3, the grid layout manager is used instead of pack. What is the difference? ``` grid - expandable table, good for most purpose ``` 25. What is the meaning of ``` a. f.grid(row=0, column=0) # f is an instance of tkinter.Frame //Frame is in left-top b. l.grid(row=0, column=0, columnspan=3) # l is a tkinter.Label //label is in left-top and will extend to column 3 ``` 26. What is the inlined equivalent code to [w.grid(row=1,column=i) for i,w in enumerate([pm, b, nm])] where pm, b, nm are all instances of tkinter.Button? ``` pm.grid(row = 1, column = 0) b.grid(row = 1, column = 1) nm.grid(row = 1, column = 2) ``` 27. In the word finder example, the text to search is entered into the Entry widget that is set up using the following code ``` 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 or regular expression we want to find yes ``` 28. 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: ``` result_box.delete(0, tkinter.END) for i, w in enumerate(matched_words): result_box.insert(i, w) ``` ``` 1. clear the contain in current result_box 2. insert the new result in result_box ``` 29. Continuing with the word finder example, ``` a. Explain what the second line does when reading the list of words from the file: fh = open('/usr/share/dict/words') words = list(map(lambda x: x[:-1] if x[-1]=='\n' else x, fh.readlines())) fh.close() //to delete the newline in readlines() string b. Give an alternative code that uses str split() method in conjunction with fh.read() to achieve the same as the second line //s = fh.read() s.split('\n') ``` 30. Give the regular expressions and the corresponding description | strings containing six (or more) o's | (.\*?o){6} | |-|-| |string containing exactly six o's|([\^o]\*o[\^o]\*o[\^o]\*o[\^o]\*o[\^o]\*o\[^o]\*o[\^o]\*)| |words that contain at least a 3-character sequence twice|(.{3}).\*\1| |8-character palindrome|^(.)(.)(.)(.)\4\3\2\1$| |word (of any length) in the form of the same substring twice (e.g., soso)|(.\*?).\*\1| 31. In the clock example, can the time be updated every second if you don't use a thread? Why or why not? ``` no, single threaded => clock won't get updated! ``` 32. Continuing with the clock example, does the following code do? ``` import threading th = threading.Thread(target=update_clock) th.start() ``` ``` create Thread th will run target function update_clock and start th ``` 33. In the clock example, why is it necessary to have the line quit = True after f.mainloop()? ``` f.mainloop() quit = True ``` considering that the update_clock() function looks like ``` 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) ``` ``` if quit don't set true then the update_clock will continue forever ```