0% found this document useful (0 votes)
7 views

SolutionOfPythonQS 23-24

The document covers various Python programming concepts including list comprehension, operators, functions, and libraries like matplotlib and pandas. It provides examples and explanations for topics such as tuple unpacking, mutable sequences, string concatenation, and error handling. Additionally, it includes tasks related to file manipulation, data visualization, and user input validation.

Uploaded by

aryamann khare
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

SolutionOfPythonQS 23-24

The document covers various Python programming concepts including list comprehension, operators, functions, and libraries like matplotlib and pandas. It provides examples and explanations for topics such as tuple unpacking, mutable sequences, string concatenation, and error handling. Additionally, it includes tasks related to file manipulation, data visualization, and user input validation.

Uploaded by

aryamann khare
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

SECTION A

Q1.a. Describe the concept of list comprehension with a suitable example.


Answer: List comprehension is a concise way to create lists in Python. It consists of brackets
containing an expression followed by a for clause, then zero or more for or if clauses. The
expressions can be anything, meaning you can put all kinds of objects in lists.

Example:

Q1.b. Differentiate between / and // operator with an example.


Answer:

• / is the division operator that performs floating-point division.


• // is the floor division operator that performs division and then rounds down to the
nearest integer.

Example:

Q1.c. Compute the output of the following Python code:


Answer: The code joins each character in the words of the string with '&'.

Output:

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


Answer: To use functions from library.py in main.py, you need to import the module.

Example:

Q1.e. Describe the difference between linspace and arange.


Answer:

• linspace: Generates numbers evenly spaced over a specified interval. It includes the
endpoint.
• arange: Generates numbers in a specified range with a specified step, and does not
necessarily include the endpoint.

Example:

Q1.f. Explain why the program generates an error:


Answer: The error is generated because x[1] is a string and strings in Python are immutable, meaning
you cannot change their characters directly. The statement x[1][1] = 'bye' tries to assign a new
value to a character in the string, which is not allowed.

Q1.g. Describe about different functions of matplotlib and pandas.


Answer:

• Matplotlib: It is a plotting library used for creating static, animated, and interactive
visualizations in Python.
o plot(): To plot 2D data.
o scatter(): To create a scatter plot.
o hist(): To create a histogram.
o bar(): To create a bar chart.
o show(): To display the plot.
• Pandas: It is a library used for data manipulation and analysis.
o read_csv(): To read a CSV file into a DataFrame.
o head(): To return the first n rows of a DataFrame.
o describe(): To generate descriptive statistics.
o dropna(): To remove missing values.
o merge(): To merge DataFrames.

SECTION B

Q2.a. Illustrate Unpacking tuples, mutable sequences, and string concatenation with
examples.
Answer:

Unpacking Tuples:

Tuple unpacking in Python allows you to assign the elements of a tuple to multiple variables in a single
line of code. This is a powerful and convenient feature of the language.

Mutable Sequences:
Mutable sequences in Python are data structures whose contents can be changed after creation.

Key properties of mutable sequences:

• Can be modified in-place


• Support operations like append, extend, insert, remove
• Changes to the sequence affect all references to it

This is in contrast to immutable sequences like tuples and strings, which cannot be changed after
creation.

String Concatenation:

String concatenation in Python refers to combining two or more strings into a single string. Here are
some common methods:

1.Using the + operator:

str1 = "Hello"

str2 = "World"

result = str1 + " " + str2

print(result) # Output: Hello World

2. Using the join() method:

words = ["Python", "is", "awesome"]

sentence = " ".join(words)

print(sentence) # Output: Python is awesome

3. String multiplication for repetition:

repeat = "Na" * 4 + " Batman!"

print(repeat) # Output: NaNaNaNa Batman!


Q2.b. Illustrate different list slicing constructs for the following operations on the list:

Answer : let L = [1, 2, 3, 4, 5, 6, 7, 8, 9]

1. Return a list of numbers starting from the last to the second item of the list.

To slice a list from the last element to the second item, you can use negative indexing and
slicing:

Explanation:

• L[-1:0:-1] starts from the last element (index -1) and slices backwards to the second
item (index 1), excluding the first item.

2. Return a list that starts from the 3rd item to the second last item.

To slice from the 3rd item to the second last item:

Explanation:

• L[2:-1] starts from the 3rd item (index 2) and goes up to but does not include the second
last item (index -1).

3. Return a list that has only even position elements of list L to list M.

To get the even position elements (0-based index) from the list:

Explanation:
• L[1::2] starts from the second element (index 1) and takes every second element from
there, effectively capturing the elements at even positions in 0-based indexing.

4. Return a list that starts from the middle of the list L.

To slice from the middle of the list:

Explanation:

• mid_index = len(L) // 2 calculates the middle index of the list.


• L[mid_index:] slices the list from the middle index to the end.

5. Return a list that reverses all the elements starting from the middle index only
and returns the entire list.

To reverse the elements starting from the middle index and return the entire list:

Explanation:

• mid_index = len(L) // 2 calculates the middle index of the list.


• L[mid_index:][::-1] reverses the sublist from the middle index to the end.
• L[:mid_index] + L[mid_index:][::-1] concatenates the first half (up to the middle)
with the reversed second half.

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

Explanation: The list comprehension [x % 2 for x in L] iterates through each element in L,


divides it by 2, and stores the remainder in the new list.
Q2.c. Construct a function perfect_square(number) that returns a number if it is a perfect
square otherwise it returns -1.
Answer :

To construct a function perfect_square(number) that checks if a number is a perfect square


and returns the number if it is, or -1 if it is not, you can use the following approach. The idea is
to calculate the integer square root of the number and check if squaring this root gives back the
original number.

Explanation:

• Import math module: The math module provides access to the mathematical functions
defined by the C standard.
• Calculate the integer square root: The math.isqrt(number) function returns the
integer part of the square root of the given number. For example, math.isqrt(10)
returns 3.
• Check if the number is a perfect square: If the square of the integer square root equals
the original number (root * root == number), then the number is a perfect square, and
the function returns the number itself. Otherwise, it returns -1.

Example Usage:

• perfect_square(4) returns 4 because 22=42^2 = 422=4.


• perfect_square(10) returns -1 because 10 is not a perfect square.
• perfect_square(16) returns 16 because 42=164^2 = 1642=16.
Q2.d. Construct a program to change the contents of the file by reversing each character
separated by comma.

To construct a program that changes the contents of a file by reversing each character in the file
separated by commas, we can follow these steps:

1. Read the contents of the file.


2. Split the contents by commas to get individual elements.
3. Reverse each element.
4. Join the reversed elements back with commas.
5. Write the modified contents back to the file.

Q2.e. Construct a plot for following dataset using matplotlib: using this data:
To construct a plot using the provided dataset, we can utilize the matplotlib library in Python.
We'll plot the data for Calories, Potassium, and Fat for each food item. Here’s the step-by-step
code to achieve this:

1. Read the data.


2. Organize the data into lists.
3. Use matplotlib to create the plots.
Q3.a. Determine a Python function removeNth(s, n) that takes as input a string s
and an integer n >= 0 and removes a character at index n. If n is beyond the
length of s, then the whole string s is returned.

Answer :

Explanation:

• The function removeNth takes two arguments: s (a string) and n (an integer).
• Condition Check: if n < 0 or n >= len(s): This checks if n is out of the valid range (i.e.,
less than 0 or greater than or equal to the length of the string). If n is out of bounds, the function
returns the original string s.
• String Slicing:
o s[:n] gives the substring from the start of the string to the character before the n-th
character.
o s[n+1:] gives the substring from the character after the n-th character to the end of
the string.
o By concatenating these two slices, the character at the n-th index is removed.

Q3.b. 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.

Answer:

Explanation:

• Input Handling: input_string.split(',') splits the input string into a list of words using
the comma as a delimiter.
• Sorting: words.sort() sorts the list of words alphabetically.
• Output Formatting: ','.join(words) joins the sorted list of words into a single string,
separated by commas.
• The function returns the alphabetically sorted comma-separated sequence.

Q4.a. Construct a program to check the validity of password input by users


based on given criteria.
Answer:

Explanation:

• Regex Imports: import re imports the regular expressions library, which allows for advanced
string searching and matching.
• Length Check: if (len(password) < 6 or len(password) > 12): Ensures the
password is between 6 and 12 characters long.
• Lowercase Letter Check: if not re.search(r'[a-z]', password): Checks for at least
one lowercase letter.
• Uppercase Letter Check: if not re.search(r'[A-Z]', password): Checks for at least
one uppercase letter.
• Digit Check: if not re.search(r'\d', password): Checks for at least one digit.
• Special Character Check: if not re.search(r'[@#$]', password): Checks for at least
one special character among @, #, or $.
• The function returns True if all criteria are met; otherwise, it returns False.
• List Comprehension: Filters and collects valid passwords from the input string into a list.

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

While Loop Example:


Explanation:

• Initialization: i = 0 initializes the variable i to 0.


• Condition Check: while i < 5 checks if i is less than 5.
• Loop Body: print(i) prints the current value of i.
• Increment: i += 1 increases the value of i by 1 after each iteration.
• The loop repeats until i is no longer less than 5.

For Loop Example:

Explanation:

• Range Generation: range(5) generates a sequence of numbers from 0 to 4.


• Iteration: for i in range(5) iterates over each number in the generated sequence.
• Loop Body: print(i) prints the current value of i.

If Statement Example:

Explanation:

• Initialization: num = 10 initializes the variable num to 10.


• Condition Checks:
o if num > 5: Checks if num is greater than 5. If true, prints "Number is greater than 5".
o elif num == 5: If the first condition is false, checks if num is equal to 5. If true, prints
"Number is 5".
o else: If all previous conditions are false, prints "Number is less than 5".

Q5.a. Construct a function ret_smaller(l) that returns the smallest list from a nested list.
If two lists have the same length, then return the first list that is encountered.

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]

Solution:

1. Function Definition:

We define a function ret_smaller that takes one argument lists, which is a list of lists.

2. Initialize the Smallest List:

We initialize smallest_list to be the first list in lists. This is our starting point for
comparison.

3. Iterate through the Lists:

We iterate over each list lst in lists. If the length of lst is smaller than the length of
smallest_list, we update smallest_list to be lst.

4. Return the Smallest List:

After checking all the lists, we return the smallest_list.

Q5.b. Construct the following filters:

1. Filter all the numbers


2. Filter all the strings starting with a vowel
3. Filter all the strings that contain any of the following nouns: Agra, Ramesh, Tomato,
Patna.

Create a program that implements these filters to clean the text.

Solution:

1. Filter Numbers:

We define a function filter_numbers that takes a list data and returns a list of items that
are either integers or floats.

2. Filter Strings Starting with a Vowel:

We define a function filter_vowel_strings that takes a list data and returns a list of
strings that start with a vowel (both uppercase and lowercase vowels are considered).

3. Filter Specific Strings:

We define a function filter_specific_strings that takes a list data and returns a list
of strings that contain any of the specific nouns ('Agra', 'Ramesh', 'Tomato', 'Patna').

4. Test Data and Applying Filters:


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

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

Solution:

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

Solution:

1. Import Required Libraries:

2. Process CSV File:


Explanation:

• We define a function process_csv that takes a file path file_path.


• We use pd.read_csv to read the CSV file into a DataFrame df.
• We extract the last column of df into an array last_column.
• We remove the last column from df and save the remaining data back to df.
• We extract the first two columns of df into first_two_columns.
• We use plt.scatter to plot the first two columns.
• We return the data without the last column and the last column itself.

Q7.b. Design a calculator with the following buttons and functionalities like addition,
subtraction, multiplication, division and clear.
The calc function manages the calculator's operations based on the button pressed. It supports:

• Evaluating expressions (= button).


• Clearing the input (c button).
• Deleting the last character (<- button).
• Inserting the mathematical constant eee (e button).
• Calculating percentages (% button).
• Adding numbers and operators to the current input.

By using event.widget.cget('text'), the function dynamically handles various button


presses, making the calculator interactive and functional.

You might also like