Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Python program #452

Open
Roshini08 opened this issue May 6, 2024 · 4 comments
Open

Python program #452

Roshini08 opened this issue May 6, 2024 · 4 comments

Comments

@Roshini08
Copy link

Write a Python program to combine two dictionaries by adding values for common keys.

dict1 = {'a': 10, 'b': 20, 'c': 30}
dict2 = {'b': 30, 'c': 40, 'd': 50}
combined_dict ={}
for key in dict1:
if key in dict2:
combined_dict[key] = dict1[key] + dict2[key]
else:
combined_dict[key] = dict1[key]
for key in dict2dict2:
if key not in combined_dict:
combined_dict[key] = dict2[key]

print("Combined dictionary:", combined_dict)
Sample Output :
Combined dictionary: {'a': 10, 'b': 50, 'c': 70, 'd': 50}

Write a Python program to convert a dictionary of lists into a list of dictionaries.

dict_of_lists = {'Name': ['John', 'Alice', 'Bob'],
'Age': [25, 30, 35],
'City': ['New York', 'Paris', 'London']}

list_length =len(next(iter(dict_of_lists.values())))
list_of_dicts =[]
for i in range(list_length):
new_dict = {]
for key, values in dict_of_lists.items():
new_dict[key] = values[i]
for dictionary in list_of_dicts:
print(dictionary)
Sample Output:
{'Name': 'John', 'Age': 25, 'City': 'New York'}
{'Name': 'Alice', 'Age': 30, 'City': 'Paris'}
{'Name': 'Bob', 'Age': 35, 'City': 'London'}

Write a Python program to create a dictionary from two lists, where one list contains keys and the other contains values.

keys = ['Name', 'Age', 'City']
values = ['John', 25, 'New York']
result_dict = dict(zip(keys, values))
print("Dictionary from two lists:", result_dict)
Sample Output :
Dictionary from two lists: {'Name': 'John', 'Age': 25, 'City': 'New York'}

Write a Python program to create a dictionary of dictionaries.

inner_dict1 = {'a': 1, 'b': 2, 'c': 3}
inner_dict2 = {'x': 10, 'y': 20, 'z': 30}
outer_dict = {'dict1': inner_dict1, 'dict2': inner_dict2}
print("Dictionary of dictionaries:", outer_dict)
Sample Output :
Dictionary of dictionaries: {'dict1': {'a': 1, 'b': 2, 'c': 3}, 'dict2': {'x': 10, 'y': 20, 'z': 30}}

Write a Python program to create a dictionary where the keys are numbers from 1 to 5 and the values are their squares.

square_dict = {}
for num in range(1, 6):
square_dict[num] = num ** 2
print(square_dict)
Sample Output :
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Write a Python program to find the second largest value in a dictionary.

data = {'a': 10, 'b': 20, 'c': 30, 'd': 15, 'e': 25}

unique_values = sorted(set(data.values()), reverse=True)
if len(unique_values) >= 2:
second_largest = unique_values[1]
keys = [key for key, value in data.items() if value == second_largest]
print(f"The second largest value in the dictionary is {second_largest}.")
print(f"It appears with key(s): {keys}")
else:
print("There is no second largest value in the dictionary.")
Sample Output :
The second largest value in the dictionary is 25.
It appears with key(s): ['e']

Write a Python program to multiply all the values in a dictionary.

data = {'a': 2, 'b': 3, 'c': 4}
product = 1
for value in data.values():
product *= value
print("Product of all values in the dictionary:", product)
Sample Output
Product of all values in the dictionary: 24

Write a Python program to print a dictionary in table format.

data = {'Name': ['John', 'Alice', 'Bob'],
'Age': [25, 30, 35],
'City': ['New York', 'Paris', 'London']}
max_lengths = {key: max(len(str(key)), max(len(str(x)) for x in values)) for key, values in data.items()}
print("|", end="")
for key, max_length in max_lengths.items():
print(f" {key.ljust(max_length)} |", end="")
print()
print("+", end="")
for _, max_length in max_lengths.items():
print(f"-{'-' * max_length}-+", end="")
print()
for i in range(len(data['Name'])):
print("|", end="")
for key, values in data.items():
print(f" {str(values[i]).ljust(max_lengths[key])} |", end="")
print()
print("+", end="")
for _, max_length in max_lengths.items():
print(f"-{'-' * max_length}-+", end="")
print()

Sample Output :
| Name | Age | City |
+--------+-----+---------+
| John | 25 | New York|
| Alice | 30 | Paris |
| Bob | 35 | London |
+--------+-----+---------+

Write a Python program to sort a dictionary by its keys.

data = {'b': 2, 'a': 1, 'c': 3}
sorted_data = dict(sorted(data.items()))
print("Sorted dictionary by keys:", sorted_data)
Sample Output :
Sorted dictionary by keys: {'a': 1, 'b': 2, 'c': 3}

Write a Python program to update the values of a specific key in a dictionary.

data = {'a': 1, 'b': 2, 'c': 3}
data['b'] = 20
print("Updated dictionary:", data)
Sample Output :
Updated dictionary: {'a': 1, 'b': 20, 'c': 3}

You are developing a dictionary-based spelling checker. Write a Python program to check the spelling of words in a document using a dictionary of valid words.

You are developing a dictionary-based spelling checker. Write a Python program to check the spelling of words in a document using a dictionary of valid words.
Sample Dictionary: valid_words = {'apple', 'banana', 'orange', 'grape'}
Sample Output: Misspelled words: ['aple', 'bannana']
valid_words = {'apple', 'banana', 'orange', 'grape'}

document = input("Enter the document: ")

words = document.split()

misspelled_words = []

for word in words:

if word.lower() not in valid_words:
    misspelled_words.append(word)

print("Misspelled words:", misspelled_words)
Sample output :
Enter the document: apple banana grape strawberry
Misspelled words: ['strawberry']

You are developing a movie recommendation system. Write a Python program to recommend movies to a user based on their preferences stored in a dictionary.

You are developing a movie recommendation system. Write a Python program to recommend movies to a user based on their preferences stored in a dictionary.
Sample Dictionary: preferences = {'Action': ['The Dark Knight', 'Inception'], 'Comedy': ['The Hangover', 'Superbad']}
Sample Output: Recommendations: ['The Dark Knight', 'Inception']
preferences = {}
num_genres = int(input("Enter the number of genres: "))
for _ in range(num_genres):
genre = input("Enter the genre: ")
movies = input(f"Enter the movies for {genre} (comma-separated): ").split(',')
preferences[genre] = [movie.strip() for movie in movies]
user_preferences = input("Enter your movie preferences (comma-separated): ").split(',')
recommendations = []
for genre, movies in preferences.items():
recommended_movies = [movie for movie in movies if movie not in user_preferences]
recommendations.extend(recommended_movies)

print("Recommendations:", recommendations)
Sample Output :
Enter the number of genres: 2
Enter the genre: Action
Enter the movies for Action (comma-separated): The Dark Knight, Inception
Enter the genre: Comedy
Enter the movies for Comedy (comma-separated): The Hangover, Superbad
Enter your movie preferences (comma-separated): Inception, The Hangover
Recommendations: ['The Dark Knight', 'Superbad']

You are developing a voting system for a school election. Write a Python program to count the number of votes each candidate receives and store the results in a dictionary. Sample Dictionary: votes = {'Candidate1': 150, 'Candidate2': 200, 'Candidate3': 180} Sample Output: Candidate1: 150, Candidate2: 200, Candidate3: 180 Note : input from the user

You are developing a voting system for a school election. Write a Python program to count the number of votes each candidate receives and store the results in a dictionary.
Sample Dictionary: votes = {'Candidate1': 150, 'Candidate2': 200, 'Candidate3': 180}
Sample Output: Candidate1: 150, Candidate2: 200, Candidate3: 180
Note : input from the user
votes = {}
num_candidates = int(input("Enter the number of candidates: "))

for i in range(1, num_candidates + 1):
candidate_name = input(f"Enter the name of candidate {i}: ")
vote_count = int(input(f"Enter the number of votes for {candidate_name}: "))
votes[candidate_name] = vote_count
print("Dictionary of votes:", votes)

print("Output:")
for candidate, count in votes.items():
print(f"{candidate}: {count}")
Sample Output :
Enter the number of candidates: 3
Enter the name of candidate 1: Candidate1
Enter the number of votes for Candidate1: 150
Enter the name of candidate 2: Candidate2
Enter the number of votes for Candidate2: 200
Enter the name of candidate 3: Candidate3
Enter the number of votes for Candidate3: 180

Dictionary of votes: {'Candidate1': 150, 'Candidate2': 200, 'Candidate3': 180}
Output:
Candidate1: 150
Candidate2: 200
Candidate3: 180

You are implementing a word frequency counter for a text processing application. Write a Python program to count the frequency of each word in a given text and store the results in a dictionary.

Sample Text: "This is a sample text. This text contains sample words."
Sample Output: {'This': 2, 'is': 1, 'a': 1, 'sample': 2, 'text.': 1, 'contains': 1, 'words.': 1}
text = input("Enter the text: ")
words = text.split()
word_freq = {}
for word in words:
word = word.strip('.,?!')
word = word.lower()
word_freq[word] = word_freq.get(word, 0) + 1
print("Word frequency count:")
print(word_freq)
sample output :
Enter the text: This is a sample text. This text contains sample words.
Word frequency count:
{'this': 2, 'is': 1, 'a': 1, 'sample': 2, 'text': 1, 'contains': 1, 'words': 1}

You have a dictionary representing student grades in various subjects. Write a Python program to calculate the average grade for each student.

You have a dictionary representing student grades in various subjects. Write a Python program to calculate the average grade for each student.
Sample Dictionary: grades = {'John': [85, 90, 88], 'Alice': [75, 80, 82], 'Bob': [92, 88, 90]}
Sample Output: John: 87.67, Alice: 79.00, Bob: 90.00
grades = {}
num_students = int(input("Enter the number of students: "))
for i in range(num_students):
student_name = input(f"Enter the name of student {i+1}: ")
student_grades = input(f"Enter the grades for {student_name} (comma-separated): ").split(',')
student_grades = [int(grade.strip()) for grade in student_grades] # Convert grades to integers
grades[student_name] = student_grades
average_grades = {student: sum(grades) / len(grades) for student, grades in grades.items()}
print("Average grades:")
for student, avg_grade in average_grades.items():
print(f"{student}: {avg_grade:.2f}")
Sample Output :
Enter the number of students: 3
Enter the name of student 1: John
Enter the grades for John (comma-separated): 85, 90, 88
Enter the name of student 2: Alice
Enter the grades for Alice (comma-separated): 75, 80, 82
Enter the name of student 3: Bob
Enter the grades for Bob (comma-separated): 92, 88, 90
Average grades:
John: 87.67
Alice: 79.00
Bob: 90.00

You have a list of strings representing names of students in a class. Write a Python program to Remove any duplicate names from the list and print the updated list.

student_names = ["Alice", "Bob", "Charlie", "Alice", "David", "Bob", "Eve"]
unique_names = []
for name in student_names:
if name not in unique_names:
unique_names.append(name)
print("Updated list of unique names:", unique_names)
Sample Output :
Updated list of unique names: ['Alice', 'Bob', 'Charlie', 'David', 'Eve']

#You have a list of strings representing words. Develop a Python program to Count the number of vowels (a, e, i, o, u) in each word and print the word along with its vowel count.

words = ["hello", "world", "python", "programming", "example"]
for word in words:
vowel_count = 0
for char in word:
if char.lower() in ['a', 'e', 'i', 'o', 'u']:
vowel_count += 1
print(f"Word: {word}, Vowel Count: {vowel_count}")
Sample Output :
Word: hello, Vowel Count: 2
Word: world, Vowel Count: 1
Word: python, Vowel Count: 1
Word: programming, Vowel Count: 3
Word: example, Vowel Count: 3

You have a list of temperatures measured in Celsius. Write a Python program to Convert each temperature to Fahrenheit and print the resulting list.

temperatures_celsius = [0, 10, 20, 30, 40]
temperatures_fahrenheit = []
for celsius in temperatures_celsius:
fahrenheit = (celsius * 9/5) + 32
temperatures_fahrenheit.append(fahrenheit)
print("Temperatures in Fahrenheit:", temperatures_fahrenheit)
Sample Output :
Temperatures in Fahrenheit: [32.0, 50.0, 68.0, 86.0, 104.0]

You have a list of tuples representing (name, age) pairs of people. Write a Python program to convert this list of tuples into a dictionary where the names are keys and the ages are values

people = [("Alice", 25), ("Bob", 30), ("Charlie", 35)]
people_dict = {}
for name, age in people:
people_dict[name] = age
print("Dictionary with names as keys and ages as values:", people_dict)

Sample Output:
Dictionary with names as keys and ages as values: {'Alice': 25, 'Bob': 30, 'Charlie': 35}

You have a list of tuples, each containing a student's name and their corresponding scores in three subjects (Math, Physics, Chemistry). Write a Python program to sort the list of tuples based on the total score (sum of scores in all subjects) in descending order.

You have a list of tuples, each representing a person's name and their corresponding age (e.g., [("Alice", 25), ("Bob", 30), ...]). Write a Python program to Calculate the average age of all the people in the list and print it.students_scores = [("Alice", 90, 85, 95), ("Bob", 80, 75, 85), ("Charlie", 95, 90, 100)]
sorted_students = sorted(students_scores, key=lambda x: sum(x[1:]), reverse=True
print("Sorted list of tuples based on total score (in descending order):")
for student in sorted_students:
print(student)
Sample Output :
Sorted list of tuples based on total score (in descending order):
('Charlie', 95, 90, 100)
('Alice', 90, 85, 95)
('Bob', 80, 75, 85)

You have a list of tuples, each representing a person's name and their corresponding age (e.g., [("Alice", 25), ("Bob", 30), ...]). Write a Python program to Calculate the average age of all the people in the list and print it.

people = [("Alice", 25), ("Bob", 30), ("Charlie", 40), ("David", 35)]
total_age = 0
count = 0

for person in people:
age = person[1]
total_age += age

count += 1

average_age = total_age / count
print("Average age:", average_age)

Sample Output : Average age: 32.5

You have a tuple containing the names of months in a year. Write a Python program to slice the tuple and create a new tuple containing only the names of the first half of the months.

months = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
first_half_months = months[:len(months)//2]
print("Names of the first half of the months:", first_half_months)
Sample Output :
Names of the first half of the months: ('January', 'February', 'March', 'April', 'May', 'June')

You have two lists of integers. Develop a Python program to create a new list that contains the common elements present in both lists.

list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
common_elements = []
for element in list1:
if element in list2:
common_elements.append(element)
print("Common elements:", common_elements)
Sample Output :
Common elements: [4, 5]

You have two tuples containing integers. Write a Python program to concatenate the two tuples and create a new tuple with the elements from both tuples.

tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
new_tuple = tuple1 + tuple2
print("Concatenated tuple:", new_tuple)
Sample output:
Concatenated tuple: (1, 2, 3, 4, 5, 6)

You have two tuples representing dates in the format (year, month, day). Write a Python program to compare the two dates and print whether the first date is earlier, later, or the same as the second date.

date1 = (2022, 10, 15)
date2 = (2023, 5, 20)
if date1 < date2:
print("The first date is earlier than the second date.")
elif date1 > date2:
print("The first date is later than the second date.")
else:
print("The first date is the same as the second date.")
Sample Output:
Sample tuples
date1 = (2022, 10, 15)
date2 = (2023, 5, 20)
Expected output
The first date is earlier than the second date.

You're creating a budget tracking application. Write a Python program to calculate the total expenses for each category stored in a dictionary.

You're creating a budget tracking application. Write a Python program to calculate the total expenses for each category stored in a dictionary.
Sample Dictionary: expenses = {'Food': [100, 150], 'Transportation': [50, 75], 'Entertainment': [75, 100]}
Sample Test Case: expenses
Sample Output: {'Food': 250, 'Transportation': 125, 'Entertainment': 175}

expenses = {}

num_categories = int(input("Enter the number of categories: "))

for _ in range(num_categories):
category = input("Enter the category: ")
amounts = input(f"Enter the expenses for {category} (comma-separated): ").split(',')
expenses[category] = [int(amount.strip()) for amount in amounts]

total_expenses = {category: sum(amounts) for category, amounts in expenses.items()}

print("Total expenses:")
print(total_expenses)
Sample output :
Enter the number of categories: 3
Enter the category: Food
Enter the expenses for Food (comma-separated): 100, 150
Enter the category: Transportation
Enter the expenses for Transportation (comma-separated): 50, 75
Enter the category: Entertainment
Enter the expenses for Entertainment (comma-separated): 75, 100
Total expenses:
{'Food': 250, 'Transportation': 125, 'Entertainment': 175}

You're developing a hotel reservation system. Write a Python program to check the availability of rooms for a given date stored in a dictionary.

You're developing a hotel reservation system. Write a Python program to check the availability of rooms for a given date stored in a dictionary.
Sample Dictionary: room_availability = {'Standard': {'2024-04-12': 10, '2024-04-13': 5}, 'Deluxe': {'2024-04-12': 5, '2024-04-13': 2}}
Sample Test Case: '2024-04-13'
Sample Output: {'Standard': 5, 'Deluxe': 2}

room_availability = {
'Standard': {'2024-04-12': 10, '2024-04-13': 5},
'Deluxe': {'2024-04-12': 5, '2024-04-13': 2}
}

date = input("Enter the date (YYYY-MM-DD): ")

availability = {room_type: availability.get(date, 0) for room_type, availability in room_availability.items()}

print("Room availability for", date + ":", availability)
Sample Output:
Enter the date (YYYY-MM-DD): 2024-04-13
Room availability for 2024-04-13: {'Standard': 5, 'Deluxe': 2}

You work for a finance company that manages investment portfolios for clients. Your team is tasked with analyzing the performance of various investment instruments over time. Each instrument's performance is represented as a list of tuples, where each tuple contains the date and the corresponding value of the investment. Your task is to identify the investment instrument that has shown the highest growth rate over a specified period.

Design a Python program to analyze the performance of investment instruments. Create lists to represent the performance data of three investment instruments over time. Then, prompt the user to enter a start and end date for the analysis period. Calculate the growth rate for each instrument over the specified period and determine which instrument has shown the highest growth rate. Display the name of the instrument along with its growth rate.

instrument1 = [("2023-01-01", 1000), ("2023-03-01", 1200), ("2023-06-01", 1400)]
instrument2 = [("2023-01-01", 2000), ("2023-03-01", 1800), ("2023-06-01", 2500)]
instrument3 = [("2023-01-01", 1500), ("2023-03-01", 1700), ("2023-06-01", 1800)]

start_date = input("Enter start date (YYYY-MM-DD): ")
end_date = input("Enter end date (YYYY-MM-DD): ")

max_growth_rate = -1
best_instrument = None

def date_to_int(date):
year, month, day = map(int, date.split('-'))
return year * 10000 + month * 100 + day

for instrument, data in [("Instrument 1", instrument1), ("Instrument 2", instrument2), ("Instrument 3", instrument3)]:
start_value = None
end_value = None

for date, value in data:
    if date_to_int(date) == date_to_int(start_date):
        start_value = value
    elif date_to_int(date) == date_to_int(end_date):
        end_value = value

if start_value is not None and end_value is not None:
    growth_rate = ((end_value - start_value) / start_value) * 100
    print(f"{instrument}: Growth rate = {growth_rate:.2f}%")

    if growth_rate > max_growth_rate:
        max_growth_rate = growth_rate

print(f"The instrument with the highest growth rate is {best_instrument} with a growth rate of {max_growth_rate:.2f}%.")

Sample Output :
Instrument 1: Growth rate = 40.00%
Instrument 2: Growth rate = 25.00%
Instrument 3: Growth rate = 20.00%
The instrument with the highest growth rate is Instrument 1 with a growth rate of 40.00%.

You are part of a team developing an inventory management system for a retail company. The system needs to track product availability across multiple warehouses. Each warehouse is represented as a list of tuples, where each tuple contains the product identifier and the quantity available. Your task is to implement a feature that checks if a given product is available in any of the warehouses and returns the total quantity available.

Design a Python program to implement the inventory management system. Create lists to represent three warehouses, each containing tuples of product identifiers and quantities available. Then, prompt the user to enter a product identifier and check if the product is available in any of the warehouses. If available, display the total quantity available across all warehouses; otherwise, display a message indicating that the product is out of stock.

warehouse1 = [("product1", 50), ("product2", 30), ("product3", 20)]
warehouse2 = [("product4", 40), ("product2", 20), ("product5", 60)]
warehouse3 = [("product6", 70), ("product3", 10), ("product7", 25)]

product_id = input("Enter product identifier: ")

total_quantity = 0
found = False

for warehouse in [warehouse1, warehouse2, warehouse3]:
for item in warehouse:
if item[0] == product_id:
total_quantity += item[1]
found = True
break

if found:
print(f"Total quantity of product {product_id}: {total_quantity}")
else:
print("Product is out of stock.")

Sample Output :
Total quantity of product product3: 30

'''You are working for a social media analytics company. Your team is responsible for analyzing user engagement metrics to provide insights to clients. One of your tasks involves identifying trending topics based on user comments. Each comment is represented as a tuple containing the comment text and the number of likes it received. Your goal is to develop a function to identify the top trending topics based on the frequency of specific keywords mentioned in the comments.
Design a Python function identify_trending_topics (comments: List[Tuple[str, int]], keywords: List[str]) -> List[str] that takes a list of comment tuples and a list of keywords as input. Each comment tuple consists of the comment text and the number of likes it received. The function should identify the top trending topics by counting the frequency of each keyword mentioned in the comments and return a list of keywords sorted in descending order of their frequency.
Ensure your implementation efficiently handles cases where multiple keywords have the same frequency. Provide explanations for your design choices and any assumptions made.'''

comments = [
("Great product, love the features!", 50),
("The customer service was terrible, won't recommend.", 20),
("Best purchase ever, highly recommended.", 100),
("The delivery was delayed, very disappointed.", 10),
("Amazing quality, exceeded my expectations.", 80)
]

keywords = ["product", "customer service", "recommend", "delivery", "quality"]

keyword_freq = {keyword: 0 for keyword in keywords}

for comment, likes in comments:
for keyword in keywords:
if keyword in comment.lower():
keyword_freq[keyword] += 1

sorted_keywords = sorted(keyword_freq.items(), key=lambda x: x[1], reverse=True)

top_trending_topics = [keyword for keyword, freq in sorted_keywords]

print("Top Trending Topics:")
for topic in top_trending_topics:
print(topic)
Sample Output :
Top Trending Topics:
product
quality
recommend
delivery
customer service

@ali-kanbar
Copy link

what is the issue?

@Roshini08
Copy link
Author

[20/05, 8:55 am] Chandru: 1. You are developing a Python program for an online food ordering system that includes decision-making elements. The system should allow users to browse a menu, add items to their cart, specify delivery details, and place orders. Additionally, the system should dynamically apply discounts based on order totals, validate delivery addresses for availability, and adjust delivery times based on current order volume.
Your program should include the following functionalities incorporating decision-making logic:
Dynamic Discounts: Implement a system that automatically applies discounts based on the total amount of the order. For example, offer a 10% discount for orders above $50 and a 15% discount for orders above $100.
• Test Case Description: Verify that discounts are applied correctly based on the total order amount.
• Input: User adds items to the cart, resulting in different total amounts.
• Expected Output: Discounts are applied according to predefined thresholds, and the order total reflects the correct discounted amount.

Address Validation: Validate delivery addresses to ensure they are within the delivery radius of the restaurant. If the address is outside the delivery area, prompt the user to choose another address or opt for pickup.
• Test Case Description: Test the system's ability to validate delivery addresses.
• Input: User enters different delivery addresses, some within the delivery radius and some outside.
• Expected Output: Valid addresses are accepted, while invalid addresses prompt the user to choose another address or opt for pickup.

class MenuItem:
def init(self, name, price):
self.name = name
self.price = price

class ShoppingCart:
def init(self):
self.items = []

def add_item(self, item):
    self.items.append(item)

def calculate_total(self):
    return sum(item.price for item in self.items)

class OrderSystem:
DISCOUNT_THRESHOLDS = {
50: 0.10,
100: 0.15
}

def __init__(self):
    self.shopping_cart = ShoppingCart()

def apply_discount(self, total_amount):
    discount_rate = 0
    for threshold, rate in self.DISCOUNT_THRESHOLDS.items():
        if total_amount >= threshold:
            discount_rate = max(discount_rate, rate)
    return total_amount * (1 - discount_rate)

def validate_address(self, address):
    # Add logic to validate address within delivery radius
    pass

def place_order(self, delivery_address):
    total_amount = self.shopping_cart.calculate_total()
    discounted_amount = self.apply_discount(total_amount)
    if self.validate_address(delivery_address):
        # Proceed with order
        print(f"Order total: ${discounted_amount:.2f}")
        # Add logic to adjust delivery time based on order volume
    else:
        print("Delivery address is not valid. Please choose another address or opt for pickup.")

def main():
order_system = OrderSystem()

# Test dynamic discounts
cart = order_system.shopping_cart
cart.add_item(MenuItem("Pizza", 20))
cart.add_item(MenuItem("Burger", 40))
cart.add_item(MenuItem("Salad", 35))
total_amount = cart.calculate_total()
discounted_amount = order_system.apply_discount(total_amount)
print(f"Total amount: ${total_amount:.2f}, Discounted amount: ${discounted_amount:.2f}")

# Test address validation
delivery_address = "123 Main St, City, State, ZIP"
order_system.validate_address(delivery_address)

if name == "main":
main()
[20/05, 8:55 am] Chandru: 1. Write a Python program to check if a given number is positive, negative, or zero
n=int(input("Enter to a number to find positive or negative :"))
if n==0:
print(f"{n} it is Zero")
elif n>0:
print(f"{n} is Positive")
else:
print(f"{n} is Negative.")

  1.    Create a program that takes a user's age as input and outputs whether they are eligible to vote or not (considering the legal voting age is 18).
    

age=int(input("Enter your age : "))
if age>=18:
print("Your are eligible for voting ")
else:
print("Your are not eligible for voting ")

  1.    Write a Python program to determine whether a given year is a leap year or not
    

y=int(input("Enter year to find leap year or not :"))
if (y%4==0 and y%100==0 ) and y%400==0:
print(f"{y} is Leap year..")
elif (y%4==0 and y%100!=0 ) and y%400!=0:
print(f"{y} is Leap year..")
else:
print(f"{y} is Not a Leap year..")

  1.    Develop a program that takes a user's temperature as input and outputs whether they have a fever or not (considering a fever if temperature is equal to or above 100.4°F or 38°C).
    

h=int(input("Enter your choice 1.Faherinheit or 2.Celsius:"))
if h==1:
f=float(input("Enter the temperature in Faherinheit :"))
if f>=100.4:
print("You have a fever")
else:
print("You have no fever..")
elif h==2:
c=float(input("Enter the temperature in Celsius :"))
if c>=32:
print("You have a fever")
else:
print("You have no fever..")
else:
print("Invalid Input...")

  1.    Create a Python program to find the largest among three numbers entered by the user.
    

a,b,c=input("Enter any three number :")
if a>b and a>c:
print(f"{a} is the biggest number")
elif b>a and b>c:
print(f"{b} is the biggest number")
else:
print(f"{c} is the biggest number")

  1.    Write a program to calculate the total cost of a meal, including tax and tip, based on user input for the meal cost and percentage rates for tax and tip.
    

cost=int(input("Enter the cost of the meals :"))
tax=float(input("Enter the tax :"))
tip=float(input("Enter the tips :"))
taper=(taxcost)/100
tiper=(tip
cost)/100
print("The total cost for meals (incl tax and tip) : ",cost+taper+tiper)

  1.    Develop a program to classify a triangle based on the lengths of its sides (scalene, isosceles, or equilateral).
    

s1,s2,s3=input("Enter the three sides of a triangle :")
if s1==s2==s3:
print("Its is Equilateral Triangle ")
elif s1==s2 or s1==s3 or s2==s3:
print("Its is Isoceles Triangle")
else:
print("Its is Scalene Triangle")

  1.    Create a program that determines whether a given year is a leap year and has 366 days or a common year with 365 days.
    

y=int(input("Enter year to find leap year or not :"))
if (y%4==0 and y%100==0 ) and y%400==0:
print(f"{y} is Leap year..\nIts has 366")
elif (y%4==0 and y%100!=0 ) and y%400!=0:
print(f"{y} is Leap year..\nIts has 366")
else:
print(f"{y} is Not a Leap year..\nIts has 365")

  1.    Write a Python program to check whether a character entered by the user is a vowel or a consonant.
    

ch=input("Enter the character to check for vowels or not :")
vo=['a','e','i','u','o']
if ch in vo:
print("The Character is Vowels...")
else:
print("The Character is not Vowels...")

  1.    Write a Python program that prompts the user to enter three numbers and then outputs them in ascending order.
    

a,b,c=input("Enter any three number :")
k=sorted([a,b,c])
print(f"The numbers in ascending order :")
for i in k:
print(i,end=" ")
[20/05, 8:55 am] Chandru: 1. Develop a program that takes a user's score as input and outputs their corresponding grade based on the following grading scale: A (90-100), B (80-89), C (70-79), D (60-69), F (0-59).
• Test Case 1: Input score: 85. Expected output: Grade B.
• Test Case 2: Input score: 60. Expected output: Grade D.
• Test Case 3: Input score: 95. Expected output: Grade A.

def get_grade(score):
if 90 <= score <= 100:
return "A"
elif 80 <= score <= 89:
return "B"
elif 70 <= score <= 79:
return "C"
elif 60 <= score <= 69:
return "D"
elif 0 <= score <= 59:
return "F"
else:
return "Invalid score"

test_cases = [85, 60, 95]
expected_outputs = ["B", "D", "A"]

for i, test_case in enumerate(test_cases):
result = get_grade(test_case)
print(f"Input score: {test_case}. Expected output: Grade {expected_outputs[i]}. Actual output: Grade {result}.")

  1. Create a program that simulates a simple ATM machine, prompting the user for their account balance and withdrawal amount, then outputs whether the transaction is successful or not based on the available balance and withdrawal amount.
    • Test Case 1: Account balance: $1000, Withdrawal amount: $500. Expected output: Transaction successful.
    • Test Case 2: Account balance: $200, Withdrawal amount: $300. Expected output: Insufficient funds.
    • Test Case 3: Account balance: $1500, Withdrawal amount: $1500. Expected output: Transaction successful

def atm_simulation():
# Prompt the user to enter their account balance
try:
account_balance = float(input("Enter your account balance: $"))
except ValueError:
print("Invalid input. Please enter a valid number for the account balance.")
return

# Prompt the user to enter the withdrawal amount
try:
    withdrawal_amount = float(input("Enter the withdrawal amount: $"))
except ValueError:
    print("Invalid input. Please enter a valid number for the withdrawal amount.")
    return

# Check if the withdrawal amount is less than or equal to the account balance
if withdrawal_amount <= account_balance:
    print("Transaction successful.")
else:
    print("Insufficient funds.")

Run the ATM simulation

if name == "main":
atm_simulation()

  1. Design a program that calculates the roots of a quadratic equation ax^2 + bx + c = 0 based on user input for the coefficients a, b, and c, and outputs the roots
    • Test Case 1: Coefficients: a=1, b=-3, c=2. Expected output: Roots: 2.0, 1.0.
    • Test Case 2: Coefficients: a=2, b=5, c=2. Expected output: Roots: -0.5, -2.0.
    • Test Case 3: Coefficients: a=1, b=-4, c=4. Expected output: Roots: 2.0, 2.0.

import math

def calculate_roots(a, b, c):
# Calculate the discriminant
discriminant = b**2 - 4ac

if discriminant > 0:
    # Two distinct real roots
    root1 = (-b + math.sqrt(discriminant)) / (2*a)
    root2 = (-b - math.sqrt(discriminant)) / (2*a)
    return root1, root2
elif discriminant == 0:
    # One real root (double root)
    root = -b / (2*a)
    return root, root
else:
    # No real roots
    return None, None

def main():
try:
# Prompt user for coefficients a, b, and c
a = float(input("Enter coefficient a: "))
b = float(input("Enter coefficient b: "))
c = float(input("Enter coefficient c: "))

    # Calculate roots
    root1, root2 = calculate_roots(a, b, c)

    if root1 is not None and root2 is not None:
        print(f"Roots: {root1}, {root2}")
    else:
        print("No real roots.")

except ValueError:
    print("Invalid input. Please enter valid numbers for the coefficients.")

if name == "main":
main()

  1. Develop a program that takes a user's age and gender as input and outputs their recommended heart rate range during exercise based on the American Heart Association's guidelines.
    • Test Case 1: Age: 30, Gender: Male. Expected output: 93 - 157 bpm.
    • Test Case 2: Age: 45, Gender: Female. Expected output: 88 - 149 bpm.
    • Test Case 3: Age: 55, Gender: Male. Expected output: 85 - 145 bpm.

def calculate_target_heart_rate(age, gender):
if gender.lower() == 'male':
max_heart_rate = 220 - age
elif gender.lower() == 'female':
max_heart_rate = 226 - age
else:
return "Invalid gender input. Please enter 'male' or 'female'."

lower_limit = int(0.5 * max_heart_rate)
upper_limit = int(0.85 * max_heart_rate)

return lower_limit, upper_limit

def main():
age = int(input("Enter your age: "))
gender = input("Enter your gender (male/female): ")

lower_limit, upper_limit = calculate_target_heart_rate(age, gender)
if isinstance(lower_limit, int) and isinstance(upper_limit, int):
    print("Recommended heart rate range during exercise:", lower_limit, "-", upper_limit, "bpm")
else:
    print(lower_limit)

if name == "main":
main()

5.Write a program that prompts the user to enter a month and year and then outputs the number of days in that month (considering leap years for February).
• Test Case 1: Input month: February, year: 2020. Expected output: 29 days.
• Test Case 2: Input month: April, year: 2023. Expected output: 30 days.
• Test Case 3: Input month: December, year: 2021. Expected output: 31 days.

import calendar

def get_days_in_month(month, year):
# Capitalizing the first letter of the month for consistency
month = month.capitalize()

# Getting the index of the month (1 for January, 2 for February, ..., 12 for December)
month_index = list(calendar.month_name).index(month)

# Using the monthrange function to get the number of days in the specified month and year
num_days = calendar.monthrange(year, month_index)[1]

return num_days

def main():
month = input("Enter the month: ")
year = int(input("Enter the year: "))

days_in_month = get_days_in_month(month, year)

print(f"Number of days in {month}, {year}: {days_in_month} days")

if name == "main":
main()

@Roshini08
Copy link
Author

Objective:
To practice file handling operations in Python by creating, reading, and processing student data from files, and generating an analysis based on specific conditions.
Instructions:
• Create a Python script that performs the following tasks.
• Use comments to explain each part of your code.
• Ensure your code is well-organized and follows best practices.

  1. Assignment Tasks:
    • Create a File with Student Data:
    • Write a Python function create_result_file(file_path) that creates a file named result.txt.
    • The file should contain the following data for 30 students: name, register number, grades for five subjects, total marks, and percentage.
    • Use the given grade points to calculate the total and percentage:
    'O' - 10 points
    'A' - 9 points
    'B' - 8 points
    'C' - 7 points
    'D' - below 6 points
    'U' - 0 points (Arrear)
  2. Read and Display File Content:
    Write a function read_result_file(file_path) that reads and prints the content of result.txt.
  3. Analyze Student Data:
    • Write a function analyze_results(input_file, output_file) that reads data from result.txt and writes the analysis to analysis.txt.
    • The analysis should categorize students based on their percentage into the following groups:
    I. Students who score 90% and above
    II. Students who score equal to or above 80% and below 90%
    III. Students who score equal to or above 70% and below 80%
    IV. Students who score below 70%
    V. Students having arrear

import random

#Define grade points
grade_points = {'O': 10, 'A': 9, 'B': 8, 'C': 7, 'D': 5, 'U': 0}

#Generate random student data
names = ["Student_" + str(i) for i in range(1, 31)]
students = []
for name in names:
register_number = random.randint(1000, 9999)
grades = random.choices(list(grade_points.keys()), k=5)
total_marks = sum(grade_points[grade] for grade in grades)
percentage = (total_marks / 50) * 100 # Each subject max points = 10
students.append((name, register_number, grades, total_marks, percentage))

#Create result.txt
with open('result.txt', 'w') as file:
for student in students:
name, register_number, grades, total_marks, percentage = student
grades_str = ','.join(grades)
file.write(f"{name},{register_number},{grades_str},{total_marks},{percentage:.2f}\n")

#read and display the content of result.txt
with open('result.txt', 'r') as file:
content = file.read()
print(content)

#analyze the results and write to analysis.txt
categories = {
'90_and_above': [],
'80_to_89': [],
'70_to_79': [],
'below_70': [],
'arrear': []
}

for student in students:
name, register_number, grades, total_marks, percentage = student
if 'U' in grades:
categories['arrear'].append(student)
elif percentage >= 90:
categories['90_and_above'].append(student)
elif percentage >= 80:
categories['80_to_89'].append(student)
elif percentage >= 70:
categories['70_to_79'].append(student)
else:
categories['below_70'].append(student)

with open('analysis.txt', 'w') as file:
for category, students in categories.items():
file.write(f"Category: {category.replace('_', ' ').title()}\n")
file.write(f"{'Name':<15}{'Register Number':<15}{'Total Marks':<15}{'Percentage':<10}\n")
file.write("="*55 + "\n")
for student in students:
name, register_number, grades, total_marks, percentage = student
file.write(f"{name:<15}{register_number:<15}{total_marks:<15}{percentage:<10.2f}\n")
file.write("\n")

#Read and display the content of analysis.txt
with open('analysis.txt', 'r') as file:
content = file.read()
print(content)


@Roshini08
Copy link
Author

Write a Python program that takes three integers as input and prints the largest among them. However, if two or more integers are equal and larger than the third integer, print "Equal numbers are larger". If all three integers are equal, print "All numbers are equal".

num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
num3 = int(input("Enter the third number: "))

if num1 == num2 == num3:
print("All numbers are equal")
elif num1 == num2 > num3 or num1 == num3 > num2 or num2 == num3 > num1:
print("Equal numbers are larger")
else:
print("The largest number is:", max(num1, num2, num3))

  1. Write a Python program that takes three numbers as input and prints them in ascending order. However, if two or more numbers are equal, print "Numbers are not distinct.

num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
num3 = int(input("Enter the third number: "))

if num1 == num2 == num3:
print("Numbers are not distinct")
else:
numbers = [num1, num2, num3]
numbers.sort()
print("The numbers in ascending order:", numbers)

  1. Write a Python program that takes two numbers as input and performs basic arithmetic operations (addition, subtraction, multiplication, division) on them.

num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

print("Addition:", num1 + num2)
print("Subtraction:", num1 - num2)
print("Multiplication:", num1 * num2)
if num2 != 0:
print("Division:", num1 / num2)
else:
print("Division by zero is not allowed")

  1. Write a Python program that converts temperature from Celsius to Fahrenheit. The program should take Celsius temperature as input and print the equivalent temperature in Fahrenheit.

celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print("Temperature in Fahrenheit:", fahrenheit)

  1. Write a Python program to check if a given number is even or odd

num = int(input("Enter a number: "))
if num % 2 == 0:
print("The number is even")
else:
print("The number is odd")

  1. Write a Python program that calculates the sum of digits of a given number.

num = int(input("Enter a number: "))
sum_of_digits = 0
while num > 0:
sum_of_digits += num % 10
num //= 10
print("Sum of digits:", sum_of_digits)

  1. Write a Python program to calculate the factorial of a given number

num = int(input("Enter a number: "))
factorial = 1
for i in range(1, num + 1):
factorial *= i
print("Factorial of", num, "is", factorial)

  1. Write a Python program that finds the maximum element in a given list of numbers.

numbers = [int(x) for x in input("Enter numbers separated by space: ").split()]
print("Maximum element:", max(numbers))

  1. Write a Python program to calculate the simple interest. The program should take principal amount, rate of interest, and time as input and print the simple interest.

principal = float(input("Enter the principal amount: "))
rate = float(input("Enter the rate of interest: "))
time = float(input("Enter the time period (in years): "))
simple_interest = (principal * rate * time) / 100
print("Simple interest:", simple_interest)

  1. Write a Python program to generate the Fibonacci series up to n terms, where n is provided by the user.

n = int(input("Enter the number of terms: "))
fibonacci = [0, 1]
for i in range(2, n):
fibonacci.append(fibonacci[-1] + fibonacci[-2])
print("Fibonacci series up to", n, "terms:", fibonacci)

  1. Write a Python program to check if a given number is prime or not.

num = int(input("Enter a number: "))
if num > 1:
for i in range(2, int(num/2) + 1):
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")

  1. Write a Python program to count the occurrences of each word in a given string

string = input("Enter a string: ")
word_count = {}
for word in string.split():
word_count[word] = word_count.get(word, 0) + 1
print("Occurrences of each word:", word_count)

  1. Write a Python program to check if two strings are anagrams of each other

str1 = input("Enter the first string: ")
str2 = input("Enter the second string: ")
if sorted(str1) == sorted(str2):
print("The strings are anagrams")
else:
print("The strings are not anagrams")

  1. Write a Python function to reverse a given string.

string = input("Enter a string: ")
print("Reversed string:", string[::-1])

  1. Write a Python function to count the number of vowels in a given string.

string = input("Enter a string: ")
vowels = "aeiouAEIOU"
count = 0
for char in string:
if char in vowels:
count += 1
print("Number of vowels:", count)

  1. Write a Python program that takes two strings as input from the user and concatenates them together. Display the concatenated string as output.

str1 = input("Enter the first string: ")
str2 = input("Enter the second string: ")
concatenated_string = str1 + str2
print("Concatenated string:", concatenated_string)

  1. Write a Python program that takes a string as input from the user and prints its length.

string = input("Enter a string: ")
print("Length of the string:", len(string))

  1. Write a Python program that takes a string as input from the user and converts it to uppercase and lowercase. Display both the uppercase and lowercase versions of the string.

string = input("Enter a string: ")
print("Uppercase:", string.upper())
print("Lowercase:", string.lower())

  1. Write a Python program that takes a string as input from the user and extracts a substring from it. Display the extracted substring.

string = input("Enter a string: ")
start = int(input("Enter the start index: "))
end = int(input("Enter the end index: "))
print("Extracted substring:", string[start:end])

  1. Write a Python program that takes a sentence as input from the user and counts the number of words in it. Display the count of words.

sentence = input("Enter a sentence: ")
word_count = len(sentence.split())
print("Number of words in the sentence:", word_count)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants