Python Coddes
Python Coddes
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"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),
flight_number = int(input())
delay = input()
print(current_position)
number = float(input())
room = input()
temperature = float(input())
humidity = float(input())
print(f"Room: {room}")
print(f"Temperature: {temperature:.2f}")
print(f"Humidity: {humidity:.2f}%")
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())
real2,imag2 = b.real,b.imag
n=complex(imag2,real2)
m=complex(imag1,real1)
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:")
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())
investment1 = float(input())
investment2 = float(input())
portfolio_id = int(input())
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())
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()
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.
(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()
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)
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))
def is_p(num):
if num < 2:
return False
if num % i == 0:
return False
return True
l1 = list(map(int, input().split()))
l2 = list(map(int, input().split()))
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)
print(PQ)
print(RS)
print(r)
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("{}")
reg = set(map(int,input().split()))
att = set(map(int,input().split()))
dro = set(map(int,input().split()))
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:
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))
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())
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):
customer_id = data[0]
expenditures = data[1:]
total_expenditure = sum(expenditures)
max_expenditure = max(expenditures)
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]
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.")