=====List=====
What will be the output of the following Python code?
def f(i, values = []):
values.append(i)
return values
f(1)
f(2)
v = f(3)
print(v)
[1, 2, 3]
What will be the output of the following Python code?
names1 = ['Amir', 'Bala', 'Chales']
if 'amir' in names1: print(1)
else:
print(2)
2
What will be the output of the following Python code?
names1 = ['Amir', 'Bala', 'Charlie']
names2 = [name.lower() for name in names1]
print(names2[2][0])
c
What will be the output of the following Python code?
numbers = [1, 2, 3, 4]
numbers.append([5,6,7,8])
print(len(numbers))
5
To which of the following the “in” operator can be used to check if an item is in it?
a) Lists
b) Dictionary
c) Set
d) All of the mentioned
All of the mentioned
What will be the output of the following Python code?
list1 = [1, 2, 3, 4]
list2 = [5, 6, 7, 8]
print(len(list1 + list2))
8
What will be the output of the following Python code?
def addItem(listParam):
listParam += [1]
mylist = [1, 2, 3, 4]
addItem(mylist)
print(len(mylist))
5
- What will be the output of the following Python code?
def increment_items(L, increment):
i=0
while i < len(L):
L[i] = L[i] + increment i=i+1
values = [1, 2, 3]
print(increment_items(values, 2))
print(values)
None
[3, 4, 5]
What will be the output of the following Python code?
def example(L): i=0
result = []
while i < len(L):
result.append(L[i])
i=i+3
return result
a) Return a list containing every third item from L starting at index 0
b) Return an empty list
c) Return a list containing every third index from L starting at index 0
d) Return a list containing the items from L starting from index 0, omitting every third item
A
What will be the output of the following Python code?
veggies = ['carrot', 'broccoli', 'potato', 'asparagus']
veggies.insert(veggies.index('broccoli'), 'celery')
print(veggies)
[‘carrot’, ‘celery’, ‘broccoli’, ‘potato’, ‘asparagus’]
Programming Question
- Write a function that returns the index of the smallest element in a list of integers. If the number of such elements is greater than 1, return the smallest index.
参考答案
def indexOfSmallestElement(lst):
sml = 0
for index in range(lst):
if lst[index] < lst[sml]:
sml = index
return sml
2.
Given the list of student homework grades
grades = [9, 7, 7, 10, 3, 9, 6, 6, 2]
write:
(a) An expression that evaluates to the number of 7 grades
(b) A statement that changes the last grade to 4
(c) An expression that evaluates to the maximum grade
(d) A statement that sorts the list grades
(e) An expression that evaluates to the average grade
参考答案
(a) grades.count(7)
(b) grades[-1] = 4
(c) max(grades)
(d) grades.sort()
(e) sum(grades) / len(grades)
3.
Write a function showResult() that given a list of grades and get the counts the occurrences of each in ascending order. And print out the max grade and the class average.Here is a sample run of the program:
grades = [9, 7, 7, 10, 3, 9, 6, 6, 2]
showResult(grades)
2 students got 2 marks
1 student got 3 makrs
2 students got 6 marks
2 students got 7 marks
2 students got 9 marks
1 student got 10 mark
Max mark is 10
Average is 6.555555555555555
参考答案
def showResult(grades):
grades.sort()
m = 0
s = 0
lst = []
for i in range(len(grades)):
print(i)
grade = grades[i]
m = max(m, grade)
s = s + grade
if not (grade in lst):
count = grades.count(grades[i])
prefix = ''
if count == 1:
prefix = ' student got '
else:
prefix = ' students got '
marks = ''
if grade == 1:
marks = ' mark'
else:
marks = ' marks'
print(count, prefix, grade, marks)
lst.append(grade)
print('The max mark is ', m)
print('The average is ', sum / len(lst))
Write a function printPositive() that takes a 2D list as input which consists of numbers. The function returns nothing and prints only the positive numbers from the 2D list.
For example:
lst = [[-1, 0 , 8, 4, -5],[ 3, 5, 9, -4, 0],[ 1, 4, 8, 7, 2],[ 6, 7, -4, -8, 3]]
printPositive(lst)
0 8 4
3 5 9 0
1 4 8 7 2
6 7 3
参考答案
def printPositive(m):
for i in range(len(m)):
for j in range(len(m[0])):
if m[i][j] >= 0:
print(m[i][j], end = ' ')
print()
Write a function sumMatrix() that takes a 2D list as input and calculate the Sum of all the elements
For example:
lst = [[1, 2, 3],
[1, 2, 3],
[1, 2, 3]]
print(sumMatrix(lst))
18
参考答案
def sumMatrix(m):
sum = 0
for i in range(len(m)):
for j in range(len(m[0])):
sum = sum + m[i][j]
return sum
Write a function sumMajorDiagonal() that takes a 2D list as input and calculate the Sum of all the elements
in the major diagonal
For example:
lst = [[1, 2, 3],
[1, 2, 3],
[1, 2, 3]]
print(sumMajorDiagonal(lst))
6
参考答案
def sumMajorDiagonal(m):
sum = 0
for i in range(len(m)):
for j in range(len(m[0])):
sum = sum + m[i][j]
return sum
=====Loop======
What will be the output of the following Python code?
x = 123
for i in x:
print(i)
a) 1 2 3
b) 123
c) error
d) none of the mentioned
What will be the output of the following Python code?
d = {0: 'a', 1: 'b', 2: 'c'} for i in d:
print(i)
a) 0 1 2
b) a b c
c)0a 1b 2c
d) none of the mentioned
What will be the output of the following Python code?
d = {0: 'a', 1: 'b', 2: 'c'}
for x, y in d:
print(x, y)
a) 0 1 2
b) a b c
c)0a 1b 2c
d) none of the mentioned
What will be the output of the following Python code?
d = {0: 'a', 1: 'b', 2: 'c'}
for x, y in d.items():
print(x, y)
a) 0 1 2
b) a b c
c)0a 1b 2c
d) none of the mentioned
What will be the output of the following Python code?
d = {0: 'a', 1: 'b', 2: 'c'} for x in d.keys():
print(d[x])
a) 0 1 2
b) a b c
c)0a 1b 2c
d) none of the mentioned
What will be the output of the following Python code?
d = {0: 'a', 1: 'b', 2: 'c'}
for x in d.values():
print(x)
a) 0 1 2
b) a b c
c)0a 1b 2c
d) none of the mentioned
What will be the output of the following Python code?
d = {0: 'a', 1: 'b', 2: 'c'}
for x in d.values():
print(d[x])
a) 0 1 2
b) a b c
c)0a 1b 2c
d) none of the mentioned
What will be the output of the following Python code?
d = {0, 1, 2}
for x in d.values():
print(x)
a) 0 1 2
b) None None None
c) error
d) none of the mentioned
What will be the output of the following Python code?
d = {0, 1, 2}
for x in d:
print(x)
a) 0 1 2
b) {0, 1, 2} {0, 1, 2} {0, 1, 2}
c) error
d) none of the mentioned
What will be the output of the following Python code?
d = {0, 1, 2}
for x in d:
print(d.add(x))
a) 0 1 2
b) 0 1 2 0 1 2 0 1 2 ...
c) None None None
d) None of the mentioned
What will be the output of the following Python code?
for i in range(0):
print(i)
a) 0
b) no output
c) error
loop solution: 1. C 2.A 3.D 4.C 5.B 6.B 7.D 8.C 9.A 10.C 11.B
Programming Question
num_list = [1, 5, 3, 5, 6, 8, 2, 5, 9, 5]
What does the command num_list.count(5) display?
Implement the built in function with own implementation of a function named count given a list and a number
find the first encounter index of number in the list, return -1 if not found
[color]The answer is 1 since the first encounter of 5 is in index 1[/color]
def count(list, number):
for i in range(len(list)):
if list[i] == number:
return i
return -1
Which of the following will give the sum of the elements in the list?
A) sum(num_list)
B) num_list.sum()
C) sum.num_list()
D) None of the above
Implement the built in function with own implementation of a function named sum given a list and return the sum of the list numbers
[color]The answer is A[/color]
def sum(list):
result = 0
for num in list:
result = result + num
return result
Implement function isPrime() that takes a positive integer as input and returns True
if it is a prime number and False otherwise.
def isPrime(n):
start = 2
for i in range(start, n):
if n % i == 0:
return False
return True
Use the isPrime() function to Implement a function called printPrimes() that takes a positive integer and print all the prime numbers within 2 and n [2, n) and return the last prime number within the range
def printPrimes(n):
start = 2
prime = 2
for i in range(start, n):
if isPrime(i):
prime = i
print(prime)
return prime
=====String=====
This set of Python Coding Questions & Answers focuses on “Strings”. 1. What is “Hello”.replace(“l”, “e”)?
a) Heeeo
b) Heelo
c) Heleo
d) None
To retrieve the character at index 3 from string s=”Hello” what command do we execute (multiple answers allowed)?
a) s[]
b) s.getitem(3)
c) s.getitem(3)
d) s.getItem(3)
To return the length of string s what command do we execute?
a) s.len()
b) len(s)
c) size(s)
d) s.size()
If a class defines the str(self) method, for an object obj for the class, you can use which command to invoke the str method.
a) obj.str()
b) str(obj)
c) print obj
d) all of the mentioned
To check whether string s1 contains another string s2, use ________
a) s1.contains(s2)
b) s2 in s1
c) s1.contains(s2)
d) si.in(s2)
Suppose i is 5 and j is 4, i + j is same as ________
a) i.add(j)
b) i.add(j)
c) i.Add(j)
d) i.__ADD(j)
What will be the output of the following Python code?
class Count:
def init(self, count = 0):
self.__count = count
c1 = Count(2)
c2 = Count(2)
print(id(c1) == id(c2), end = " ")
s1 = "Good"
s2 = "Good" print(id(s1) == id(s2))
a) True False
b) True True
c) False True
d) False False
What will be the output of the following Python code?
class Name:
def init(self, firstName, mi, lastName):
self.firstName = firstName self.mi = mi self.lastName = lastName
firstName = "John"
name = Name(firstName, 'F', "Smith") firstName = "Peter"
name.lastName = "Pan" print(name.firstName, name.lastName)
a) Peter Pan
b) John Pan
c) Peter Smith
d) John Smith
What function do you use to read a string?
a) input(“Enter a string”)
b) eval(input(“Enter a string”))
c) enter(“Enter a string”)
d) eval(enter(“Enter a string”))
Suppose x is 345.3546, what is format(x, “10.3f”) (_ indicates space).
a) __345.355
b) ___345.355
c) ____345.355
d) _____345.354
Sring solution
1.A 2.C 3.A 4.D 5.A 6.B 7.C 8.B 9.A 10.B
========Dictionaries========
Which of the following statements create a dictionary?
a) d = {}
b) d = {“john”:40, “peter”:45}
c) d = {40:”john”, 45:”peter”}
d) All of the mentioned
What will be the output of the following Python code snippet?
d = {"john":40, "peter":45}
a) “john”, 40, 45, and “peter”
b) “john” and “peter”
c) 40 and 45
d) d = (40:”john”, 45:”peter”)
What will be the output of the following Python code snippet?
d = {"john":40, "peter":45} "john" in d
a) True
b) False
c) None
d) Error
What will be the output of the following Python code snippet?
d1 = {"john":40, "peter":45} d2 = {"john":466, "peter":45} d1 == d2
a) True
b) False
c) None
d) Error
What will be the output of the following Python code snippet?
d1 = {"john":40, "peter":45} d2 = {"john":466, "peter":45} d1 > d2
a) True
b) False
c) Error
d) None
What will be the output of the following Python code snippet?
d = {"john":40, "peter":45} d["john"]
a) 40
b) 45
c) “john”
d) “peter”
Suppose d = {“john”:40, “peter”:45}, to delete the entry for “john” what command do we use?
a) d.delete(“john”:40)
b) d.delete(“john”)
c) del d[“john”]
d) del d(“john”:40)
Suppose d = {“john”:40, “peter”:45}. To obtain the number of entries in dictionary which command do we use?
a) d.size()
b) len(d)
c) size(d)
d) d.len()
What will be the output of the following Python code snippet?
d = {"john":40, "peter":45} print(list(d.keys()))
a) [“john”, “peter”]
b) [“john”:40, “peter”:45]
c) (“john”, “peter”)
d) (“john”:40, “peter”:45)
Suppose d = {“john”:40, “peter”:45}, what happens when we try to retrieve a value using the expression d[“susan”]?
a) Since “susan” is not a value in the set, Python raises a KeyError exception
b) It is executed fine and no exception is raised, and it returns None
c) Since “susan” is not a k
Dictionary
1.D 2.B 3.A 4.B 5.C 6.A 7.C 8.B 9.A 10.C
=============Files=============
To open a file c:\scores.txt for reading, we use _____________
a) infile = open(“c:\scores.txt”, “r”)
b) infile = open(“c:\scores.txt”, “r”)
c) infile = open(file = “c:\scores.txt”, “r”)
d) infile = open(file = “c:\scores.txt”, “r”)
To open a file c:\scores.txt for writing, we use ____________
a) outfile = open(“c:\scores.txt”, “w”)
b) outfile = open(“c:\scores.txt”, “w”)
c) outfile = open(file = “c:\scores.txt”, “w”)
d) outfile = open(file = “c:\scores.txt”, “w”)
To open a file c:\scores.txt for appending data, we use ____________
a) outfile = open(“c:\scores.txt”, “a”)
b) outfile = open(“c:\scores.txt”, “rw”)
c) outfile = open(file = “c:\scores.txt”, “w”)
d) outfile = open(file = “c:\scores.txt”, “w”)
Which of the following statements are true?
a) When you open a file for reading, if the file does not exist, an error occurs
b) When you open a file for writing, if the file does not exist, a new file is created
c) When you open a file for writing, if the file exists, the existing file is overwritten with the new file
d) All of the mentioned
To read two characters from a file object infile, we use ____________
a) infile.read(2)
b) infile.read()
c) infile.readline()
d) infile.readlines()
To read the entire remaining contents of the file as a string from a file object infile, we use
a) infile.read(2)
b) infile.read()
c) infile.readline()
d) infile.readlines()
What will be the output of the following Python code?
f = None
for i in range (5):
with open("data.txt", "w") as f: if i > 2:
break
print(f.closed)
a) True
b) False
c) None
d) Error
To read the next line of the file from a file object infile, we use ____________
a) infile.read(2)
b) infile.read()
c) infile.readline()
d) infile.readlines()
To read the remaining lines of the file from a file object infile, we use ____________
a) infile.read(2)
b) infile.read()
c) infile.readline()
d) infile.readlines()
The readlines() method returns ____________
a) str
b) a list of lines
c) a list of single characters
d) a list of integers
Files
1.B 2.B 3.A 4.D 5.A 6.B 7.A 8.C 9.D 10.B
Programming Question
1.
Implement a Python function find_longest_word() that takes as input
a filename in the current directory and returns the longest word in the specified file.
Let’s assume there is a unique longest word, so you don’t need to worry about tie
breaking. In addition, we assume that the text doesn’t have any punctuation. A sample
run is shown below:
words.txt includes text “I am a student learning Python”
---> find_longest_word("words.txt")
---> learning
参考答案
def find_longest_word(filename):
f = open(fname, 'r')
content = inFile.read()
words = content.split()
longest = ''
for word in words:
if len(word) > len(longest):
longest = word
return longest
2.
The function censor() takes the name of a file (a string) as input. The function should open the file, read it, and then write it into file censored.txt with this modification: Every occurrence of a four-letter word in the file should be replaced with string 'xxxx'.
--> censor('example.txt') File: example.txt
Note that this function produces no output, but it does create file censored.txt in the current folder.
def censor(filename):
f = open(fname, 'r')
content = inFile.read()
words = content.split()
for word in words:
if len(word) == 4:
word = 'xxxx'
f = open('censored.txt', 'w')
for word in words:
f.write(word)