Consider the function: def hello(): return "Hello, world!" Which of the following is the correct way to make a decorator that could be used to make hello() return "#Hello, world!#"?
def hello(): return "#Hello, world!#" 1.0%
def hashes(fn): def wrapped(): return "#" + fn() + "#" return wrapped @hashes def hello(): return "Hello, world!" 96.0%
def hashes(fn): def wrapped(): return "#" + "#" return wrapped @hashes def hello(): return "Hello, world!" 0.0%
def hashes(fn): def wrapped(): print "#" + fn() + "#" return @hashes def hello(): return "Hello, world!" 1.0%
Examine the following prototype for the 'open' function of the file class in Python 2.2+: open(fname [,mode [,buffering]]) Which of the following is correct for the 'buffering' argument?
0 for none 0.0%
1 for line oriented 0.0%
An integer larger than 1 for number of bytes 35.0%
All of these 65.0%
Given a program that saved a text file in the directory "/temp_files", which of the following will make sure that "/temp_files" exists before writing the file?
d = os.path.dirname("/temp_files") if not os.path.exists(d): os.makedirs(d) 17.0%
d = os.path("/temp_files") if not os.path(d): os.makedirs(d) 2.0%
d = os.path.dirname("/temp_files") if os.path.exists(d): os.makedirs(d) 2.0%
if not os.path.exists("/temp_files"): os.makedirs(d) 76.0%
How can a list be split into equal sized chunks?
f = lambda x, n, acc=[]: f(x[n:], n, acc+[(x[:n])]) if x else acc 9.0%
def chunks(l, n): for i in xrange(0, len(l), n): yield l[i:i+n] 75.0%
def split_seq(seq, num_pieces): start = 0 for i in xrange(num_pieces): stop = start + len(seq[i::num_pieces]) yield seq[start:stop] start = stop 3.0%
chunks = lambda l, n: [l[x: x+n] for x in xrange(0, len(l), n)] chunks(l, 10) 12.0%
How can a null object be declared in Python?
none 0.0%
None 100.0%
null 0.0%
How can a numeric String (eg. "545.2222") be converted to Float or Integer?
import string parseStr = lambda x: x.isalpha() and x or x.isdigit() and (x) or x.isalnum() and x or len(set(string.punctuation).intersection(x)) == 1 and x.count('.') == 1 and float(x) or x parseStr("545.2222") 0.0%
def convert(n): try: return int(n) except ValueError: return float(n + 0.5) convert("545.2222") 0.0%
a = "545.2222" float(a) int(float(a)) 94.0%
def parseIntOrFloat(s): return eval(s) 5.0%
How can an element be removed from a list using its list index?
myList.remove(index) 0.0%
pop myList[index] 0.0%
del myList[index] 95.0%
myList.delete(index) 4.0%
How many arguments can a print statement handle?
One 2.0%
Any number of string arguments only 2.0%
Any number of numeric arguments only 0.0%
Any number of string or numeric arguments 94.0%
In Python 2.x, which of the following is the way to check to make sure that the variable 'x' is not a string?
assert isinstance(x, basestring) 8.0%
assert not isinstance(x, basestring) 83.0%
assert not instance(x, basestring) 4.0%
assert not x.isinstance(basestring) 4.0%
In Python, built-in exceptions can be inherited from. Which of the following is the base exception class?
Exceptions 0.0%
BaseException 15.0%
Exception 84.0%
Except 0.0%
In Python, what is the default maximum level of recursion?
500 0.0%
1000 94.0%
10000 0.0%
There is no default maximum level 5.0%
Inheriting from a base class enables a custom class to use a few new capabilities, such as slots and properties. Which of the following is the base class of new-style datatypes?
base 0.0%
object 96.0%
dict 0.0%
custom 0.0%
None of these 3.0%
It is possible to use encoding other than ASCII in Python source files. The best way to do it is to put one more special comment line right after the #! line to define the source file encoding. Whi...
coding: iso-8859-15 0.0%
# -*- iso-8859-15 -*- 3.0%
# -*- coding: iso-8859-15 -*- 96.0%
None of these 0.0%
Object is the base class of new-style datatypes. Which of the following functions is not a member of the object class?
object.__eq__(self, other) 0.0%
object.__notequal__(self, other) 100.0%
object.__repr__(self) 0.0%
None of these 0.0%
object.__ne__(self, other) 3.0%
object.__nz__(self) 93.0%
None of these 3.0%
One common way to test a capability in Python is to try to do something, and catch any exceptions that occur. Which of the following is the correct mechanism of trapping an error?
try: code to be verified will come here exception <except>: 0.0%
try: code to be verified will come here except <exception>: 100.0%
try: code to be verified will come here exception: 0.0%
try: code to be verified will come here exception <exception>: 0.0%
Read the following statements: >>> import array >>> a = array.array('c','spam and eggs') >>> a[0] = 'S' >>> a[-4:] = array.array('c','toast') >>> print ''.join(a) Which of the following will be t...
Spam and toast 96.0%
spam and toast 3.0%
Spam and eggs 0.0%
spamandtoast 0.0%
spamandeggs 0.0%
Read the following statements: >>> import string >>> s = 'mary 11had a little lamb' >>> print s Which of the following will be the output of the above code snippet?
mary had a little lamb 8.0%
mary 11 had a little lamb 0.0%
mary had a little lamb 88.0%
mary 11had a little lamb 2.0%
Read the following statements: >>> lst = ['spam','and','eggs'] >>> lst[2] = 'toast' >>> print ''.join(lst) >>> print ' '.join(lst) Which of the following is the output of the second print stateme...
spam and eggs 0.0%
spamandeggs 0.0%
spamandtoast 0.0%
spam and toast 100.0%
Read the following statements: >>> word = 'Help' + 'A' >>> '<' + word*5 + '>' Which of the following will be the output of the above code snippet?
'<HelpAHelpAHelpAHelpAHelpA>' 100.0%
'<HelpA5>' 0.0%
'<HelpA*5>' 0.0%
An error 0.0%
None of these 0.0%
Read the following statements: Statement 1: A simple assignment statement binds a name into the current namespace, unless that name has been declared as global. Statement 2: A name declared as gl...
Statement 1 is true, but statement 2 is false. 0.0%
Statement 2 is true, but statement 1 is false. 3.0%
Both statements are true. 96.0%
Both statements are false. 0.0%
Read the following statements: Statement 1: Many string module functions are now also available as string object methods. Statement 2: To use string object methods, there is no need to import the...
Statement 1 is true, but statement 2 is false. 0.0%
Statement 2 is true, but statement 1 is false. 3.0%
Both statements are true. 96.0%
Both statements are false. 0.0%
The core text processing tasks in working with email are parsing, modifying, and creating the actual messages. Which of the following modules deal with parsing and processing email messages?
MimeWriter 3.0%
mimify 3.0%
Both MimeWriter and mimify 85.0%
Neither MimeWriter nor mimify 7.0%
The least sophisticated form of text output in Python is writing to open files. In particular, which of the following streams can be used?
STDOUT 60.0%
STDERR 39.0%
STDPRN 0.0%
STDFIL 0.0%
The most important element of the email package is the message. The email class provides the classes for messages in Python. Which of the following classes is used for the message?
email.Message 3.0%
email.message.Message 96.0%
email.messages 0.0%
email.emailmessage 0.0%
Various email and news clients store messages in a variety of formats, many providing hierarchical and structured folders. Which of the following provides a uniform API for reading the messages sto...
mailstruct 0.0%
emailarch 0.0%
emailfolders 0.0%
mailbox 100.0%
What is a metaclass in Python?
A class that is inherited from 16.0%
A class that inherits from another class 0.0%
Something that can be attached to any class, that gives it a constant set of attributes 66.0%
Something that creates "class" objects 16.0%
What is the best way to check if the object 'myobject' is iterable in Python?
myobject.isIter() 0.0%
try: [ e for e in myobject] except TypeError: print myobject, 'is not iterable' 100.0%
try: iter.myobject except: print myobject, 'is not iterable' 0.0%
if [ e for e in myobject]: print myobject, 'is iterable' else: print myobject, 'is not iterable' 0.0%
What is the correct way to delete a directory that is not empty using Python?
os.remove('/directory') 0.0%
os.rmtree('/directory') 0.0%
shutil.rmtree('/directory') 0.0%
import shutil shutil.rmtree('/directory') 100.0%
What is the most flexible way to call the external command "ls -l" in Python?
from subprocess import call call(["ls", "-l"]) 91.0%
from subprocess import call call("ls -l") 0.0%
os.system("ls -l") 8.0%
os.system(["ls"], ["-l"]) 0.0%
What is the output of the following code: name = 'Jon' name.rjust(4, 'A')
'Jon A' 0.0%
'A Jon' 0.0%
'AJon' 100.0%
'JonA' 0.0%
What is the output of the following code? def foo(param1, *param2): print param1 print param2 def bar(param1, **param2): print param1 print param2 foo(1,2,3,4,5) bar(1,a=2,b=3)
TypeError: foo() got multiple values for keyword argument 'param1' 0.0%
1 (2, 3, 4, 5) 1 (2, 3) 0.0%
1 (2, 3, 4, 5) 1 {'a': 2, 'b': 3} 100.0%
1 {2, 3, 4, 5} 1 ('a': 2, 'b': 3) 0.0%
What is the result of the following code: >>> import itertools >>> x = itertools.count(0) >>> x.__class__.__name__
Nothing 0.0%
'count' 100.0%
'Object' 0.0%
'None' 0.0%
What will be the output of the following statements: >>> import string >>> string.ljust(width=30,s="Mary had a little lamb")
'Mary had a little lamb ' 72.0%
'Mary had a little lamb' 0.0%
' Mary had a little lamb' 0.0%
None of these 27.0%
What would the 'sorted_tel' be in the following code: tel = {'jack': 4098, 'sape': 5139, 'bill': 3678, 'mike': 2122} sorted_tel = sorted(tel.items(), key=lambda x: x[1])
A dictionary sorted by the second element. 0.0%
A list of Tuples sorted by the second element. 100.0%
A list of dictionaries sorted by the first element. 0.0%
A dictionary sorted by the first element. 0.0%
A list of Tuples sorted by the first element. 0.0%
When is the "yield" keyword used in Python?
When other processes need to take precedence over the Python script 3.0%
To break out of a loop 0.0%
When a function needs to return a list that only needs to be read through once 96.0%
Never 0.0%
Which function could be used to list every file and folder in the current directory?
os.dirnames('.') 0.0%
os.listdir('.') 100.0%
os.listdir('/') 0.0%
os.ls() 0.0%
Which is not used to install Python packages?
easy_install 0.0%
pip 3.0%
distribute 0.0%
installtools 96.0%
Which is the correct way to remove an installed Python package?
easy_install -v <package> 0.0%
pip uninstall <package> 100.0%
easy_install -u <package> 0.0%
pip -m <package> 0.0%
Which list flattening method will have the shortest running time?
l = [ [1, 2, 3], [4, 5, 6], [7], [8, 9] ] * 99 import itertools list( itertools.chain.from_iterable( l ) ) 95.0%
l = [ [1, 2, 3], [4, 5, 6], [7], [8, 9] ] * 99 reduce( lambda x, y: x + y, l ) 0.0%
l = [ [1, 2, 3], [4, 5, 6], [7], [8, 9] ] * 99 sum( l, [ ] ) 4.0%
l = [ [1, 2, 3], [4, 5, 6], [7], [8, 9] ] * 99 [ item for sublist in l for item in sublist ] 0.0%
Which of the following are the main features of Python?
Cross-platform 27.0%
Extensible 23.0%
Object-oriented, with multiple inheritance 24.0%
Written in Java 0.0%
Overloading of common operators 24.0%
All of these 0.0%
Which of the following code snippets concatenates the list a_list = [1, 2, 3] with the tuple a_tuple = (4, 5), so the result would be [1, 2, 3, 4, 5]?
a_list + a_tuple 0.0%
a_list.extend(a_tuple) 100.0%
a_list.append(a_tuple) 0.0%
a_list.append(*a_tuple) 0.0%
Which of the following commands would produce the following result: result: 'line 1
line 2'
result = '
line 1
line 2
'.rstrip() 0.0%
result = '
line 1
line 2
'.split() 0.0%
result = '
line 1
line 2
'.strip() 100.0%
result = '
line 1
line 2
'.lstrip() 0.0%
result = '
line 1
line 2
'.splitlines() 0.0%
Which of the following exceptions occurs while importing a module?
ModuleError 0.0%
ImportError 100.0%
ImportModuleError 0.0%
ReferenceError 0.0%
Which of the following functions can change the maximum level of recursion?
setmaxrecursion function in the sys module 0.0%
setrecursionlimit function in the sys module 100.0%
setmaximumrecursion function in the sys module 0.0%
None of these 0.0%
Which of the following functions is used to send audio data via the Internet?
email.MIMEAudio(audiodata [,subtype [,encoder [,**params]]]) 0.0%
email.SendAudio(audiodata [,subtype [,encoder [,**params]]]) 0.0%
email.MIMEAudio.MIMEAudio(audiodata [,subtype [,encoder [,**params]]]) 100.0%
email.MIMEAudio.SendAudio(audiodata [,subtype [,encoder [,**params]]]) 0.0%
Which of the following functions modifies the list in place to indicate which items are directories, and which are plain files?
dircache.listdir(path, lst) 0.0%
dircache.annotate(path, lst) 100.0%
dircache.filter(path, lst) 0.0%
dircache.scan(path, lst) 0.0%
Which of the following is a way to find a local computer's IP address with Python?
import socket socket.gethostbyname(socket.gethostname()) 100.0%
socket.gethostbyname(socket.gethostname()) 0.0%
import socket gethostbyname(socket.gethostname()) 0.0%
import ifconfig print (ifconfig -a) 0.0%
Which of the following is the base class for new-style file objects?
base 0.0%
file 100.0%
fileobject 0.0%
filebase 0.0%
Which of the following is the best method to find the indices of all occurances of a word in a string? line = 'mary had a little lamb, little lamb, little lamb' word = 'lamb'
import re indices = [occurance.start() for occurance in re.finditer(word, line)] 95.0%
def find_all(line, word): start = 0 while True: start = line.find(word, start) if start == -1: return yield start start += len(word) indices = list(find_all(line, word)) 5.0%
indices = [i - 1 for i in range(len(line)) if line.startswith(word, i - 1)] 0.0%
None of these 0.0%
Which of the following is the best way to reverse the string 'Test String' in Python?
string.reverse('Test String') 0.0%
'Test String'[::-1] 95.0%
reversed('Test String') 4.0%
'Test String'[-1:0] 0.0%
Which of the following is the correct method for changing a global variable inside a function?
def change_globvar(): globvar = 1 0.0%
def change_globvar(): global globvar globvar = 1 95.0%
def change_globvar(): import globvar globvar = 1 4.0%
def change_globvar(): global globvar = 1 0.0%
Which of the following is the correct prototype for the 'open' function of the file class in python 2.2+?
open(fname [,mode [,buffering]]) 100.0%
open(fname [,buffering [,mode]]) 0.0%
open(fname [,mode]) 0.0%
open(fname,mode,buffering) 0.0%
open(fname,buffering,mode) 0.0%
None of these 0.0%
Which of the following is the correct prototype of the string.find() function?
string.find(s, sub ,start ,end) 0.0%
string.find(s, sub ,start [,end]) 0.0%
string.find(s, sub [,start [,end]]) 100.0%
string.find(s, sub [,start] ,end) 0.0%
Which of the following is the correct way to call the private method, myPrivateMethod(), in class MyClass, using dir(obj)? class MyClass: def __myPrivateMethod(self): print "Private Me...
__myPrivateMethod 0.0%
_MyClass__myPrivateMethod 100.0%
myPrivateMethod 0.0%
A private method will not be shown in the output. 0.0%
Which of the following is the correct way to check to see if the variable theVar is an integer?
isinstance(theVar, int) 100.0%
theVar.isinstance(int) 0.0%
int.isinstance(theVar) 0.0%
is(theVar, int) 0.0%
Which of the following is the correct way to execute a program from inside Python without having to consider how the arguments/quotes are formatted?
import subprocess subprocess.call('C:\Temp\a b c\Notepad.exe', 'C:\test.txt') 0.0%
os.call(['C:\Temp\a b c\Notepad.exe', 'C:\test.txt']) 0.0%
import subprocess subprocess.call(['C:\Temp\a b c\Notepad.exe', 'C:\test.txt']) 100.0%
subprocess.call(['C:\Temp\a b c\Notepad.exe', 'C:\test.txt']) 0.0%
Which of the following is the correct way to flush output of Python print?
import sys sys.stdout.flush() 91.0%
class flushfile(file): def __init__(self, f): self.f = f def write(self, x) self.f.write(x) self.f.flush() import sys sys.stdout = flushfile(sys.stdout) 0.0%
import sys sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) 0.0%
Running python with the -u command-line switch 8.0%
Which of the following is the correct way to get the size of a list in Python?
list.length() 0.0%
len(list) 95.0%
sizeof(list) 4.0%
list.size() 0.0%
Which of the following is the correct way to write a generator which will output the numbers between 1 and 100 (inclusive)?
def onehundred(start, end): current = start while current <= end: yield current current += 1 for x in onehundred(1, 100): print x 100.0%
def onehundred(start, end): current = start while current <= end: return current current += 1 for x in onehundred(1, 100): print x 0.0%
def onehundred(start, end): current = start while current <= end: yield current current += 2 for x in onehundred(1, 100): print x 0.0%
def onehundred(start, end): while current <= end: yield current current += 1 for x in onehundred(1, 100): print x 0.0%
Which of the following members of the object class compare two parameters?
object.__eq__(self, other) 50.0%
object.__ne__(self, other) 50.0%
object.__compare__(self, other) 0.0%
object.__equals__(self, other) 0.0%
object.__co__(self, other) 0.0%
None of these 0.0%
Which of the following methods returns the ASCII value of a character in Python?
ascii 0.0%
ord 100.0%
asciicode 0.0%
None of these 0.0%
Which of the following modules is used internally to determine whether a path matches?
dircmp 0.0%
filecompare 0.0%
fncmp 0.0%
fnmatch 100.0%
Which of the following modules keep prior directory listings in the memory to avoid the need for a new call to the file system?
sys 0.0%
FileSys 0.0%
dirsys 0.0%
dircache 100.0%
Which of the following modules lets you check whether two files are identical, and whether two directories contain some identical files?
dircomp 0.0%
filecompare 0.0%
filecmp 100.0%
structcomp 0.0%
Which of the following options are true regarding these two code samples? Code sample 1: def main(): for i in xrange(10**8): pass main() Code sample 2: for i in xrange(10**8): pass
Code sample 2 would take a longer time to complete than code sample 1. This is because in code sample 1, 'i' is local, whereas in code sample 2 it is global. 78.0%
Code sample 1 would take a longer time to complete than code sample 2. This is because code sample 1 would take additional time in defining and calling the function. 0.0%
Code sample 2 would take less time to complete because Python is able to detect pass as a null operation, and skip the whole loop. 0.0%
None of these. 21.0%
Which of the following protocol libraries can be used for an email implementation in a Python application?
telnetlib 0.0%
smtplib 100.0%
ftplib 0.0%
None of these 0.0%
Which of the following statements are true? A. ._variable is semi-private and meant just for convention. B. .__variable is considered superprivate and gets name mangled to prevent accidental acces...
A 0.0%
B 0.0%
C 0.0%
A, B, and C 100.0%
Which of the following statements can be used to remove an item from a list by giving the index?
remove listname[index] 0.0%
del listname[index] 95.0%
kill listname[index] 4.0%
None of these 0.0%
Which of the following statements copy the contents of a list and not just a reference to the list?
newlist = oldlist 0.0%
newlist = oldlist[:] 100.0%
newlist = oldlist(dummy) 0.0%
None of these 0.0%
Which of the following statements imports every name in a module namespace into the current namespace?
from modname import All 0.0%
from modname import * 100.0%
from modname import ? 0.0%
from modname import All as * 0.0%
Which of the following variables store parameters passed from outside?
sys.param 0.0%
sys.arg 0.0%
sys.argv 100.0%
sys.prm 0.0%
Which of the following will determine the number of CPUs available in the operating environment?
import os os..cpu_count() 14.0%
import sys sys..cpu_count() 0.0%
import psutil sutil.NUM_CPUS 28.0%
import multiprocessing multiprocessing.cpu_count() 57.0%
Which of the following will disable output buffering in Python?
Using the -u command line switch 33.0%
class Unbuffered: def __init__(self, stream): self.stream = stream def write(self, data): self.stream.write(data) self.stream.flush() def __getattr__(self, attr): return getattr(self.stream, attr) import sys sys.stdout=Unbuffered(sys.stdout) 33.0%
Setting the PYTHONUNBUFFERED environment variable 33.0%
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) 0.0%
Which of the following will throw an exception in Python?
call Exception("Here is an Exception!") 0.0%
throw Exception("Here is an Exception!") 0.0%
raise Exception("Here is an Exception!") 100.0%
create Exception("Here is an Exception!") 0.0%
Which Python module can be used for copying files?
util 0.0%
shutil 93.0%
copy 0.0%
filecopy 6.0%
Which user input method will act like a file-object on which read and readline functions can be called?
sys.stdin 100.0%
raw_input() 0.0%
input() 0.0%
sys.argv 0.0%
Writing to STDOUT and STDERR is fairly inflexible, and most of the time the print statement accomplishes the same purpose more flexibly. How many arguments can a print statement handle?
1 0.0%
2 0.0%
7 0.0%
Any number 100.0%