OPPE 2 MAY 24 - Set 2
Problem 1 - Data Types and Expressions [6 x 5 = 30 Marks]
Implement all the functions based on given docstrings. There would be 6 functions and 6 test
cases corresponding to each of the functions.
Note: Use return statements appropriately according to the return type. If return type is None
don't return anything. For the function you didn't attempt write pass in the function body or
remove the function from the code and don't leave any function body empty which may cause
syntax errors.
def digit_product(n: int) -> int:
'''Calculate the product of the digits of an integer.
Args:
n (int): The integer whose digits are to be multiplied.
Returns:
int: The product of the digits.
Examples:
>>> digit_product(123)
6
>>> digit_product(101)
0
'''
...
def capitalize_first_and_last(sentence: str) -> str:
'''Capitalize the first and last characters of each word of the sentence.
Args:
sentence (str): Input string sentence of space seperated words.
Returns:
str: The string with the first and last characters of each word capitalized.
Examples:
>>> capitalize_first_and_last("hello world")
'HellO WorlD'
>>> capitalize_first_and_last("python programming")
'PythoN ProgramminG'
'''
...
Download Notes and PYQs from Unknown IITians
def kth_longest_word(words: list, k: int) -> str:
'''Find the k-th longest word in a list of words where each word has a unique length.
Args:
words (list): The list of words.
k (int): The position (1-based) of the longest word to find.
Returns:
str: The k-th longest word in the list.
Examples:
>>> kth_longest_word(['apple', 'banana', 'cherry', 'date'], 2) 'apple'
>>> kth_longest_word(['elephant', 'dog', 'cat', 'hippopotamus'], 1) 'hippopotamus'
>>> kth_longest_word(['a', 'abc', 'abcd', 'ab'], 3)
'ab'
'''
...
def unflatten(t: tuple, m: int, n: int) -> tuple:
'''Given a flat tuple of length m*n, convert it into a tuple of tuples with dimensions m x n.
Args:
t (tuple): Flat tuple of length m*n.
m (int): Number of rows in resulting tuple of tuples.
n (int): Number of columns in resulting tuple of tuples.
Returns:
tuple: A tuple of tuples with dimension m x n.
Examples:
>>> unflatten((1, 2, 3, 4, 5, 6), 2, 3)
((1, 2, 3), (4, 5, 6))
>>> unflatten((1, 2, 3, 4), 2, 2)
((1, 2), (3, 4))
'''
...
def is_heterogram(sentence: str) -> bool:
'''Check if a given sentence is a heterogram or not.
A heterogram is a word, phrase, or sentence in which no letter of the alphabet occurs more
than once.
Ignore the multiple occurences of space.
Download Notes and PYQs from Unknown IITians
Args:
s (str): The input sentence.
Returns:
bool: True if the sentence is heterogram, False otherwise.
Examples:
>>> is_heterogram('The big dwarf only jumps')
True
>>> is_heterogram('Blue bat')
False
>>> is_heterogram('Hello World')
False
'''
...
def filter_keys_by_value(d: dict, threshold: int) -> None: '''Filter the dictionary keys where the value is
greater than the given threshold.
Modify the dictionary in place, do not return a new dictionary.
Args:
d (dict): The input dictionary.
threshold (int): The threshold value.
Returns:
None
Examples:
>>> d = {'a': 1, 'b': 5, 'c': 3}
>>> filter_keys_by_value(d, 3)
>>> d
{'b': 5}
>>> d = {1: 10, 2: 20, 3: 5, 4: 30}
>>> filter_keys_by_value(d, 15)
>>> d
{2: 20, 4: 30}
'''
...
Problem 2 - Data Processing [20 Marks]
A happy number is a number defined by the following process:
Starting with any positive integer, replace the number by the sum of square of its digits.
Repeat the process until the number equals 1(where it will stay), or it loops endlessly in a
Download Notes and PYQs from Unknown IITians
cycle that doesn't include 1.
Those numbers for which the process ends in 1 are happy.
Example1:
19 is a happy number .
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
Example2:
4 is not a happy number.
The cycle for 4 is as follows:
4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 (and repeats)
Define a function n_happy_numbers that accepts a list of positive integers and returns the count of
happy numbers in the given list.
def n_happy_numbers(numbers: list) -> int:
'''Find the number of happy numbers in the given list numbers.
Args:
numbers (list[int]): Given list of positive integers.
Returns:
int: Count of happy numbers in the given list.
'''
...
Problem 3 - Data Processing [20 Marks]
You are given a list of dictionaries overs where each dictionary corresponds to a single over
Download Notes and PYQs from Unknown IITians
bowled by a bowler. Each over contains:
Bowler name as key.
Value associated with this key is a list of events for the over, where each event could
be:
An integer value {1, 2, 3, 4, 6} indicating runs scored on that ball.
'W' indicating a wicket taken on that ball.
'Wd' indicating a wide ball, which incurs 1 extra run.
'Nb[i]' indicating a no-ball, where i represents runs scored on that ball, and incurs 1
extra run in addition to the runs from the no-ball itself.
Each over has 6 valid balls (ie. excluding extras like wide and no balls).
One of the entry is given for your reference:
{'Ashwin': [1, 1, 0, 'W', 'Wd', 6, 'Nb[4]', 0]}
Here, 'Ashwin' gave 14 runs in the over and took 1 wicket. 1 + 1 + 0 + 1( extra
: wide ) + 6 + 5( extras : noball) + 0 = 14
Define a function named best_performers , that accepts overs as argument and returns a list of
best bowlers based on their performances.
Bowlers are sorted on the basis of most wickets taken. If two bowlers have taken same number of
wickets, then the best performer among them is decided on the basis of lower economy rate.
Economy Rate: Defined as the total runs conceded (including extras) divided by the total number
of overs bowled by the bowler. Round
the economy rate upto two decimal places.
def best_performers(overs: list) -> list:
'''Given a list of dictionaries, generate a ranking board, based on wickets taken and economy of the
bowler.
The output should be list of tuples, sorted on the basis of ranking of bowler.
Args:
overs (list[dict]): list of dictionaries, where each dictionary represents the performance
of a bowlers in a over.
Download Notes and PYQs from Unknown IITians
Returns:
list of tuples - where each entry has format: (bowler_name, wickets, economy_rate).
'''
...
Problem 4 - File Handling [30 Marks]
You are given two CSV files:
1. shopping_file : Contains details of items purchased by the customer which includes names
and quantity of the items purchased.
SNo,ProductName,Qty
2. prices_file : Contains details like product Id, name and price of all available items.
Id,ProductName,Price
The variable shopping_file represents the name of the file containing product purchase details,
and prices_file represents the name of the file containing product prices.
Define a function calculate_total_price that
takes shopping_file and prices_file as argument and returns the total amount of goods
purchased by the customer.
def calculate_total_price(prices_file: str, shopping_file: str) -> int: '''Compute the total amount
spent on the products.
Args:
prices_file (str): path of file containing product purchase details. shopping_file (str): path of
file containing product prices.
Returns:
float: The total amount.
'''
...
Download Notes and PYQs from Unknown IITians