Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 5
Problem Statements
1. Write a python code to accept a list and print each item on a separate line
Solution:
# Accepting items for the list from the user
print("Enter items for the list, one at a time. Type 'done' when finished:")
user_list = [] # Initial empty list
while True:
item = input("Enter item: ")
if item.lower() == 'done': # Stop when 'done' is entered
break
user_list.append(item) # Add each entered item to the list
# Printing each item on a new line
for item in user_list:
print(item)
2. Write a python code to check if a list is sorted, if not sort the list in ascending order.
Solution : l = [1, 7, 3, 4, 5]
# Define a list
my_list = [3, 1, 4, 2, 5] # Example list; change as needed
# Check if the list is sorted
if my_list == sorted(my_list):
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 5
print("The list is already sorted:", my_list)
else:
# Sort the list in ascending order
my_list.sort()
print("The list was not sorted. Sorted list:", my_list)
3. Write a python program to reverse a String using loops and lists.
Solution :
input_string = input("Enter a string to reverse: ")
reversed_list = [ ]
for char in input_string:
reversed_list.insert(0, char) # Insert each character at the beginning of the list
reversed_string = ''.join(reversed_list)
print("Reversed string:", reversed_string)
Explanation:
● Get user input
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 5
● Initialize an empty list to hold the reversed characters
● Loop through each character in the input string
● Join the list into a string
● Print the reversed string
4. Write a python program to split a List into Even and Odd Elements
Solution
l=[1,2,4,6,5,7]
even=[]
odd=[]
for i in l:
if i%2==0:
even.append(i)
else:
odd.append(i)
print("The entered list is",l)
print("The list with even numbers is",even)
print("The list with odd numbers is",odd)
Explanation
●
● l is initialized with a list of integers.
● even and odd are initialized as empty lists to hold even and odd numbers,
respectively.
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 5
● The for loop iterates over each element i in the list l.
● The condition i % 2 == 0 checks if i is even. The modulus operator % returns
the remainder of the division of i by 2. If the remainder is 0, it means the number
is even.
● If i is even, it’s appended to the even list using even.append(i).
● If i is not even (i.e., odd), it’s appended to the odd list using odd.append(i).
● prints the original list, the list of even numbers, and the list of odd numbers.
5. Write a program that takes a list of integers and returns the count of the least frequently
occurring element. Assume that only one element has the minimum frequency.
Solution :
n=int(input("Enter the number of elements"))
l=[]
for i in range(n):
a=int(input("Enter the element"))
l.append(a)
if n==0:
print("No elements")
elif n==1:
print("Least frequency element is",l[0])
else:
min_count=None
least_frequency_item=None
for item in l:
count=l.count(item)
if min_count==None or count<min_count:
min_count=count
least_frequency_item=item
n=int(input("Enter the number of elements"
Explanation
● asks the user for the number of elements they want to input. This number
is stored in n.
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 5
● An empty list l is initialized to store the elements
● for loop runs n times, prompting the user to enter an integer each time.
Each entered integer is appended to the list l.
● If the user enters 0 for n, the program prints "No elements" and exits.
● If n is 1, it simply prints the only element as the least frequent element
since it appears once.
If there are more than one elements, a dictionary frequency is created to
count how many times each element appears in the list.
The loop iterates over each item in the list l:
● If the item is already a key in the frequency dictionary, its count is incremented
by 1.
● If it’s not already a key, it’s added to the dictionary with a count of 1.
● The min() function is used to find the key (element) in the frequency
dictionary that has the smallest value (count).
● The key=frequency.get argument specifies that the comparison should
be done based on the values in the dictionary (i.e., the counts).
● The minimum count is retrieved using
frequency[least_frequency_item
● Print the least frequent element along with its count.
6. You are designing an attendance system. In which attendance of the day is maintained
in the given format.
attendance_records = [("A", "P"), ("B", "A"), ("C", "P"), ("D",
"A"), ("E", "P"), ("F", "P"), ("G", "A"), ("H", "P"), ("I",
"P"), ("J", "P")]
i. Calculate the total no of present count and absence count of the day.
ii. It seems attendance of the student is wrong, check whether the attendance is
actually wrong, if so change it in place. (take the name of the student and new
statues as input.)
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 5
iii. Suppose you are adding a new student to the list. Add using list methods.
Solution :
attendance=[('A','P'),('B','A'),('C','P'),('D','A'),('E','P'),('F','P'),('G','A'),('H','P'),('I'
,'P'),('J','P')]
p=0
A=0
for i in attendance:
if i[1]=="P":
p+=1
else:
A+=1
print("The no.of absent is",A,"and no.of present is",p)
name=input("Enter your name")
new_status=input("Enter your status")
for i in range(len(attendance)):
if attendance[i][0]==name:
if new_status==attendance[i][1]:
print("NO changes")
else:
attendance[i]=list(attendance[i])
attendance[i][1]=new_status
attendance[i]=tuple(attendance[i])
print("Staus update")
break
p=0
A=0
for i in attendance:
if i[1]=="P":
p+=1
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 5
else:
A+=1
print("The no.of absent is",A,"and no.of present is",p)
new_student=input("Enter name")
status=input("Enter your status")
new_record=(new_student,status)
attendance.append(new_record)
print(attendance)
Explanation:
● A list of tuples, where each tuple contains a student’s name and their attendance
status ('P' for present, 'A' for absent).
● Two counters, p for present and A for absent, are initialized.
● The program loops through each record in the attendance list and increments
the respective counter based on the status.
● Print the total number of present and absent students.
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 5
7. Music Playlist Management: You are building a playlist management system. Write a
python program using lists to:
i. Merge two separate playlists into one.
ii. Remove duplicate songs from the merged playlist.
iii. Rotate the merged playlist by n positions.
iv. Create two separate playlists from the merged one: one for songs starting with
vowels and one for songs starting with consonants.
Solution :
(1)
P1 = ['HELLO', 'UPTOWN FUNK', 'AFRICA', 'SHAPE OF YOU']
P2 = ['YESTERDAY', 'HELLO', 'ELEANOR RIGBY', 'AMAZING GRACE']
(2)
merged_playlist = list(set(P1 + P2))
print("Merged Playlist:", merged_playlist)
(3)
n = int(input("Enter the number of positions to rotate the playlist: "))
n = n % len(merged_playlist) # Handle rotation greater than playlist length
rotated_playlist = merged_playlist[-n:] + merged_playlist[:-n]
print("Rotated Playlist:", rotated_playlist)
(4)
vowel_playlist = []
consonant_playlist = []
for song in rotated_playlist:
if song[0].upper() in 'AEIOU': # Check first character
vowel_playlist.append(song)
else:
consonant_playlist.append(song)
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 5
print("Playlist with Vowels:", vowel_playlist)
print("Playlist with Consonants:", consonant_playlist)
Explanation:
● (1) The two playlists P1 and P2 are combined and converted to a set
to remove duplicates, then back to a list.
● (2) The user is prompted to enter how many positions to rotate the
playlist. The rotation handles cases where the number exceeds the
playlist length using modulo.
● (3) The code iterates through the rotated playlist and categorizes
songs into vowel_playlist and consonant_playlist based on
the first character of each song.
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 5
8. Sales Analysis: You are given a list of daily sales amounts for a store over a month.
Write a program to:
i. Remove any sales data that is a negative value.
ii. Calculate the average sales for the month.
iii. Find the day with the highest sales.
iv. Find the day with the lowest sales.
Solution :
Sample list of daily sales amounts over a month
sales_data = [1200, 1500, -500, 1800, 2100, 0, 1700, 1300, 1400, -100, 1600,
2000, 1900, 2200, 1100, 2400, 1000, 900, 1800, 1700, 2600,
2300, 1500, 1600, 1700, -300, 2100, 1800, 2500, 2600, 1200]
i. Remove any sales data that is a negative value
cleaned_sales_data = [sale for sale in sales_data if sale >= 0]
ii. Calculate the average sales for the month
average_sales = sum(cleaned_sales_data) / len(cleaned_sales_data)
iii. Find the day with the highest sales
highest_sales = max(cleaned_sales_data)
highest_sales_day = cleaned_sales_data.index(highest_sales) + 1 # +1 for day count
starting from 1
iv. Find the day with the lowest sales
lowest_sales = min(cleaned_sales_data)
lowest_sales_day = cleaned_sales_data.index(lowest_sales) + 1
Display results
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 5
print("Cleaned sales data (no negatives):", cleaned_sales_data)
print("Average sales for the month:", average_sales)
print(f"Day with the highest sales: Day {highest_sales_day} with sales of
{highest_sales}")
print(f"Day with the lowest sales: Day {lowest_sales_day} with sales of {lowest_sales}")
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 5
9. Krishna is a teacher who wants to put up math tables in a cells format.
1 2 3 4 5 …n
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
.
.
.
n … … … … …n*n
So help him out to display the above by writing a python program to achieve the same up to n
numbers.
Solution:
# Get the value of n from the user
n = int(input("Enter the value of n: "))
# Generate the multiplication table
for i in range(1, n + 1):
for j in range(1, n + 1):
print(f"{i * j}\t", end="") # Print each product followed by a tab
print() # Move to the next line after each row
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 5
10. Jone is running a small business where he lends out vehicles on rent. He needs to track
vehicle’s, borrower details, and rented details in a secured data structure.
Eg- Vehicle - Type - Car
- Reg_no - 2478
Borrower details - Name - Alice
- Phone_no - 975318642
Rent Details - Borrow date - 15/10/2024 10.30.15 AM
- Expected return - 18/10/2024 10.30.15 AM
- rent - Rs. 1000 per day
- extra_rent - Rs 50 per hour
- deposit - Rs 1500
- in_hand - True
Write a program that works dynamically and stores the required details in a well structured data
structure (use lists and tuples and combination of both). Add features to check rent details, add
new rent, calculate rent the entry from the data structure and show all entries.(make in_hand to
false on return). Make use of models such as “datetime” for date and time usage.
Solution :
from datetime import datetime, timedelta
# Structure to store rental information
rentals = []
# Function to add a new rental
def add_rental(vehicle_type, reg_no, name, phone_no, borrow_date, expected_return,
rent_per_day, extra_rent_per_hour, deposit):
rental_entry = {
"Vehicle": (vehicle_type, reg_no),
"Borrower": (name, phone_no),
"Rent Details": {
"Borrow date": borrow_date,
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 5
"Expected return": expected_return,
"Rent per day": rent_per_day,
"Extra rent per hour": extra_rent_per_hour,
"Deposit": deposit,
"In hand": True
}
}
rentals.append(rental_entry)
print("Rental added successfully!")
# Function to calculate rent on return
def calculate_rent(return_date, entry):
rent_details = entry["Rent Details"]
borrow_date = rent_details["Borrow date"]
expected_return = rent_details["Expected return"]
rent_per_day = rent_details["Rent per day"]
extra_rent_per_hour = rent_details["Extra rent per hour"]
# Calculate days and extra hours
total_days = (return_date - borrow_date).days
extra_hours = (return_date - (borrow_date + timedelta(days=total_days))).seconds //
3600
total_rent = (total_days * rent_per_day) + (extra_hours * extra_rent_per_hour)
rent_details["In hand"] = False # Mark as returned
return total_rent
# Function to check rent details by vehicle registration number
def check_rent_details(reg_no):
for entry in rentals:
if entry["Vehicle"][1] == reg_no:
return entry
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 5
return None
# Function to show all entries
def show_all_entries():
for entry in rentals:
vehicle, borrower, rent_details = entry["Vehicle"], entry["Borrower"], entry["Rent
Details"]
print(f"\nVehicle Type: {vehicle[0]}, Reg No: {vehicle[1]}")
print(f"Borrower Name: {borrower[0]}, Phone No: {borrower[1]}")
print("Rent Details:")
for key, value in rent_details.items():
print(f" {key}: {value}")