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

Python Coddes

The document contains a series of Python programming exercises designed to address various real-world scenarios, including data recording, calculations, and data analysis. Each exercise provides a specific problem statement followed by a sample code solution that demonstrates the implementation of Python concepts such as input handling, data structures, and mathematical operations. The exercises range from simple tasks like formatting output to more complex challenges involving data manipulation and analysis.

Uploaded by

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

Python Coddes

The document contains a series of Python programming exercises designed to address various real-world scenarios, including data recording, calculations, and data analysis. Each exercise provides a specific problem statement followed by a sample code solution that demonstrates the implementation of Python concepts such as input handling, data structures, and mathematical operations. The exercises range from simple tasks like formatting output to more complex challenges involving data manipulation and analysis.

Uploaded by

jayjagu96
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

PYTHON CODDES

WEEK 1 LAB EXERCISE

1. Liam works at a car dealership and is responsible for recording the details of
cars that arrive at the showroom. To make his job easier, he wants a
program that can take the car's make, model, and price, and display the
information in a formatted summary.

car_make = input()

car_model = input()

car_price = float(input())

print(f"Car Make: {car_make}")

print(f"Car Model: {car_model}")

print(f"Price: Rs.{car_price:.2f}")

2. Alex is an air traffic controller who needs to record and manage flight delays
efficiently. Given a flight number, the delay in minutes (as a string), and the
coordinates of the flight's current position (as a complex number),

Help Alex convert and store this information in a structured format

flight_number = int(input())

delay = input()

real, imaginary = map(float, input().split())

current_position = complex(real, imaginary)

print(current_position)

print(f"{flight_number}, {delay}, {real}, {imaginary}")

3. A science experiment produces a decimal value as the result. However, the


scientist needs to convert this value into an integer so that it can be used in
further calculations.

Write a Python program that takes a floating-point number as input and


converts it into an integer.

number = float(input())

print(f"The integer value of {number} is: {int(number)}")


4. A smart home system tracks the temperature and humidity of each room.
Create a program that takes the room name (string), temperature (float),
and humidity (float).

Display the room's climate details.

room = input()

temperature = float(input())

humidity = float(input())

print(f"Room: {room}")

print(f"Temperature: {temperature:.2f}")

print(f"Humidity: {humidity:.2f}%")

5. Mandy is working on a mathematical research project involving complex


numbers. For her calculations, she often needs to swap the real and
imaginary parts of two complex numbers.

Mandy needs a Python program that takes two complex numbers as input and
swaps their real and imaginary values.

a=complex(input())

b=complex(input())

real1,imag1 = a.real , a.imag

real2,imag2 = b.real,b.imag

n=complex(imag2,real2)

m=complex(imag1,real1)

print(f"New first complex number:{m}")

print(f"New second complex number:{n}")

6. Ashok is developing a data analytics tool to keep track of various metrics. He


needs to write a program that takes three integer values and one float value
as input. The program should then print the values in a specified order to
help with reporting and analysis.

metric1 = int(input())

metric2=int(input())
metric3=int(input())

measurment = float(input())

print(metric1)

print(f"{measurment:.1f}")

print(metric2)

print(f"{measurment:.1f}")

print(metric3)

print(f"{measurment:.1f}")

7. A company has hired two employees, Alice and Bob. The company wants to
swap the salaries of both employees. Alice's salary is an integer value and
Bob's salary is a floating-point value.

alice_salary = int(input())

bob_salary = float(input())

print("Initial salaries:")

print(f"Alice's salary = {alice_salary}")

print(f"Bob's salary = {bob_salary}")

alice_salary, bob_salary = bob_salary, alice_salary

print("\nNew salaries after swapping:")

print(f"Alice's salary = {alice_salary}")

print(f"Bob's salary = {bob_salary}")

8. Emma is creating a recipe app and needs a program to store and display
recipe details. The program should take the recipe name, number of
ingredients, and preparation time as inputs. It should then format and
display this information.

recipe_name=input()

num_ingredients=int(input())

prep_time=float(input())

print(recipe_name)
print(num_ingredients)

print(f"{prep_time:.1f}")

9. Olivia is creating a wellness dashboard for her new fitness app, FitTrack. She
needs a program that can capture and display key details about a user's
workout. The program should read the user’s full name, the total steps they
ran, the energy they expended in kilojoules, and the duration of their
workout in hours. After collecting this information, the program will generate
a detailed summary of the user’s fitness activity.

user_name = input()

total_steps = int(input())

calories_burned = float(input())

workout_duration = float(input())

print(f"User Name: {user_name}")

print(f"Total Steps: {total_steps}")

print(f"Calories Burned: {calories_burned:.1f}")

print(f"Workout Duration: {workout_duration:.1f} hours")

10. John is developing a financial application to help users manage their


investment portfolios. As part of the application, he needs to write a
program that receives the portfolio's main value and the values of two
specific investments as inputs. The program should then display these
values in reverse order for clear visualization.

investment1 = float(input())

investment2 = float(input())

portfolio_id = int(input())

print("The values in the reverse order:")

print(portfolio_id)

print(investment2)

print(investment1)
11. Given a list of positive and negative numbers, arrange them such that all
negative integers appear before all the positive integers in the array. The
order of appearance should be maintained.

inpu = eval(input())

neg = [num for num in inpu if num < 0]

pos = [num for num in inpu if num >= 0]

res = neg + pos

print("List =", res)

12. Leah, a linguistics researcher, wants to quantify the difference between two
strings by comparing the ASCII values of their corresponding characters.
She needs a measure of how closely related two words are in terms of their
character composition.

s1 = input()

s2 = input()

dif = sum(abs(ord(s1[i]) - ord(s2[i])) for i in range(len(s1)))

print(dif)

13. Kyara is analyzing a series of measurements taken over time. She needs to
identify all the "peaks" in this list of integers. A peak is defined as an element
that is greater than its immediate neighbors. Boundary elements are
considered peaks if they are greater than their single neighbor.

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

peaks = [numbers[i] for i in range(len(numbers))

if (i == 0 and numbers[i] > numbers[i+1]) or

(i == len(numbers) - 1 and numbers[i] > numbers[i-1]) or

(0 < i < len(numbers) - 1 and numbers[i] > numbers[i-1] and numbers[i] >
numbers[i+1])]

print("Peaks:", peaks)
14. Maria, a cryptography enthusiast, wants to subtly transform each character
of a given string into a new code sequence. She decides that characters with
even ASCII values will be incremented by 2, and those with odd ASCII values
will be decremented by 1.

s = input()

tra = ''.join(chr(ord(char) + 2) if ord(char) % 2 == 0 else chr(ord(char) - 1) for char


in s)

print(tra)

15. Alex is working with grayscale pixel intensities from an old photo that has
been scanned in a single row. To detect edges in the image, Alex needs to
calculate the differences between each pair of consecutive pixel intensities.
n = int(input())
pi=list(map(int,input().split()))
dif = tuple(abs(pi[i] - pi[i + 1]) for i in range(n - 1))
print(dif)
16. Gina is working on a data analysis task where she needs to extract sublists
from a given list of integers and find the median of each sublist. For each
median found, she also needs to determine its negative index in the original
list.
def find(n,arr,ranges):
res = []
for start, end in ranges:
sublist = arr[start - 1:end]
sublist.sort()
leng = len(sublist)
if leng % 2 == 1:
med = sublist[leng // 2]
else:
med = sublist[(leng // 2)-1]
neg = -(n - arr.index(med))
res.append(f"{med} : {neg}")
return res
n = int(input())
arr = list(map(int,input().split()))
r = int(input())
ranges = [tuple(map(int,input().split())) for _ in range(r)]
output = find(n,arr,ranges)
for line in output:
print(line)
17. Riley is analyzing DNA sequences and needs to determine which bases
match at the same positions in two given DNA sequences. Each DNA
sequence is represented as a tuple of integers, where each integer
corresponds to a DNA base.
def find_matching_bases(n, seq1, m, seq2):
min_len = min(n, m)
matching_bases = []

for i in range(min_len):
if seq1[i] == seq2[i]:
matching_bases.append(seq1[i])

return matching_bases
n = int(input())
seq1 = list(map(int, input().split()))
m = int(input())
seq2 = list(map(int, input().split()))
matching_bases = find_matching_bases(n, seq1, m, seq2)
print(" ".join(map(str, matching_bases)))
18. James is an engineer working on designing a new rocket propulsion system.
He needs to solve a quadratic equation to determine the optimal launch
trajectory. The equation is of the form ax2 +bx+c=0.
import cmath
def find_roots(a, b, c):
discriminant = b**2 - 4*a*c
if discriminant > 0:
root1 = (-b + discriminant**0.5) / (2*a)
root2 = (-b - discriminant**0.5) / (2*a)
return (root1, root2)
elif discriminant == 0:
root = -b / (2*a)
return (root, root)
else:
root1 = (-b + cmath.sqrt(discriminant)) / (2*a)
root2 = (-b - cmath.sqrt(discriminant)) / (2*a)
return (root1, root2)
n = int(input())
coefficients = list(map(int, input().split()))
a, b, c = coefficients
if a == 0:
print("Invalid input: 'a' must not be zero for a quadratic equation.")
else:
roots = find_roots(a, b, c)
print(roots)

19. Lucas, a cybersecurity analyst, wants to generate a unique


"fingerprint" number for any given string by XOR-ing all its character
codes. This number can be used as a quick integrity check or a hash-
like signature to detect tampering.

def xor_fingerprint(s):

result = 0

for char in s:

result ^= ord(char)

return result

s = input()

fingerprint = xor_fingerprint(s)

print(fingerprint)
20. Julia, a data engineer, wants to apply a custom encoding rule to a
string of characters. According to her rule, if a character's ASCII value
is divisible by 3, it is doubled; otherwise, 5 is added to it.

def custom(s):

result=""

for char in s:

asci=ord(char)

if asci % 3 ==0:
trans = asci*2

else:

trans = asci+5

result += chr(trans)

return result

s = input()

print(custom(s))

21. Emma and Liam are mathematics enthusiasts exploring prime


numbers through unique combinations. They decide to find pairs of
numbers, one from each of their chosen lists, such that the sum of the
pair is a prime number.

def is_p(num):

if num < 2:

return False

for i in range(2, int(num ** 0.5) + 1):

if num % i == 0:

return False

return True

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

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

p = frozenset((a, b) for a in l1 for b in l2 if is_p(a + b))

print(frozenset(p))
22. Emily is a librarian who keeps track of books borrowed and returned
by her patrons. She maintains four sets of book IDs: the first set
represents books borrowed, the second set represents books
returned, the third set represents books added to the collection, and
the fourth set represents books that are now missing. Emily wants to
determine which books are still borrowed but not returned, as well as
those that were added but are now missing. Finally, she needs to find
all unique book IDs from both results.

P = set(map(int, input().split()))

Q = set(map(int, input().split()))

R = set(map(int, input().split()))

S = set(map(int, input().split()))

PQ = sorted(P - Q, reverse=True)

RS = sorted(R - S, reverse=True)

r = sorted(set(PQ) | set(RS), reverse=True)

print(PQ)

print(RS)

print(r)

23. Noah, a global analyst at a demographic research firm, has been


tasked with identifying which country experienced the largest
population growth over a two-year period. He has a dataset where
each entry consists of a country code and its population figures for
two consecutive years. Noah needs to determine which country had
the highest increase in population and present the result in a specific
format.

n = int(input())

mi = float('-inf')
mc = ""

for _ in range(n):

c = input().strip()

p1 = int(input())

p2 = int(input())

g = p2 - p1

if g > mi:

mi = g

mc = c

if mc:

print(f"{{{mc}:{mi}}}")

else:

print("{}")

24. Professor Adams needs to analyze student participation in three


recent academic workshops. She has three sets of student IDs: the
first set contains students who registered for the workshops, the
second set contains students who actually attended, and the third set
contains students who dropped out.

reg = set(map(int,input().split()))

att = set(map(int,input().split()))

dro = set(map(int,input().split()))

ra = reg & att

ad = ra - dro
print(ra)

print(ad)

25. Liam is analyzing a list of product IDs from a recent sales report. He
needs to determine how frequently each product ID appears and
calculate the following metrics:

from collections import defaultdict

n = int(input())

pc = defaultdict(int)

for _ in range(n):

pi = int(input())

pc[pi] += 1

tu = len(pc)

av = sum(pc.values()) / tu

print(dict(pc))

print(f"Total Unique IDs: {tu}")

print(f"Average Frequency: {av:.2f}")

26. Alex is tasked with managing the membership lists of several exclusive
clubs. Each club has its own list of members, and Alex needs to determine
the unique members who are part of exactly one club when considering all
clubs together.

k = int(input())

sets = [set(map(int, input().split())) for _ in range(k)]

symmetric_diff = sets[0]

for s in sets[1:]:

symmetric_diff ^= s

sum_of_diff = sum(symmetric_diff)

print(symmetric_diff)
print(sum_of_diff)

27. Ella is analyzing the sales data for a new online shopping platform. She has a
record of customer transactions where each customer’s data includes their
ID and a list of amounts spent on different items. Ella needs to determine the
total amount spent by each customer and identify the highest single
expenditure for each customer.

n = int(input())

customer_data = {}

for _ in range(n):

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

customer_id = data[0]

expenditures = data[1:]

total_expenditure = sum(expenditures)

max_expenditure = max(expenditures)

customer_data[customer_id] = [total_expenditure, max_expenditure]

print(customer_data)

28. Riya owns a store and keeps track of item prices from two different suppliers
using two separate dictionaries. He wants to compare these prices to
identify any differences. Your task is to write a program that calculates the
absolute difference in prices for items that are present in both dictionaries.
For items that are unique to one dictionary (i.e., not present in the other),
include them in the output dictionary with their original prices.
n1 = int(input())
dict1 = {}
for _ in range(n1):
key = int(input())
value = int(input())
dict1[key] = value
n2 = int(input())
dict2 = {}
for _ in range(n2):
key = int(input())
value = int(input())
dict2[key] = value
result = {}
for key in dict1:
if key in dict2:
result[key] = abs(dict1[key] - dict2[key])
else:
result[key] = dict1[key]

for key in dict2:


if key not in result:
result[key] = dict2[key]
print(result)
29. Samantha is working on a text analysis tool that compares two words to find
common and unique letters. She wants a program that reads two words, w1,
and w2, and performs the following operations:
w1 = input().lower().strip()
w2 = input().lower().strip()
p = set(w1)
q = set(w2)
print(sorted(p & q))
print(sorted(p ^ q))
print(p.issuperset(q))
print(not bool(p.intersection(q)))
30. Sophia is solving a quadratic equation to determine the nature and roots of
the equation for her mathematics project. A quadratic equation is in the
form ax2+bx+c=0.
a, b, c = map(int, input().split())
discriminant = b * b - 4 * a * c
if discriminant > 0:
root1 = (-b + (discriminant ** 0.5)) / (2 * a)
root2 = (-b - (discriminant ** 0.5)) / (2 * a)
roots = frozenset({round(root1, 2), round(root2, 2)})
elif discriminant == 0:
root = -b / (2 * a)
roots = frozenset({round(root, 2)})
else:
roots = frozenset()
print(roots)
31. Emily is organizing a taco party and needs to determine the total number of
tacos required and the total cost. Each attendee at the party will consume 2
tacos. To ensure there are enough tacos:
n = int(input())
c = 25
if n >= 10:
t = (n*2) + 5
else:
t = max(n*2,20)
tc=t*c
print("Number of tacos needed: ",t)
print("Total cost: ",tc)
32. Bob, the owner of a popular bakery, wants to create a special offer code for
his customers. To generate the code, he plans to combine the day of the
month with the number of items left in stock.
d = int(input())
s = int(input())
o = d^s
print("Offer code: ",o)
33. Jack is working on a digital jigsaw puzzle where each piece has unique edge
values. To solve the puzzle, he needs to match pieces by ensuring the sum of
the edge values of two pieces, when the first edge value is shifted left by 2-
bit positions, equals a specified target value.
e1 = int(input())
e2 = int(input())
t = int(input())
s = e1 << 2
m = (s + e2) == t
print(s)
print("Match result: ",m)
34. In a family, two children receive allowances based on the gardening tasks
they complete. The older child receives an allowance rate of Rs.5 for each
task, with a base allowance of Rs.50. The younger child receives an
allowance rate of Rs.3 for each task, with a base allowance of Rs.30.
n = int(input())
m = int(input())
o = 50 + (n*5)
y = 30 + (m*3)
t=o+y
print("Older child allowance: Rs.",o)
print("Younger child allowance: Rs.",y)
print("Total allowance: Rs.",t)
35. Shawn, a passionate baker, is planning to bake cookies for a large party. His
original recipe makes 15 cookies, with the following ingredient quantities: 2.5
cups of flour, 1 cup of sugar, and 0.5 cups of butter.
n = int(input())
f = (2.5/15)*n
s = (1.0/15)*n
b = (0.5/15)*n
print(f"Flour: {f:.2f} cups")
print(f"Sugar: {s:.2f} cups")
print(f"Butter: {b:.2f} cups")
36. Pranav, an enthusiastic kid visited the "Fun Fair 2017" along with his family.
His father wanted him to purchase entry tickets from the counter for his
family members. Being a little kid, he is just learning to understand units of
money. Pranav has paid some amount of money for the tickets but he wants
your help to give him back the change of Rs. N using the minimum number of
rupee notes.
N = int(input())
notes = [100, 50, 10, 5, 2, 1]
count = (N // 100) + ((N % 100) // 50) + ((N % 100 % 50) // 10) + \
((N % 100 % 50 % 10) // 5) + ((N % 100 % 50 % 10 % 5) // 2) + \
((N % 100 % 50 % 10 % 5 % 2) // 1)
print(count)
37. Mandy is debating with her friend Rachel about an interesting mathematical
claim. Rachel asserts that for any positive integer n, the ratio of the sum of n
and its triple to the integer itself is always 4. Mandy, intrigued by this
statement, decides to validate it using logical operators and basic
arithmetic.
n = int(input())
c=n+3*n
i = (c / n) == 4
print(f"Sum: {c }")
print(f"Rachel's statement is: {i}")
38. Liam and his friends are sharing the cost of a group purchase. The total cost
of the purchase is subject to a 10% discount. One of the friends receives a
35% bonus, which means they will pay a larger portion of the discounted
cost. The remaining cost is then divided equally among the other friends.
f = float(input())
n = int(input())
d = f * 0.9
b= d * 0.35
r= d - b
o = r / (n - 1)
print(f"Cost after a 10% discount: {d:.2f}")
print(f"Friend with a 35% bonus pays: {b:.2f}")
print(f"Each of the other friends pays: {o:.2f}")
39. Alex is working on a system where each error needs to be processed based
on specific calculations involving error codes and system statuses. Given an
error code and a system status, write a program to calculate the final error
code. The final error code is determined using bitwise operations and
modulo.
E = int(input())
S = int(input()
r = (E & S) ^ (S >> 4)
print(r % 256)
40.Anwar, an electrical engineer, is designing a circuit involving complex
impedance. He has two impedance values, each represented as complex
numbers. He needs to modify these values by negating the imaginary
component (representing the inductive reactance) while doubling the real
component (representing the resistance).
r1 = int(input())
i1 = int(input())
r2 = int(input())
i2 = int(input())
modified_z1 = complex(2 * r1, -i1)
modified_z2 = complex(2 * r2, -i2)
print(modified_z1)
print(modified_z2)
41. Write a program that updates the current high score (represented as a byte)
to a new value using bitwise OR.Use the bitwise OR (|) operator to perform a
bitwise OR operation between the current high score and the new score. This
operation combines the binary representations of both scores, setting bits to
1 where either the current high score or the new score has a corresponding
bit set to 1.
a = int(input(),2)
b = int(input(),2)
c = a|b
print(f"Updated high score (binary): {bin(c)[2:]}")
42. Zomato tracks favorite dishes in its app. As a programmer, you have to write
a program that takes the dish name, restaurant name, and rating and
displays the details.
a = input()
b = input()
c = float(input())
print("Dish Name: ",a)
print("Restaurant: ",b)
print(f"Rating: {c:.1f}")
43. Isabella and Oliver are on the hunt for the perfect comedy movie to watch
together. To ensure maximum entertainment, they've established a few
criteria. First and foremost, they want to be in the right mood for the movie.
Secondly, they need to have a solid block of time to dedicate to watching it.
And lastly, they're hoping for a fresh and new experience, so they're looking
for a movie they haven't seen before.
g = input() == "True"
f = input() == "True"
s = input() == "True"
if g and f and not s:
print("Watch a comedy.")
else:
print("Don't watch a comedy.")
44.Sophia and Daniel are deciding whether to go on a picnic. They'll go if it's a
sunny day ('sunny_day' - boolean) or if they have prepared enough food for
the trip ('food_prepared' - boolean). Additionally, they won't go if they have
received an important work call ('work_call' - boolean). Write a program to
help them decide.
s = input() == "True"
d = input() == "True"
k = input() == "True"
if (s and d) and not k:
print("They Should go on the picnic!")
else:
print("They Should not go on the picnic!")
45.Jhon was given two numbers, and he need to swap the values without using
any temporary variables. Instead, he'll use the XOR operation to achieve
this. Help him by writing a program that takes the two numbers as input
from the user and swaps their values using XOR. Finally, display the
swapped values.
a = int(input())
b = int(input())
a = a^b
b = a^b
a = a^b
print("After swapping: ")
print(a)
print(b)
46. Uma is a dedicated follower of a superhero team's missions, and she's eager
to know whether her favorite heroine, Mia, possesses the remarkable power
of invisibility.
i = input().strip().lower()
if i == "yes":
print("Mia has invisibility")
else:
print("Mia does not have invisibility")
47. In the intricate machinery of a cooling system, a byte serves as the guardian
of the fan's speed. To harness a subtle adjustment, your mission is to create
a program that gracefully employs the power of a right shift to reduce the
fan's speed to half.
c = int(input().strip())
r = c >> 1
print(f"The reduced speed after halving is: {r}")
48.Sophia and Benjamin are considering buying a new computer. They have
specific criteria for making the decision:They will buy the computer if it's on
sale.They will buy the computer if it meets their performance requirements
(performance_score > 85).They won't buy the computer if it's too
heavy.Write a program using Logical operators to help Sophia and Benjamin
decide whether to buy the computer or not.
sale = input().strip() == "True"
performance_score = int(input().strip())
too_heavy = input().strip() == "True"

if (sale and performance_score > 85) and not too_heavy:


print("They will buy the computer")
else:
print("They won't buy the computer")
49. Mia and Elijah are faced with a decision regarding whether they should take
a day off from work. Their decision hinges on three key factors: their health
status, the presence of a special event, and the importance of an impending
deadline.
u = input().strip()
s = input().strip()
b = input().strip()
if( u == "yes" and s == "yes") and b == "no":
print("Take a day off!")
else:
print("Do not take a day off.")
50. Mukesh is in control of an elevator, and each floor the elevator can travel to
is represented by a single bit in a byte. This means that a byte can have up to
8 floors, each represented by a 0 or 1, where 1 means the elevator should stop
at that floor.
c = int(input().strip(),2)
n = c | (1 << 5)
print(f"New destination byte: {format(n,'08b')}")
51. Mithu is planning a vacation and is researching the weather conditions of
the destination. She wants to classify the temperature based on different
categories such as freezing, cold, normal, hot, and very hot. To simplify her
research, she decided to write a program that categorizes temperatures into
various weather conditions.
i = int(input())
if i < 0:
print("Freezing weather")
elif 0 <= i <=9:
print("Very cold weather")
elif 10 <= i <= 19:
print("Cold weather")
elif 20 <= i <= 29:
print("Normal in temperature")
elif 30 <= i <= 39:
print("it's hot")
elif i >= 40:
print("it's very hot")
52. Nandhini is working on a project that involves converting the full names of
months into their respective abbreviations. To simplify her task, she wants
to write a program that can perform this conversion for her. She reached out
to you for help in developing this program.
ma = {
"January" : "Jan",
"February" : "Feb",
"March" : "Mar",
"April" : "Apr",
"May" : "May",
"June" : "Jun",
"July" : "Jul",
"August" : "Aug",
"September" : "Sep",
"October" : "Oct",
"November" : "Nov",
"December" : "Dec",
}
m = input()
print(f"The abbreviation for {m} is {ma[m]}.")
53. You are given an input string that contains alphanumeric characters. The
task is to extract the numeric digits from the input string, count the
occurrences of lowercase letters and count the occurrences of uppercase
letters.
s = input()
d = "".join([ch for ch in s if ch.isdigit()])
l = sum(1 for ch in s if ch.islower())
u = sum(1 for ch in s if ch.isupper())
print(d)
print(l)
print(u)
54.Fazil needs a triangle classification program. Given the lengths of the sides
of a triangle (side1, side2, and side3), the program determines whether the
triangle is classified as Equilateral, Isosceles, or Scalene based on the
following conditions:
a = float(input())
b = float(input())
c = float(input())
if a == b == c:
print("The triangle is classified as Equilateral")
elif a==b or b==c or a==c:
print("The triangle is classified as Isosceles")
else:
print("The triangle is classified as Scalene")
55. May wants a program to identify and classify input characters into one of
the following categories: digit, lowercase character, uppercase character, or
special character. The program should take a single character as input from
the user and then determine its category using an if-else-if ladder.
i = input()
if '0' <= i <= '9':
print("Digit")
elif 'a' <= i <= 'z':
print("Lowercase character")
elif 'A' <= i <= 'Z':
print("uppercase character")
else:
print("Special character")
56. Prakya is studying ancient numeral systems and is particularly fascinated
by Roman numerals. She wishes to create a program that can convert
regular numbers into their Roman numeral equivalents. To achieve this, she
seeks your assistance in developing the conversion tool.
def int_to_roman(num):
if num < 1 or num > 3999:
return "Invalid input"
roman_numerals = [("M", 1000), ("CM", 900), ("D", 500), ("CD", 400),("C", 100),
("XC", 90), ("L", 50), ("XL", 40),("X", 10), ("IX", 9), ("V", 5), ("IV", 4),("I", 1)]
result = ""
for symbol, value in roman_numerals:
while num >= value:
result += symbol
num -= value
return result
num = int(input().strip())
print(int_to_roman(num))
57. Janani is studying coordinate geometry, and she is curious about the
quadrants in a coordinate plane. She wants to create a program that takes
two integer inputs representing the coordinates of a point and determines in
which quadrant the point lies.
x = int(input().strip())
y = int(input().strip())
if x > 0 and y > 0:
print("The coordinate point lies in the first quadrant.")
elif x < 0 and y > 0:
print("The coordinate point lies in the second quadrant.")
elif x < 0 and y < 0:
print("The coordinate point lies in the third quadrant.")
elif x > 0 and y < 0:
print("The coordinate point lies in the fourth quadrant.")
else:
print("The coordinate point lies at the origin.")
58. Mandy, the HR manager, has implemented a new system to automate the
calculation of employee bonuses and taxes based on tenure. Employees
with more than 5 years of service receive a bonus, which is a percentage of
their annual salary. He also calculates the tax on the total income, which
includes the salary and bonus, and finally, he computes the net salary after
tax.
S = float(input().strip())
N = int(input().strip())
B = float(input().strip())
T = float(input().strip())
if N > 5:
net_bonus = (B / 100) * S
print(f"You have earned a bonus of {net_bonus:.1f} units.")
else:
net_bonus = 0
print("Sorry, you are not eligible for a bonus.")
tax_amount = (T / 100) * (S + net_bonus)
net_salary = S + net_bonus - tax_amount
print(f"Tax Amount: {tax_amount:.1f} units")
print(f"Net Salary: {net_salary:.1f} units")
59. John is passionate about maintaining a healthy lifestyle and has recently
started using a fitness tracker to monitor his body fat percentage. He inputs
his height and waist measurements into the tracker, and the program
calculates and categorizes his body fat percentage based on certain
criteria.
height = float(input().strip())
waist = float(input().strip())
body_fat_percentage = 64 - (20 * (height / waist))
print(f"{body_fat_percentage:.2f}%")
if 2 <= body_fat_percentage <= 5:
print("Essential fat")
elif 6 <= body_fat_percentage <= 13:
print("Athletes")
elif 14 <= body_fat_percentage <= 17:
print("Fitness")
elif 18 <= body_fat_percentage <= 24:
print("Average")
else:
print("Obese")
60. Banu is an astrologer who specializes in identifying people's zodiac signs
based on their birthdates. She wants to develop a simple tool that can assist
her in determining the zodiac signs of individuals. She's seeking your help to
write a program that automates this process.
day = int(input().strip())
month = input().strip()
if (month == "March" and 21 <= day <= 31) or (month == "April" and 1 <= day <=
19):
zodiac = "Aries"
elif (month == "April" and 20 <= day <= 30) or (month == "May" and 1 <= day <=
20):
zodiac = "Taurus"
elif (month == "May" and 21 <= day <= 31) or (month == "June" and 1 <= day <=
20):
zodiac = "Gemini"
elif (month == "June" and 21 <= day <= 30) or (month == "July" and 1 <= day <=
22):
zodiac = "Cancer"
elif (month == "July" and 23 <= day <= 31) or (month == "August" and 1 <= day
<= 22):
zodiac = "Leo"
else:
zodiac = "Other"
print(f"Your zodiac sign is {zodiac}")
61. Tom wants to create a dictionary that lists the first n prime numbers, where
each key represents the position of the prime number, and the value is the
prime number itself.
def is_(nu):
if nu < 2:
return False
for i in range(2,int(nu**0.5)+1):
if nu % i ==0:
return False
return True
n = int(input().strip())
p = {}
c=0
cu = 1
while c < n:
cu += 1
if is_(cu):
c += 1
p[c] = cu
print(p)

62.Shruthi is planning her monthly expenses and allocates a certain


amount (an integer) to different categories like food, transport,
grocery, rent, and entertainment (represented from 1 to 5
respectively). She has the budget allocations for two months, each
stored in a dictionary where keys represent categories and values
represent the amounts allocated.
def merged():
n = int(input())
budget ={}
for _ in range(n):
c = int(input())
a= int(input())
budget[c] = a
m = int(input())
for _ in range (m):
c = int(input())
a= int(input())
budget[c] = budget.get(c,0) + a
print("Merged Budget",budget)
merged()
63. Meenu is a diligent programmer who loves to work on tasks related to list
manipulation. Today, she's tasked with a problem that involves determining
whether a given list contains unique elements or if there are duplicates
present.
i = list(map(int,input().strip().split()))
print(f"List: {i}")
if len(i) == len(set(i)):
print("All elements are unique")
else:
print("List contains duplicate elements")
64. Ram is working on a program to find the maximum value in a tuple of integers.
Write a Python program that takes a tuple of integers as input, iterates through
the elements, and outputs the maximum value in the tuple.
i = tuple(map(int,input().strip().split()))
m = max(i)
print(m)
65. Given a list of positive and negative numbers, arrange them such that all
negative integers appear before all the positive integers in the array. The order
of appearance should be maintained.
i = eval(input().strip())
s = [num for num in i if num <0]
d = [num for num in i if num >=0]
a= s+d
print(a)

66. Jack, a retail manager, is evaluating the performance of his store's products
based on their monthly sales. He needs a program that will calculate the
average monthly sales for each product and filter out those with an average
sales value greater than a specified threshold. The filtered products should be
displayed in descending order of their average sales, with each average
rounded to two decimal places.
a = int(input())
b= int(input())
s = {}
for _ in range(b):
d = input().split(" ",1)
p = d[0]
sa = eval(d[1])
t = sum(sa.values())
num = len(sa)
avg = t/num
if avg > a:
s[p] = round(avg,2)
sorts = sorted(s.items(),key=lambda x:x[1],reverse = True)
r = {k:f"{v:.2f}"for k,v in sorts}
print(r)
67. Emerson is managing a list of task IDs for a project. To streamline task
management, he needs to remove every nth task from the list. Help Emerson by
creating a program that reads a tuple of task IDs and an integer n, then removes
every nth task from the tuple and returns the updated tuple.
s = int(input())
t = tuple(map(int,input().split()))
n = int(input())
r = tuple(t[i] for i in range(len(t)) if (i+1)%n != 0)
print(r)
68. Bobby is organizing a plant exhibition and needs to keep track of different plant
varieties. Each line of input corresponds to a different plant category, with the
first number on the line indicating how many types of plants are listed in that
category. Bobby needs to count how many times each plant variety appears
across all categories.
n = int(input())
pc = {}
for _ in range(n):
d = list(map(int,input().split()))
pl = d[1:]
for p in pl:
pc[p] = pc.get(p,0) + 1
print(pc)
69. Raja needs a program that helps him manage his shopping list efficiently. The
program should allow him to perform the following operations:
s = list(map(int,input().split()))
r = int(input())
n = list(map(int,input().split()))
print(f"List1:{s}")
if r in s:
s.remove(r)
print(f"List after removal: {s}")
else:
print("Element not found in the list")
s.extend(n)
print(f"Final list:{s}")
70. George is analyzing two data streams representing IDs from different systems.
He needs to identify the IDs that are common between the two systems but only
if they appear an odd number of times in the combined list of IDs.
n = int(input())
t1 = tuple(map(int,input().split()))
m = int(input())
t2 = tuple(map(int,input().split()))
c = t1+t2
cd = set(t1) & set(t2)
r = sorted([x for x in cd if c.count(x)%2 == 1])
if r:
print(tuple(r))
else:
print("No common elements found.")

You might also like