Upwork Python Test 2016.
78 Answered Test Questions:
1. Which of the following will disable output buffering in Python?
Answers:
a. Using the -u command line switch
a. 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)
a. Setting the PYTHONUNBUFFERED environment variable
a. sys.stdout = os.fdopen(sys.stdout.fileno(), ‘w’, 0)
2. Which of the following members of the object class compare two parameters?
Answers:
a. object.__eq__(self, other)
a. object.__ne__(self, other)
a. object.__compare__(self, other)
a. object.__equals__(self, other)
a. object.__co__(self, other)
a. None of these
3. Object is the base class of new-style datatypes. Which of the following functions is not a member of the object class?
Answers:
a. object.__eq__(self, other)
a. object.__ne__(self, other)
a. object.__nz__(self)
a. object.__repr__(self)
a. None of these
4. In Python, what is the default maximum level of recursion?
Answers:
a. 500
a. 1000
a. 10000
a. There is no default maximum level
5. 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 stored in all the most popular folder formats?
Answers:
a. mailstruct
a. emailarch
a. emailfolders
a. mailbox
6. Which of the following are the main features of Python?
Answers:
a. Cross-platform
a. Extensible
a. Object-oriented, with multiple inheritance
a. Written in Java
a. Overloading of common operators
a. All of these
7. Which of the following variables store parameters passed from outside?
Answers:
a. sys.param
a. sys.arg
a. sys.argv
a. sys.prm
8. Which of the following functions can change the maximum level of recursion?
Answers:
a. setmaxrecursion function in the sys module
a. setrecursionlimit function in the sys module
a. setmaximumrecursion function in the sys module
a. None of these
9. Read the following statements:
1. Which of the following will disable output buffering in Python?
Answers:
a. Using the -u command line switch
a. 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)
a. Setting the PYTHONUNBUFFERED environment variable
a. sys.stdout = os.fdopen(sys.stdout.fileno(), ‘w’, 0)
2. Which of the following members of the object class compare two parameters?
Answers:
a. object.__eq__(self, other)
a. object.__ne__(self, other)
a. object.__compare__(self, other)
a. object.__equals__(self, other)
a. object.__co__(self, other)
a. None of these
3. Object is the base class of new-style datatypes. Which of the following functions is not a member of the object class?
Answers:
a. object.__eq__(self, other)
a. object.__ne__(self, other)
a. object.__nz__(self)
a. object.__repr__(self)
a. None of these
4. In Python, what is the default maximum level of recursion?
Answers:
a. 500
a. 1000
a. 10000
a. There is no default maximum level
5. 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 stored in all the most popular folder formats?
Answers:
a. mailstruct
a. emailarch
a. emailfolders
a. mailbox
6. Which of the following are the main features of Python?
Answers:
a. Cross-platform
a. Extensible
a. Object-oriented, with multiple inheritance
a. Written in Java
a. Overloading of common operators
a. All of these
7. Which of the following variables store parameters passed from outside?
Answers:
a. sys.param
a. sys.arg
a. sys.argv
a. sys.prm
8. Which of the following functions can change the maximum level of recursion?
Answers:
a. setmaxrecursion function in the sys module
a. setrecursionlimit function in the sys module
a. setmaximumrecursion function in the sys module
a. None of these
9. 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)
>>> 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 the output of the above code snippet?
Answers:
a. Spam and toast
a. spam and toast
a. Spam and eggs
a. spam and eggs
a. spamandtoast
a. spamandeggs
10. How can a numeric String (eg. “545.2222”) be converted to Float or Integer?
Answers:
a. 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”)
a. def convert(n): try: return int(n) except ValueError: return float(n + 0.5) convert(“545.2222”)
a. a = “545.2222” float(a) int(float(a))
a. def parseIntOrFloat(s): return eval(s)
11. Which of the following is the correct prototype of the string.find() function?
Answers:
a. string.find(s, sub ,start ,end)
a. string.find(s, sub ,start [,end])
a. string.find(s, sub [,start [,end]])
a. string.find(s, sub [,start] ,end)
12. 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. Which of the following is the correct statement to define encoding?
Answers:
a. coding: iso-8859-15
a. # -*- iso-8859-15 -*-
a. # -*- coding: iso-8859-15 -*-
a. None of these
13. How can a null object be declared in Python?
Answers:
a. none
a. None
a. null
a. Null
14. Which of the following modules lets you check whether two files are identical, and whether two directories contain some identical files?
Answers:
a. dircomp
a. filecompare
a. filecmp
a. structcomp
15. Which function could be used to list every file and folder in the current directory?
Answers:
a. os.dirnames(‘.’)
a. os.listdir(‘.’)
a. os.listdir(‘/’)
a. os.ls()
16. 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?
Answers:
a. MimeWriter
a. mimify
a. Both MimeWriter and mimify
a. Neither MimeWriter nor mimify
17. Which of the following is the correct prototype for the ‘open’ function of the file class in python 2.2+?
Answers:
a. open(fname [,mode [,buffering]])
a. open(fname [,buffering [,mode]])
a. open(fname [,mode])
a. open(fname,mode,buffering)
a. open(fname,buffering,mode)
a. None of these
18. Which user input method will act like a file-object on which read and readline functions can be called?
Answers:
a. sys.stdin
a. raw_input()
a. input()
a. sys.argv
19. Which of the following protocol libraries can be used for an email implementation in a Python application?
Answers:
a. telnetlib
a. smtplib
a. ftplib
a. None of these
20. Which of the following statements imports every name in a module namespace into the current namespace?
Answers:
a. from modname import All
a. from modname import *
a. from modname import ?
a. from modname import All as *
21. Which is the correct way to remove an installed Python package?
Answers:
a. easy_install -v a. pip uninstall
a. easy_install -u a. pip -m 22. 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?
Answers:
a. try: code to be verified will come here exception :
a. try: code to be verified will come here except :
a. try: code to be verified will come here exception:
a. try: code to be verified will come here exception :
23. Which of the following is the correct way to get the size of a list in Python?
Answers:
a. list.length()
a. len(list)
a. sizeof(list)
a. list.size()
24. What will be the output of the following statements:
Answers:
a. Spam and toast
a. spam and toast
a. Spam and eggs
a. spam and eggs
a. spamandtoast
a. spamandeggs
10. How can a numeric String (eg. “545.2222”) be converted to Float or Integer?
Answers:
a. 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”)
a. def convert(n): try: return int(n) except ValueError: return float(n + 0.5) convert(“545.2222”)
a. a = “545.2222” float(a) int(float(a))
a. def parseIntOrFloat(s): return eval(s)
11. Which of the following is the correct prototype of the string.find() function?
Answers:
a. string.find(s, sub ,start ,end)
a. string.find(s, sub ,start [,end])
a. string.find(s, sub [,start [,end]])
a. string.find(s, sub [,start] ,end)
12. 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. Which of the following is the correct statement to define encoding?
Answers:
a. coding: iso-8859-15
a. # -*- iso-8859-15 -*-
a. # -*- coding: iso-8859-15 -*-
a. None of these
13. How can a null object be declared in Python?
Answers:
a. none
a. None
a. null
a. Null
14. Which of the following modules lets you check whether two files are identical, and whether two directories contain some identical files?
Answers:
a. dircomp
a. filecompare
a. filecmp
a. structcomp
15. Which function could be used to list every file and folder in the current directory?
Answers:
a. os.dirnames(‘.’)
a. os.listdir(‘.’)
a. os.listdir(‘/’)
a. os.ls()
16. 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?
Answers:
a. MimeWriter
a. mimify
a. Both MimeWriter and mimify
a. Neither MimeWriter nor mimify
17. Which of the following is the correct prototype for the ‘open’ function of the file class in python 2.2+?
Answers:
a. open(fname [,mode [,buffering]])
a. open(fname [,buffering [,mode]])
a. open(fname [,mode])
a. open(fname,mode,buffering)
a. open(fname,buffering,mode)
a. None of these
18. Which user input method will act like a file-object on which read and readline functions can be called?
Answers:
a. sys.stdin
a. raw_input()
a. input()
a. sys.argv
19. Which of the following protocol libraries can be used for an email implementation in a Python application?
Answers:
a. telnetlib
a. smtplib
a. ftplib
a. None of these
20. Which of the following statements imports every name in a module namespace into the current namespace?
Answers:
a. from modname import All
a. from modname import *
a. from modname import ?
a. from modname import All as *
21. Which is the correct way to remove an installed Python package?
Answers:
a. easy_install -v a. pip uninstall
a. easy_install -u a. pip -m 22. 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?
Answers:
a. try: code to be verified will come here exception :
a. try: code to be verified will come here except :
a. try: code to be verified will come here exception:
a. try: code to be verified will come here exception :
23. Which of the following is the correct way to get the size of a list in Python?
Answers:
a. list.length()
a. len(list)
a. sizeof(list)
a. list.size()
24. What will be the output of the following statements:
>>> import string
>>> string.ljust(width=30,s=”Mary had a little lamb”)
Answers:
a. ‘Mary had a little lamb ‘
a. ‘Mary had a little lamb’
a. ‘ Mary had a little lamb’
a. None of these
25. 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?
Answers:
a. email.Message
a. email.message.Message
a. email.messages
a. email.emailmessage
26. Consider the function:
>>> string.ljust(width=30,s=”Mary had a little lamb”)
Answers:
a. ‘Mary had a little lamb ‘
a. ‘Mary had a little lamb’
a. ‘ Mary had a little lamb’
a. None of these
25. 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?
Answers:
a. email.Message
a. email.message.Message
a. email.messages
a. email.emailmessage
26. Consider the function:
def hello():
return “Hello, world!”
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!#”?
Answers:
a. def hello(): return “#Hello, world!#”
a. def hashes(fn): def wrapped(): return “#” + fn() + “#” return wrapped @hashes def hello(): return “Hello, world!”
a. def hashes(fn): def wrapped(): return “#” + “#” return wrapped @hashes def hello(): return “Hello, world!”
a. def hashes(fn): def wrapped(): print “#” + fn() + “#” return @hashes def hello(): return “Hello, world!”
27. Object is the base class of new-style datatypes. Which of the following functions is not a member of the object class?
Answers:
a. object.__eq__(self, other)
a. object.__notequal__(self, other)
a. object.__repr__(self)
a. None of these
28. Which of the following modules keep prior directory listings in the memory to avoid the need for a new call to the file system?
Answers:
a. sys
a. FileSys
a. dirsys
a. dircache
29. Which of the following modules is used internally to determine whether a path matches?
Answers:
a. dircmp
a. filecompare
a. fncmp
a. fnmatch
30. Examine the following prototype for the ‘open’ function of the file class in Python 2.2+:
Answers:
a. def hello(): return “#Hello, world!#”
a. def hashes(fn): def wrapped(): return “#” + fn() + “#” return wrapped @hashes def hello(): return “Hello, world!”
a. def hashes(fn): def wrapped(): return “#” + “#” return wrapped @hashes def hello(): return “Hello, world!”
a. def hashes(fn): def wrapped(): print “#” + fn() + “#” return @hashes def hello(): return “Hello, world!”
27. Object is the base class of new-style datatypes. Which of the following functions is not a member of the object class?
Answers:
a. object.__eq__(self, other)
a. object.__notequal__(self, other)
a. object.__repr__(self)
a. None of these
28. Which of the following modules keep prior directory listings in the memory to avoid the need for a new call to the file system?
Answers:
a. sys
a. FileSys
a. dirsys
a. dircache
29. Which of the following modules is used internally to determine whether a path matches?
Answers:
a. dircmp
a. filecompare
a. fncmp
a. fnmatch
30. 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?
Answers:
a. 0 for none
a. 1 for line oriented
a. An integer larger than 1 for number of bytes
a. All of these
31. Which of the following statements copy the contents of a list and not just a reference to the list?
Answers:
a. newlist = oldlist
a. newlist = oldlist[:]
a. newlist = oldlist(dummy)
a. None of these
32. Which of the following functions is used to send audio data via the Internet?
Answers:
a. email.MIMEAudio(audiodata [,subtype [,encoder [,**params]]])
a. email.SendAudio(audiodata [,subtype [,encoder [,**params]]])
a. email.MIMEAudio.MIMEAudio(audiodata [,subtype [,encoder [,**params]]])
a. email.MIMEAudio.SendAudio(audiodata [,subtype [,encoder [,**params]]])
33. Read the following statements:
Answers:
a. 0 for none
a. 1 for line oriented
a. An integer larger than 1 for number of bytes
a. All of these
31. Which of the following statements copy the contents of a list and not just a reference to the list?
Answers:
a. newlist = oldlist
a. newlist = oldlist[:]
a. newlist = oldlist(dummy)
a. None of these
32. Which of the following functions is used to send audio data via the Internet?
Answers:
a. email.MIMEAudio(audiodata [,subtype [,encoder [,**params]]])
a. email.SendAudio(audiodata [,subtype [,encoder [,**params]]])
a. email.MIMEAudio.MIMEAudio(audiodata [,subtype [,encoder [,**params]]])
a. email.MIMEAudio.SendAudio(audiodata [,subtype [,encoder [,**params]]])
33. 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 global is bound to the global (module-level) namespace.
Statement 2: A name declared as global is bound to the global (module-level) namespace.
Which of the following is correct?
Answers:
a. Statement 1 is true, but statement 2 is false.
a. Statement 2 is true, but statement 1 is false.
a. Both statements are true.
a. Both statements are false.
34. Which of the following commands would produce the following result:
result: ‘line 1\nline 2’
Answers:
a. result = ‘\nline 1\nline 2\n’.rstrip()
a. result = ‘\nline 1\nline 2\n’.split()
a. result = ‘\nline 1\nline 2\n’.strip()
a. result = ‘\nline 1\nline 2\n’.lstrip()
a. result = ‘\nline 1\nline 2\n’.splitlines()
35. Which is not used to install Python packages?
Answers:
a. easy_install
a. pip
a. distribute
a. installtools
36. Which of the following exceptions occurs while importing a module?
Answers:
a. ModuleError
a. ImportError
a. ImportModuleError
a. ReferenceError
37. Which of the following statements can be used to remove an item from a list by giving the index?
Answers:
a. remove listname[index]
a. del listname[index]
a. kill listname[index]
a. None of these
38. Read the following statements:
Answers:
a. Statement 1 is true, but statement 2 is false.
a. Statement 2 is true, but statement 1 is false.
a. Both statements are true.
a. Both statements are false.
34. Which of the following commands would produce the following result:
result: ‘line 1\nline 2’
Answers:
a. result = ‘\nline 1\nline 2\n’.rstrip()
a. result = ‘\nline 1\nline 2\n’.split()
a. result = ‘\nline 1\nline 2\n’.strip()
a. result = ‘\nline 1\nline 2\n’.lstrip()
a. result = ‘\nline 1\nline 2\n’.splitlines()
35. Which is not used to install Python packages?
Answers:
a. easy_install
a. pip
a. distribute
a. installtools
36. Which of the following exceptions occurs while importing a module?
Answers:
a. ModuleError
a. ImportError
a. ImportModuleError
a. ReferenceError
37. Which of the following statements can be used to remove an item from a list by giving the index?
Answers:
a. remove listname[index]
a. del listname[index]
a. kill listname[index]
a. None of these
38. Read the following statements:
>>> word = ‘Help’ + ‘A’
>>> ‘<‘ + word*5 + ‘>’
>>> ‘<‘ + word*5 + ‘>’
Which of the following will be the output of the above code snippet?
Answers:
a. ”
a. ”
a. ‘<HelpA*5>’
a. An error
a. None of these
39. The least sophisticated form of text output in Python is writing to open files. In particular, which of the following streams can be used?
Answers:
a. STDOUT
a. STDERR
a. STDPRN
a. STDFIL
40. Which of the following options are true regarding these two code samples?
Answers:
a. ”
a. ”
a. ‘<HelpA*5>’
a. An error
a. None of these
39. The least sophisticated form of text output in Python is writing to open files. In particular, which of the following streams can be used?
Answers:
a. STDOUT
a. STDERR
a. STDPRN
a. STDFIL
40. 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()
def main():
for i in xrange(10**8):
pass
main()
Code sample 2:
for i in xrange(10**8):
pass
Answers:
a. 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.
a. 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.
a. 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.
a. None of these.
41. How many arguments can a print statement handle?
Answers:
a. One
a. Any number of string arguments only
a. Any number of numeric arguments only
a. Any number of string or numeric arguments
42. When is the “yield” keyword used in Python?
Answers:
a. When other processes need to take precedence over the Python script
a. To break out of a loop
a. When a function needs to return a list that only needs to be read through once
a. Never
43. What is the best way to check if the object ‘myobject’ is iterable in Python?
Answers:
a. myobject.isIter()
a. try: [ e for e in myobject] except TypeError: print myobject, ‘is not iterable’
a. try: iter.myobject except: print myobject, ‘is not iterable’
a. if [ e for e in myobject]: print myobject, ‘is iterable’ else: print myobject, ‘is not iterable’
44. In Python, built-in exceptions can be inherited from. Which of the following is the base exception class?
Answers:
a. Exceptions
a. BaseException
a. Exception
a. Except
45. 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?
Answers:
a. d = os.path.dirname(“/temp_files”) if not os.path.exists(d): os.makedirs(d)
a. d = os.path(“/temp_files”) if not os.path(d): os.makedirs(d)
a. d = os.path.dirname(“/temp_files”) if os.path.exists(d): os.makedirs(d)
a. if not os.path.exists(“/temp_files”): os.makedirs(d)
46. Read the following statements:
for i in xrange(10**8):
pass
Answers:
a. 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.
a. 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.
a. 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.
a. None of these.
41. How many arguments can a print statement handle?
Answers:
a. One
a. Any number of string arguments only
a. Any number of numeric arguments only
a. Any number of string or numeric arguments
42. When is the “yield” keyword used in Python?
Answers:
a. When other processes need to take precedence over the Python script
a. To break out of a loop
a. When a function needs to return a list that only needs to be read through once
a. Never
43. What is the best way to check if the object ‘myobject’ is iterable in Python?
Answers:
a. myobject.isIter()
a. try: [ e for e in myobject] except TypeError: print myobject, ‘is not iterable’
a. try: iter.myobject except: print myobject, ‘is not iterable’
a. if [ e for e in myobject]: print myobject, ‘is iterable’ else: print myobject, ‘is not iterable’
44. In Python, built-in exceptions can be inherited from. Which of the following is the base exception class?
Answers:
a. Exceptions
a. BaseException
a. Exception
a. Except
45. 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?
Answers:
a. d = os.path.dirname(“/temp_files”) if not os.path.exists(d): os.makedirs(d)
a. d = os.path(“/temp_files”) if not os.path(d): os.makedirs(d)
a. d = os.path.dirname(“/temp_files”) if os.path.exists(d): os.makedirs(d)
a. if not os.path.exists(“/temp_files”): os.makedirs(d)
46. Read the following statements:
>>> lst = [‘spam’,’and’,’eggs’]
>>> lst[2] = ‘toast’
>>> print ”.join(lst)
>>> print ‘ ‘.join(lst)
>>> lst[2] = ‘toast’
>>> print ”.join(lst)
>>> print ‘ ‘.join(lst)
Which of the following is the output of the second print statement in the above code snippet?
Answers:
a. spam and eggs
a. spamandeggs
a. spamandtoast
a. spam and toast
47. Read the following statements:
Answers:
a. spam and eggs
a. spamandeggs
a. spamandtoast
a. spam and toast
47. Read the following statements:
>>> import string
>>> s = ‘mary\011had a little lamb’
>>> print s
>>> s = ‘mary\011had a little lamb’
>>> print s
Which of the following will be the output of the above code snippet?
Answers:
a. mary had a little lamb
a. mary\011 had a little lamb
a. mary had a little lamb
a. mary\011had a little lamb
48. Read the following statements:
Answers:
a. mary had a little lamb
a. mary\011 had a little lamb
a. mary had a little lamb
a. mary\011had a little lamb
48. 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 string module.
Statement 2: To use string object methods, there is no need to import the string module.
Which of the following is correct?
Answers:
a. Statement 1 is true, but statement 2 is false.
a. Statement 2 is true, but statement 1 is false.
a. Both statements are true.
a. Both statements are false.
49. 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])
Answers:
a. A dictionary sorted by the second element.
a. A list of Tuples sorted by the second element.
a. A list of dictionaries sorted by the first element.
a. A dictionary sorted by the first element.
a. A list of Tuples sorted by the first element.
50. 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?
Answers:
a. base
a. object
a. dict
a. custom
a. None of these
51. How can a list be split into equal sized chunks?
Answers:
a. f = lambda x, n, acc=[]: f(x[n:], n, acc+[(x[:n])]) if x else acc
a. def chunks(l, n): for i in xrange(0, len(l), n): yield l[i:i+n]
a. 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
a. chunks = lambda l, n: [l[x: x+n] for x in xrange(0, len(l), n)] chunks(l, 10)
52. 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?
Answers:
a. 1
a. 2
a. 7
a. Any number
53. Which of the following is the best way to reverse the string ‘Test String’ in Python?
Answers:
a. string.reverse(‘Test String’)
a. ‘Test String'[::-1]
a. reversed(‘Test String’)
a. ‘Test String'[-1:0]
54. What is the result of the following code:
>>> import itertools
>>> x = itertools.count(0)
>>> x.__class__.__name__
Answers:
a. Nothing
a. ‘count’
a. ‘Object’
a. ‘None’
55. What is the most flexible way to call the external command “ls -l” in Python?
Answers:
a. from subprocess import call call([“ls”, “-l”])
a. from subprocess import call call(“ls -l”)
a. os.system(“ls -l”)
a. os.system([“ls”], [“-l”])
56. Which of the following is the correct method for changing a global variable inside a function?
Answers:
a. def change_globvar(): globvar = 1
a. def change_globvar(): global globvar globvar = 1
a. def change_globvar(): import globvar globvar = 1
a. def change_globvar(): global globvar = 1
57. Which list flattening method will have the shortest running time?
Answers:
a. l = [ [1, 2, 3], [4, 5, 6], [7], [8, 9] ] * 99 import itertools list( itertools.chain.from_iterable( l ) )
a. l = [ [1, 2, 3], [4, 5, 6], [7], [8, 9] ] * 99 reduce( lambda x, y: x + y, l )
a. l = [ [1, 2, 3], [4, 5, 6], [7], [8, 9] ] * 99 sum( l, [ ] )
a. l = [ [1, 2, 3], [4, 5, 6], [7], [8, 9] ] * 99 [ item for sublist in l for item in sublist ]
58. Which of the following is the correct way to flush output of Python print?
Answers:
a. import sys sys.stdout.flush()
a. 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)
a. import sys sys.stdout = os.fdopen(sys.stdout.fileno(), ‘w’, 0)
a. Running python with the -u command-line switch
59. 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’
Answers:
a. import re indices = [occurance.start() for occurance in re.finditer(word, line)]
a. 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))
a. indices = [i – 1 for i in range(len(line)) if line.startswith(word, i – 1)]
a. None of these
60. In Python 2.x, which of the following is the way to check to make sure that the variable ‘x’ is not a string?
Answers:
a. assert isinstance(x, basestring)
a. assert not isinstance(x, basestring)
a. assert not instance(x, basestring)
a. assert not x.isinstance(basestring)
61. Which of the following will throw an exception in Python?
Answers:
a. call Exception(“Here is an Exception!”)
a. throw Exception(“Here is an Exception!”)
a. raise Exception(“Here is an Exception!”)
a. create Exception(“Here is an Exception!”)
62. Which of the following functions modifies the list in place to indicate which items are directories, and which are plain files?
Answers:
a. dircache.listdir(path, lst)
a. dircache.annotate(path, lst)
a. dircache.filter(path, lst)
a. dircache.scan(path, lst)
63. Which Python module can be used for copying files?
Answers:
a. util
a. shutil
a. copy
a. filecopy
64. Which of the following statements are true?
Answers:
a. Statement 1 is true, but statement 2 is false.
a. Statement 2 is true, but statement 1 is false.
a. Both statements are true.
a. Both statements are false.
49. 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])
Answers:
a. A dictionary sorted by the second element.
a. A list of Tuples sorted by the second element.
a. A list of dictionaries sorted by the first element.
a. A dictionary sorted by the first element.
a. A list of Tuples sorted by the first element.
50. 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?
Answers:
a. base
a. object
a. dict
a. custom
a. None of these
51. How can a list be split into equal sized chunks?
Answers:
a. f = lambda x, n, acc=[]: f(x[n:], n, acc+[(x[:n])]) if x else acc
a. def chunks(l, n): for i in xrange(0, len(l), n): yield l[i:i+n]
a. 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
a. chunks = lambda l, n: [l[x: x+n] for x in xrange(0, len(l), n)] chunks(l, 10)
52. 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?
Answers:
a. 1
a. 2
a. 7
a. Any number
53. Which of the following is the best way to reverse the string ‘Test String’ in Python?
Answers:
a. string.reverse(‘Test String’)
a. ‘Test String'[::-1]
a. reversed(‘Test String’)
a. ‘Test String'[-1:0]
54. What is the result of the following code:
>>> import itertools
>>> x = itertools.count(0)
>>> x.__class__.__name__
Answers:
a. Nothing
a. ‘count’
a. ‘Object’
a. ‘None’
55. What is the most flexible way to call the external command “ls -l” in Python?
Answers:
a. from subprocess import call call([“ls”, “-l”])
a. from subprocess import call call(“ls -l”)
a. os.system(“ls -l”)
a. os.system([“ls”], [“-l”])
56. Which of the following is the correct method for changing a global variable inside a function?
Answers:
a. def change_globvar(): globvar = 1
a. def change_globvar(): global globvar globvar = 1
a. def change_globvar(): import globvar globvar = 1
a. def change_globvar(): global globvar = 1
57. Which list flattening method will have the shortest running time?
Answers:
a. l = [ [1, 2, 3], [4, 5, 6], [7], [8, 9] ] * 99 import itertools list( itertools.chain.from_iterable( l ) )
a. l = [ [1, 2, 3], [4, 5, 6], [7], [8, 9] ] * 99 reduce( lambda x, y: x + y, l )
a. l = [ [1, 2, 3], [4, 5, 6], [7], [8, 9] ] * 99 sum( l, [ ] )
a. l = [ [1, 2, 3], [4, 5, 6], [7], [8, 9] ] * 99 [ item for sublist in l for item in sublist ]
58. Which of the following is the correct way to flush output of Python print?
Answers:
a. import sys sys.stdout.flush()
a. 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)
a. import sys sys.stdout = os.fdopen(sys.stdout.fileno(), ‘w’, 0)
a. Running python with the -u command-line switch
59. 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’
Answers:
a. import re indices = [occurance.start() for occurance in re.finditer(word, line)]
a. 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))
a. indices = [i – 1 for i in range(len(line)) if line.startswith(word, i – 1)]
a. None of these
60. In Python 2.x, which of the following is the way to check to make sure that the variable ‘x’ is not a string?
Answers:
a. assert isinstance(x, basestring)
a. assert not isinstance(x, basestring)
a. assert not instance(x, basestring)
a. assert not x.isinstance(basestring)
61. Which of the following will throw an exception in Python?
Answers:
a. call Exception(“Here is an Exception!”)
a. throw Exception(“Here is an Exception!”)
a. raise Exception(“Here is an Exception!”)
a. create Exception(“Here is an Exception!”)
62. Which of the following functions modifies the list in place to indicate which items are directories, and which are plain files?
Answers:
a. dircache.listdir(path, lst)
a. dircache.annotate(path, lst)
a. dircache.filter(path, lst)
a. dircache.scan(path, lst)
63. Which Python module can be used for copying files?
Answers:
a. util
a. shutil
a. copy
a. filecopy
64. 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 access.
C. .__variable__ is typically reserved for built-in methods or variables.
Answers:
a. A
a. B
a. C
a. A, B, and C
65. How can an element be removed from a list using its list index?
Answers:
a. myList.remove(index)
a. pop myList[index]
a. del myList[index]
a. myList.delete(index)
66. Which of the following is the correct way to check to see if the variable theVar is an integer?
Answers:
a. isinstance(theVar, int)
a. theVar.isinstance(int)
a. int.isinstance(theVar)
a. is(theVar, int)
67. Which of the following is the base class for new-style file objects?
Answers:
a. base
a. file
a. fileobject
a. filebase
68. Which of the following methods returns the ASCII value of a character in Python?
Answers:
a. ascii
a. ord
a. asciicode
a. None of these
69. What is the output of the following code:
B. .__variable is considered superprivate and gets name mangled to prevent accidental access.
C. .__variable__ is typically reserved for built-in methods or variables.
Answers:
a. A
a. B
a. C
a. A, B, and C
65. How can an element be removed from a list using its list index?
Answers:
a. myList.remove(index)
a. pop myList[index]
a. del myList[index]
a. myList.delete(index)
66. Which of the following is the correct way to check to see if the variable theVar is an integer?
Answers:
a. isinstance(theVar, int)
a. theVar.isinstance(int)
a. int.isinstance(theVar)
a. is(theVar, int)
67. Which of the following is the base class for new-style file objects?
Answers:
a. base
a. file
a. fileobject
a. filebase
68. Which of the following methods returns the ASCII value of a character in Python?
Answers:
a. ascii
a. ord
a. asciicode
a. None of these
69. What is the output of the following code:
name = ‘Jon’
name.rjust(4, ‘A’)
Answers:
a. ‘Jon A’
a. ‘A Jon’
a. ‘AJon’
a. ‘JonA’
70. Which of the following is a way to find a local computer’s IP address with Python?
Answers:
a. import socket socket.gethostbyname(socket.gethostname())
a. socket.gethostbyname(socket.gethostname())
a. import socket gethostbyname(socket.gethostname())
a. import ifconfig print (ifconfig -a)
71. What is a metaclass in Python?
Answers:
a. A class that is inherited from
a. A class that inherits from another class
a. Something that can be attached to any class, that gives it a constant set of attributes
a. Something that creates “class” objects
72. Which of the following is the correct way to call the private method, myPrivateMethod(), in class MyClass, using dir(obj)?
name.rjust(4, ‘A’)
Answers:
a. ‘Jon A’
a. ‘A Jon’
a. ‘AJon’
a. ‘JonA’
70. Which of the following is a way to find a local computer’s IP address with Python?
Answers:
a. import socket socket.gethostbyname(socket.gethostname())
a. socket.gethostbyname(socket.gethostname())
a. import socket gethostbyname(socket.gethostname())
a. import ifconfig print (ifconfig -a)
71. What is a metaclass in Python?
Answers:
a. A class that is inherited from
a. A class that inherits from another class
a. Something that can be attached to any class, that gives it a constant set of attributes
a. Something that creates “class” objects
72. 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 Method”
def __myPrivateMethod(self):
print “Private Method”
obj = MyClass()
print dir(obj)
Answers:
a. __myPrivateMethod
a. _MyClass__myPrivateMethod
a. myPrivateMethod
a. A private method will not be shown in the output.
73. What is the output of the following code?
print dir(obj)
Answers:
a. __myPrivateMethod
a. _MyClass__myPrivateMethod
a. myPrivateMethod
a. A private method will not be shown in the output.
73. What is the output of the following code?
def foo(param1, *param2):
print param1
print param2
print param1
print param2
def bar(param1, **param2):
print param1
print param2
print param1
print param2
foo(1,2,3,4,5)
bar(1,a=2,b=3)
Answers:
a. TypeError: foo() got multiple values for keyword argument ‘param1’
a. 1 (2, 3, 4, 5) 1 (2, 3)
a. 1 (2, 3, 4, 5) 1 {‘a’: 2, ‘b’: 3}
a. 1 {2, 3, 4, 5} 1 (‘a’: 2, ‘b’: 3)
74. 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?
Answers:
a. import subprocess subprocess.call(‘C:\\Temp\\a b c\\Notepad.exe’, ‘C:\\test.txt’)
a. os.call([‘C:\\Temp\\a b c\\Notepad.exe’, ‘C:\\test.txt’])
a. import subprocess subprocess.call([‘C:\\Temp\\a b c\\Notepad.exe’, ‘C:\\test.txt’])
a. subprocess.call([‘C:\\Temp\\a b c\\Notepad.exe’, ‘C:\\test.txt’])
75. What is the correct way to delete a directory that is not empty using Python?
Answers:
a. os.remove(‘/directory’)
a. os.rmtree(‘/directory’)
a. shutil.rmtree(‘/directory’)
a. import shutil shutil.rmtree(‘/directory’)
76. Which of the following is the correct way to write a generator which will output the numbers between 1 and 100 (inclusive)?
Answers:
a. def onehundred(start, end): current = start while current <= end: yield current current += 1 for x in onehundred(1, 100): print x
a. def onehundred(start, end): current = start while current <= end: return current current += 1 for x in onehundred(1, 100): print x
a. def onehundred(start, end): current = start while current <= end: yield current current += 2 for x in onehundred(1, 100): print x
a. def onehundred(start, end): while current <= end: yield current current += 1 for x in onehundred(1, 100): print x
77. 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]?
Answers:
a. a_list + a_tuple
a. a_list.extend(a_tuple)
a. a_list.append(a_tuple)
a. a_list.append(*a_tuple)
78. Which of the following will determine the number of CPUs available in the operating environment?
Answers:
a. import os os..cpu_count()
a. import sys sys..cpu_count()
a. import psutil sutil.NUM_CPUS
a. import multiprocessing multiprocessing.cpu_count()
bar(1,a=2,b=3)
Answers:
a. TypeError: foo() got multiple values for keyword argument ‘param1’
a. 1 (2, 3, 4, 5) 1 (2, 3)
a. 1 (2, 3, 4, 5) 1 {‘a’: 2, ‘b’: 3}
a. 1 {2, 3, 4, 5} 1 (‘a’: 2, ‘b’: 3)
74. 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?
Answers:
a. import subprocess subprocess.call(‘C:\\Temp\\a b c\\Notepad.exe’, ‘C:\\test.txt’)
a. os.call([‘C:\\Temp\\a b c\\Notepad.exe’, ‘C:\\test.txt’])
a. import subprocess subprocess.call([‘C:\\Temp\\a b c\\Notepad.exe’, ‘C:\\test.txt’])
a. subprocess.call([‘C:\\Temp\\a b c\\Notepad.exe’, ‘C:\\test.txt’])
75. What is the correct way to delete a directory that is not empty using Python?
Answers:
a. os.remove(‘/directory’)
a. os.rmtree(‘/directory’)
a. shutil.rmtree(‘/directory’)
a. import shutil shutil.rmtree(‘/directory’)
76. Which of the following is the correct way to write a generator which will output the numbers between 1 and 100 (inclusive)?
Answers:
a. def onehundred(start, end): current = start while current <= end: yield current current += 1 for x in onehundred(1, 100): print x
a. def onehundred(start, end): current = start while current <= end: return current current += 1 for x in onehundred(1, 100): print x
a. def onehundred(start, end): current = start while current <= end: yield current current += 2 for x in onehundred(1, 100): print x
a. def onehundred(start, end): while current <= end: yield current current += 1 for x in onehundred(1, 100): print x
77. 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]?
Answers:
a. a_list + a_tuple
a. a_list.extend(a_tuple)
a. a_list.append(a_tuple)
a. a_list.append(*a_tuple)
78. Which of the following will determine the number of CPUs available in the operating environment?
Answers:
a. import os os..cpu_count()
a. import sys sys..cpu_count()
a. import psutil sutil.NUM_CPUS
a. import multiprocessing multiprocessing.cpu_count()
No comments:
Post a Comment