(Sem Iii) (Aktu) Python Theory Examination 2023-24 Solution
(Sem Iii) (Aktu) Python Theory Examination 2023-24 Solution
PYTHON PROGRAMMING
Illustrate Unpacking tuples, mutable sequences, and string concatenation with examples
Unpacking Tuples
Tuple unpacking allows you to assign elements of a tuple to multiple variables in a single step.
# Tuple Unpacking
person = ("Alice", 25, "Engineer")
name, age, profession = person
Mutable Sequence
A mutable sequence allows modification after creation. Lists are a common example.
# Lists are mutable
fruits = ["apple", "banana", "cherry"]
# Modifying an element
fruits[1] = "blueberry"
print(fruits) # ['apple', 'blueberry', 'cherry']
String Concatenation
greeting = "Hello" + " " + "World"
print(greeting) # Hello World
String concatenation combines multiple strings into one.
1. Return a list of numbers starting from the last to second item of the list
L = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# 1. Return a list of numbers starting from the last to second item of the list
print(L[-1:0:-1]) # [9, 8, 7, 6, 5, 4, 3, 2]
2. Return a list that start from 3rd item to second last item.
L = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(L[2:-1]) # [3, 4, 5, 6, 7, 8]
3. Return a list that has only even position elements of list L to list M.
L = [1, 2, 3, 4, 5, 6, 7, 8, 9]
M = L[1::2]
print(M) # [2, 4, 6, 8]
4. Return a list that starts from the middle of the list L
L = [1, 2, 3, 4, 5, 6, 7, 8, 9]
mid_index = len(L) // 2
print(L[mid_index:]) # [5, 6, 7, 8, 9]
5. Return a list that reverses all the elements starting from element at index 0 to middle index only and
return the entire list.
L = [1, 2, 3, 4, 5, 6, 7, 8, 9]
mid_index = len(L) // 2
L[:mid_index] = L[:mid_index][::-1]
print(L) # [4, 3, 2, 1, 5, 6, 7, 8, 9]
6. Divide each element of the list by 2 and replace it with the remainder
L = [1, 2, 3, 4, 5, 6, 7, 8, 9]
L = [x % 2 for x in L]
print(L) # [0, 1, 0, 1, 1, 0, 1, 0, 1]
import math
def perfect_square(number):
if number < 0:
return -1 # Negative numbers can't be perfect squares
sqrt_num = math.isqrt(number) # Get the integer square root
return number if sqrt_num * sqrt_num == number else -1
# Example cases
print(perfect_square(1)) # 1
print(perfect_square(2)) # -1
print(perfect_square(4)) # 4
print(perfect_square(9)) # 9
print(perfect_square(10)) # -1
def sort_words_alphabetically(input_sequence):
# Split the input sequence into a list of words
words = input_sequence.split(',')
# Strip any leading or trailing whitespace from each word
words = [word.strip() for word in words]
# Sort the words alphabetically
words.sort()
# Join the sorted words into a comma-separated string
sorted_sequence = ', '.join(words)
return sorted_sequence
# Input from the user
input_sequence = input("Enter a comma-separated sequence of words: ")
# Sort and print the result
sorted_sequence = sort_words_alphabetically(input_sequence)
print("Sorted sequence:", sorted_sequence)
Your program should accept a sequence of comma separated passwords and will check them according to the
above criteria. Passwords that match the criteria are to be printed, each separated by a comma
def is_valid_password(password):
# Check length of password
if len(password) < 6 or len(password) > 12:
return False
# Flags to check criteria
has_lower = has_upper = has_digit = has_special = False
# Check each character in the password
for char in password:
if char.islower(): has_lower = True
elif char.isupper(): has_upper = True
elif char.isdigit(): has_digit = True
elif char in {'$', '#', '@'}: has_special = True
# Return True only if all criteria are met
return has_lower and has_upper and has_digit and has_special
# Input from the user
passwords_input = input("Enter comma-separated passwords: ")
password_list = passwords_input.split(',')
valid_passwords = [password for password in password_list if is_valid_password(password)]
print(','.join(valid_passwords))
Construct a function ret smaller(l) that returns smallest list from a nested list. If two lists have same length then
return the first list that is encountered.
For example:
ret smaller([ [ -2, -1, 0, 0.12, 1, 2], [3, 4, 5], [6 , 7, 8, 9, 10], [11, 12, 13, 14, 15]])
returns [3,4,5]
ret smaller([ [ -2, -1, 0, 0.12, 1, 2], [‘a’, ’b’, ’c’, ’d’, 3, 4, 5], [6 , 7, 8, 9, 10], [11, 12, 13, 14, 15]])
returns [6 , 7, 8, 9, 10]
def ret_smaller(l):
# Initialize the first list as the smallest
smallest = l[0]
# Loop through the rest of the lists
for sublist in l[1:]:
# If the current sublist is smaller in length, update the smallest
if len(sublist) < len(smallest):
smallest = sublist
return smallest
def filter_numbers(word):
# Return True if the word is not a number
return not word.isdigit()
def filter_vowel_starting_strings(word):
vowels = {'a', 'e', 'i', 'o', 'u'}
# Return True if the word starts with a vowel (case-insensitive)
return word and word[0].lower() in vowels
def filter_noun_containing_strings(word):
nouns = {'agra', 'ramesh', 'tomato', 'patna'}
# Return True if the word does not contain any of the specified nouns
(case-insensitive)
num_to_words = [
'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'
]
def number_to_text(number):
return " ".join([num_to_words[int(n)] for n in number])
def replace_numbers_with_text(text):
words = text.split()
for i, word in enumerate(words):
if word.isdigit(): # Check if the word is a number
words[i] = number_to_text(word)
return ' '.join(words)
def process_file(file_path):
try:
# Read the file
with open(file_path, 'r') as file:
content = file.read()
# Replace numbers with their text representation
updated_content = replace_numbers_with_text(content)
# Write the updated content back to the file
with open(file_path, 'w') as file:
file.write(updated_content)
print("File has been updated successfully.")
except Exception as e:
print(f"An error occurred: {e}")
# Example usage
file_path = 'example.txt' # Replace with your file path
process_file(file_path)
def extract_digit_words(input_file):
with open(input_file, 'r') as f:
# Read the content of the file
text = f.read()
# Split the text by whitespace to get words
words = text.split()
# Filter words that consist of digits only
digit_words = [word for word in words if word.isdigit()]
# Print the words that are composed of digits only
for word in digit_words:
print(word)
# Example usage
extract_digit_words('input.txt')
import csv
import matplotlib.pyplot as plt
# Function to read cities.csv, remove the last column, and plot the first two columns
def process_and_plot_csv(file_name):
# Initialize arrays to store the data
first_two_columns = []
last_column = []
# Read the CSV file
with open(file_name, 'r') as file:
reader = csv.reader(file)
header = next(reader) # Skip the header row
for row in reader:
# Save the first two columns to a list
first_two_columns.append([float(row[0]), float(row[1])])
# Save the last column to another array
last_column.append(row[-1]) # Last column in each row
# Separate the first two columns into x and y values
x_values = [row[0] for row in first_two_columns]
y_values = [row[1] for row in first_two_columns]
# Plot the first two columns
plt.scatter(x_values, y_values)
plt.title("Plot of First Two Columns")
plt.xlabel("First Column")
plt.ylabel("Second Column")
plt.show()
# Optionally, print the arrays
print("First two columns data:", first_two_columns)
print("Last column data:", last_column)
# Example usage
process_and_plot_csv('cities.csv')
List comprehension provides a syntactically elegant way to create and manipulate lists in Python. It allows you
to generate a new list by applying an expression to each item in an iterable (such as a list, range, or string).
squares = [x ** 2 for x in range(1, 6)]
print(squares)
This (/) operator performs standard division and returns the result as a float, even if the operands are integers.
result = 7 / 2
print(result) # Output: 3.5
This (//) operator performs division and returns the result as an integer (rounded down to the nearest whole
number).
result = 7 // 2
print(result) # Output: 3
def count(s):
for str in string.split():
s = "&".join(str)
return s
print(count("Python is fun to learn."))
In line no 3 we are trying to change the string contents, which is not possible in Python. In python string objects
are immutable.
Matplotlib is a powerful Python library widely used for creating static, animated, and interactive visualizations in
Python. Here are some key functions and features of Matplotlib:
1. Figure: The plt.figure() function creates a new figure, which is like a blank canvas where you can plot
your data.
2. Axes: Axes are the actual plots within the figure. You can create axes using plt.subplot() or plt.subplots()
functions.
3. Plotting: Matplotlib provides various functions to create different types of plots like line plots (plt.plot()),
scatter plots (plt.scatter()), bar plots (plt.bar()), histogram (plt.hist()), pie charts (plt.pie()), etc.
The Pandas library in Python provides high-level data structures and functions designed to make working with
structured or tabular data fast, easy