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

Answers Python base

Uploaded by

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

Answers Python base

Uploaded by

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

1.

Data Parsing and Aggregation

# Function to calculate total revenue

def calculate_total_revenue(file_name):

total_revenue = 0

with open(file_name, 'r') as file:

for line in file:

product, quantity, price = line.strip().split(',')

total_revenue += int(quantity) * float(price)

return total_revenue

# Function to calculate total quantity sold per product

def total_quantity_per_product(file_name):

quantities = {}

with open(file_name, 'r') as file:

for line in file:

product, quantity, price = line.strip().split(',')

quantities[product] = quantities.get(product, 0) + int(quantity)

return quantities

# Function to find product with highest revenue

def highest_revenue_product(file_name):

revenue = {}

with open(file_name, 'r') as file:

for line in file:

product, quantity, price = line.strip().split(',')


revenue[product] = revenue.get(product, 0) + int(quantity) *
float(price)

return max(revenue, key=revenue.get)

2. String Manipulation and Pattern Matching

# Function to validate an email

def is_valid_email(email):

return "@" in email and email.endswith(".com")

# Filter valid emails from list

def filter_valid_emails(email_list):

return [email for email in email_list if is_valid_email(email)]

# Count the number of valid emails

def count_valid_emails(email_list):

return len(filter_valid_emails(email_list))

3. Basic Statistical Analysis

# Calculate average temperature

def average_temperature(temperatures):

return sum(temperatures) / len(temperatures)

# Find max and min temperatures

def max_min_temperature(temperatures):

return max(temperatures), min(temperatures)


# Count days above average temperature

def days_above_average(temperatures):

avg_temp = average_temperature(temperatures)

return sum(1 for temp in temperatures if temp > avg_temp)

4. File Operations and Data Organization

# Function to read file and store data in dictionary

def read_student_data(file_name):

student_grades = {}

with open(file_name, 'r') as file:

for line in file:

name, grade = line.strip().split(',')

student_grades[name] = int(grade)

return student_grades

# Find student with the highest grade

def top_student(student_grades):

return max(student_grades, key=student_grades.get)

# Calculate average grade

def average_grade(student_grades):

return sum(student_grades.values()) / len(student_grades)

# Save students above average grade to new file

def save_above_average(file_name, student_grades):


avg_grade = average_grade(student_grades)

with open(file_name, 'w') as file:

for student, grade in student_grades.items():

if grade > avg_grade:

file.write(f"{student}\n")

5. Inventory Management System

# Add a new book to inventory

def add_book(inventory, book):

inventory.append(book)

# Update quantity of a book by title

def update_quantity(inventory, title, quantity):

for book in inventory:

if book['title'] == title:

book['quantity'] = quantity

break

# Calculate total inventory value

def total_inventory_value(inventory):

return sum(book['quantity'] * book['price'] for book in inventory)

# Find book with highest price

def most_expensive_book(inventory):

return max(inventory, key=lambda book: book['price'])


6. Simple Password Validator

# Check if password is valid

def is_valid_password(password):

if len(password) < 8:

return False

has_upper = any(c.isupper() for c in password)

has_lower = any(c.islower() for c in password)

has_digit = any(c.isdigit() for c in password)

return has_upper and has_lower and has_digit

# Filter valid passwords from list

def filter_valid_passwords(password_list):

return [password for password in password_list if


is_valid_password(password)]

7. Sales Commission Calculation

# Calculate commission for given sales amount

def calculate_commission(sales_amount):

return sales_amount * 0.05 if sales_amount < 1000 else sales_amount *


0.10

# Get commission list for sales figures

def commission_list(sales_figures):

return [calculate_commission(sales) for sales in sales_figures]


# Find salesperson with highest commission

def highest_commission_salesperson(sales_figures):

commissions = commission_list(sales_figures)

return sales_figures[commissions.index(max(commissions))]

8. Simple Encryption and Decryption

# Encrypt message using Caesar Cipher

def encrypt_message(message, shift):

encrypted_message = ""

for char in message:

if char.isalpha():

shift_base = ord('A') if char.isupper() else ord('a')

encrypted_message += chr((ord(char) - shift_base + shift) % 26 +


shift_base)

else:

encrypted_message += char

return encrypted_message

# Decrypt message using Caesar Cipher

def decrypt_message(encrypted_message, shift):

return encrypt_message(encrypted_message, -shift)

9. Basic Recursive Function

# Recursive factorial function

def factorial(n):
if n == 0:

return 1

else:

return n * factorial(n - 1)

# Test factorial function from 1 to 10

def test_factorials():

return {n: factorial(n) for n in range(1, 11)}

10. Word Frequency Counter

# Function to count word frequency

def word_frequency(text):

words = text.split()

frequency = {}

for word in words:

frequency[word] = frequency.get(word, 0) + 1

return frequency

# Find most common word and its frequency

def most_common_word(frequency):

return max(frequency, key=frequency.get), frequency[max(frequency,


key=frequency.get)]

# Display top 5 most frequent words

def top_5_words(frequency):

return sorted(frequency.items(), key=lambda x: x[1], reverse=True)[:5]

You might also like