[go: up one dir, main page]

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

Algorithm 1

The document outlines a series of programming assignments focused on algorithms, categorized into easy and medium levels. Each assignment includes a specific task, such as calculating sums, averages, and checking for prime numbers, along with sample test cases for clarity. The document serves as a guide for learners to develop their programming skills through practical exercises.

Uploaded by

lohithd20ca047
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)
53 views12 pages

Algorithm 1

The document outlines a series of programming assignments focused on algorithms, categorized into easy and medium levels. Each assignment includes a specific task, such as calculating sums, averages, and checking for prime numbers, along with sample test cases for clarity. The document serves as a guide for learners to develop their programming skills through practical exercises.

Uploaded by

lohithd20ca047
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
You are on page 1/ 12

Assignment

Assignment #: 1

Topic : Algorithm

Level 1: Easy

1. Sum of Two Numbers: To add two numbers and display their sum, ask the user to input
the first and second numbers. Add these numbers together and display the result. For
example, if the user inputs 5 and 3, the program will display 8. Similarly, if the inputs are
-2 and 10, the result will be 8. This simple process creates a program that adds two numbers
and shows the result.

Question: Write an algorithm to read two numbers from the user and compute their sum.

Sample Testcase:

Testcase Testcase 1 Testcase 2


Input A=5, B=2 A=23, B=43
Output C=7 C=56

2. Calculate Average of Three Numbers: To calculate the average of three numbers, start
by asking the user to input the first, second, and third numbers. Add these numbers together
and divide the sum by three to get the average. Finally, display the average to the user. For
example, if the user inputs 4, 8, and 12, the program will display 8 as the average. Similarly,
if the inputs are 10, 20, and 30, the average will be 20. This simple process creates a
program that calculates and displays the average of three numbers.

Question: Develop an algorithm to input three numbers and compute their average.

Sample Testcase:

Testcase Testcase 1 Testcase 2


Input 5, 10, 15 12, 18, 24
Output 10.0 18.0

3. Check Even or Odd: To check if a number is even or odd, start by asking the user to input
a number. If the number is divisible by 2 (i.e., the remainder is 0), it is even. Otherwise, it
is odd. Finally, display whether the number is even or odd. For example, if the user inputs
4, the program will display Even. Similarly, if the input is 7, the program will display Odd.
This simple process creates a program that checks and displays whether a number is even
or odd.
Question: Create an algorithm that inputs a number and determines if it is even or odd.

Sample Testcase:

Testcase Testcase 1 Testcase 2


Input 5 9
Output Odd Even

4. Fibonacci Series: The Fibonacci series starts with 0 and 1, where each subsequent number
is the sum of the two preceding numbers. For example, starting from 0 and 1, the next
number is 1 (0 + 1), then 2 (1 + 1), 3 (1 + 2), and so on. It's a sequence where each number
is the sum of the two before it.

Question: Design an algorithm to generate the Fibonacci series up to a specified number


of terms.

Sample Testcase:

Testcase Testcase 1 Testcase 2


Input 5 8
Output 0, 1, 1, 2, 3 0, 1, 1, 2, 3, 5, 8, 13

5. Factorial Calculation: Factorial calculation involves multiplying a number by all positive


integers less than it down to 1. For example, 5!5!5! (read as "five factorial") is calculated
as 5×4×3×2×1=1205 \times 4 \times 3 \times 2 \times 1 = 1205×4×3×2×1=120. It's a
fundamental operation used in mathematics for various calculations, including
permutations, combinations, and probability.

Question: Write an algorithm to compute the factorial of a non-negative integer input by


the user.

Sample Testcase:

Testcase Testcase 1 Testcase 2


Input 5 3
Output 120 6

6. Check Leap Year: A leap year is a year with 366 days instead of the usual 365. It happens
every four years to adjust our calendar to match the Earth's orbit around the sun. To check
if a year is a leap year, two rules apply: first, the year must be divisible by 4; second, if the
year is divisible by 100, it must also be divisible by 400. For example, 2020 was a leap
year because it's divisible by 4 but not by 100. However, 1900 was not a leap year because
although divisible by 4 and 100, it's not divisible by 400. Leap years ensure our calendar
stays accurate with seasonal changes like equinoxes and solstices occurring predictably
each year.

Question: Develop an algorithm that inputs a year and determines if it is a leap year or not.

Sample Testcase:

Testcase Testcase 1 Testcase 2


Input 2020 2023
Output True False

7. Function to Calculate Area of a Rectangle: To find the area of a rectangle, multiply its
length by its width. You start by inputting these two dimensions from the user. For
example, if the length is 5 units and the width is 3 units, multiplying them gives an area of
15 square units. This calculation determines how much space the rectangle covers on a
surface, using the formula A= length * Width. It's a basic concept used in fields like
construction, geometry, and everyday measurements.

Question: Design an algorithm to define a function that calculates and returns the area of
a rectangle given its length and width as inputs.

Sample Testcase:

Testcase Testcase 1 Testcase 2


Input 10, 7 5, 3
Output 70 15

8. Function to Check Prime Number: To check if a number is prime, you start by asking
the user to input a number. Then, you verify if the number is greater than 1 (since 1 is not
prime). Next, you check if the number is divisible by any number other than 1 and itself.
If it isn't divisible by any other numbers, then it is prime. For example, if the user inputs 7,
you check if 7 is divisible by 2, 3, 4, 5, or 6. Since 7 is not divisible by any of these numbers,
it is prime. This method is commonly used to determine prime numbers in mathematics.

Question: Create an algorithm to define a function that takes an integer input and returns
True if it is a prime number, otherwise False.

Sample Testcase:

Testcase Testcase 1 Testcase 2


Input 7 9
Output True False
9. Sum of List Elements: To compute the sum of elements in a list, you begin by prompting
the user to input a list of integers. Then, you iterate through each element in the list, adding
them together to get the total sum. Finally, you display the computed sum to the user. For
example, if the user inputs [3, 7, 2, 1], the program calculates the sum as 13 by adding 3 +
7 + 2 + 1. This process effectively determines the total sum of all elements contained within
the list, making it a fundamental operation in data analysis and numerical computations.

Question: Write an algorithm to input a list of integers and compute the sum of all elements
in the list.

Sample Testcase:

Testcase Testcase 1 Testcase 2


Input [1, 2, 3, 4, 5] [-10, 0, 10]
Output 15 0

10. Count Occurrences of an Element in a List: To count occurrences of a specific element


in a list, you start by asking the user to input both a list of integers and a target number to
count. Then, you iterate through each element in the list and check how many times the
target number appears. Finally, you display the count of occurrences to the user. For
example, if the user inputs the list [1, 2, 3, 2, 2, 4] and wants to count occurrences of 2, the
program would determine that 2 appears 3 times in the list. This task involves iterating
through the list and tallying instances of the specified element, providing a useful tool for
data analysis and manipulation in various programming scenarios.

Question: Develop an algorithm to input a list of integers and a target number, then count
how many times the target number appears in the list.

Sample Testcase:

Testcase Testcase 1 Testcase 2


Input List = [1, 2, 3, 4, 2, 2, 5], List = ['a', 'b', 'a', 'c', 'a', 'd'],

Target = 2 Target = 'a'


Output 3 3

Level 2: Medium

1. Calculate Total Salary: To calculate the total salary in rupees, you first ask the user to
input the number of employees and their respective salaries in rupees. Then, multiply each
employee's salary by their number of hours worked to calculate their total salary. Finally,
sum up all the individual salaries to get the total salary for all employees in rupees. For
example, if there are three employees with salaries of Rs. 500 per hour, Rs. 750 per hour,
and Rs. 1000 per hour, and they worked 40 hours each, the total salary would be calculated
as follows:

• Employee 1: Rs. 500/hour * 40 hours = Rs. 20,000


• Employee 2: Rs. 750/hour * 40 hours = Rs. 30,000
• Employee 3: Rs. 1000/hour * 40 hours = Rs. 40,000
• Total Salary = Rs. 20,000 + Rs. 30,000 + Rs. 40,000 = Rs. 90,000

This method involves multiplying each employee's hourly rate by the number of hours
worked to determine individual salaries and then summing these amounts to calculate the
overall total salary in rupees.

Question: Design an algorithm to input the number of hours worked and hourly wage of
an employee, then calculate and print the total salary.

Sample Testcase:

Testcase Testcase 1 Testcase 2


Input Number of employees: 3 Number of employees: 2

Hourly salaries (in Rs.): [500, Hourly salaries (in Rs.): [600,
750, 1000] 900]

Hours worked per employee: 40 Hours worked per employee:


50
Output 90000 Rs. 75000 Rs.

2. Temperature Conversion: To convert temperatures between Celsius and Fahrenheit


scales, you start by asking the user to input a temperature in one scale. Then, based on
whether the input is in Celsius or Fahrenheit, you apply a simple mathematical formula to
convert it to the other scale.

Celsius to Fahrenheit: Multiply the Celsius temperature by 9/5 and add 32.

Example: To convert 20°C to Fahrenheit: F=(9/5)×20+32=68°F

Fahrenheit to Celsius: Subtract 32 from the Fahrenheit temperature and then multiply by
5/9.

Example: To convert 68°F to Celsius: C=(5/9)×(68−32)=20°C.

These formulas allow for quick and accurate temperature conversions between Celsius and
Fahrenheit, which are widely used in daily life, weather reports, and various scientific and
industrial applications.
Question: Write an algorithm to input a temperature in Celsius and convert it to Fahrenheit
using the formula.

Sample Testcase:

Testcase Testcase 1 Testcase 2


Input 25 0
Output 77.0 32.0

3. Simple Interest Calculation: Calculating simple interest involves gathering the principal
amount, annual interest rate, and time period from the user. Using the formula,

Simple Interest=(P×R×T)/100.

Where, P is the principal amount, R is the annual interest rate, and T is the time period in
years, you compute the interest.

For example, if someone invests Rs. 10,000 at 5% interest for 2 years, the calculation would
be Simple Interest=(10000×5×2)100=Rs.1000. This method is straightforward and
commonly used in financial transactions to determine interest earnings or payments
accurately.

Question: Develop an algorithm to compute the simple interest for a given principal
amount, interest rate, and time period provided by the user.

Sample Testcase:

Testcase Testcase 1 Testcase 2


Input Principal amount = 1000 Principal amount = 2500

Annual interest rate (%) = 5 Annual interest rate (%) = 8.5

Time period (years) = 2 Time period (years) = 3.5


Output Simple Interest = 100.0 Simple Interest = 744.375

4. Counting Vowels: Counting vowels in a string involves going through each character and
checking if it's a vowel (a, e, i, o, u). You start by asking the user to input a string. Then,
you count how many times these vowels appear in the string, both in lowercase and
uppercase. For example, if the input is "Hello World", the program would find and display
that there are 3 vowels in total. This method is useful for tasks like text analysis and basic
text processing.

Questions: Design an algorithm that reads a string input and counts the number of vowels
(a, e, i, o, u) present in the string.
Sample Testcase:

Testcase Testcase 1 Testcase 2


Input Hello World Python Programming
Output 3 4

5. Finding Maximum and Minimum: To find the maximum and minimum values in a list,
you start by asking the user to input a list of numbers. Then, you scan through the list to
identify the largest and smallest values present. This involves iterating through each
number, updating variables to track the maximum and minimum values as you go. Finally,
you display these values to the user. For example, if the input list is [3, 1, 7, 2, 5], the
program would determine that the maximum value is 7 and the minimum value is 1. This
method is useful for tasks like data analysis and finding extremes in numerical datasets.

Questions: Write an algorithm to input a list of integers and find the maximum and
minimum values in the list.

Sample Testcase:

Testcase Testcase 1 Testcase 2


Input [10, -5, 0, 15, -3] [3, 7, 2, 8, 5]
Output Maximum: 15 Maximum: 8

Minimum: -5 Minimum: 2

6. Sorting Numbers: Sorting a list of numbers means arranging them in either ascending
(smallest to largest) or descending (largest to smallest) order. You start by asking the user
to input a list of numbers. Using built-in functions like Python's sorted() or list methods
like .sort(), you then rearrange these numbers. For example, if the input is [3, 1, 7, 2, 5],
sorting would produce [1, 2, 3, 5, 7] in ascending order. Sorting is crucial in programming
for tasks like organizing data for efficient searching and presenting information
systematically.

Question: Develop an algorithm to sort a list of integers in ascending order using the
Bubble Sort algorithm.

Sample Testcase:

Testcase Testcase 1 Testcase 2


Input [5, 2, 8, 1, 3] [10, -5, 0, 15, -3]
Output [1, 2, 3, 5, 8] [-5, -3, 0, 10, 15]

7. Check Palindrome: Checking if a string is a palindrome involves verifying whether it


reads the same forward and backward. To start, you prompt the user to enter a string. Next,
you compare the string to its reverse counterpart. If both versions are identical, then the
string is confirmed to be a palindrome. For instance, if the input string is "radar", the
program would detect it as a palindrome because reversing "radar" still yields "radar". This
process is essential in programming for various applications, including verifying data
correctness, implementing efficient text processing algorithms, and conducting basic string
manipulations.

Question: Design an algorithm to define a function that checks if a given string is a


palindrome (reads the same forward and backward).

Sample Testcase:

Testcase Testcase 1 Testcase 2


Input Madam Hello
Output True False

8. Calculate Power: Calculating the power of a number involves multiplying a base number
by itself a specified number of times, known as the exponent. You start by asking the user
to input two numbers: the base and the exponent. Using Python's ** operator or the pow()
function, you then compute the result of raising the base to the exponent. For example, if
the user enters a base of 2 and an exponent of 3, the program calculates 2^3, resulting in 8.
This process is fundamental in mathematics and programming, used for tasks like
computing growth rates, performing mathematical modeling, and solving various scientific
equations involving powers and exponents.

Question: Write an algorithm to define a function that computes the power of a number
given the base and exponent.

Sample Testcase:

Testcase Testcase 1 Testcase 2


Input Base = 2, Exponent = 5 Base = 3, Exponent = 4
Output 32 81

9. Remove Duplicates: To remove duplicates from a list, the algorithm systematically


processes each element to ensure only unique values are retained. Beginning with an empty
list L_unique, it iterates through each element of the input list L. For every element
encountered, it checks if it already exists in L_unique. If not, the element is added to
L_unique. This method effectively filters out duplicates while preserving the original order
of elements as they first appear in L. For instance, given an input list [1, 2, 2, 3, 4, 4, 5],
the algorithm produces an output list [1, 2, 3, 4, 5], ensuring that each unique value appears
exactly once. This approach is straightforward and suitable for tasks where maintaining
unique data elements is essential, such as data preprocessing and analysis..

Questions: Develop an algorithm to input a list of integers and remove duplicate elements,
ensuring only unique elements remain in the list.
Sample Testcase:

Testcase Testcase 1 Testcase 2


Input [1, 2, 3, 2, 4, 1] ['a', 'b', 'a', 'c', 'b']
Output [1, 2, 3, 4] ['a', 'b', 'c']

10. Sum of Even Numbers: Finding the sum of even numbers in a list involves iterating
through each integer in the list and selectively adding those numbers that are divisible by
2. Initially, you prompt the user to input a list of integers. Then, you initialize a variable to
accumulate the sum of these even numbers. As you iterate through each number in the list,
you use the modulus operator % to check if the number is even. If it is, you add it to the
accumulating sum. Finally, you display the total sum of these even numbers to the user.
For example, given the list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], the program would compute the
sum of even numbers (2 + 4 + 6 + 8 + 10), resulting in 30. This approach efficiently
computes the sum of even integers, providing a straightforward method for numerical
analysis and processing of lists based on specific criteria like evenness.

Question: Design an algorithm to input a list of integers and calculate the sum of all even
numbers present in the list.

Sample Testcase:

Testcase Testcase 1 Testcase 2


Input [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [15, 20, 25, 30, 35, 40]
Output 30 90

Level 3: Hard

1. Online Shopping Checkout: Design algorithm to simulate an online shopping checkout


process. Include steps to add items to a cart, apply discounts if applicable, calculate the
total cost including taxes and shipping, and process payment.

Sample Testcase:

Testcase Testcase 1
Input Items in cart: [{"item": "Shirt", "price": 25}, {"item": "Jeans", "price": 50}]

Discounts applied: 10% off on Jeans

Shipping method: Standard (Rs. 50)


Output Total cost: Rs. 77.50

Payment processed successfully.


2. Weather Forecast Application: Write algorithm for a weather forecast application.
Implement steps to fetch weather data for a user-specified location, display current weather
conditions, forecast for the next few days, and provide alerts for severe weather conditions.

Sample Testcase:

Testcase Testcase 1
Input Location: New York, USA
Output Current weather: Partly cloudy, 28°C

Forecast for next 3 days: Day 1: Sunny, 30°C | Day 2: Thunderstorms,


25°C | Day 3: Clear skies, 27°C

No severe weather alerts.

3. Fitness Tracker: Develop algorithm for a fitness tracker application. Include


functionalities to log daily exercise activities such as running distance, calories burned, and
steps taken. Calculate weekly summaries and set goals based on user inputs.

Sample Testcase:

Testcase Testcase 1
Input Daily activities logged: Running 5 km, 400 calories burned, 7000 steps
Output Weekly summary: Total distance: 35 km, Calories burned: 2800, Steps
taken: 49000

Goal progress: 80% of weekly running goal achieved.

4. Movie Recommendation System: Design algorithm for a movie recommendation system.


Implement steps to collect user preferences, analyze movie ratings, recommend movies
based on genres and user history, and allow for user feedback to improve
recommendations.

Sample Testcase:

Testcase Testcase 1
Input User preferences: Action, Comedy

User history: Liked: Die Hard, The Hangover | Disliked: Titanic


Output Recommended movies: Die Hard 2, Rush Hour, Deadpool

User feedback: Liked Deadpool, Disliked Rush Hour.

5. Student Course Registration: Write algorithm for a student course registration system.
Include steps for students to view available courses, select courses, check prerequisites,
and register for classes while ensuring no scheduling conflicts.
Sample Testcase:

Testcase Testcase 1
Input Student: John Doe

Courses selected: Mathematics, Physics


Output Registration successful for Mathematics and Physics.

6. Recipe Search and Display: Develop algorithm for a recipe search and display
application. Implement steps to search for recipes based on ingredients, display detailed
recipe instructions including cooking time and nutritional information, and allow users to
save favorite recipes.

Sample Testcase:

Testcase Testcase 1
Input Search query: Chicken, Pasta
Output Recipe found: Chicken Alfredo Pasta

Cooking time: 30 minutes

Nutritional information: Calories: 450, Carbs: 35g, Protein: 30g

7. Password Strength Checker: Design algorithm for a function that checks the strength of
a password entered by the user. Evaluate criteria such as length, presence of uppercase
letters, lowercase letters, numbers, and special characters. Return a strength rating or
validation result.

Sample Testcase:

Testcase Testcase 1
Input Password: P@ssw0rd
Output Password strength: Strong

8. Employee Performance Evaluation: Write algorithm for a function that evaluates


employee performance based on performance metrics such as sales targets achieved,
customer satisfaction ratings, and attendance records. Provide a performance rating based
on predefined criteria.

Sample Testcase:

Testcase Testcase 1
Input Employee: Alice

Performance metrics: Sales targets achieved: 90%, Customer satisfaction:


85%, Attendance: 95%
Output Performance rating: Excellent

9. Inventory Stock Alert System: Develop algorithm for a system that monitors inventory
levels of products. Implement steps to check current stock levels against predefined
minimum thresholds, generate alerts for low stock items, and initiate restocking
procedures.

Sample Testcase:

Testcase Testcase 1
Input Product: Laptops

Current stock: 30 units

Minimum threshold: 50 units


Output Alert: Low stock! Only 30 units of Laptops remaining.

Restocking initiated.

10. Student Grade Analysis: Design algorithm for analyzing student grades stored in a list.
Implement functions to calculate average grades, identify students with failing grades,
determine class averages, and generate statistical summaries of grade distributions.

Sample Testcase:

Testcase Testcase 1
Input Grades: [85, 90, 75, 60, 95]
Output Average grade: 81

Failing grades: 1 student

Class average: 81

You might also like