0% found this document useful (0 votes)
54 views25 pages

Sol PYTHON PROG - III Sem Question Paper (2023-24) Odd

Best one

Uploaded by

Veer Kumar
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)
54 views25 pages

Sol PYTHON PROG - III Sem Question Paper (2023-24) Odd

Best one

Uploaded by

Veer Kumar
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/ 25

Subject Code: BCC-302

Roll No.

B. TECH.

(SEM III) THEORY EXAMINATION 2023-24

PYTHON PROGRAMMING

Time: 3 Hours M.MARKS: 70

Note:

1. Attempt all Sections. If require any missing data; then choose suitably.

SECTION -A

1. Attempt all questions in brief. 𝟐 × 𝟕 = 𝟏𝟒

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

Ans.

List Comprehension is very useful feature of Python. Using Comprehension


methods we can
 filter the elements from an existing list.
 perform various operations on list elements.
e.g.
lst=[23,45,67,45,21,23,45,8,9,34]
lst1=[]
lst2=[]
suppose we wish to create a list of elements having value greater than 40 in lst
lst1=[a for a in lst if a>40]
suppose we wish to multiply each element of lst by 2 and copy the result in lst2
lst2=[a*2 for a in lst]

we can also use range function


lst3=[a for a in range(1,20,3)] # create list of elements between 1 to 20 but
every third element
print(lst1)
#output [45,67,45,45]
print(lst2)
#output [46,90,132,90,42,46,90,16,18,68]
print(lst3)
#output [1,4,7,10,13,16,19]

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

Ans.

/ Operator is used to perform Division operation in Python, but // is used to


perform floor division. e.g.

>>25/4

>>6.25

>>25//4

>>6
c.Compute the output of the following python code:
def count(s):
forstr in string.split():
s = “&”.join(str)
return s
print(count(“Python is fun to learn.”))

Ans.

Syntax Error, There is no definition of string inside the count() function. But if
we consider that statement like “string”.split() then count() function insert &
after each character in “string” and then return.

Output will be

s&t&r&i&n&g

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


Ans.

Let we have a function f1() in library.py and we wish to use it in main.py, then
we will use import statement as follows:

from library import *


e.Describe the difference between linspace and argspace.

Ans.

The NumPy.linspace() function returns an array of evenly spaced values within


the specified interval.

import numpy as np

x = np.linspace(0, 30, 5)

#this function returns array of 5 values from 0 to 30 evenly distributes

e.g. [0,7.5,15,22.5,30]

There is no function in python library with name argspace

f.Explain why the program generates an error.


x = [‘12’, ’hello’, 456]
x[0] *= 3
x[1][1]=’bye’

Ans.

In line no 3 we are trying to change the string contents, which is not possible
in Python. In python string objects are immutable.
g.Describe about different functions of matplotlib and pandas.

Ans.

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()), and dealing with missing
data (dropna(), fillna()).
Section –B
2. Attempt any three of the following: 𝟑 × 𝟕 = 𝟐𝟏

a.Illustrate Unpacking tuples, mutable sequences, and string concatenation


with examples.

Ans.

we can use unpacking tuples to assign values of tuple to individual variables.


This is commonly used when you have a function returning multiple values
packed into a tuple, or when you want to iterate over the elements of a tuple.

tuple_example = (1, 2, 3)

# Unpacking the tuple into three variables

a, b, c = tuple_example

print(a)

# Output: 1

print(b)

# Output: 2

print(c)

# Output: 3
b.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.Ans.List slicing is very impressive feature of python. We can
access the elements of the list using several slicing easy to use methods.

>>L= [1, 2, 3, 4, 5, 6, 7, 8, 9]

>> print(L[1:][::-1])

>>print(L[2:-1])

>>print(L[1::2])

>>print(L[len(L)//2:])

>>print(L[:len(L)//2-1:-1])
c.Construct a function perfect_square(number) that returns a number if it is
a perfectsquare otherwise it returns -1.

For example:
perfect_square(1) returns 1
perfect_square (2) returns -1.

Ans.

import math

defperfect_square(n):

m=n**0.5

m=math.floor(m)

if m*m==n:

return 1

else:

return -1

print(perfect_square(25))

print(perfect_square(24))
d.Construct a program to change the contents of the file by reversing each
characterseparated by comma:

Hello!!
Output
H,e,l,l,o,!,!.

Ans.

#Let the file name is p1.txt

f=open(“p1.txt”,”r”)

data=f.read()

f.close()

s=“,”.join(data)

f1=open(“p1.txt”,”w”)

f1.write(s)

f1.close()
e.Construct a plot for following dataset using matplotlib :
Food Calories Potassium fat
Meat 250 40 8
Banana 130 55 5
Avocados 140 20 3
Sweet 120 30 6
Potatoes
Spinach 20 40 1
Watermelon 20 32 1.5
Coconut 10 10 0
water
Beans 50 26 2
Legumes 40 25 1.5
Tomato 19 20 2.5
Ans.

import matplotlib.pyplot as plt

food=["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]

plt.plot(food,calories)

plt.plot(food,potassium)

plt.plot(food,fat)

plt.show()

Section –C

3. Attempt any one part of the following: 𝟕×𝟏=𝟕

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

Ans.

def removenth(s,n):

ans=""

if n<len(s):

fori in range(len(s)):

if(i!=n):
ans=ans+s[i]

else:

ans=s

returnans

print(removenth("Mango",1))

print(removenth("Mango",3))

print(removenth("Mango",7))

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.

Suppose the following input is supplied to the program:


without, hello, bag, world
Then, the output should be:
bag, hello, without, world
Ans.

values=input("Enter comma Separated Values:")


lst=values.split(",")
print(lst)
lst.sort()
for item in lst:
print(item)
4. Attempt any one part of the following: 𝟕×𝟏=𝟕
a.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.

Ans.

def checkPassword(strpass):

islower=False

isdigit=False

isupper=False
isspecial=False

for char in strpass:

asc=ord(char)

if asc>=65 and asc<=90:

isupper=True

if asc>=97 and asc<=122:

islower=True

if asc>=48 and asc<=57:

isdigit=True

if char in ['$','#','@']:

isspecial=True

if len(strpass)>=6 and len(strpass)<=12 and isupper and islower and isdigit


and isspecial:

return True

else:

return False

passwords=input("Enter comma Separated Values:")

lst=passwords.split(",")
validlst=[]

for password in lst:

if checkPassword(password):

validlst.append(password)

print(",".join(validlst))

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

Ans.

As we know that loops are used to execute the same statement or group of
statement multiple times.
If we knows the number of cycles or iteration then we use "for" loop, but
sometimes we have just some condition to stop the cycle, in such cases we use
"while" loop.
Both loops have some specific features associated with them.

e.g.
for i in range(10):
print(i)
#Output
1
2
3
4
5
6
7
8
9

lst=["ABC","XYZ","MNO"]
for item in list:
print(item)
#Output
ABC
XYZ
MNO
x=500
while x>100:
print(x)
x=x-100
#output
500
400
300
200
5. Attempt any one part of the following: 𝟕 × 𝟏 = 𝟕

a.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]

Ans.
def smaller(l):

smalllst=l[0]

for lst in l:

if len(smalllst)>len(lst):

smalllst=lst

return smalllst

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

Ans.

# Define a function to check if a character is a number

def is_not_digit(char):

return not char.isdigit()

# Define a function to check if a word starts with a vowel

def starts_with_vowel(word):
vowels = 'aeiouAEIOU'

return word[0] in vowels

# Define a function to check if a word contains any of the specified nouns

def contains_noun(word):

nouns = ['Agra', 'Ramesh', 'Tomato', 'Patna']

return any(noun in word for noun in nouns)

# Define the input text

s = input()

# Use filter() to remove all the numbers from the string

filtered_string = ''.join(filter(is_not_digit, s))

# Split the filtered string into words

words = filtered_string.split()

# Use filter() to remove all the words that start with a vowel

filtered_words = filter(lambda word: not starts_with_vowel(word), words)

# Use filter() to remove all the words that contain any of the specified nouns

filtered_words = filter(lambda word: not contains_noun(word),


filtered_words)

# Join the filtered words back into a string

filtered_sentence = ' '.join(filtered_words)


# Print the filtered sentence

print(filtered_sentence)

6. Attempt any one part of the following: 𝟕 × 𝟏 = 𝟕

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

Ans.

f=open("data.txt","r")

s=f.read()

f.close()

lst=["zero","one","two","three","four","five","six","seven","eight","nine"]

for i in range(10):

s=s.replace(str(i),lst[i])
f=open("data.txt","w")

f.write(s)

f.close()

b.Construct a program which accepts a sequence of words separated by


whitespace as file input. Print the words composed of digits only.

Ans.

def find_digit_words(file_path):

try:

with open(file_path, 'r') as file:

content = file.read()

words = content.split()

digit_words = [word for word in words if word.isdigit()]

return digit_words

except FileNotFoundError:

print("File not found!")

file_path = input("Enter the path to the file: ")

digit_words = find_digit_words(file_path)
print("Words composed of digits only:")

for word in digit_words:

print(word)

7. Attempt any one part of the following: 𝟕×𝟏=𝟕

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

Ans.

import csv

import matplotlib.pyplot as plt

def read_csv(file_path):

data = []

last_column = []

with open(file_path, 'r') as file:

csv_reader = csv.reader(file)

for row in csv_reader:

data.append(row[:-1]) # Remove the last column


last_column.append(row[-1])

return data, last_column

def plot_data(data):

x = [float(row[0]) for row in data]

y = [float(row[1]) for row in data]

plt.scatter(x, y)

plt.xlabel('X')

plt.ylabel('Y')

plt.title('Scatter Plot of First Two Columns')

plt.show()

# Change the path to your cities.csv file

file_path = 'cities.csv'

data, last_column = read_csv(file_path)

plot_data(data)
b.Design a calculator with the following buttons and functionalities like
addition, subtraction, multiplication, division and clear.

Ans.

You might also like