Untitled
unknown
plain_text
a year ago
32 kB
8
Indexable
Week 1:
2. If you run a 10-kilometer race in 43 minutes 30 seconds, calculate your average time per mile and
your average speed in miles per hour using Python
Calculator. (Hint: there are 1.61 kilometers in a mile).
# Given values
distance_km = 10 # distance in kilometers
total_time_minutes = 43 # minutes
total_time_seconds = 30 # seconds
# Convert distance from kilometers to miles
km_to_mile = 1.61
distance_miles = distance_km / km_to_mile
# Convert total time to hours
total_time_hours = total_time_minutes / 60 + total_time_seconds / 3600
# Calculate average speed in miles per hour
average_speed_mph = distance_miles / total_time_hours
# Calculate average time per mile
average_time_per_mile_hours = total_time_hours / distance_miles
average_time_per_mile_minutes = average_time_per_mile_hours * 60 # convert hours to minutes
average_time_per_mile_seconds = average_time_per_mile_minutes * 60 # convert minutes to seconds
# Output the results
print(f"Average speed: {average_speed_mph:.2f} miles per hour")
print(f"Average time per mile: {int(average_time_per_mile_minutes)} minutes and {average_time_per_mile_seconds % 60:.2f} seconds")
//
3. Write a program to find the simple interest for a given value P, T and R. The program must take the
input from the user.
# Function to calculate simple interest
def calculate_simple_interest(principal, time, rate):
simple_interest = (principal * time * rate) / 100
return simple_interest
# Main program
def main():
try:
# Get input from the user
principal = float(input("Enter the principal amount (P): "))
time = float(input("Enter the time period in years (T): "))
rate = float(input("Enter the annual interest rate (R) in percentage: "))
# Calculate simple interest
simple_interest = calculate_simple_interest(principal, time, rate)
# Display the result
print(f"The simple interest for P = {principal}, T = {time} years, and R = {rate}% is: {simple_interest}")
except ValueError:
print("Please enter valid numeric values for P, T, and R.")
if __name__ == "__main__":
main()
//
4. Write a python program to generate first n Fibonacci number and factorial of n using function.
def generate_fibonacci(n):
"""Generate the first n Fibonacci numbers."""
fibonacci_sequence = []
a, b = 0, 1
while len(fibonacci_sequence) < n:
fibonacci_sequence.append(a)
a, b = b, a + b
return fibonacci_sequence
def factorial(n):
"""Calculate the factorial of n."""
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
def main():
try:
# Get input from the user
n = int(input("Enter a positive integer n: "))
if n < 0:
raise ValueError("The number must be a positive integer.")
# Generate the first n Fibonacci numbers
fibonacci_sequence = generate_fibonacci(n)
print(f"The first {n} Fibonacci numbers are: {fibonacci_sequence}")
# Calculate the factorial of n
n_factorial = factorial(n)
print(f"The factorial of {n} is: {n_factorial}")
except ValueError as e:
print(f"Invalid input: {e}")
if __name__ == "__main__":
main()
//
Week 2:
1. Write a function to calculate the square of first n natural numbers.
def squares_of_natural_numbers(n):
"""Calculate the squares of the first n natural numbers."""
squares = [i**2 for i in range(1, n+1)]
return squares
def main():
try:
# Get input from the user
n = int(input("Enter a positive integer n: "))
if n <= 0:
raise ValueError("The number must be a positive integer.")
# Calculate the squares of the first n natural numbers
squares = squares_of_natural_numbers(n)
print(f"The squares of the first {n} natural numbers are: {squares}")
except ValueError as e:
print(f"Invalid input: {e}")
if __name__ == "__main__":
main()
//
2. Write a function that draws a grid like the following:
+ - - - -+ - - - -+
| | |
| | |
| | |
| | |
+ - - - -+ - - - -+
| | |
| | |
| | |
| | |
+ - - - -+ - - - -+
def draw_grid():
# Define the components of the grid
plus = '+'
minus = '-'
pipe = '|'
space = ' '
# Create the horizontal and vertical parts of the grid
horizontal_line = plus + space + (minus + space) * 4 + plus + space + (minus + space) * 4 + plus
vertical_line = pipe + space * 9 + pipe + space * 9 + pipe
# Print the grid
for _ in range(2):
print(horizontal_line)
for _ in range(4):
print(vertical_line)
print(horizontal_line)
# Main function to call the draw_grid function
def main():
draw_grid()
if __name__ == "__main__":
main()
//
3. Write a function that takes any number of arguments and returns their sum.
def sum_of_arguments(*args):
"""Return the sum of any number of arguments."""
total_sum = sum(args)
return total_sum
# Main function to demonstrate the sum_of_arguments function
def main():
# Example usage
print(sum_of_arguments(1, 2, 3)) # Output: 6
print(sum_of_arguments(4, 5, 6, 7, 8)) # Output: 30
print(sum_of_arguments(10)) # Output: 10
print(sum_of_arguments()) # Output: 0
print(sum_of_arguments(1.5, 2.5, 3.5)) # Output: 7.5
if __name__ == "__main__":
main()
//
4. Write a function that takes four parameters—a, b, c and n—and then checks to see if Fermat’s
theorem, an + bn = cn, holds. If n is greater than 2 and it turns out to be true then the program should
print, “Holy smokes, Fermat was wrong!” Otherwise, the program should print, “No, that doesn’t
work.”
def check_fermat(a, b, c, n):
"""Check if Fermat's Last Theorem holds for the given values of a, b, c, and n."""
if n > 2 and (a**n + b**n == c**n):
print("Holy smokes, Fermat was wrong!")
else:
print("No, that doesn’t work.")
# Main function to demonstrate the check_fermat function
def main():
try:
# Get input from the user
a = int(input("Enter the value of a: "))
b = int(input("Enter the value of b: "))
c = int(input("Enter the value of c: "))
n = int(input("Enter the value of n: "))
# Check Fermat's theorem
check_fermat(a, b, c, n)
except ValueError:
print("Please enter valid integer values for a, b, c, and n.")
if __name__ == "__main__":
main()
//
Week 3:
1. Write a function that takes a string argument and returns true if it is a palindrome and False
otherwise.
def is_palindrome(s):
"""Check if the given string is a palindrome."""
# Remove non-alphanumeric characters and convert to lowercase
cleaned_s = ''.join(char.lower() for char in s if char.isalnum())
# Check if the cleaned string reads the same forward and backward
return cleaned_s == cleaned_s[::-1]
# Main function to demonstrate the is_palindrome function
def main():
# Example usage
test_strings = [
"A man, a plan, a canal, Panama",
"racecar",
"hello",
"No 'x' in Nixon",
"Was it a car or a cat I saw?"
]
for s in test_strings:
print(f"'{s}' -> {is_palindrome(s)}")
if __name__ == "__main__":
main()
//
2. A number, a, is a power of b if it is divisible by b and a/b is a power of b. Write a function that takes
parameters a and b and returns True if a is a power of b.
def is_power(a, b):
"""Check if 'a' is a power of 'b'."""
if a < b:
return False
if a == b:
return True
if b == 1:
return a == 1
return a % b == 0 and is_power(a // b, b)
# Main function to demonstrate the is_power function
def main():
# Example usage
test_cases = [
(8, 2), # True: 8 is 2^3
(9, 3), # True: 9 is 3^2
(10, 2), # False: 10 is not a power of 2
(27, 3), # True: 27 is 3^3
(1, 1), # True: 1 is 1^1
(16, 4), # True: 16 is 4^2
(20, 4), # False: 20 is not a power of 4
(0, 5), # False: 0 is not a power of any number (except itself)
(1, 2) # True: 1 is 2^0
]
for a, b in test_cases:
print(f"is_power({a}, {b}) -> {is_power(a, b)}")
if __name__ == "__main__":
main()
//
3. Write a function that takes a string as a parameter. Calculate the length of a string without using the
Len function. Print the length concatenated with the string and aligned towards the extreme right of
the output screen.
def calculate_length(string):
"""Calculate the length of a string without using the len() function."""
length = 0
# Iterate through each character in the string
for _ in string:
length += 1
return length
def print_right_aligned(string):
"""Print the length of the string concatenated with the string, aligned towards the extreme right."""
length = calculate_length(string)
print(f"{length:>{length}} {string}")
# Main function to demonstrate the print_right_aligned function
def main():
test_strings = [
"Hello, World!",
"Python",
"OpenAI",
"Lorem ipsum dolor sit amet",
"1234567890",
""
]
for test_string in test_strings:
print_right_aligned(test_string)
if __name__ == "__main__":
main()
//
Week 4:
1. Write a recursive function to calculate the factorial of a given number.
def factorial(n):
"""Calculate the factorial of a given number."""
# Base case: factorial of 0 is 1
if n == 0:
return 1
# Recursive case: factorial of n is n times factorial of n-1
else:
return n * factorial(n - 1)
# Main function to demonstrate the factorial function
def main():
try:
# Get input from the user
n = int(input("Enter a non-negative integer: "))
if n < 0:
raise ValueError("The number must be non-negative.")
# Calculate the factorial
result = factorial(n)
print(f"The factorial of {n} is: {result}")
except ValueError as e:
print(f"Invalid input: {e}")
if __name__ == "__main__":
main()
//
2. Write a function that takes a nested list of integers and adds up the elements from all the nested lists.
def sum_nested_list(nested_list):
"""Recursively sum up all elements in a nested list."""
total_sum = 0
for element in nested_list:
if isinstance(element, list):
# If the element is a list, recursively sum its elements
total_sum += sum_nested_list(element)
else:
# If the element is an integer, add it to the total sum
total_sum += element
return total_sum
# Main function to demonstrate the sum_nested_list function
def main():
nested_list = [[1, 2, 3], [4, 5], [6, [7, 8], 9], 10]
total_sum = sum_nested_list(nested_list)
print("Sum of elements in the nested list:", total_sum)
if __name__ == "__main__":
main()
//
3. Write a function called middle that takes a list and returns a new list that contains all but the first and
last elements. So middle ([1, 2, 3, 4]) should return [2, 3].
def middle(lst):
"""Return a new list containing all but the first and last elements of the input list."""
return lst[1:-1]
# Main function to demonstrate the middle function
def main():
# Test the middle function
test_list = [1, 2, 3, 4]
result = middle(test_list)
print("Result:", result)
if __name__ == "__main__":
main()
//
Week 5:
1. ROT13 is a weak form of encryption that involves “rotating” each letter in a word by 13 places. To
rotate a letter means to shift it through the alphabet, wrapping around to the beginning if necessary,
so ’A’ shifted by 3 is ’D’ and ’Z’ shifted by 1 is ’A’. Write a function that takes a string and an
integer as parameters, and then returns a new string that contains the letters from the original string
“rotated” by the given amount. Use the built-in functions ord, which converts a character to a
numeric code, and chr, which converts numeric codes to characters.
def rotate_letter(letter, n):
"""Rotate a single letter by n places in the alphabet."""
if letter.islower():
start = ord('a')
elif letter.isupper():
start = ord('A')
else:
return letter
rotated = chr((ord(letter) - start + n) % 26 + start)
return rotated
def rotate_string(string, n):
"""Rotate each letter in a string by n places."""
rotated_string = ''
for letter in string:
rotated_string += rotate_letter(letter, n)
return rotated_string
# Main function to demonstrate the rotate_string function
def main():
# Test the rotate_string function
original_string = "Hello, World!"
rotated_string = rotate_string(original_string, 13)
print("Original string:", original_string)
print("Rotated string:", rotated_string)
if __name__ == "__main__":
main()
//
2. Write a Python program to convert a list of characters into a string.
def list_to_string(char_list):
"""Convert a list of characters into a string."""
return ''.join(char_list)
# Main function to demonstrate the list_to_string function
def main():
# Test the list_to_string function
char_list = ['H', 'e', 'l', 'l', 'o']
string_result = list_to_string(char_list)
print("Original list:", char_list)
print("Converted string:", string_result)
if __name__ == "__main__":
main()
//
3. Write a Python program to find the index of an item in a specified list.
def find_index(lst, item):
"""Find the index of an item in a specified list."""
try:
index = lst.index(item)
return index
except ValueError:
return f"The item '{item}' is not in the list."
# Main function to demonstrate the find_index function
def main():
# Test the find_index function
my_list = ['apple', 'banana', 'orange', 'grape']
item_to_find = 'orange'
index_result = find_index(my_list, item_to_find)
print(f"Index of '{item_to_find}':", index_result)
if __name__ == "__main__":
main()
//
Week 6: List Exercises
1. Write a program to add two lists index-wise. Create a new list that contains the 0th index item from
both the lists, then the 1st index item, and so on till the last element. any leftover items will get
added at the end of the new list.
i/p: list1 = ["M", "na", "i", "Ke"]
list2 = ["y", "me", "s", "lly"]
o/p: ['My', 'name', 'is', 'Kelly']
def add_lists(list1, list2):
"""Add two lists index-wise."""
result = []
# Iterate through the indices of both lists simultaneously
for i in range(max(len(list1), len(list2))):
# Concatenate the elements at the same index and add to the result list
element = list1[i] + list2[i] if i < len(list1) and i < len(list2) else (list1[i] if i < len(list1) else list2[i])
result.append(element)
return result
# Main function to demonstrate the add_lists function
def main():
# Input lists
list1 = ["M", "na", "i", "Ke"]
list2 = ["y", "me", "s", "lly"]
# Add the lists index-wise
result = add_lists(list1, list2)
# Print the result
print("Result:", result)
if __name__ == "__main__":
main()
//
2. Write a program to turn every item of a list into its square.
def square_list(lst):
"""Turn every item of a list into its square."""
squared_list = [x ** 2 for x in lst]
return squared_list
# Main function to demonstrate the square_list function
def main():
# Input list
original_list = [1, 2, 3, 4, 5]
# Turn every item of the list into its square
squared_list = square_list(original_list)
# Print the result
print("Original list:", original_list)
print("Squared list:", squared_list)
if __name__ == "__main__":
main()
//
3. Write a program to concatenate two list:
i/p: list1 = ["Hello ", "take "]
list2 = ["Dear", "Sir"]
o/p: ['Hello Dear', 'Hello Sir', 'take Dear', 'take Sir']
def concatenate_lists(list1, list2):
"""Concatenate two lists."""
concatenated_list = [x + y for x in list1 for y in list2]
return concatenated_list
# Main function to demonstrate the concatenate_lists function
def main():
# Input lists
list1 = ["Hello ", "take "]
list2 = ["Dear", "Sir"]
# Concatenate the lists
result = concatenate_lists(list1, list2)
# Print the result
print("Result:", result)
if __name__ == "__main__":
main()
//
4. Write a program to remove empty string from the list of String using filter function:
i/p: list1 = ["Mike", "", "Emma", "Kelly", "", "Brad"]
o/p: ["Mike", "Emma", "Kelly", "Brad"]
def remove_empty_strings(lst):
"""Remove empty strings from a list of strings using filter function."""
filtered_list = list(filter(lambda x: x != "", lst))
return filtered_list
# Main function to demonstrate the remove_empty_strings function
def main():
# Input list
list1 = ["Mike", "", "Emma", "Kelly", "", "Brad"]
# Remove empty strings from the list
result = remove_empty_strings(list1)
# Print the result
print("Result:", result)
if __name__ == "__main__":
main()
//
5. Write a program to iterate both lists simultaneously and display items from list1 in original order and
items from list2 in reverse order. [Hint: Use the zip () function.]
def iterate_lists(list1, list2):
"""Iterate both lists simultaneously, displaying items from list1 in original order and items from list2 in reverse order."""
for item1, item2 in zip(list1, reversed(list2)):
print(item1, item2)
# Main function to demonstrate the iterate_lists function
def main():
# Input lists
list1 = ["A", "B", "C", "D", "E"]
list2 = ["W", "X", "Y", "Z"]
# Iterate both lists simultaneously and display items as described
iterate_lists(list1, list2)
if __name__ == "__main__":
main()
//
Week 7: Tuples Excercises
1. Write a Python program to convert a list of tuples into a dictionary.
def list_of_tuples_to_dict(list_of_tuples):
"""Convert a list of tuples into a dictionary."""
dictionary = {key: value for key, value in list_of_tuples}
return dictionary
# Main function to demonstrate the list_of_tuples_to_dict function
def main():
# Input list of tuples
list_of_tuples = [("a", 1), ("b", 2), ("c", 3)]
# Convert the list of tuples into a dictionary
result = list_of_tuples_to_dict(list_of_tuples)
# Print the result
print("Result:", result)
if __name__ == "__main__":
main()
//
2. Write a program to
a. reverse a tuple.
b. Swap two tuples.
def reverse_tuple(t):
"""Reverse a tuple."""
return t[::-1]
def swap_tuples(t1, t2):
"""Swap two tuples."""
return t2, t1
# Main function to demonstrate the reverse_tuple and swap_tuples functions
def main():
# Original tuples
tuple1 = (1, 2, 3, 4, 5)
tuple2 = ('a', 'b', 'c', 'd', 'e')
# Reverse tuple1
reversed_tuple1 = reverse_tuple(tuple1)
print("Reversed tuple1:", reversed_tuple1)
# Swap tuple1 and tuple2
swapped_tuple1, swapped_tuple2 = swap_tuples(tuple1, tuple2)
print("Swapped tuple1:", swapped_tuple1)
print("Swapped tuple2:", swapped_tuple2)
if __name__ == "__main__":
main()
//
3. write a Python program to print the value 20 from the given tuple: tuple1 = ("Orange",
[10, 20, 30], (5, 15, 25)), and modify the first item (20) of a list inside the tuple to
220.
def modify_tuple(tuple1):
"""Print and modify the value 20 from the given tuple."""
# Access the value 20 and print it
value_20 = tuple1[1][1]
print("Value 20:", value_20)
# Modify the first item (20) of the list inside the tuple to 220
tuple1[1][1] = 220
# Main function to demonstrate the modify_tuple function
def main():
# Given tuple
tuple1 = ("Orange", [10, 20, 30], (5, 15, 25))
# Print and modify the value 20 from the tuple
modify_tuple(tuple1)
# Print the modified tuple
print("Modified tuple:", tuple1)
if __name__ == "__main__":
main()
//
Write a program to unpack the following tuple into four variables and display each variable and
count the occurrence of 20.
i/p: tuple1 = (10, 20, 30, 20)
o/p: tuple1 = (10, 20, 30, 40)
# Your code
print(a) # should print 10
print(b) # should print 20
print(c) # should print 30
print(d) # should print 20
# Given tuple
tuple1 = (10, 20, 30, 20)
# Unpack the tuple into four variables
a, b, c, d = tuple1
# Display each variable
print("a:", a) # should print 10
print("b:", b) # should print 20
print("c:", c) # should print 30
print("d:", d) # should print 20
# Count the occurrence of 20
occurrences_of_20 = tuple1.count(20)
print("Count of occurrence of 20:", occurrences_of_20)
//
Week 8: Sets
1. Given a Python list sample_list = ["Blue", "Green", "Red"], write a program to add all its elements
into a given set. sample_set = {"Yellow", "Orange", "Black"} [Hint: use update () function]
def add_list_to_set(sample_set, sample_list):
"""Add all elements of a list to a given set."""
sample_set.update(sample_list)
# Main function to demonstrate adding elements of a list to a set
def main():
# Given list and set
sample_list = ["Blue", "Green", "Red"]
sample_set = {"Yellow", "Orange", "Black"}
# Add elements of the list to the set
add_list_to_set(sample_set, sample_list)
# Print the updated set
print("Updated set:", sample_set)
if __name__ == "__main__":
main()
//
2. Write a python code to return a new set of identical items from two sets, also return a new set with
unique items from both sets by removing duplicates. set1 = {10, 20, 30, 40, 50}; set2 = {30, 40, 50,
60, 70}.
def process_sets(set1, set2):
"""Return a new set of identical items and a new set with unique items from two sets."""
# Set of identical items
identical_items = set1.intersection(set2)
# Set with unique items from both sets
unique_items = set1.union(set2)
return identical_items, unique_items
# Main function to demonstrate processing two sets
def main():
# Given sets
set1 = {10, 20, 30, 40, 50}
set2 = {30, 40, 50, 60, 70}
# Process sets
identical_items, unique_items = process_sets(set1, set2)
# Print results
print("Identical items:", identical_items)
print("Unique items:", unique_items)
if __name__ == "__main__":
main()
//
3. Write a python code to remove items from set1 that are not common to both set1 and set2; set1 =
{10, 20, 30, 40, 50}; set2 = {30, 40, 50, 60, 70}.
def process_sets(set1, set2):
"""Return a new set of identical items and a new set with unique items from two sets."""
# Set of identical items
identical_items = set1.intersection(set2)
# Set with unique items from both sets
unique_items = set1.union(set2)
return identical_items, unique_items
# Main function to demonstrate processing two sets
def main():
# Given sets
set1 = {10, 20, 30, 40, 50}
set2 = {30, 40, 50, 60, 70}
# Process sets
identical_items, unique_items = process_sets(set1, set2)
# Print results
print("Identical items:", identical_items)
print("Unique items:", unique_items)
if __name__ == "__main__":
main()
//
Week 9: Dictionary Exercises
1. Write a Python program to convert them into a dictionary in a way that item from list1 is the key i.e.
keys = ['Ten', 'Twenty', 'Thirty'], and item from list2 is the value i.e. values = [10, 20, 30], and print
the keys of the dictionary and their values in alphabetical order. [Hint: use update () function.]
def lists_to_dictionary(keys, values):
"""Convert two lists into a dictionary."""
dictionary = dict(zip(keys, values))
return dictionary
# Main function to demonstrate converting lists into a dictionary
def main():
# Given lists
keys = ['Ten', 'Twenty', 'Thirty']
values = [10, 20, 30]
# Convert lists into a dictionary
result_dict = lists_to_dictionary(keys, values)
# Print keys and their values in alphabetical order
sorted_keys = sorted(result_dict.keys())
for key in sorted_keys:
print(key, ":", result_dict[key])
if __name__ == "__main__":
main()
//
2. Write a Python program to insert a key in between and delete a key from the dictionary.
def insert_and_delete(dictionary, key_to_insert, value_to_insert, key_to_delete):
"""Insert a key with its value and delete another key from the dictionary."""
# Insert a key and its value
dictionary[key_to_insert] = value_to_insert
# Delete a key
if key_to_delete in dictionary:
del dictionary[key_to_delete]
else:
print("Key to delete not found.")
# Main function to demonstrate inserting and deleting keys in a dictionary
def main():
# Given dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}
# Key and value to insert
key_to_insert = 'd'
value_to_insert = 4
# Key to delete
key_to_delete = 'b'
# Insert a key and its value, and delete another key
insert_and_delete(my_dict, key_to_insert, value_to_insert, key_to_delete)
# Print the updated dictionary
print("Updated dictionary:", my_dict)
if __name__ == "__main__":
main()
//
3. Write a Python program to check if value 200 exists in the following dictionary: sample_dict =
{'a': 100, 'b': 200, 'c': 300}
def check_value_exists(dictionary, value):
"""Check if a value exists in the dictionary."""
return value in dictionary.values()
# Main function to demonstrate checking if a value exists in a dictionary
def main():
# Given dictionary
sample_dict = {'a': 100, 'b': 200, 'c': 300}
# Value to check
value_to_check = 200
# Check if the value exists in the dictionary
if check_value_exists(sample_dict, value_to_check):
print(f"Value {value_to_check} exists in the dictionary.")
else:
print(f"Value {value_to_check} does not exist in the dictionary.")
if __name__ == "__main__":
main()
//
4. Write a program to rename a key city to a location in the following dictionary:
sample_dict = {
"name": "Kelly",
"age":25,
"salary": 8000,
"city": "New york"
}
def rename_key(dictionary, old_key, new_key):
"""Rename a key in the dictionary."""
if old_key in dictionary:
dictionary[new_key] = dictionary.pop(old_key)
# Main function to demonstrate renaming a key in a dictionary
def main():
# Given dictionary
sample_dict = {
"name": "Kelly",
"age": 25,
"salary": 8000,
"city": "New York"
}
# Rename the key 'city' to 'location'
rename_key(sample_dict, 'city', 'location')
# Print the updated dictionary
print("Updated dictionary:", sample_dict)
if __name__ == "__main__":
main()
//
5. Write a Python program to change Brad’s salary to 8500 in the following dictionary:
sample_dict = {
'emp1': {'name': 'Jhon', 'salary': 7500},
'emp2': {'name': 'Emma', 'salary': 8000},
'emp3': {'name': 'Brad', 'salary': 500}
}
def change_salary(dictionary, employee_name, new_salary):
"""Change the salary of an employee in the dictionary."""
if employee_name in dictionary:
dictionary[employee_name]['salary'] = new_salary
# Main function to demonstrate changing an employee's salary in a dictionary
def main():
# Given dictionary
sample_dict = {
'emp1': {'name': 'John', 'salary': 7500},
'emp2': {'name': 'Emma', 'salary': 8000},
'emp3': {'name': 'Brad', 'salary': 500}
}
# Change Brad's salary to 8500
change_salary(sample_dict, 'emp3', 8500)
# Print the updated dictionary
print("Updated dictionary:", sample_dict)
if __name__ == "__main__":
main()
//
Week 10: File Handling
1. Write a python program to
a. To create two new files f1 and f2
b. To read and display the contents, count the number of lines, and find the word whose count is
more in f1 and f2 respectively.
c. To create and display the file f3 which is a combination of f1 and f2.
def create_files():
"""Create two new files f1.txt and f2.txt."""
with open("f1.txt", "w") as f1:
f1.write("apple banana banana cherry\napple cherry cherry\nbanana banana cherry")
with open("f2.txt", "w") as f2:
f2.write("apple banana cherry\napple apple banana cherry\nbanana banana cherry")
def read_file(file_name):
"""Read a file and display its contents."""
with open(file_name, "r") as file:
content = file.read()
print("Contents of", file_name + ":", content)
return content
def count_lines_and_words(content):
"""Count the number of lines and find the word with the highest count."""
lines = content.split("\n")
line_count = len(lines)
word_count = {}
for line in lines:
words = line.split()
for word in words:
word_count[word] = word_count.get(word, 0) + 1
max_word = max(word_count, key=word_count.get)
return line_count, max_word
def create_and_display_combined_file(f1_content, f2_content):
"""Create and display a file which is a combination of f1 and f2."""
combined_content = f1_content + "\n" + f2_content
with open("f3.txt", "w") as f3:
f3.write(combined_content)
print("Contents of f3.txt:", combined_content)
# Main function to demonstrate file handling operations
def main():
# Create two new files f1.txt and f2.txt
create_files()
# Read and display the contents of f1.txt and f2.txt
content_f1 = read_file("f1.txt")
content_f2 = read_file("f2.txt")
# Count the number of lines and find the word with the highest count in each file
line_count_f1, max_word_f1 = count_lines_and_words(content_f1)
line_count_f2, max_word_f2 = count_lines_and_words(content_f2)
# Display the number of lines and the word with the highest count in each file
print("Number of lines in f1.txt:", line_count_f1)
print("Word with the highest count in f1.txt:", max_word_f1)
print("Number of lines in f2.txt:", line_count_f2)
print("Word with the highest count in f2.txt:", max_word_f2)
# Create and display the combined file f3.txt
create_and_display_combined_file(content_f1, content_f2)
if __name__ == "__main__":
main()
//
2. Write a program that reads words.txt and prints only the words with more than 20characters (not
counting white space).
def print_words_with_more_than_20_characters(file_name):
"""Read words from a file and print only the words with more than 20 characters."""
with open(file_name, "r") as file:
words = file.read().split()
long_words = [word for word in words if len(word.replace(" ", "")) > 20]
for word in long_words:
print(word)
# Main function to demonstrate printing words with more than 20 characters
def main():
file_name = "words.txt"
print("Words with more than 20 characters:")
print_words_with_more_than_20_characters(file_name)
if __name__ == "__main__":
main()
Editor is loading...
Leave a Comment