Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

Sample Test_solved

May 16, 2023

1. (10 points) Write the following mathematical expressions in Python.

a. 𝑠 = 𝑠0 + 𝑣0 𝑡 + 12 𝑔𝑡2 + 13 𝑔𝑡3

𝐶 𝐷
b. 𝐴 = 𝐵5 (1 + 100 )

2. (10 points) Write a program that reads four integers and prints “two pairs” if the input
consists of two matching pairs (in some order) and “not two pairs” otherwise. For example,
1 2 2 1 two pairs
1 2 2 3 not two pairs
2 2 2 2 two pairs
[ ]: numbers = input().split() # split input string by space into list of strings, e.
↪g. ['1', '2', '3', '4', '5']

# count the number of occurrences of each number in the list


counts = [numbers.count(num) for num in set(numbers)] # set(numbers) returns a␣
↪set of unique numbers in the list

if counts.count(2) == 2:
print("two pairs")
else:
print("not two pairs")

not two pairs


3. (10 points) Write a function that takes in a string and returns a new string with all vowels
replaced with the letter ‘x’. For example,
Take a string: "Hello World!"
The new string will be "Hxllx, wxrld!"

[ ]: def replace_vowels(string):
vowels = 'aeiouAEIOU' # string of vowels
new_string = ''
# iterate through each character in string
for char in string:
if char in vowels: # if char is a vowel
new_string += 'x'
else:
new_string += char

1
return new_string

# Test
original_string = "Hello World!"
new_string = replace_vowels(original_string)
print(new_string) # Output: "Hxllx Wxrld!"

Hxllx Wxrld!
4. (10 points) Use recursion to determine the number of digits in an integer n. Hint: If n is <
10, it has one digit. Otherwise, it has one more digit than n // 10.

[ ]: # define a function to count the number of digits in a number


def count_digits(n):
if n < 10:
return 1
else:
return 1 + count_digits(n // 10) # recursive call

# Test
count_digits(133457) # Output: 6

[ ]: 6

5. (10 points) Write a python program that reads a file containing a list of names and sorts
them alphabetically. Use exception handling to handle cases where the file cannot be opened
or an error occurs during sorting. For example,
Sorted names:
Anh
Cuong
Hai
Lam
Thai
Tuan
[ ]: # Structure of a try-except block: try block, except block, else block, finally␣
↪block

try:
with open("input.txt", "r") as file: # open file in read mode
names = file.readlines() # read all lines into a list, names =␣
↪['Tom\n', 'Mary\n', 'Peter\n']

names.sort() # sort the list, names = ['Mary\n', 'Peter\n', 'Tom\n']


print("Sorted names:")
for name in names: # iterate through each name in the list
print(name.strip()) # strip() removes the newline character at the␣
↪end of each name

except FileNotFoundError: # handle file not found error

2
print("File not found.")
except Exception as e: # handle other exceptions
print("An error occurred:", e)

['Thai \n', 'Tuan\n', 'Cuong\n', 'Lam\n', 'Hai\n', 'Anh\n']


Sorted names:
Anh
Cuong
Hai
Lam
Thai
Tuan
6. (10 points) Write a program that allows a user to input two sets of integers and then prints
the union, intersection, and difference of the sets. For example,
set1 = {1, 3, 5, 7, 9}
set2 = {2, 3, 4, 6, 8}
Union of the sets is: {1, 2, 3, 4, 5, 6, 7, 8, 9}
Intersection of the sets is: {3}
Difference of set1 and set2 is: {1, 5, 9, 7}
Difference of set2 and set1 is: {8, 2, 4, 6}
[ ]: # Take user input for two sets of integers
set1 = set(map(int, input("Enter integers for set1 separated by spaces: ").
↪split())) #map() is used to convert each string in the list to an integer, e.

↪g. ['1', '2', '3'] -> [1, 2, 3]

set2 = set(map(int, input("Enter integers for set2 separated by spaces: ").


↪split())) # split() is used to split the input string by spaces into a list␣

↪of strings, e.g. '1 2 3' -> ['1', '2', '3']

#set(list)
print(set1)
print(set2)
# Print the union of the sets
print("Union of the sets is:", set1.union(set2) ) # Another way: print("Union␣
↪of the sets is:", set1 | set2)

# Print the intersection of the sets


print("Intersection of the sets is:", set1.intersection(set2)) # Another way:␣
↪print("Intersection of the sets is:", set1 & set2)

# Print the difference of set1 and set2


print("Difference of set1 and set2 is:", set1.difference(set2)) # Another way:␣
↪print("Difference of set1 and set2 is:", set1 - set2)

# Print the difference of set2 and set1


print("Difference of set2 and set1 is:", set2.difference(set1)) # Another way:␣
↪print("Difference of set2 and set1 is:", set2 - set1)

3
{1, 2, 3, 5}
{3, 4, 5, 7}
Union of the sets is: {1, 2, 3, 4, 5, 7}
Intersection of the sets is: {3, 5}
Difference of set1 and set2 is: {1, 2}
Difference of set2 and set1 is: {4, 7}
7. Write a program to create a dictionary with student names and their corresponding test
scores, and returns the name of the student with the highest score. For example,
{'Alice': 85, 'Bob': 92, 'Charlie': 80, 'David': 95}
Return the name: David
[ ]: scores = {'Alice': 85, 'Bob': 92, 'Charlie': 80, 'David': 95} # make a␣
↪dictionary of scores and names

highest_score = max(scores.values()) # get the highest score in the dictionary


for name, score in scores.items(): # iterate through each key-value pair in the␣
↪dictionary

if score == highest_score:
print(name)

David
8. (10 points) Write a program to:
• Create a class called “Animal” with methods “eat” and “move”.
• Create inheriting classes “Bird” and “Mammal”. Each should have a unique attribute, and
their own implementation of “move”.
For example,
Sparrow is eating.
Sparrow is flapping its wings and flying.
Cheetah is eating.
Cheetah is running at 70 mph.

[ ]: class Animal: # Create a class Animal


def eat(self): # Create a method eat()
print("Animal is eating.") # Print a message "Animal is eating."

def move(self): # Create a method move()


print("Animal is moving.")

class Bird(Animal): # Create a class Bird that inherits from Animal


def __init__(self, name): # Atributes of Bird
self.name = name # Create an attribute name

def move(self): # Override the move() method


print(f"{self.name} is flapping its wings and flying.") # Method is␣
↪only a message to print

4
class Mammal(Animal):
def __init__(self, name):
self.name = name

def move(self):
print(f"{self.name} is running at 70 mph.")

sparrow = Bird("Sparrow") # Create an object of class Bird


sparrow.eat()
sparrow.move()

cheetah = Mammal("Cheetah")
cheetah.eat()
cheetah.move()

Animal is eating.
Sparrow is flapping its wings and flying.
Animal is eating.
Cheetah is running at 70 mph.
9. (10 points) Write a program to create a 2D array of random integers using
numpy.random.randint() function and calculate the average value of each column. For
example,
Array:
[[ 7 7 1 3]
[ 9 6 3 6]
[ 9 3 10 6]
[ 5 8 7 5]
[ 4 7 2 5]]
Column averages:
[6.8 6.2 4.6 5. ]
[ ]: import numpy as np

# Create a 2D array of random integers


array = np.random.randint(0, 10, size=(5, 4)) # 5 rows, 4 columns (5 điểm)

# Calculate the average value of each column


column_averages = np.mean(array, axis=0) # axis=0 means calculate the average␣
↪of each column

print("Array:\n", array)
print("Column averages:\n", column_averages)

Array:
[[7 0 3 6]
[8 1 4 9]
[8 7 0 5]

5
[1 0 2 7]
[0 9 2 8]]
Column averages:
[4.8 3.4 2.2 7. ]
10. (10 points) Write a program to creat and sort the below dataframe in pandas based on the
column “Salary”.
Name Age Salary
0 John 25 50000
1 Alice 30 60000
2 Bob 18 40000
3 Jane 21 35000
4 Dan 27 70000
[ ]: import pandas as pd

# Create a DataFrame using a dictionary


data = {'Name': ['John', 'Alice', 'Bob', 'Jane', 'Dan'],
'Age': [25, 30, 18, 21, 27],
'Salary': [50000, 60000, 40000, 35000, 70000]}

df = pd.DataFrame(data)
sorted_df = df.sort_values(by='Salary') # sort the DataFrame by the column␣
↪'Salary'

print(sorted_df)

Name Age Salary


3 Jane 21 35000
2 Bob 18 40000
0 John 25 50000
1 Alice 30 60000
4 Dan 27 70000

You might also like