0% found this document useful (0 votes)
35 views12 pages

Total Prize Money Calculation in Python

The document describes a problem involving mapping words from a dictionary to number key sequences on an old mobile phone. The goal is to find the input sequence that matches the most words in the given dictionary. It provides an example where the dictionary contains 4 words and the input sequence 66 matches the most words. The solution involves inverting the mapping of numbers to letters and finding the most common number sequences in the dictionary words.

Uploaded by

js9118164
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)
35 views12 pages

Total Prize Money Calculation in Python

The document describes a problem involving mapping words from a dictionary to number key sequences on an old mobile phone. The goal is to find the input sequence that matches the most words in the given dictionary. It provides an example where the dictionary contains 4 words and the input sequence 66 matches the most words. The solution involves inverting the mapping of numbers to letters and finding the most common number sequences in the dictionary words.

Uploaded by

js9118164
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

Complex Problem-1

Total Prize Money

Student Name: Harsh Singh UID: 23MAI10028


Branch: ME-AIML Section/Group: MAI 1
Subject Name: Advanced Python Programming Lab Subject Code: 23CSH-623

1. Problem:
In a coding contest, there are prizes for the top rankers. The prize scheme is as follows:

 Top 1010 participants receive rupees X each.


 Participants with rank 11 to 100 (both inclusive) receive rupees Y each.
Find the total prize money over all the contestants.

Input Format:

First line will contain T, number of test cases. Then the test cases follow.

Each test case contains of a single line of input, two integers X and Y - the prize for top 10
rankers and the prize for ranks 11 to 100 respectively.

Input Samples:

1000 100

1000 1000

80 1

400 30

Output Samples:

19000

100000

890

6700
2. Source Code:
def calculate_prize_money(x, y):
total_prize = 0

# Prize for top 10 rankers


total_prize += 10 * x

# Prize for ranks 11 to 100


total_prize += 90 * y

return total_prize

# Function to read input and process each test case


def main():
# Read the number of test cases
t = int(input())

# Process each test case


for _ in range(t):
# Read prize for top 10 rankers and ranks 11 to 100
x, y = map(int, input().split())

# Calculate and print the total prize money for the test case
result = calculate_prize_money(x, y)
print(result)

# Run the main function


if _name_ == "_main_":
main()

3. Output Screenshot:
Complex Problem-2
Area or perimeter

Student Name: Harsh Singh UID: 23MAI10028


Branch: ME-AIML Section/Group: MAI 1
Subject Name: Advanced Python Programming Lab Subject Code: 23CSH-623

1. Problem
Write a program to obtain length (L) and breadth (B) of a rectangle and check whether
its area is greater or perimeter is greater or both are equal.

Input Format

First line will contain the length (L) of the rectangle.


Second line will contain the breadth (B) of the rectangle.

Input sample:
1
2
Output sample:
Peri
6
2. Source Code:

# cook your dish here


l=int(input())
b=int(input())
Area=l*b
Peri=2*(l+b)
if (Area>Peri):
print("Area")
print(Area)
else:
print("Peri")
print(Peri)

3. Screenshot/Output:
Complex Problem-3
ATM

Student Name: Harsh Singh UID: 23MAI110028


Branch: ME-AIML Section/Group: MAI 1
Subject Name: Advanced Python Programming Lab Subject Code: 23CSH-623

1. Problem:

Pooja would like to withdraw X $US from an ATM. The cash machine will only accept
the transaction if X is a multiple of 5, and Pooja's account balance has enough cash to
perform the withdrawal transaction (including bank charges). For each successful
withdrawal the bank charges 0.50 $US.

Calculate Pooja's account balance after an attempted transaction.

Input Format:

Each input contains 2 integers X and Y.


X is the amount of cash which Pooja wishes to withdraw.
Y is Pooja's initial account balance.

Input Sample:

30 120.00

Output Sample:

89.5

2. Source Code:
n,atm=map(float,input().split())
n=int(n)
if (n+0.5<=atm and n%5==0):
print(float(atm-n-0.5))
else:
print(float(atm))
3. Screenshot/Output:
Complex Problem-4
Chef and Subarrays

Student Name: Harsh Singh UID: 23MAI10028


Branch: ME-AIML Section/Group: MAI 1
Subject Name: Advanced Python Programming Lab Subject Code: 23CSH-623

1. Problems:
Read problems statements in Mandarin Chinese, Russian and Vietnamese as well.
Chef likes problems involving arrays. Unfortunately, the last one he tried to solve
didn't quite get solved.

Chef has an array A of N positive numbers. He wants to find the number of subarrays
for which the sum and product of elements are equal.

Please help Chef find this number.

Input Format:
The first line of input contains an integer T denoting the number of test cases. T test
cases follow. The first line of each test contains the integer N. The next line contains
N integers — A1, A2, ..., AN — denoting the array.
Sample Input:
3
3
132
4
4121
6
122221
Sample Output:
4
5
9

2. Source Code:

# Function to find the number of subarrays with equal sum and product
def count_subarrays(arr, n):
result = 0
for i in range(n):
current_sum = arr[i]
current_product = arr[i]

if current_sum == current_product:
result += 1

for j in range(i + 1, n):


current_sum += arr[j]
current_product *= arr[j]

if current_sum == current_product:
result += 1

return result

# Main function to read input and print output


def main():
# Read the number of test cases
t = int(input().strip())

for _ in range(t):
# Read the size of the array
n = int(input().strip())

# Read the array elements


arr = list(map(int, input().split()))

# Call the function to count subarrays and print the result


result = count_subarrays(arr, n)
print(result)

# Run the program


if __name__ == "__main__":
main()
3. Screenshot/Output:
Complex Problems-5
SMS Dictionary

Student Name: Harsh Singh UID: 23MAI10028


Branch: ME-AIML Section/Group: MAI 1
Subject Name: Advanced Python Programming Lab Subject Code: 23CSH-623
1. Problem:
In the pre-smartphone era, most mobile phones with numeric keypads had a private
dictionary of words to allow users to type messages quicker. On a typical phone of this
type, each number key is assigned a subset of the alphabet {a,b,…,z}: 2 is assigned the
subset {a,b,c}, 3 is assigned {d,e,f}, 4 is assigned {g,h,i}, 5 is assigned {j,k,l}, 6 is
assigned {m,n,o}, 7 is assigned {p,q,r,s}, 8 is assigned {t,u,v} and 9 is assigned
{w,x,y,z}.

When the user types a sequence of numbers, this sequence is mapped to all possible
words that can be constructed from the key assignment. For instance, if the user types
66, this could correspond to any one of the letter sequences "mm", "mn", "mo", "nm",
"nn", "no", "om", "on" or "oo". These letter sequences are looked up in the dictionary
stored in the phone and all matches are reported. For instance, if the phone's dictionary
contains only "on" and "no" from this set of sequences, the user will be offered a choice
of "on" or "no" to insert in the message. Similarly, the input 4663 might be interpreted
as either "good" or "home". An input sequence may have a unique interpretation---for
example, the only word in the dictionary matching the input 28 may be "at". Other
sequences may not match any word in the dictionary—for instance, 99999.

Your task is the following. Given the typical assignment from number keys to letters of
the alphabet given above and given a dictionary of words, report the input sequence that
matches the largest number of words in the dictionary. For example, if the dictionary
consists of the words {at,on,good,no} then the answer is 66, because 66 matches both
"on" and "no" while no other input matches more than one word in the dictionary. On
the other hand, with the dictionary {at,on,good,no,home,gone}, the answer is 4663,
because 4663 matches three words, "good", "home" and "gone" in the dictionary.

Solution hint:
For each word in the input, compute the number key sequence that creates it by inverting
the mapping 2→{a,b,c}, 3→{d,e,f} etc. Store the number corresponding to the word in
an array.

After reading all the input, sort the numbers in the array.
Input format:
The first line of input is an integer M, the number of words in the dictionary. This is
followed by M lines of input. Each line contain one word from the dictionary, where a
word is sequence of characters from the lowercase alphabet {a,b,c,…,z}.

Note: Each word in the dictionary is, in general, an arbitrary sequence of letters from
{a,b,c,…,z}. In particular, it is not assumed that the words stored in the dictionary are
valid words in English or any other language.

Sample Input:
4
at
on
good
no

Sample Output:
66

2. Source Code:
# Function to convert a word to its corresponding number key sequence
def word_to_number_key(word):
key_mapping = {'abc': '2', 'def': '3', 'ghi': '4', 'jkl': '5',
'mno': '6', 'pqrs': '7', 'tuv': '8', 'wxyz': '9'}

number_key = ''
for char in word:
for key, value in key_mapping.items():
if char in key:
number_key += value
break

return number_key

# Function to find the input sequence that matches the maximum number of
words
def max_matching_sequence(dictionary):
word_to_number = [word_to_number_key(word) for word in dictionary]
# Sort the number sequences
word_to_number.sort()

# Count occurrences of each number sequence


count_dict = {}
for num in word_to_number:
count_dict[num] = count_dict.get(num, 0) + 1

# Find the number sequence with the maximum count


max_sequence = max(count_dict, key=count_dict.get)

return max_sequence

# Read input values


m = int(input())
dictionary = [input().strip() for _ in range(m)]

# Call the function to find the maximum matching sequence and print the result
result = max_matching_sequence(dictionary)
print(result)

3. Screenshot/Output:

Common questions

Powered by AI

The algorithm's effectiveness in identifying the sequence that matches the most dictionary words relies on converting each word into its numeric key sequence based on traditional mobile keypad mappings. These sequences are stored and frequency-counted, with the sequence having the highest count being the desired output. This method efficiently handles large dictionaries by leveraging the constraints of keypad-to-letter correspondences, ensuring that only plausible sequences are considered. However, the algorithm's performance may vary depending on dictionary size and word distribution, potentially requiring further optimization for handling extensive inputs or languages with different character mappings .

The ATM withdrawal logic includes a condition that the withdrawal amount (X) must be a multiple of 5 and that the account balance must be sufficient to cover both the withdrawal and a transaction fee of 0.50 USD. If these conditions are met, the account is debited with the amount plus the fee; otherwise, the transaction is rejected, and the balance remains unchanged. This logic ensures that the ATM provides exact change and avoids processing small denominations of currency. However, the requirement of a multiple of 5 may inconvenience users needing flexibility with withdrawal amounts. It emphasizes the importance of maintaining adequate balances to accommodate both planned withdrawals and unforeseen charges .

The ATM system design, requiring withdrawal amounts to be multiples of 5 and sufficient balance to include a transaction fee, exhibits robustness by ensuring smooth operations regarding cash dispensation and fee management. This design minimizes errors associated with small currency denominations and maintains transaction integrity by confirming balance sufficiency before processing. However, its rigidity might limit user convenience by not supporting flexibility for withdrawals. Therefore, while efficient in controlled environments, the system might need enhancements or alternative configurations to better fit diverse real-world banking practices and preferences .

The program calculates the area and the perimeter of a rectangle given its length (L) and breadth (B). The area is computed as the product L * B, while the perimeter is calculated as 2 * (L + B). The logic checks whether the area is greater than the perimeter by comparing these two values. If the area exceeds the perimeter, the program outputs 'Area' along with its value; otherwise, it outputs 'Peri' and its value. This comparison is based on the mathematical properties that often, for smaller dimensions of L and B, the perimeter may surpass the area, while for larger dimensions, the area may become dominant .

An efficient algorithm for counting subarrays with equal sums and products could involve dynamic programming or prefix sums to pre-compute cumulative values, reducing redundant calculations. Leveraging data structures such as hash maps could store sums and products encountered at different points, facilitating quick checks instead of recalculating for each subarray. Mathematical properties or constraints (such as constraints on element values) could also be utilized to narrow down potential candidates before conducting thorough checks, thereby optimizing the solution space and execution time .

The approach to finding subarrays where sum and product are equal involves iterating through all possible subarrays of a given array A of N positive numbers. For each subarray, both the sum and the product of elements are calculated. These calculations are compared, and if they are equal, a counter is incremented. The algorithm systematically considers each element as a starting point, progressively including more elements to form subarrays until the end of the array is reached. This exhaustive strategy, while computationally intense, ensures all possible subarrays are evaluated for the specified condition. The challenge lies in optimizing this process due to its potential combinatorial complexity .

To ensure broader participation in coding contests, the prize model can be modified to include more tiers with progressive rewards. Introducing smaller prizes or incentives for participation or achieving certain problem thresholds could engage more contestants. Random rewards, peer recognition, or educational opportunities for all participants upon achieving particular scores could also enhance engagement. Ultimately, a balanced approach that rewards diverse efforts while maintaining competitive allure would likely motivate increased participation across varying skill levels .

The traditional SMS dictionary system maps number sequences to words by assigning specific letters to each number key on a mobile keypad. Numbers 2 to 9 correspond to groups of three or four letters, such as 2 mapping to {a, b, c}. When a numeric sequence is typed, it can represent multiple potential letter sequences. These possibilities are cross-referenced with a dictionary to identify meaningful words. For instance, inputting '66' could correspond to sequences like 'mm', 'mn', 'om', etc., and only those present in the dictionary are suggested. This method maximizes the anticipation of input words by limiting possible letter combinations using predefined groups .

Solving subarray problems where both the sum and product of elements need to be equal has significant computational implications due to the potential number of subarray combinations. The naive approach checks every possible subarray, leading to a time complexity of O(N^2) for checking all pairs and O(N^3) if calculating sums and products from scratch each time. Optimizing this requires careful management of computed values and efficient iteration strategies. Moreover, numerical overflow or precision errors might occur when handling large arrays or numbers. These challenges necessitate refined algorithms that can leverage mathematical properties of numbers to efficiently reduce unnecessary computations .

The prize distribution model used in coding contests is designed to incentivize participants to aim for top performance. By allocating a higher prize amount to the top 10 rankers (X), the contest fosters a competitive environment encouraging participants to strive for excellence. The additional tier of prizes for ranks 11 to 100 (Y) ensures that a larger group is rewarded for their effort, maintaining engagement among contestants who may not secure top positions. This dual-tier system motivates participants at different performance levels, promoting sustained participation and effort. The impact on motivation is significant as it acknowledges a wider array of achievements, incentivizing participants to improve their problem-solving skills in hopes of climbing the ranks to reach the top tier .

You might also like