0% found this document useful (0 votes)
46 views16 pages

(Sem Iii) (Aktu) Python Theory Examination 2023-24 Solution

The document provides a comprehensive overview of Python programming concepts, including tuple unpacking, mutable sequences, string concatenation, list slicing, and functions. It also covers data visualization using matplotlib, password validation, and text filtering techniques. Additionally, it includes examples of file processing and manipulation in Python.

Uploaded by

rishabhyadav7923
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views16 pages

(Sem Iii) (Aktu) Python Theory Examination 2023-24 Solution

The document provides a comprehensive overview of Python programming concepts, including tuple unpacking, mutable sequences, string concatenation, list slicing, and functions. It also covers data visualization using matplotlib, password validation, and text filtering techniques. Additionally, it includes examples of file processing and manipulation in Python.

Uploaded by

rishabhyadav7923
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

(SEM III) THEORY EXAMINATION 2023-24

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.

Made with 🍀 @rishabh.real


Illustrate different list slicing constructs for the following operations on the following 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
2. Return a list that start from 3rd item to second last item.
3. Return a list that has only even position elements of list L to list M.
4. Return a list that starts from the middle of the list L
5. Return a list that reverses all the elements starting from element at index 0 to middle index only and return
the entire list.

Divide each element of the list by 2 and replace it with the remainder

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]

Made with 🍀 @rishabh.real


Construct a function perfect_square(number) that returns a number if it is a perfect square otherwise it returns
-1. ​

For example: ​
perfect_square(1) returns 1 ​
perfect_square (2) returns -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

Made with 🍀 @rishabh.real


Construct a plot for following dataset using matplotlib :​

import matplotlib.pyplot as plt​


import numpy as np​

# Dataset​
foods = ['Meat', 'Banana', 'Avocados', 'Sweet Potatoes', 'Spinach', 'Watermelon',
'Coconut Water', 'Beans', 'Legumes', 'Tomato']​
calories = [250, 130, 140, 120, 20, 20, 10, 50, 40, 19]​
potassium = [40, 55, 20, 30, 40, 32, 10, 26, 25, 20]​
fat = [8, 5, 3, 6, 1, 1.5, 0, 2, 1.5, 2.5]​

# Set up the figure and axis​
fig, ax = plt.subplots(figsize=(12, 6))​

# Bar width​
bar_width = 0.2​
index = np.arange(len(foods))​

# Plotting the bars​
bar1 = ax.bar(index - bar_width, calories, bar_width, label='Calories', color='skyblue')​
bar2 = ax.bar(index, potassium, bar_width, label='Potassium', color='lightgreen')​
bar3 = ax.bar(index + bar_width, fat, bar_width, label='Fat', color='salmon')​

# Adding labels and title​
ax.set_xlabel('Food Items')​
ax.set_ylabel('Amount')​
ax.set_title('Nutritional Content of Foods')​
ax.set_xticks(index)​
ax.set_xticklabels(foods, rotation=45, ha='right')​
ax.legend()​

# Display the plot​
plt.tight_layout()​
plt.show()

Made with 🍀 @rishabh.real


Determine a python function removenth(s,n) that takes an input a string and an integer n>=0 and removes a
character at index n. If n is beyond the length of s, then whole s is returned. ​

For example:
removenth(“MANGO”,1) returns MNGO
removenth(“MANGO”,3) returns MANO

def removenth(s, n):​


# Check if n is within the bounds of the string​
if n >= 0 and n < len(s):​
# Remove the character at index n​
return s[:n] + s[n+1:]​
else:​
# Return the original string if n is out of bounds​
return s​

# Example usage​
print(removenth("MANGO", 1)) # Output: MNGO​
print(removenth("MANGO", 3)) # Output: MANO​
print(removenth("MANGO", 10)) # Output: MANGO (n is out of bounds)

Made with 🍀 @rishabh.real


Construct a program that accepts a comma separated sequence of words as input and prints the words in a
comma-separated sequence after sorting them alphabetically.​

Suppose the following input is supplied to the program:​
without, hello, bag, world​

Then, the output should be:​
bag, hello, without, world

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)

Made with 🍀 @rishabh.real


A website requires the users to input username and password to register.​
Construct a program to check the validity of password input by users. ​
Following are the criteria for checking the password:
1. At least 1 letter between [a-z]
2. At least 1 number between [0-9]
3. At least 1 letter between [A-Z]
4. At least 1 character from [$#@]
5. Minimum length of transaction password: 6
6. Maximum length of transaction password: 12

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))

Made with 🍀 @rishabh.real


Explore the working of while, and for loop with examples.

Already answered in 2022-23 paper

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

Construct following filters:


1. Filter all the numbers
2. Filter all the strings starting with a vowel
3. Filter all the strings that contains any of the following noun: Agra, Ramesh, Tomato, Patna.

Create a program that implements these filters to clean the text

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)​

Made with 🍀 @rishabh.real


return not any(noun in word.lower() for noun in nouns)​

def clean_text(text):​
# Split the text into words​
words = text.split()​

# Apply filters using the filter function​
words = list(filter(filter_numbers, words)) # Filter numbers​
words = list(filter(filter_vowel_starting_strings, words)) # Filter strings starting
with vowels​
words = list(filter(filter_noun_containing_strings, words)) # Filter strings
containing nouns​

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

# Example usage​
text = "123 Agra is a city in India. Ramesh loves Tomato 456 and Patna is a capital city.
Apple is a fruit."​
cleaned_text = clean_text(text)​
print("Cleaned Text:", cleaned_text)

Made with 🍀 @rishabh.real


Change all the numbers in the file to text. Construct a program for the same. ​

Example: Given 2 integer numbers, return their product only if the product is equal to or lower than 10. ​
And the result should be: Given two integer numbers, return their product only if the product is equal to or lower
than one zero

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)

Made with 🍀 @rishabh.real


Construct a program which accepts a sequence of words separated by whitespace as file input. Print the words
composed of digits only.

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')

Made with 🍀 @rishabh.real


Construct a program to read cities.csv dataset, remove last column and save it in an array. Save the last
column to another array. Plot the first two columns.

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')​

Made with 🍀 @rishabh.real


import tkinter as tk​

def click(num):​
entry.insert(tk.END, num)​

def clear():​
entry.delete(0, tk.END)​

def equal():​
try:​
result = eval(entry.get())​
entry.delete(0, tk.END)​
entry.insert(0, str(result))​
except:​
entry.delete(0, tk.END)​
entry.insert(0, "Error")​

root = tk.Tk()​
root.title("Calculator")​

entry = tk.Entry(root, width=25, borderwidth=5)​
entry.grid(row=0, column=0, columnspan=4)​

buttons = [​
('7', 1, 0), ('8', 1, 1), ('9', 1, 2), ('/', 1, 3),​
('4', 2, 0), ('5', 2, 1), ('6', 2, 2), ('*', 2, 3),​
('1', 3, 0), ('2', 3, 1), ('3', 3, 2), ('-', 3, 3),​
('0', 4, 0), ('C', 4, 1), ('=', 4, 2), ('+', 4, 3)​
]​

Made with 🍀 @rishabh.real



for (text, row, col) in buttons:​
if text == 'C':​
btn = tk.Button(root, text=text, padx=20, pady=20, command=clear)​
elif text == '=':​
btn = tk.Button(root, text=text, padx=20, pady=20, command=equal)​
else:​
btn = tk.Button(root, text=text, padx=20, pady=20, command=lambda t=text:
click(t))​
btn.grid(row=row, column=col)​

root.mainloop()

Made with 🍀 @rishabh.real


SHORT ANSWERS

Describe the concept of list comprehension with a suitable example 2

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)

Differentiate between / and // operator with an example

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

Compute the output of the following python code:

def count(s):​
for str in string.split():​
s = "&".join(str)​
return s​

print(count("Python is fun to learn."))

Syntax Error, There is no definition of string inside the count() function. ​



But if we consider that statement like “string”.split() then output will be s&t&r&i&n&g

Explain why the program generates an error. ​


x = ['12', 'hello', 456]​
x[0] *= 3 ​
x[1][1]='bye'

In line no 3 we are trying to change the string contents, which is not possible in Python. In python string objects
are immutable.

Made with 🍀 @rishabh.real


How to use the functions defined in library.py in main.py

Describe about different functions of matplotlib and pandas.

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

Pandas offers a rich set of functions for data manipulation, including:


-​ merging and joining datasets (merge(), concat())
-​ reshaping data (pivot_table(), stack(), unstack())
-​ sorting data (sort_values(), sort_index())
-​ dealing with missing data (dropna(), fillna()).

Made with 🍀 @rishabh.real

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy