SolutionOfPythonQS 23-24
SolutionOfPythonQS 23-24
Example:
Example:
Output:
Example:
• 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:
• 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.
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:
str1 = "Hello"
str2 = "World"
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.
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.
Explanation:
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:
Divide each element of the list by 2 and replace it with the remainder.
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:
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:
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:
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.
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.
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.
Explanation:
If Statement Example:
Explanation:
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]])
Solution:
1. Function Definition:
We define a function ret_smaller that takes one argument lists, which is a list of lists.
We initialize smallest_list to be the first list in lists. This is our starting point for
comparison.
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.
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.
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).
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').
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:
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: