Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Answer 1

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 12

ANSWER 1

ANSWER2
# Accept values from user in a tuple
user_tuple = tuple(input("Enter values for the tuple (comma-separated): ").split(","))

# Add a tuple to it
new_tuple = user_tuple + (10, 20, 30)

# Display elements of the tuple


print("Elements of the tuple:")
for item in new_tuple:
print(item)

# Display maximum and minimum values


print("Maximum value:", max(new_tuple))
print("Minimum value:", min(new_tuple))

ANS3

# Input values for two tuples


tuple1 = tuple(input("Enter values for the first tuple (comma-separated): ").split(","))
tuple2 = tuple(input("Enter values for the second tuple (comma-separated): ").split(","))

# Print the original tuples


print("Original Tuples:")
print("Tuple 1:", tuple1)
print("Tuple 2:", tuple2)

# Interchange the tuples


tuple1, tuple2 = tuple2, tuple1

# Compare the tuples


if tuple1 == tuple2:
print("The tuples are equal.")
else:
print("The tuples are not equal.")

ANS4

# Input 'n' classes and names of their class teachers


n = int(input("Enter the number of classes: "))
class_dict = {}
for i in range(n):
class_name = input("Enter the class name: ")
teacher_name = input("Enter the name of the class teacher: ")
class_dict[class_name] = teacher_name

# Display the dictionary


print("Class-Teacher Dictionary:")
for class_name, teacher_name in class_dict.items():
print(f"Class: {class_name}, Teacher: {teacher_name}")

# Accept a particular class from the user and display the class teacher
selected_class = input("Enter the class for which you want to know the teacher: ")
if selected_class in class_dict:
print(f"Class: {selected_class}, Teacher: {class_dict[selected_class]}")
else:
print("Class not found in the dictionary.")

ANS5

# Store student names and their percentage in a dictionary


student_dict = {}
n = int(input("Enter the number of students: "))
for i in range(n):
name = input("Enter student name: ")
percentage = float(input("Enter student percentage: "))
student_dict[name] = percentage

# Delete a particular student name from the dictionary


delete_name = input("Enter the student name to delete: ")
if delete_name in student_dict:
del student_dict[delete_name]
print(f"Student '{delete_name}' deleted from the dictionary.")
else:
print("Student name not found in the dictionary.")

# Display the dictionary after deletion


print("Updated Dictionary:")
for name, percentage in student_dict.items():
print(f"Student: {name}, Percentage: {percentage}")

ANS6

def display_customer_details(customers):
print("Customer Details:")
print("{:<10} {:<15} {:<10} {:<15}".format("Name", "Items Bought", "Cost", "Phone Number"))
for name, details in customers.items():
items_bought = details["items_bought"]
cost = details["cost"]
phone_number = details["phone_number"]
print("{:<10} {:<15} {:<10} {:<15}".format(name, items_bought, cost, phone_number))

# Input the number of customers


n = int(input("Enter the number of customers: "))

# Create an empty dictionary to store the customer details


customers = {}

# Input details for each customer and store them in the dictionary
for i in range(n):
print(f"\nEnter details for customer {i+1}:")
name = input("Name: ")
items_bought = input("Items Bought: ")
cost = float(input("Cost: "))
phone_number = input("Phone Number: ")

# Store the details in the dictionary


customers[name] = {
"items_bought": items_bought,
"cost": cost,
"phone_number": phone_number
}

# Display the customer details in a tabular form


display_customer_details(customers)
ANS7

def capitalize_first_last_letters(string):
words = string.split() # Split the string into individual words
capitalized_words = []

for word in words:


if len(word) > 1:
capitalized_word = word[0].upper() + word[1:-1] + word[-1].upper()
else:
capitalized_word = word.upper()
capitalized_words.append(capitalized_word)

return ' '.join(capitalized_words) # Join the words back into a string

# Input the string


string = input("Enter a string: ")

# Capitalize the first and last letters of each word in the string
result = capitalize_first_last_letters(string)

# Display the result


print("Modified string:", result)

In this program, the capitalize_first_last_letters() function takes a string as


input. It splits the string into individual words using the split() method, and then
iterates over each word. For each word, it checks if the length is greater than 1. If it is,
it capitalizes the first letter, leaves the middle letters as they are ( word[1:-1]), and
capitalizes the last letter. If the word has only one character, it simply capitalizes it.
The modified words are stored in a list.

Finally, the modified words are joined back into a string using the join() method
with a space as the separator. The resulting string is then displayed as the modified
string.

ANS8

def remove_duplicates(string):
# Create an empty set to store unique characters
unique_chars = set()

# Create an empty string to store the result


result = ""

for char in string:


# Check if the character is already in the set of unique characters
if char not in unique_chars:
# Add the character to the set and append it to the result string
unique_chars.add(char)
result += char

return result

# Input the string


string = input("Enter a string: ")

# Remove duplicate characters from the string


result = remove_duplicates(string)

# Display the result


print("String with duplicate characters removed:", result)

In this program, the remove_duplicates() function takes a string as input. It uses a


set data structure, unique_chars, to store unique characters encountered in the
string. It also creates an empty string, result, to store the final result.

The program iterates over each character in the input string. For each character, it
checks if the character is already in the unique_chars set. If the character is not in
the set, it means it is a unique character, so it adds the character to the set and
appends it to the result string.

After processing all characters in the input string, the function returns the result
string, which contains the input string with duplicate characters removed.

Finally, the modified string is displayed as the output.

ANS9

def compute_digit_sum(string):
digit_sum = 0

for char in string:


if char.isdigit():
digit_sum += int(char)

return digit_sum

# Input the string


string = input("Enter a string: ")

# Compute the sum of digits in the string


sum_of_digits = compute_digit_sum(string)

# Display the result


print("Sum of digits in the string:", sum_of_digits)
In this program, the compute_digit_sum() function takes a string as input. It
initializes a variable digit_sum to keep track of the sum of digits, starting with a
value of 0.

The program then iterates over each character in the input string. For each character,
it checks if the character is a digit using the isdigit() method. If the character is a
digit, it converts it to an integer using the int() function and adds it to the
digit_sum.

After processing all characters in the string, the function returns the digit_sum,
which represents the sum of digits in the given string.

Finally, the sum of digits is displayed as the output.

ANS10

from collections import Counter

def find_second_most_repeated_word(string):
# Split the string into words
words = string.split()

# Count the frequency of each word using Counter


word_counts = Counter(words)

# Find the second most common word


second_most_common_word = word_counts.most_common(2)[1][0]

return second_most_common_word

# Input the string


string = input("Enter a string: ")

# Find the second most repeated word


second_most_repeated_word = find_second_most_repeated_word(string)

# Display the result


print("Second most repeated word:", second_most_repeated_word)

In this program, we utilize the Counter class from the collections module, which
provides a convenient way to count the frequency of elements in a list or any
iterable.

The find_second_most_repeated_word() function takes a string as input. It first


splits the string into individual words using the split() method. Then, it uses the
Counter class to count the frequency of each word in the words list.
Next, we retrieve the two most common words using the most_common() method of
the Counter object. Since the method returns a list of tuples in descending order of
frequency, we extract the second tuple and access its first element, which
corresponds to the second most repeated word.

Finally, the program displays the second most repeated word as the output

ANS11

def exchange_first_and_last_chars(string):
# Check if the string has at least two characters
if len(string) >= 2:
# Swap the first and last characters using slicing
new_string = string[-1] + string[1:-1] + string[0]
return new_string
else:
# Return the string as is if it has less than two characters
return string

# Input the string


string = input("Enter a string: ")

# Change the string by exchanging first and last characters


new_string = exchange_first_and_last_chars(string)

# Display the result


print("New string with first and last characters exchanged:", new_string)

In this program, the exchange_first_and_last_chars() function takes a string as


input. It first checks if the string has at least two characters using the len() function.
If the condition is met, it swaps the first and last characters by creating a new string
using slicing. The first character is concatenated with the sliced portion of the string
excluding the first and last characters, followed by the last character.

If the string has less than two characters, the function returns the string as it is, since
there are no characters to swap.

Finally, the program displays the new string with the first and last characters
exchanged as the output.

ANS12

def multiply_list_items(lst):
result = 1

for item in lst:


result *= item
return result

# Input the list


lst = []
n = int(input("Enter the number of elements in the list: "))

for i in range(n):
element = int(input("Enter element {}: ".format(i+1)))
lst.append(element)

# Multiply all the items in the list


product = multiply_list_items(lst)

# Display the result


print("Product of all the items in the list:", product)

In this program, the multiply_list_items() function takes a list as input. It


initializes a variable result to 1, which will store the cumulative product of the items.

The program prompts the user to enter the number of elements in the list and then
asks for each element. The elements are appended to the list lst.

Next, the program calls the multiply_list_items() function, passing the list lst.
The function iterates over each item in the list and multiplies it with the result
variable, updating the result with each iteration.

After processing all the items, the function returns the final product stored in result.

Finally, the program displays the product of all the items in the list as the output.

ANS13

def get_smallest_number(lst):
if len(lst) == 0:
return None

smallest = lst[0]

for num in lst:


if num < smallest:
smallest = num

return smallest

# Input the list


lst = []
n = int(input("Enter the number of elements in the list: "))
for i in range(n):
element = int(input("Enter element {}: ".format(i+1)))
lst.append(element)

# Get the smallest number from the list


smallest_number = get_smallest_number(lst)

# Display the result


if smallest_number is None:
print("The list is empty.")
else:
print("The smallest number in the list is:", smallest_number)

In this program, the get_smallest_number() function takes a list as input. It first


checks if the list is empty. If it is, the function returns None to indicate that there is no
smallest number.

If the list is not empty, the function initializes the variable smallest with the first
number in the list. It then iterates over each number in the list and compares it with
the current smallest number. If a smaller number is found, the smallest variable is
updated.

After processing all the numbers in the list, the function returns the smallest number.

The program prompts the user to enter the number of elements in the list and then
asks for each element. The elements are appended to the list lst.

Finally, the program calls the get_smallest_number() function, passing the list lst.
It displays the smallest number in the list as the output, or a message indicating that
the list is empty if applicable.

ANS14

def append_lists(list1, list2):


list1.extend(list2)
return list1

# Input the first list


list1 = []
n1 = int(input("Enter the number of elements in the first list: "))

for i in range(n1):
element = int(input("Enter element {}: ".format(i+1)))
list1.append(element)

# Input the second list


list2 = []
n2 = int(input("Enter the number of elements in the second list: "))

for i in range(n2):
element = int(input("Enter element {}: ".format(i+1)))
list2.append(element)

# Append the second list to the first list


appended_list = append_lists(list1, list2)

# Display the result


print("Resultant list after appending the second list to the first list:", appended_list)

In this program, the append_lists() function takes two lists as input. It uses the
extend() method to append the second list to the first list. The modified first list is
then returned.

The program prompts the user to enter the number of elements in the first list,
followed by each element. The elements are appended to the list list1.

Similarly, the program asks for the number of elements in the second list and
prompts for each element, which are then appended to the list list2.

Next, the program calls the append_lists() function, passing the two lists list1
and list2. It assigns the returned appended list to the variable appended_list.

Finally, the program displays the resultant list after appending the second list to the
first list as the output.

ANS15

def generate_squared_list():
squared_list = [i**2 for i in range(1, 31)]
first_five = squared_list[:5]
last_five = squared_list[-5:]
return first_five, last_five

# Generate the squared list


first_five_elements, last_five_elements = generate_squared_list()

# Display the result


print("First five elements:", first_five_elements)
print("Last five elements:", last_five_elements)

In this program, the generate_squared_list() function generates a list of the


squares of numbers between 1 and 30 using a list comprehension. It then slices the
first five elements using squared_list[:5] and the last five elements using
squared_list[-5:]. The function returns these two sliced lists.
The program calls the generate_squared_list() function and assigns the returned
first five elements to the variable first_five_elements and the returned last five
elements to the variable last_five_elements.

Finally, the program displays the first five elements and last five elements as the
output.

ANS16
def get_unique_values(input_list):
unique_values = list(set(input_list))
return unique_values

# Input the list


input_list = []
n = int(input("Enter the number of elements in the list: "))

for i in range(n):
element = input("Enter element {}: ".format(i+1))
input_list.append(element)

# Get unique values from the list


unique_values = get_unique_values(input_list)

# Display the result


print("Unique values:", unique_values)

In this program, the get_unique_values() function takes a list as input. It converts


the list to a set, which automatically removes duplicate values, and then converts the
set back to a list. The resulting list contains only unique values.

The program prompts the user to enter the number of elements in the list, followed
by each element. The elements are appended to the list input_list.

Next, the program calls the get_unique_values() function, passing the input_list
as an argument. It assigns the returned list of unique values to the variable
unique_values.

Finally, the program displays the unique values extracted from the list as the output.

ANS17

def convert_string_to_list(input_string):
char_list = list(input_string)
return char_list

# Input the string


input_string = input("Enter a string: ")
# Convert the string to a list
string_list = convert_string_to_list(input_string)

# Display the result


print("String converted to list:", string_list)

In this program, the convert_string_to_list() function takes a string as input. It


uses the list() function to convert the string into a list of characters. The resulting
list contains each character from the string as separate elements.

The program prompts the user to enter a string and assigns it to the variable
input_string.

Next, the program calls the convert_string_to_list() function, passing the


input_string as an argument. It assigns the returned list of characters to the
variable string_list.

Finally, the program displays the string converted to a list as the output. Each
character of the string will be represented as a separate element in the list.

You might also like