PYTHON FUNCTIONS
1 Problem Statement
Samantha is building a ramp for her garden and needs to determine the exact length of the ramp
(the hypotenuse) to ensure it fits between the ground and a raised platform. She knows the
height of the platform and the horizontal distance from the base, which form the two shorter
sides of a right-angled triangle.
Help Samantha write a program that calculates and displays the length of the ramp using the
Pythagorean theorem. Use the pow() function for exponentiation.
Formula: c = √(a² + b²) where c is the hypotenuse and a & b are the other two sides of a right-
angled triangle.
Input Format
The input consists of two floating-point numbers, a and b, in each line representing the lengths
of the two shorter sides of a right-angled triangle.
Output Format
The output displays "The length of the hypotenuse is: " followed by the calculated length of
the hypotenuse rounded to two decimal places.
Solution
#def calculate_hypotenuse(a, b):
hypotenuse = (pow(a, 2) + pow(b, 2))**0.5
return hypotenuse
# Input
side1 = float(input())
side2 = float(input())
result = calculate_hypotenuse(side1, side2)
print(f"The length of the hypotenuse is: {result:.2f}")
2 Problem Statement
In a local school, the teacher is organizing a number game for kids where each child is asked
to call out all odd numbers from 1 up to a given number N. The teacher needs a program that
can assist in generating this list of odd numbers to quickly verify the children's answers.
The program should take a positive integer n and return a list of odd numbers from 1 to N
(inclusive, if N is odd). The list should be printed in a single line, with odd numbers separated
by commas.
Input Format
The input consists of a single integer N, representing the upper limit for generating odd
numbers.
Output Format
The output prints a single line containing a comma-separated list of odd numbers from 1 to
N.
#def find_odd_numbers(*args):
first = True
for n in args:
for i in range(1, n + 1, 2):
if not first:
print(", ", end="")
print(i, end="")
first = False
user_input = input()
numbers = map(int, user_input.split())
find_odd_numbers(*numbers)
3 Problem Statement
Emily is a budding programmer who loves solving mathematical problems. One day, she comes
across a challenge to find the largest of three numbers using a custom function.
Determined to tackle the challenge, she decided to create a program. Can you help her write
the code and solve the problem?
Function Specifications: find_max(a, b, c)
Input Format
The input consists of three space-separated floating-point values: a, b, and c.
Output Format
The output prints a floating point value, which is the largest of the given three numbers,
rounded off to two decimal places.
#def find_max(a, b, c):
max_val = a
if b > max_val:
max_val = b
if c > max_val:
max_val = c
return max_val
# Input: space-separated floats
num1, num2, num3 = map(float, input().split())
maximum = find_max(num1, num2, num3)
print(f"{maximum:.2f}",end="")
4 Problem Statement
Meena is analyzing a list of integers and needs to count how many numbers in the list are even
and how many are odd. She decides to use lambda functions to filter the even and odd numbers
from the list.
Write a program that takes a list of integers, counts the number of even and odd numbers using
lambda functions, and prints the results.
Input Format
The first line contains an integer n, representing the number of integers in the list.
The second line contains n space-separated integers.
Output Format
The first line of output prints an integer representing the count of even numbers.
The second line of output prints an integer representing the count of odd numbers.
n = int(input())
array_nums = [int(i) for i in input().split()[:n]]
odd_ctr = len(list(filter(lambda x: (x % 2 != 0), array_nums)))
even_ctr = len(list(filter(lambda x: (x % 2 == 0), array_nums)))
print(even_ctr)
print(odd_ctr)
5 Problem Statement
Sophia is developing a feature for her online banking application that calculates the total sum
of digits in customers' account numbers. This sum is used to generate unique verification
codes for secure transactions. She needs a program that takes an account number as input and
outputs the sum of its digits.
Help Sophia to complete her task.
Function Specification: def sum_digits(num)
Input Format
The input consists of an integer, representing the customer's account number.
Output Format
The output prints an integer representing the sum of the digits of the account number.
num = int(input())
def sum_digits(num):
digit_sum = 0
while num > 0:
digit = num % 10
digit_sum += digit
num //= 10
return digit_sum
def sum_digits(num):
# Convert the number to a string to easily iterate through each digit
return sum(int(digit) for digit in str(num))
# Input handling
num = int(input()) # Take input as an integer
# Output the sum of digits
print(sum_digits(num))
sum = sum_digits(num)
print(sum)
5 Problem Statement
Arjun is working on a mathematical tool to manipulate lists of numbers. He needs a program
that reads a list of integers and generates two lists: one containing the squares of the input
numbers, and another containing the cubes. Arjun wants to use lambda functions for both tasks.
Write a program that computes the square and cube of each number in the input list using
lambda functions.
Input Format
The input consists of a single line of space-separated integers representing the list of input
numbers.
Output Format
The first line contains a list of the squared values of the input numbers.
The second line contains a list of the cubed values of the input numbers.
inp_list = list(map(int, input().split()))
square_nums = list(map(lambda x: x ** 2, inp_list))
cube_nums = list(map(lambda x: x ** 3, inp_list))
print(square_nums)
print(cube_nums)
6 Problem Statement
Mia, an ardent lover of words, has an enchanting tuple filled with a myriad of magical words.
She embarks on a quest to discover the word with the highest number of vowels, hoping to
uncover the gem among her linguistic treasures. However, Mia, being the adventurous spirit
she is, insists on a challenge—no built-in functions allowed! Write a program to assist Mia in
finding the word with the most vowels in her tuple, using only fundamental operations.
Note:
Use a lambda function to simplify the task of counting vowels in each word within the tuple.
Input Format
The first line contains an integer 'n', denoting the number of words in the tuple.
The next 'n' lines contain the words, where each word consists of only lowercase alphabetical
characters.
Output Format
The output displays a string representing the word with the highest number of vowels.
n = int(input())
words = []
for _ in range(n):
word = input().lower()
[Link](word)
max_vowel_word = max(words, key=lambda word: sum(1 for char in
word if char in "aeiou"))
print(max_vowel_word)
7 Problem Statement
Priya is working on a task where she needs to calculate a specific value for each number in a
list. For each number, she needs to compute the difference between the product and the sum
of its digits. Priya decides to use a lambda function to apply this calculation to each element
in the list of integers.
Write a program that takes a list of integers and applies the following lambda function to each
integer:
difference = (product of digits) - (sum of digits)
Input Format
The first line contains an integer n, representing the number of integers in the list.
The second line contains n space-separated integers.
Output Format
For each number in the list, output prints the result (the difference between the product and
the sum of its digits) on a separate line.
n = int(input())
numbers = list(map(int, input().split()))
calculate_difference = lambda num: (lambda digits: (reduce(lambda x, y:
x * y, digits) - sum(digits)))(list(map(int, str(num))))
from functools import reduce
result = list(map(calculate_difference, numbers))
for res in result:
print(res)
8 Problem Statement
Aryan works at a logistics company and needs a program to calculate shipping costs based on
a package's weight and destination. The destinations can be Domestic, International, or
Remote, each with a fixed rate per kilogram. These rates should be defined as global constants.
Help Aryan build a program that computes and displays the total shipping cost accurately.
Constant Values:
DOMESTIC_RATE = 5.0
INTERNATIONAL_RATE = 10.0
REMOTE_RATE = 15.0
Function Signature: calculate_shipping(weight, destination)
Formula: shipping cost = weight * destination rate
Input Format
The first line of the input consists of a float representing the weight of the package.
The second line consists of a string representing the destinations(Domestic or International, or
Remote).
Output Format
The program outputs any one of the following:
1. If the input is valid and the destination is recognized, the output should consist of a single line
stating the calculated shipping cost for the given weight and destination in the format:
"Shipping cost to [destination] for a [weight] kg package: [calculated cost]" with two decimal
places.
2. If the input weight is not a positive float, print "Invalid weight. Weight must be greater than
0."
3. If the input destination is not one of the valid options, print "Invalid destination."
DOMESTIC_RATE = 5.0
INTERNATIONAL_RATE = 10.0
REMOTE_RATE = 15.0
def calculate_shipping(weight, destination):
if weight <= 0:
print("Invalid weight. Weight must be greater than 0.")
return None
if destination == "Domestic":
shipping_cost = weight * DOMESTIC_RATE
elif destination == "International":
shipping_cost = weight * INTERNATIONAL_RATE
elif destination == "Remote":
shipping_cost = weight * REMOTE_RATE
else:
print("Invalid destination.")
return None
return shipping_cost
weight = float(input())
destination = input()
shipping_cost = calculate_shipping(weight, destination)
if shipping_cost is not None:
print(f"Shipping cost to {destination} for a {weight} kg package:
{shipping_cost:.2f}")
9 Problem Statement
Imagine you are developing a text analysis tool for a cybersecurity company. Your task is to
create a function that analyzes input strings to categorize and count the characters into four
categories: uppercase letters, lowercase letters, digits, and special characters. The company
needs this tool to process log files and identify potential security threats.
Function Signature: analyze_string(input_string)
Input Format
The input consists of a single string (without space), which may include uppercase letters,
lowercase letters, digits, and special characters.
Output Format
The first line contains an integer representing the count of uppercase letters in the format
"Uppercase letters: [count]".
The second line contains an integer representing the count of lowercase letters in the format
"Lowercase letters: [count]".
The third line contains an integer representing the count of digits in the format "Digits: [count]".
The fourth line contains an integer representing the count of special characters in the format
"Special characters: [count]".
def analyze_string(input_string):
uppercase_count = 0
lowercase_count = 0
digit_count = 0
special_count = 0
for char in input_string:
if [Link]():
uppercase_count += 1
elif [Link]():
lowercase_count += 1
elif [Link]():
digit_count += 1
else:
special_count += 1
return uppercase_count, lowercase_count, digit_count, special_count
input_string = input()
uppercase_count, lowercase_count, digit_count, special_count =
analyze_string(input_string)
print("Uppercase letters:", uppercase_count)
print("Lowercase letters:", lowercase_count)
print("Digits:", digit_count)
print("Special characters:", special_count)
10 Problem Statement
Sophia is developing a feature for her online banking application that calculates the total sum
of digits in customers' account numbers. This sum is used to generate unique verification codes
for secure transactions. She needs a program that takes an account number as input and outputs
the sum of its digits.
Help Sophia to complete her task.
Function Specification: def sum_digits(num)
Input Format
The input consists of an integer, representing the customer's account number.
Output Format
The output prints an integer representing the sum of the digits of the account number.
num = int(input())
def sum_digits(num):
digit_sum = 0
while num > 0:
digit = num % 10
digit_sum += digit
num //= 10
return digit_sum
def sum_digits(num):
# Convert the number to a string to easily iterate through
each digit
return sum(int(digit) for digit in str(num))
# Input handling
num = int(input()) # Take input as an integer
# Output the sum of digits
print(sum_digits(num))
sum = sum_digits(num)
print(sum)