CH 6,7 Assignment Soln
CH 6,7 Assignment Soln
3- not possible
4. Given a string S = "CARPE DIEM". If n is length/2 (length is the length
of the given string), then what would the following return?
(a) S[: n]
(b) S[n :]
(c) S[n : n]
(d) S[1 : n]
(e) S[n : length - 1]
greet("Alice")
Output:
Hello, Alice
10)Given a list of numbers, how would you find the average, maximum,
and minimum values?
You can find the average, maximum, and minimum values in a list using
Python's built-in sum(), max(), and min() functions.
Example Code:
numbers = [10, 20, 30, 40, 50]
print("Average:", average)
print("Maximum:", maximum)
print("Minimum:", minimum)
Keywords Used:
• sum() → Adds all elements in the list.
• len() → Counts the total number of elements.
• max() → Finds the highest value.
• min() → Finds the lowest value.
10)You have a string containing a sentence. How would you reverse the
order of the words in the sentence? Hint: Use string methods like split(),
reverse(), and join() to manipulate the string.
You can reverse the order of words in a sentence using split(), reverse(),
and join() as follows:
Python Code:
sentence = "Hello world this is Python"
# Split the sentence into words
words = sentence.split()
print(reversed_sentence)
Output:
"Python is this world Hello"
Alternative (Using Slicing [::-1]):
reversed_sentence = " ".join(sentence.split()[::-1])
print(reversed_sentence)
Explanation of Keywords:
• split() → Splits the string into a list of words.
• reverse() → Reverses the list in place.
• [::-1] → An alternative way to reverse a list using slicing.
• join() → Combines the list of words back into a string.
11. Create a function that takes a string as input and returns a new
string with the following modifications:
1. Reverse the order of words.
2. Convert all characters to uppercase.
3. Remove all punctuation marks.
import string
def modify_string(input_string):
# 1. Reverse the order of words
words = input_string.split()
reversed_words = words[::-1]
return cleaned_string
# Example usage:
input_string = "Hello, world! This is Python."
result = modify_string(input_string)
print(result)
12. Check if a String is a Palindrome
# Example usage
input_string = "hello"
output_string = reverse_string(input_string)
print(output_string) # Output: "olleh"
15. Remove Duplicates from a String ● Problem: Write a function to
remove duplicate characters in a string. ● Example: Input:
"programming" → Output: "progamin"
16. Problem: Given a list of numbers, create a new list containing only
the even numbers using list comprehension.
17. Given a list of numbers, implement a function that sorts the list in
ascending order, removes all duplicate elements, inserts a new element
at a specific index, and then extends the list with another list.
#Algorithm [Steps/hints]:
1. Sort the list in ascending order.
2. Remove duplicate elements using a set and then convert it back to a
list.
3. Insert a new element at the specified index.
4. Extend the list by appending another list