# Untitled

unknown
plain_text
a month ago
20 kB
4
Indexable
Never
```Q..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)

# Define the distance of the race in kilometers and the time taken in minutes
distance_km = 10
time_minutes = 43 + 30 / 60

# Convert distance from kilometers to miles
distance_miles = distance_km / 1.61

# Calculate average time per mile
time_per_mile = time_minutes / distance_miles

# Calculate average speed in miles per hour
speed_mph = distance_miles / (time_minutes / 60)

# Output the results
print("Average time per mile:", round(time_per_mile, 2), "minutes")
print("Average speed:", round(speed_mph, 2), "miles per hour")

Q..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.

# Define the distance of the race in kilometers and the time taken in minutes
distance_km = 10
time_minutes = 43 + 30 / 60

# Convert distance from kilometers to miles
distance_miles = distance_km / 1.61

# Calculate average time per mile
time_per_mile = time_minutes / distance_miles

# Calculate average speed in miles per hour
speed_mph = distance_miles / (time_minutes / 60)

# Output the results
print("Average time per mile:", round(time_per_mile, 2), "minutes")
print("Average speed:", round(speed_mph, 2), "miles per hour")

Q..Write a python program to generate first n Fibonacci number and factorial of n using function

# Function to generate first n Fibonacci numbers
def generate_fibonacci(n):
fibonacci_sequence = []
a, b = 0, 1
for _ in range(n):
fibonacci_sequence.append(a)
a, b = b, a + b
return fibonacci_sequence

# Function to calculate factorial of a number
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)

# Input value of n from the user
n = int(input("Enter the value of n: "))

# Generate first n Fibonacci numbers
fibonacci_numbers = generate_fibonacci(n)
print("First", n, "Fibonacci numbers:", fibonacci_numbers)

# Calculate factorial of n
fact_n = factorial(n)
print("Factorial of", n, ":", fact_n)

Q..Write a function to calculate the square of first n natural numbers.

def sum_of_squares(n):
"""
Calculate the sum of the squares of the first n natural numbers.

Parameters:
n (int): The number of natural numbers.

Returns:
int: The sum of the squares of the first n natural numbers.
"""
sum_squares = 0
for i in range(1, n + 1):
sum_squares += i * i
return sum_squares

# Example usage:
n = 5
result = sum_of_squares(n)
print("The sum of squares of the first", n, "natural numbers is:", result)

Q..Write a function that draws a grid like the following:
+ - - - -+ - - - -+
| | |
| | |
| | |
| | |
+ - - - -+ - - - -+
| | |
| | |
| | |
| | |
+ - - - -+ - - - -+

def draw_grid(rows, columns):
"""
Draw a grid with the specified number of rows and columns.

Parameters:
rows (int): The number of rows in the grid.
columns (int): The number of columns in the grid.
"""
for i in range(rows):
# Draw horizontal line
print("+", end=" ")
for j in range(columns):
print("- " * 4, end="")
print("+", end=" ")
print()

# Draw vertical lines
for _ in range(4):
print("|", end=" ")
for _ in range(columns):
print(" " * 7, end="")
print("|", end=" ")
print()

# Draw bottom horizontal line
print("+", end=" ")
for j in range(columns):
print("- " * 4, end="")
print("+", end=" ")
print()

# Example usage:
rows = 2
columns = 2
draw_grid(rows, columns)

Q..Write a function that takes any number of arguments and returns their sum.

def sum_of_numbers(*args):
"""
Calculate the sum of any number of arguments.

Parameters:
*args (float): Any number of arguments.

Returns:
float: The sum of the arguments.
"""
total = 0
for num in args:
total += num

# Example usage:
result = sum_of_numbers(1, 2, 3, 4, 5)
print("Sum of numbers:", result)

Q..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 Fermat's Last Theorem for the given parameters.

Parameters:
a (int): The value of 'a'.
b (int): The value of 'b'.
c (int): The value of 'c'.
n (int): The value of 'n'.

Returns:
str: A message indicating whether Fermat's Last Theorem holds or not.
"""
if n > 2 and (a ** n + b ** n == c ** n):
return "Holy smokes, Fermat was wrong!"
else:
return "No, that doesn't work."

# Example usage:
a = 3
b = 4
c = 5
n = 3
result = check_fermat(a, b, c, n)
print(result)

Q..Write a function that takes a string argument and returns true if it is a palindrome and False
otherwise.

def is_palindrome(string):
"""
Check if a string is a palindrome.

Parameters:
string (str): The input string.

Returns:
bool: True if the string is a palindrome, False otherwise.
"""
# Remove spaces and convert to lowercase for case-insensitive comparison
clean_string = string.replace(" ", "").lower()
# Check if the string is equal to its reverse
return clean_string == clean_string[::-1]

# Example usage:
input_string = "A man a plan a canal Panama"
result = is_palindrome(input_string)
print("Is the string a palindrome?", result)

Q..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_of_b(a, b):
"""
Check if a is a power of b.

Parameters:
a (int): The number to check.
b (int): The base number.

Returns:
bool: True if a is a power of b, False otherwise.
"""
if a < b:
return False
while a % b == 0:
a //= b
return a == 1

# Example usage:
num_a = 64
num_b = 4
result = is_power_of_b(num_a, num_b)
print("Is", num_a, "a power of", num_b, "?", result)

Q..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.

Parameters:
string (str): The input string.

Returns:
int: The length of the string.
"""
length = 0
for _ in string:
length += 1
return length

# Example usage:
input_string = "Hello, World!"
length = calculate_length(input_string)

# Print the length concatenated with the string aligned towards the extreme right
print(f"{length:>30} {input_string}")

Q..Write a recursive function to calculate the factorial of a given number

def factorial(n):
"""
Calculate the factorial of a given number using recursion.

Parameters:
n (int): The number to calculate the factorial for.

Returns:
int: The factorial of the given number.
"""
# Base case: factorial of 0 is 1
if n == 0:
return 1
# Recursive case: factorial of n is n * factorial of (n-1)
else:
return n * factorial(n - 1)

# Example usage:
number = 5
result = factorial(number)
print("Factorial of", number, ":", result)

Q..Write a function that takes a nested list of integers and adds up the elements from all the nested lists

def sum_nested_lists(nested_list):
"""
Recursively sum up all the elements in a nested list of integers.

Parameters:
nested_list (list): The nested list of integers.

Returns:
int: The sum of all the elements in the nested list.
"""
total = 0
for element in nested_list:
if isinstance(element, list):
total += sum_nested_lists(element)
else:
total += element

# Example usage:
nested_list = [[1, 2, 3], [4, 5], [6, [7, 8, 9]]]
result = sum_nested_lists(nested_list)
print("Sum of elements in the nested list:", result)

Q..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):
"""
Extracts all elements from a list except the first and last elements.

Parameters:
lst (list): The input list.

Returns:
list: A new list containing all but the first and last elements of the input list.
"""
return lst[1:-1]

# Example usage:
original_list = [1, 2, 3, 4]
result = middle(original_list)
print("Original list:", original_list)
print("Resulting list:", result)

Q..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 letter by a given amount.

Parameters:
letter (str): The letter to rotate.
n (int): The amount to rotate by.

Returns:
str: The rotated letter.
"""
if letter.isalpha():
# Determine the base for uppercase and lowercase letters
base = ord('A') if letter.isupper() else ord('a')
# Rotate the letter by adding n and handling wrapping around
rotated_ord = (ord(letter) - base + n) % 26 + base
# Convert the rotated ordinal back to a letter
return chr(rotated_ord)
else:
return letter

def rotate_string(string, n):
"""
Rotate each letter in a string by a given amount using ROT13 encryption.

Parameters:
string (str): The input string.
n (int): The amount to rotate by.

Returns:
str: The rotated string.
"""
rotated_string = ''
for char in string:
rotated_string += rotate_letter(char, n)
return rotated_string

# Example usage:
input_string = "Hello, World!"
rotated_string = rotate_string(input_string, 13)
print("Original string:", input_string)
print("Rotated string:", rotated_string)

Q..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.

Parameters:
char_list (list): The list of characters.

Returns:
str: The string created from the list of characters.
"""
return ''.join(char_list)

# Example usage:
char_list = ['H', 'e', 'l', 'l', 'o']
result_string = list_to_string(char_list)
print("List of characters:", char_list)
print("String created from the list:", result_string)

Q..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.

Parameters:
lst (list): The specified list.
item: The item to find the index of.

Returns:
int: The index of the item in the list.
"""
return lst.index(item)

# Example usage:
my_list = ['apple', 'banana', 'cherry', 'date']
item_to_find = 'banana'
index = find_index(my_list, item_to_find)
print("Index of", item_to_find, "in the list:", index)

Q..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']

"""
Add two lists index-wise and create a new list.

Parameters:
list1 (list): The first input list.
list2 (list): The second input list.

Returns:
list: The new list containing elements from both input lists.
"""
new_list = []
# Iterate over both lists simultaneously
for item1, item2 in zip(list1, list2):
new_list.append(item1 + item2)
# Append any remaining elements from the longer list
remaining_items = list1[len(list2):] + list2[len(list1):]
new_list.extend(remaining_items)
return new_list

# Example usage:
list1 = ["M", "na", "i", "Ke"]
list2 = ["y", "me", "s", "lly"]
result = add_lists(list1, list2)
print("Resulting list:", result)

Q..Write a program to turn every item of a list into its square

def square_list_items(lst):
"""
Square each item in a list.

Parameters:
lst (list): The input list.

Returns:
list: A new list where each item is squared.
"""
squared_list = [item ** 2 for item in lst]
return squared_list

# Example usage:
original_list = [1, 2, 3, 4, 5]
squared_list = square_list_items(original_list)
print("Original list:", original_list)
print("Squared list:", squared_list)

Q..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 to generate a list of concatenated strings.

Parameters:
list1 (list): The first input list.
list2 (list): The second input list.

Returns:
list: A new list containing concatenated strings.
"""
concatenated_list = [x + y for x in list1 for y in list2]
return concatenated_list

# Example usage:
list1 = ["Hello ", "take "]
list2 = ["Dear", "Sir"]
result = concatenate_lists(list1, list2)
print("Resulting list:", result)

Q..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.

Parameters:
lst (list): The input list of strings.

Returns:
list: A new list with empty strings removed.
"""
return list(filter(lambda x: x != "", lst))

# Example usage:
list1 = ["Mike", "", "Emma", "Kelly", "", "Brad"]
result = remove_empty_strings(list1)
print("Resulting list:", result)

Q..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 over both lists simultaneously and display items from list1 in original order
and items from list2 in reverse order.

Parameters:
list1 (list): The first input list.
list2 (list): The second input list.

Returns:
None
"""
for item1, item2 in zip(list1, reversed(list2)):
print(item1, item2)

# Example usage:
list1 = ["apple", "banana", "cherry", "date"]
list2 = ["zoo", "yellow", "x-ray", "wombat"]
iterate_lists(list1, list2)

Q..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.

Parameters:
list_of_tuples (list): The input list of tuples.

Returns:
dict: The dictionary created from the list of tuples.
"""
dictionary = dict(list_of_tuples)
return dictionary

# Example usage:
list_of_tuples = [("a", 1), ("b", 2), ("c", 3)]
result_dict = list_of_tuples_to_dict(list_of_tuples)
print("Dictionary:", result_dict)

Q..Write a program to
a. reverse a tuple.
b. Swap two tuples.

def reverse_tuple(input_tuple):
"""
Reverse a tuple.

Parameters:
input_tuple (tuple): The input tuple.

Returns:
tuple: The reversed tuple.
"""
reversed_list = list(input_tuple)
reversed_list.reverse()
return tuple(reversed_list)

def swap_tuples(tuple1, tuple2):
"""
Swap two tuples.

Parameters:
tuple1 (tuple): The first tuple.
tuple2 (tuple): The second tuple.

Returns:
tuple: The swapped tuple1.
tuple: The swapped tuple2.
"""
return tuple2, tuple1

# Example usage:
original_tuple = (1, 2, 3, 4, 5)
reversed_tuple = reverse_tuple(original_tuple)
print("Reversed tuple:", reversed_tuple)

tuple1 = (1, 2)
tuple2 = (3, 4)
swapped_tuple1, swapped_tuple2 = swap_tuples(tuple1, tuple2)
print("Swapped tuple1:", swapped_tuple1)
print("Swapped tuple2:", swapped_tuple2)

Q..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.

tuple1 = ("Orange", [10, 20, 30], (5, 15, 25))

# Accessing and printing the value 20 from the tuple
value_20 = tuple1[1][1]
print("Value 20 from the tuple:", value_20)

# Modifying the first item (20) of the list inside the tuple to 220
tuple1[1][1] = 220

# Printing the modified tuple
print("Modified tuple:", tuple1)

Q..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)
print(a) # should print 10
print(b) # should print 20
print(c) # should print 30
print(d) # should print 20

tuple1 = (10, 20, 30, 20)

# Unpack the tuple into four variables
a, b, c, d = tuple1

# Count the occurrence of 20
count_20 = tuple1.count(20)

# Output the variables and occurrence count
print("a:", a)  # should print 10
print("b:", b)  # should print 20
print("c:", c)  # should print 30
print("d:", d)  # should print 20

print("Count of occurrence of 20:", count_20)

Q..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]

sample_list = ["Blue", "Green", "Red"]
sample_set = {"Yellow", "Orange", "Black"}

# Update the set with elements from the list
sample_set.update(sample_list)

# Print the updated set
print("Updated set:", sample_set)

Q..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}.

set1 = {10, 20, 30, 40, 50}
set2 = {30, 40, 50, 60, 70}

# Set of identical items from both sets
identical_items = set1 & set2

# Set of unique items from both sets
unique_items = set1 | set2

# Print the results
print("Identical items from both sets:", identical_items)
print("Unique items from both sets:", unique_items)

Q..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}.

set1 = {10, 20, 30, 40, 50}
set2 = {30, 40, 50, 60, 70}

# Find the common elements between set1 and set2
common_elements = set1 & set2

# Update set1 to contain only the common elements
set1.intersection_update(set2)

# Print the updated set1
print("Updated set1:", set1)
```