

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Solutions to various python programming problems, including creating files, converting integers to strings, rotating lists, and writing a custom socket subclass for reading records of a given length. The document emphasizes pythonic ways of accomplishing tasks.
Typology: Exams
1 / 2
This page cannot be seen from the preview
Don't miss anything!


Name:
Directions: Work only on this sheet (on both sides, if needed); do not turn in any supplementary sheets of paper. There is actually plenty of room for your answers, as long as you organize yourself BEFORE starting writing. In order to get full credit, SHOW YOUR WORK.
Several problems will ask you to present a “Pythonic” way of accomplishing a certain task. The term, which is common in Python circles, simply means taking advantage of Python’s features. Often it will mean that the task can be accomplished in a single line. It does not mean that you are expected to always use the most esoteric Python feature (and certainly not one which is outside the scope of our course materials), but it does mean that you should make a reasonable attempt to make good use of the language.
def inttostring(n): m = n out = ’’ for i in range(4): c = m % 256 out += _____________ m /= 256 return out
def stringtoint(s): m = 0 for i in range(4): m = ______________ return m
python x.py g
then the program will execute g. Write Pythonic code which makes the call (must be single-line code for full credit).
Write the function getrec(), in a short, Pythonic manner.
Solutions:
f = []
for i in range(1,5): f.append(open(’a’+str(i),’w’))
Note the need for the list here. You could not, for example, keep assigning the result of open() to the same variable, which would mean you could not perform any further operations on the files.
chr(c) ... 256*m+ord(s[3-i])
for numeral,integer in romanNumeral(Map.items())
Note that this presumes that dictionary itmes are stored in the order in which they are shown in the code which uses them. This works on the CSIF platform, but a more careful version would sort first.
x = x[1:] + [x[0]]
exec sys.argv[1]+’()’
def getrec(self,reclength): self.incoming = [] # not destructive, as NO characters will be left over
ncharsread = 0 while 1: chunk = self.recv(reclength-ncharsread) if chunk == []: return [] self.incoming += chunk ncharsread += len(chunk) if ncharsread == reclength: return self.incoming