O.1.1 (1) Which of the following statements is False?
Python’s built-in function type() can be used to determine an object’s data type.
A function performs its task when you call it by writing its name, followed by square brackets, [].
The parentheses after a function name in a function call contain the function’s argument — the data that the function needs to perform its task.
Python is case sensitive, so number and Number are different identifiers.
Ans: (B) a function performs its task when you call it by writing its name, followed by parentheses, ().
O.1.2 (2) Which of the following statement will have a different Boolean value than the others?
""
None
"No"
3 < 5 and 4 < 3
Ans: (C)
O.1.3 (3) Which of the following statement is True?
Python uses the ^ symbol to raise one value to the power of another (e.g., 2 ^ 10).
The value of the following expression is 2: 7.5 % 3.5.
The data type of 2 + j in Python is always a complex number.
A statement in Python can span more than one line.
Ans: (D). (A) Python uses **. (B) Should be 0.5. (C) Should be 2 + 1j.
O.1.4 (4) Which of the following statements is True?
Sets are iterable, so they are sequences and support indexing and slicing with square brackets, [].
Sets are not iterable, so you cannot process each element in a set with a for loop.
You can create an empty set with {}.
A dictionary’s keys must be immutable and unique, but multiple keys can have the same value.
Ans: (D). (A) They are not sequence. (B) Sets are iterable! (C) This is dictionary, you should use set().
O.1.5 (5) Which of the following statement is False?
If you have more than one statement in the body of if clause, those statements need to have the same indentation.
If you assign value to a new variable in the if clause. Assume that you enter the if clause during the execution; the variable will not be accessible after the if clause.
continue and break statements can be used in both for and while loops.
You can cause the program to terminate or exit before the last instruction by calling the sys.exit() function.
Ans: (B) The varible will still be accessible.
O.1.6 (6) Which of the following will NOT be printed out when calling the help() function on a custom or built-in function?
Name of the function
docstring
Body of the function
Parameter list of the function
Ans: (C)
O.1.7 (7) Which of the following statement is True?
The random.randint(1,5) statement will randomly generate integers from 1 to 4.
The parameter with default value should always be put on the leftmost part of the parameter list of a function.
When there’s no return statement in a function, it implicitly returns the value None after executing the last statement in the function’s block.
If we would like to pass an arbitrary number of positional arguments to the function, we can use a special parameter like **kwargs.
Ans: (C). (A) generates integers from 1 to 5. (B) The parameter with default value should be put on the righthand side of normal parameter. (D) We should use something like *args.
O.1.8 (8) What does the following line of code display?
print(20, 30, 40, sep=', ')
203040
20,30,40
20, 30, 40
Syntax error
Ans: (C)
O.1.9 (9) Which of the following is NOT a valid collection (container) inside Python?
Ans: (C) This is important because when you add an object to a set, its hash value is computed and used to determine its position in the set. If the object is mutable, and its contents change, then its hash value changes, and it can no longer be found in the set.
O.1.10 (10) Which of the following statements is False?
If you modify the sublist, which is sliced from a list, the original list is not modified.
When you pass a list to a function and modify the list inside the function, the original list is not modified.
Assume that spam is a string object. Considering the statement spam = spam + "world". The id (memory location) of spam before and after the execution will be different.
Assume that spam is a list object. Considering the statement spam = spam.append("world"). The id (memory location) of spam before and after the execution will be the same.
Ans: (B) the original list will also be modified. (D) is also True.
O.1.11 (11) Which of the following is not a correct way to create a string in Python?
"nsysu"
'nsysu'
""" nsysu """
str(nsysu)
Ans: (D)
O.1.12 (12) Which of the following statements is False?
String methods lower() and upper() can convert strings to all lowercase or all uppercase letters, respectively.
Python has separate data types for string and character.
Raw strings — preceded by the character r — treat each backslash as a regular character rather than the beginning of an escape sequence.
Backslash characters in strings introduce escape sequences — like \n for new-line and \t for tab.
Ans: (B) Python represents both string and characters using the same data type str
O.1.13 (13) Which of the following function can be used to find all the methods available for an object in Python?
dir()
help()
len()
type()
Ans: (A)
O.1.14 (14) Which of the following statements is False?
Attempting to divide by 0 results in a ZeroDivisionError.
Trying to access a local variable outside its function’s block causes a NameError, indicating that the variable is not defined.
After the last except clause, an optional else clause specifies code that should execute only if the code in the try suite raised an exception.
The finally clause is guaranteed to execute, regardless of whether its try clause executes successfully or an exception occurs.
Ans: (C). After the last except clause, an optional else clause specifies code that should execute only if the code in the try clause did not raise exceptions.
O.1.15 (15) Assume that we execute the following assignment statement and user inputs an integer:
O.2.2 (17) Here, we will simulate the process of a simple card game. The game is played with a standard deck of 52 cards, and we will randomly select 30 cards and divide them evenly between two players. Each player gets a hand of 15 cards. The goal of the game is to determine whether the player got a straight (i.e., five cards of consecutive face values) or not in his 15 cards. If the players got a straight, please return True. Otherwise, return False. Please complete the following game design by filling in the missing part in the function. (8%).
import randomRANKS = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]def create_deck(): suits = ['♣', '♦', '♥', '♠'] deck = [(rank, suit) for rank in RANKS for suit in suits] # Use list comprehension to create the deck.return deck# A function that takes the deck as a parameter and returns two lists, each containing 26 randomly-selected # cards from the deck. Use list slicing and the random module to implement this function.def deal_cards(deck): random.shuffle(deck) deck = deck[:30] hand1 = deck[:15] # Split it into 15 cards in each using slice hand2 = deck[15:]return hand1, hand2def get_ranks(hand):"""Return just the ranks in hand."""return [rank for rank, suit in hand]def rank_key(card):return RANKS.index(card)def sort_hand(hand):"""Order hand by index of each face in RANKS."""returnsorted(hand, key=rank_key)def is_straight(hand):"""Returns a Boolean indicating whether hand contains a straight."""# check for any 5 consecutive faces# Your code here # 1. Return just the ranks in hand ranks = get_ranks(hand)# 2. Get unique rank from the ranks ranks =set(ranks)# 3. Sort the rank using the above function ranks = sort_hand(ranks)# 4. Using for loops to test whether we get a straight or notfor i inrange(len(ranks) -5):for j inrange(8):if ranks[i:i+5] == RANKS[j:j+5]:returnTruereturnFalse# Test data 1random.seed(2023)deck = create_deck()hand1, hand2 = deal_cards(deck)s1 = is_straight(hand1)s2 = is_straight(hand2)# Test data 2random.seed(20)deck = create_deck()hand1, hand2 = deal_cards(deck)s3 = is_straight(hand1)s4 = is_straight(hand2)assert (s1,s2) == (True, True)assert (s3,s4) == (True, False)
O.2.3 (18) In cryptoanalysis, frequency analysis is often used to decipher a message when the key is unknown. It calculates the frequency of each character in the encrypted text. Write a program that uses a dictionary to summarize the frequency of each letter in a given text. Treat uppercase and lowercase letters the same, ignore spaces and assume that the user does not enter any punctuation. Display the letters and their frequency in descending order by completing the following code snippet. (8%)
Hint: Refer to our slides to know how to count the number of occurrences of each letter in a string and how to sort the dictionaries according to the value.
text ='This is some encrypted text with different words and this is some more text with a hidden message'character_counts = {}total =0# 1. Count occurrences of each letter, be sure to ignore the case and the space herefor character in"".join(text.lower().split()): character_counts.setdefault(character, 0) character_counts[character] = character_counts[character] +1 total = total +1# 2. Sort the dictionaries using the valuesdef value_key(x):return x[1]# 3. Print out the character and the associated countfor character, count insorted(character_counts.items(), key=value_key, reverse=True):print(f'{character}: {count}')
O.2.4 (19) Write a function that receives a list of email addresses and returns a list that only contains the unique addresses. Treat uppercase and lowercase letters the same. The function should use a set to get the unique email addresses from the list. (6%)
def unique_address(mail):""" Parameters ---------- mail: list The input list that contains duplicated entries Returns ------- uniques : list The list that contains unique entries """# Your code here uniques =list(set([m.lower() for m in mail]))return uniques# Test datatext = ['John.doe@hotmail.com', 'michael.smith@gmail.com', 'ann.williams@msn.com', 'james.MILLER@gmail.com','james.miller@gmail.com', 'MICHAEL.smith@gmail.com', 'john.doe@hotmail.com','michael.smith@gmail.com']uniques = unique_address(text)print(uniques)
O.2.5 (20) Assume that we have a plain text file that stores the grade for each student. Each row corresponds to each student, starting with the name of the student, followed by the three scores he/she got in each subject, separated by white space as follows: (6%)
Bob 96 80 100
Adam 73 90 95
Michael 87 75 85
Harry 85 80 75
Write program that reads the grades from the grades.txt and displays the average score for each student line by lien.
# Read the filewithopen('grades.txt') asfile:# Your code here# Iterate over each line in the filefor line infile:# Split the line into a list of strings using whitespace as a delimiter cline = line.strip().split()# Extract the student's name and grades name = cline[0] grades = [int(grade) for grade in cline[1:]]# Calculate the average grade avg_grade =sum(grades)/len(grades)# Display the average grade for the studentprint(f'{name}: {avg_grade}')
O.2.6 (21) Write a program that inputs a number of seconds from the user. Calculate the number of hours, minutes, and remaining seconds. You can assume that the user always enters a number of seconds higher than 3600. Print them separated by “ - ”. For example, if the user types 3850 seconds as input, the program should print: (5%)
1 h - 4 m - 10 s
Hint: Use the floor division and the remainder operation to calculate the number of hours, minutes, and seconds.
# Your code hereseconds =int(input('Enter a number of seconds: '))hours = seconds //3600seconds = seconds %3600minutes = seconds //60seconds = seconds %60print(hours, 'h -' , minutes , 'm -', seconds, 's')
1 h - 4 m - 10 s
O.2.7 (22) Write a program that computes the value of \(\pi\) from the following infinite series \(4 \times (1-\frac{1}{3}+\frac{1}{5}-\frac{1}{7}...-\frac{(-1)^n}{2n-1})\). Try to calculate how many terms you would need to get an error smaller than \(10^{-3}\). (6%)
Hint: Use the constant math.pi from the math module as the ground truth value for \(\pi\) and use abs() to calculate the error.
import mathapprox_pi =0print(f"Value of pi is: {math.pi}")print(f"Initial error is: {abs(approx_pi-math.pi)}")# Your code heren =0error =1print("Term\tapproximation\t\terror")while error >1e-3: n +=1 term = (-1)**(n-1) / (2*n -1) approx_pi +=4* term error =abs(approx_pi - math.pi)print(f'{n}\t{approx_pi:.10f}\t{error:.10f}')
What will be printed out when executing the code? Please also explain why you get such a result.
From (a), you see that the global variable spam has been modified. Fix the above code annotated with “Fix me here” if you do not want it to be changed.