0% found this document useful (0 votes)
22 views

Functions

Uploaded by

717823z139
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Functions

Uploaded by

717823z139
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Assignment

Assignment #: 7

Topic : Functions
Level 1: Easy
1. Write a function check_even_odd that takes a number as input and

checks whether it is even or odd.

Sample test Cases:

Test Cases Test Case1: Test Case 2:

Input 5 6

Output Odd Even

Code:
def check_even_odd(num):
if num % 2 == 0:
return "even"
else:
return "odd"

num = int(input("enter number : "))


print(check_even_odd(num))

Output:

2. Write a function find_max that takes three numbers as input and returns

the maximum of the three.

Sample test Cases:

Test Cases Test Case1: Test Case 2:

Input 3, 7, 5 10, 2, 10

Output 7 10

Code:
def find_max(num1,num2,num3):
if num1 > num2 and num3:
return num1
elif num2 > num1 and num3:
return num2
else:
return num3

num1 = int(input("enter num1 : "))


num2 = int(input("enter num2 : "))
num3 = int(input("enter num3 : "))

print(find_max(num1,num2,num3))

Output:

3. Write a function calculate_area that takes the radius of a circle as input and

returns the area. Use π = 3.14.

Sample test Cases:

Test Cases Test Case1: Test Case 2:

Input 5 10

Output 78.5 314.0

Code:
def radius_of_circle(r):
return 3.14 * r * r

r = int(input("enter r : "))
print(radius_of_circle(r))

Output:
4. Write a function celsius_to_fahrenheit that takes a temperature in Celsius

and converts it to Fahrenheit.

Sample test Cases:

Test Cases Test Case1: Test Case 2:

Input 0 100

Output 32.0 212.0

Code:
def celcius_to_farenheit(celcius):
return (9/5)*celcius + 32
celcius = int(input("enter celcius : "))
print(celcius_to_farenheit(celcius))

Output:

5. Write a function is_leap_year that takes a year as input and checks if it is a

leap year.

Sample test Cases:

Test Cases Test Case1: Test Case 2:

Input 2020 2021

Output Leap Year Not a Leap Year

Code:
def is_leap_year(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return "leap year"
else:
return "not a leap year"
else:
return "leap year"
else:
return "not a leap year"

year = int(input("enter year : "))


print(is_leap_year(year))

Output:
6. Write a function factorial that takes a number as input and returns its factorial.

Sample test Cases:

Test Cases Test Case1: Test Case 2:

Input 5 3

Output 120 6

Code:
def factorial(num):
for i in range(1,num):
num = num * i
return num

num = int(input("enter number : "))


print(factorial(num))

Output:

7. Write a function is_palindrome that takes a string as input and checks if it is

a palindrome.

Sample test Cases:

Test Cases Test Case1: Test Case 2:

Input "radar" "hello"


Output Palindrome Not a Palindrome

Code:
def is_palindrome(str):
if str == str[::-1]:
return "palindrome"
else:
return "not a palindrome"

str = (input("enter word : "))


str.lower()
print(is_palindrome(str))

Output:

8. Write a function sum_of_digits that takes a number as input and returns

the sum of its digits.

Sample test Cases:

Test Cases Test Case1: Test Case 2:

Input 123 456

Output 6 15

Code:
def sum_of_digits(number):
if number < 0:
number = -number

sum_digits = 0
while number > 0:
digit = number % 10
sum_digits += digit
number = number // 10

return sum_digits

number = int(input("Enter a number: "))


print(sum_of_digits(number))

Output:
9. Write a function string_length that takes a string as input and returns its length.

Sample test Cases:

Test Cases Test Case1: Test Case 2:

Input "hello" "openai"

Output 5 6

Code:
def string_length(str):
return len(str)

str = input("enter word :")


print(string_length(str))

Output:

10. Write a function is_prime that takes a number as input and checks if it

is prime.

Sample test Cases:

Test Cases Test Case1: Test Case 2:

Input 11 12

Output Prime Not Prime

Code:
def is_prime(number):
if number <= 1:
return "not prime"
if number <= 3:
return "prime"
if number % 2 == 0 or number % 3 == 0:
return "not prime"
i = 5
while i * i <= number:
if number % i == 0 or number % (i + 2) == 0:
return "not prime"
i += 6
return "prime"

number = int(input("Enter a number: "))


print(is_prime(number))

Output:

11. Write a function count_vowels that takes a string as input and returns

the number of vowels in the string.

Sample test Cases:


Test Cases Test Case1: Test Case 2:

Input "hello" "beautiful"

Output 2 5

Code:
def count_vowels(str):
vowels = "aeiouAEIOU"
count = 0
for char in str:
if char in vowels:
count += 1
return count

str = input("Enter a string: ")


print(count_vowels(str))

Output:

12. Write a function find_gcd that takes two numbers as input and returns

their greatest common divisor (GCD).

Sample test Cases:


Test Cases Test Case1: Test Case 2:

Input 12, 15 18, 24

Output 3 6

Code:
def find_gcd(a, b):
while b:
a, b = b, a % b
return a

num1 = int(input("Enter the first number: "))


num2 = int(input("Enter the second number: "))
print(find_gcd(num1, num2))

Output:

13. Concatenation of Array

Problem Statement: Given an integer array nums of length n, you want to create

an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for

0 <= i < n (0-indexed).

Specifically, ans is the concatenation of two nums arrays.

Return the array ans.

Constraints

n == nums.length

1 <= n <= 1000

1 <= nums[i] <= 1000

Sample test Cases:

Test Cases Test Case1: Test Case 2:

Input 12, 15 18, 24

Output 3 6
14. Shuffle the Array

Problem Statement: Given the array nums consisting of 2n elements in the

form [x1,x2,...,xn,y1,y2,...,yn].

Return the array in the form [x1,y1,x2,y2,...,xn,yn]

Constraints

1 <= n <= 500

nums.length == 2n

1 <= nums[i] <= 10^3

Sample test Cases:

Test Cases Test Case1: Test Case 2:

Input 12, 15 18, 24

Output 3 6

15. Running Sum of 1d Array

Problem Statement: Given an array nums. We define a running sum of an array as

runningSum[i] = sum(nums[0]…nums[i]).

Return the running sum of nums.

Constraints

1 <= nums.length <= 1000

-10^6 <= nums[i] <= 10^6

Sample test Cases:

Test Cases Test Case1: Test Case 2:

Input [1,2,3,4] [1,1,1,1,1]

Output [1,3,6,10] [1,2,3,4,5]

Level 2: Medium
1. A communication system converts data into binary number format for

transmission purpose. User enters data in numeric form. Write a method to

convert decimal number into binary numbers & print it.

Sample test Cases:

Test Cases Test Case1:

Input 25

Output 11001

Code:
def decimal_to_binary_builtin(n):
return bin(n).replace("0b", "")

number = int(input("Enter a decimal number: "))


print(decimal_to_binary_builtin(number))

Output

2. Write a function to find whether the blood donor is eligible or not for donating

blood. The rules laid down are as follows. a. Age should be above 18 years but not

more than 55 years. b. Weight should be more than 45kg.

Sample test Cases:

Test Cases Test Case1: Test Case2:

Input 20, 50 60, 70

Output Eligible Not Eligible

Code:
def is_eligible_to_donate(age, weight):
if age > 18 and age <= 55 and weight > 45:
return "Eligible"
return "Not Eligible"

age = int(input("Enter age : "))


weight = float(input("Enter weight : "))
print(is_eligible_to_donate(age,weight))
Output:

3. You are developing a scientific calculator app that requires implementing a

feature to calculate the power of a number. Write a function power that takes two

numbers, base and exponent, as input and returns the result of base raised to the

power of exponent.

Sample test Cases:

Test Cases Test Case1: Test Case2:

Input base = 2, exponent = 3 base = 5, exponent = 0

Output 8 0
4. You are developing a statistics module that needs a function to find the

maximum and minimum values in a list of numbers.

Sample test Cases:

Test Cases Test Case1: Test Case2:

Input numbers = [3, 5, 7, 2, 8] numbers = [10, 20, 5, 15, 25]

Output max = 8, min = 2 max = 25, min = 5

Code:
def find_max_and_min(numbers):
numbers.sort()
return numbers[0],numbers[-1]

n = int(input("enter size : "))


numbers = []
for i in range(0,n):
numbers.insert(i,int(input("enter elemets")))
print(find_max_and_min(numbers))

Output:

5. You are developing a bank account management system where customers can

perform transactions. Write a function calculate_balance that takes an initial

balance and a list of transactions (positive for deposits and negative for

withdrawals) and returns the final balance.

Sample test Cases:

Test Cases Test Case1: Test Case2:


Input initial_balance = 1000, initial_balance = 500,

transactions = [200, -100, 300, - transactions = [-100, -50, 200]

50]

Output 1350 550

Code:
def calculate_balance(initial_balance, transactions):
final_balance = initial_balance
for i in transactions:
final_balance += i
return final_balance

initial_balance = int(input("Enter the initial balance: "))


transactions = []
for i in range(0,4):
transactions.insert(i,int(input("enter tramsaction : ")))
final_balance = calculate_balance(initial_balance, transactions)
print(final_balance)

Output:

6. You are building an online shopping cart system. Write a function

calculate_total that takes a list of item prices and a discount percentage, then

returns the total price after applying the discount.

Sample test Cases:

Test Cases Test Case1: Test Case2:

Input item_prices = [100, 200, 300], item_prices = [50, 75, 100],

discount_percentage = 10 discount_percentage = 5
Output 540 213.75

Code:
def calculate_total(item_prices, discount_percentage):
total_price = sum(item_prices)
discount_amount = total_price * (discount_percentage / 100)
total_price_after_discount = total_price - discount_amount
return total_price_after_discount

item_prices = []
for i in range(0,3):
item_prices.insert(i,int(input("enter price : ")))
discount_percentage = int(input("ebter discount : "))
print(calculate_total(item_prices, discount_percentage))

Output:

7. You are developing an employee performance evaluation system. Write a

function evaluate_performance that takes the number of projects completed and

the number of hours worked, and returns a performance rating (Excellent, Good,

Average, Poor).

Sample test Cases:

Test Cases Test Case1: Test Case2:

Input projects_completed = 10, projects_completed = 5,

hours_worked = 150 hours_worked = 200

Output Excellent Average

Code:
def evaluate_performance(projects_completed, hours_worked):
perfomance = projects_completed / hours_worked

if perfomance >= 2:
return "Excellent"
elif perfomance >= 1.5:
return "Good"
elif perfomance >= 1:
return "Average"
else:
return "Poor"

projects = int(input("Enter number of projects completed: "))


hours = int(input("Enter number of hours worked: "))
print(evaluate_performance(projects, hours))

Output:

8. You are developing a travel expense calculator for business trips. Write a

function calculate_expenses that takes the number of days of the trip, daily

allowance, and other expenses, and returns the total expense.

Sample test Cases:

Test Cases Test Case1: Test Case2:

Input days = 5, daily_allowance = 50, days = 3, daily_allowance = 75,

other_expenses = 100 other_expenses = 150

Output 350 375

Code:
def expence_calculator(days,daily_allowance,other_expenses):
return days*daily_allowance+other_expenses

days = int(input("enter no of days : "))


daily_allowance = int(input("enter daily allowance : "))
other_expenses = int(input("enter other expenses : "))
print(expence_calculator(days,daily_allowance,other_expenses))

Output:
9. You are developing a weather data analysis tool. Write a function

calculate_average_temperature that takes a list of daily temperatures and returns

the average temperature for the week.

Sample test Cases:


Test Cases Test Case1: Test Case2:

Input temperatures = [30, 32, 31, 29, temperatures = [25, 27, 26, 24,

28, 30, 33] 23, 25, 28]

Output 30.43 25.43

Code:
def calculate_average_temperature(daily_temperatures):

total_temperature = sum(daily_temperatures)
average_temperature = total_temperature / 7
return average_temperature

temperatures = []
for i in range(0,7):
temperatures.insert(i,int(input("enter temperature : ")))
print(calculate_average_temperature(temperatures))

Output:
10. You are developing an online quiz grading system. Write a function grade_quiz

that takes a list of student scores (out of 20) and returns the average score and

the corresponding grade (Pass or Fail, where passing score is 12 or higher).

Sample test Cases:

Test Cases Test Case1: Test Case2:

Input scores = [15, 18, 12, 10, 17] scores = [8, 11, 10, 13, 9]

Output average = 14.4, grade = Pass average = 10.2, grade = Fail

Code:
def grade_quiz(student_scores):

total_score = sum(student_scores)
average_score = total_score / 5

if average_score >= 12:


grade = "Pass"
else:
grade = "Fail"

return average_score, grade

scores = []
for i in range(0,5):
scores.insert(i,int(input("marks : ")))
print(grade_quiz(scores))
output:
11. Sign of Product of an array

Problem statement: There is a function signFunc(x) that returns:

· 1 if x is positive.

· -1 if x is negative.

· 0 if x is equal to 0.

You are given an integer array nums. Let product be the product of all values in the

array nums.

Return signFunc(product).

Constraints:

1 <= nums.length <= 1000

-100 <= nums[i] <= 100

Sample test Cases:


Test Cases Test Case1: Test Case2: Test Case3:

Input nums = [-1,-2,-3,- nums = [1,5,0,2,-3] nums = [-1,1,-1,1,-1]

4,3,2,1]

Output 1 0 -1

12. Smallest Index With Equal Value

Problem statement : Given a 0-indexed integer array nums, return the

smallest index i of nums such that i mod 10 == nums[i], or -1 if such index does

not exist. x mod y denotes the remainder when x is divided by y.

Constraints:

1 <= nums.length <= 1000

-100 <= nums[i] <= 100

Sample test Cases:

Test Cases Test Case1: Test Case2:

Input nums = [0,1,2] nums = [4,3,2,1]

Output 0 2

Explanation: Explanation:

i=0: 0 mod 10 = 0 == nums[0]. i=0: 0 mod 10 = 0 != nums[0].

i=1: 1 mod 10 = 1 == nums[1]. i=1: 1 mod 10 = 1 != nums[1].

i=2: 2 mod 10 = 2 == nums[2]. i=2: 2 mod 10 = 2 == nums[2].

All indices have i mod 10 == i=3: 3 mod 10 = 3 != nums[3].

nums[i], so we return the smallest 2 is the only index which has i mod

index 0. 10 == nums[i].
Level 3: Hard
1. XYZ Technologies is in the process of increment the salary of the employees.

This increment is done based on their salary and their performance appraisal

rating.

If the appraisal rating is between 1 and 4, the increment is 10% of the salary.

If the appraisal rating is between 4.1 and 7, the increment is 25% of the

salary.

If the appraisal rating is between 7.1 and 10, the increment is 30% of the salary.

Help them to do this, by writing a program that displays the incremented salary.

(Use separate function to calculate the increment)

Note: If either the salary is 0 or negative (or) if the appraisal rating is not in the

range 1 to 10 (inclusive), then the output should be “Invalid Input”.

Sample test Cases:

Test Cases Test Case1: Test Case2:

Input Enter the salary 80000 Enter the salary 75000

Enter the appraisal rating 3 Enter the Performance appraisal

rating 4.3

Output 88000 93750

Code:
def salary_increament(salary,appraisal_rating):
if appraisal_rating >=1 and appraisal_rating <=4:
return salary*0.1+salary
elif 4.1 <= appraisal_rating and appraisal_rating >= 7:
return salary*0.25+salary
elif 7.1 <= appraisal_rating and appraisal_rating >= 10:
return salary*0.3+salary

salary = int(input("enter input : "))


appraisal_rating = int(input("enter rating : "))
print(salary_increament(salary,appraisal_rating))

Output:
2. XYZ college wants to recognize the department which has succeeded in getting

the maximum number of placements for this academic year. The departments

that have participated in the recruitment drive are CS, EC, ME. Help the college to

find the department getting maximum placements. Check for all the possible

output given in the sample snapshot.

Note: If any input is negative, the output should be "Input is invalid". If all

departments have equal number of placements, the output should be "None of

the department has got the highest placement". (Use separate function to check

the maximum placements)

Sample test Cases:

Test Cases Test Case1: Test Case2:

Input Enter the no of students placed in Enter the no of students placed in

CS:90 CS:55

Enter the no of students placed in Enter the no of students placed in

EC:45 EC:85

Enter the no of students placed in Enter the no of students placed in

ME:70 ME:85

Output Highest placement CS Highest placement EC ME

Code:
def find_max_placements(department_placements):
max_department = None
max_placements = -1

for department, placements in department_placements.items():


if placements > max_placements:
max_placements = placements
max_department = department

return max_department, max_placements


placements = {}
departments = ['CS', 'EC', 'ME']

for department in departments:


placements[department] = int(input(f"Enter the number of placements for
{department}: "))

print(find_max_placements(placements))

Output:

3. Write a function word_break(s, word_dict) to determine if a string can be

segmented into a space-separated sequence of one or more dictionary words.

Problem Description: Given a string s and a dictionary of strings word_dict, return

True if s can be segmented into a space-separated sequence of one or more

dictionary words, otherwise return False.

Sample test Cases:

Test Cases Test Case1: Test Case2:

Input ("leetcode", ["leet", "code"]) ("applepenapple", ["apple",

"pen"])

Output True True

4. Write a function longest_palindromic_substring(s) to find the longest

palindromic substring in a given string.

Problem Description: Given a string s, return the longest palindromic substring in s.

Sample test Cases:


Test Cases Test Case1: Test Case2:

Input "babad" "cbbd"

Output "bab" or "aba" "bb"

5. Write a function number_to_words(num) to convert a non-negative integer to its

English words representation.

Problem Description: Convert a non-negative integer num to its English words

representation.

Sample test Cases:

Test Cases Test Case1: Test Case2:

Input 123 12345

Output "One Hundred Twenty Three" "Twelve Thousand Three Hundred

Forty Five"

You might also like