0% found this document useful (0 votes)
16 views11 pages

IF100 Week14 Final-Sample Solutions

The document contains recitation exercises for a programming course, including sample final questions that cover various Python programming concepts such as string manipulation, list operations, functions, and file handling. It also includes tasks to implement functions for prime number checking, password generation, and reading files to process data. Additionally, it features exercises related to calculating Scrabble scores and managing city population data from a file.

Uploaded by

efe.bastug
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views11 pages

IF100 Week14 Final-Sample Solutions

The document contains recitation exercises for a programming course, including sample final questions that cover various Python programming concepts such as string manipulation, list operations, functions, and file handling. It also includes tasks to implement functions for prime number checking, password generation, and reading files to process data. Additionally, it features exercises related to calculating Scrabble scores and managing city population data from a file.

Uploaded by

efe.bastug
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

IF100 – Fall 2024 -2025

Week 14 - Recitation Exercises - Sample Final Questions

1. What are the outputs of the following programs?

a.
words = 'this IS thE IF100 cOUrsE'
print(words.lower())
print(words.replace("IS", 'was'))
print(words.replace("IS", 'was').lower())
print(words.split(" "))
print(words * 2)

this is the if100 course


this was thE IF100 cOUrsE
this was the if100 course
['this', 'IS', 'thE', 'IF100', 'cOUrsE']
this IS thE IF100 cOUrsEthis IS thE IF100 cOUrsE

b.
a = [1, 2]
b = []
b = b + a
b = b + a
a.append(3)
print(b,"\n",a)

[1, 2, 1, 2]
[1, 2, 3]

c.
def fun(x, y, z):
return not((x <= y) and (2 <= z))

print(fun(3,5,1))

True

1
d.
def loopy(x, y):
print('starting loopy:', x, y)
while x < y:
x += 1
y -= 2
print('after loop:', x, y)
return x

x = 1
y = 8
y = loopy(x, y)
print('after first call:', x, y)
loopy(y, x)
print('after second call:', x, y)

starting loopy: 1 8
after loop: 4 2
after first call: 1 4
starting loopy: 4 1
after loop: 4 1
after second call: 1 4

e.
for i in range(-1, 4, 1 ):
for j in range( 0, i, 1 ):
print(i + j )

1
2
3
3
4
5

2
f.
def thing_one (x):
y=0
if x == 1:
y=x
x=2
if x == 2:
y = -x
x=3
elif x == 3:
y=2*x
x=2*y
else:
y=x
print("x = " + str(x))
print("y = " + str(y))

def thing_two (l, v):


for i in range(len(l)):
l[i] += v
v=v-1

#main part
thing_one(7)
thing_one(3)
thing_one(1)
l = [20, 40, 30]
v = 6
thing_two(l, v)
print("l = " + str(l))
print("v = " + str(v))

x = 7
y = 7
x = 12
y = 6
x = 3
y = -2
l = [26, 45, 34]
v = 6

3
2. Write a function (say printPrimes) that takes an integer (say num) as its
only parameter, and prints all the prime numbers between and including 2
and num. While implementing this printPrimes function, assume that you
have a pre-defined function named isPrime, which takes an integer as its
only parameter and returns True if this integer is a prime number, and False
otherwise.

Note: You are not required to implement the isPrime function, you will only
use it.

def printPrimes(num):
for x in range(2,num+1):
if isPrime(x):
print(x)

3. Write a function (say isPrime) that takes an integer (say num) as its only
parameter, and checks whether num is a prime number or not. If it is a prime
number, then this isPrime function will return True; and it will return False
otherwise.

Note: A prime number is a number that is divisible only by itself and 1.


Otherwise, it is a composite number. You may assume that num is a
non-negative integer.

from math import *

def isPrime(num):
if num == 0 or num == 1:
return False
if num == 2:
return True
for x in range(2,ceil(sqrt(num))+1):
if num%x == 0:
return False
return True

Here are the first few prime numbers: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31,
37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109,
113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193,
197, 199, etc.

Note: For x <= num-1, the loop will not be executed!


Note: Can also be range(2,num//2+1) or range(2,num-1)instead of
range(2,ceil(sqrt(num))+1)

4
4. The piece of program below is a partial solution for the following problem:

Write a program that inputs a letter from the user and prints
its position in the alphabet. In this program, you will retrieve
the requested position from a list of lowercase letters. This
list of lowercase letters, in the same sequence with the
alphabet, should be created within a function.

However, the program is incomplete. Complete this program by filling out


the boxes with appropriate expressions so that the program solves the
above problem. You are not allowed to delete, add or update anything in the
program other than what you are going to write in the boxes.

5
5. The piece of program below is a partial solution for the following problem:

Write a function that will randomly generate a password,


made up of a capital letter, followed by 6 small letters and
followed by a digit. This function should return the generated
password.

However, the program is incomplete. Complete this program by filling out


the boxes with appropriate expressions so that the program solves the
above problem. You are not allowed to delete, add or update anything in the
program other than what you are going to write in the boxes.

6
6. Tweets have a maximum length, and so you may want to shorten a message
to make it fit in a single tweet. One way to do that would be to remove the
unnecessary space characters.

Write a program that reads tweets from a file (one tweet per line), removes
the unnecessary spaces, and prints the resulting tweet messages.

You may assume that there are no whitespace characters other than space ('
') in a message.

inFile = open("a.txt")
for line in inFile:
line = line.strip()
myStr = line[0]
for i in range(1,len(line)):
if line[i] != " ":
myStr += line[i]
elif line[i-1] != " ":
myStr += line[i]
print(myStr)
inFile.close()
---
OR
---
inFile = open("a.txt")
for line in inFile:
line = line.strip().split(" ")
myStr = ""
for word in line:
if word != "":
myStr += word + " "
print(myStr[:-1])
inFile.close()

7
7. Write a Python program that prompts for and gets the name of a file in the
current working directory, opens that file for reading, then prints out the file
line by line in the reverse order, i.e. last line first and first line last.

filename = input("Enter the filename: ")


inFile = open(filename, "r")
content = inFile.readlines()
for i in range(len(content)-1,-1,-1):
line = content[i]
print(line[:-1]) # discard \n from the end
inFile.close()

8. Given the following program, what does it do?

courseList = {}
totalEnrollment = 0
courseCnt = int(input("Course Count: "))
for i in range(courseCnt):
courseName = input("Course: ")
enrollment = int(input("Enrollment: "))
totalEnrollment = totalEnrollment + enrollment
courseList[courseName] = enrollment

avgEnrollment = totalEnrollment/courseCnt
print("Average enrollment is ",avgEnrollment)

for course in courseList:


if courseList[course] > avgEnrollment:
print(course)

Displays those courses with above average enrollment

8
9. In the game of ScrabbleTM, each letter has points associated with it. The total
score of a word is the sum of the scores of its letters. More common letters
are worth fewer points while less common letters are worth more points. The
points associated with each letter are shown below:

One point A, E, I, L, N, O, R, S, T and U

Two points D and G

Three points B, C, M and P

Four points F, H, V, W and Y

Five points K

Eight points J and X

Ten points Q and Z

Write a function that computes and returns the ScrabbleTM score for a word. A
dictionary, like the one given below, named scores, and the word whose
score will be calculated are the only two parameters to this function. You may
assume that the user will enter a string of letters only and the dictionary will
contain all the required letters.

scores = {"A":1, "B":3, "C":3, "D":2, "E":1, "F":4, "G":2,


"H":4, "I":1, "J":8, "K":5, "L":1, "M":3, "N":1,
"O":1, "Q": 10, "R":1, "S":1, "T":1, "U":1,
"V":4, "W":4, "X":8, "Y":4, "Z":10}

def calculateScore (scores, word):


word = word.upper()
score = 0
for letter in word:
score += scores[letter]
return score

9
10. Assume that we have a txt file (named as "population.txt"). In each line
of this file, we have a record of a citizen of the Turkish Republic. This record
contains two pieces of information for a specific citizen: citizenship number
("TC kimlik no" in Turkish) and the name of the city where this citizen lives.
These two pieces of information are separated by a space. In other words,
each line has the following format:

citizenshipNumber cityName

Write a program that reads this file and stores the city-population pairs in a
dictionary (like "Istanbul": 15000000, "Ankara": 7000000 etc). And then,
your program should ask for a city name from the user as input and display
the population of that city. If there is no such city in the constructed
database, then you should give an appropriate message.

10
file = open("population.txt", "r")

d = {}
for line in file:
line = line.strip()
#remove endline character(\n) at the end
m = line.split(" ")
cityName = m[1]

if cityName not in d:
d[cityName] = 1
else:
d[cityName] += 1

file.close()

city = input("Enter a city name: ")

if city in d:
print("Population is", d[city])
else:
print("There is no such city in our database")

11

You might also like