M3-R5 Python Programming Long Question with Answer

M3-R5 Python Programming Long Question with Answer

January 2021
Part Two
(Answer any Four Questions)

Q.5.
(A) NumPy की परिभाषा दें? NumPy ऐरे कैसे बनाते हैं?
Define NumPy? How to create NumPy Array ?

नम्पी क्या है
Numpy एक साइंटिफिक Python Library है जो मैथमेटीकल और लोगिकल ऑपरेशन करने में हेल्प करती हैं । Numpy Library Python की मोस्ट पोपुलर लाइब्रेरी में से है । इसका इंटरनल ज्यादातर डाटा साइंटिफिक और ए आई इत्यादी में होता है । पाइथन लिस्ट भी ऐरे के रूपमे इस्तेमाल होता है लेकिन पाइथन लिस्ट के मुकाबले में Numpy Arrays फ़ास्ट होता है ।

नम्पी ऐरे
Numpy में ऐरेस को क्रिएट करने के लिए array() फंक्शन का इस्तेमाल करना होता है । वैसे सबसे पहले Numpy को इम्पोर्ट करना होगा और इम्पोर्ट करने के लिए आपको  import numpy as np लिखना होगा ।

उदाहरण :

Ndarray को क्रिएट करने के लिए हम एक लिस्ट और टपल भी क्रिएट कर सकते हैं या फिर उस लिस्ट या तापल को array() फंक्शन पास कर देते हैं। या उसके बाद  numpy.array() फंक्शन ndarray में कन्वर्ट कर देते हैं।

import numpy as np
list_np = [1,2,3,4]   #python list
arr = np.array(list_np)
print(arr)
Output:
[1 2 3 4]

What is Numpy
Numpy is a scientific Python library that helps in performing mathematical and logical operations. Numpy Library is one of the most popular libraries in Python. Its internal is mostly in Data Scientific and AI etc. Python lists are also used as arrays, but Numpy Arrays are faster than Python lists.

Numpy Creating Arrays
To create Ndarray, we can also create a list and tuple or pass that list or tuple to the array() function. Or after that the numpy.array() function converts it to ndarray.

import numpy as np
list_np = [1,2,3,4]   #python list
arr = np.array(list_np)
print(arr)
Output:
[1 2 3 4]

(B) फ्लोचार्ट और फ्लोचार्ट में उपयोग किए जाने वाले प्रतीकों की व्याख्या करें। अल्गोरिथम, छद्म कोड लिखें और हनोई के टावर्स के लिए फ्लोचार्ट तैयार करें। Explain Flowchart and symbols used in flowchart. Write the Algorithm, pseudo code and draw the flowchart for Towers of Hanoi.

Flowchart and symbols.

Flowchart and symbols

Tower of Hanoi Algorithm:
Start
Define function
Declare variable n
Enter the number of discs
Call the function
Stop

Flowchart for Tower of Hanoi:

Flowchart for Tower of Hanoi

Q.6.
(A) आप एक पैकेज को कैसे सृजित और इम्पोर्ट करेंगे? प्रोग्राम के एक उदाहरण के साथ इसकी व्याख्या करें।
How will you create a Package and import it? Explain it with an example program.

Creating Packages
We have included a __init__.py, file inside a directory to tell Python that the current directory is a package. Whenever you want to create a package, then you have to include __init__.py file in the directory. You can write code inside or leave it as blank as your wish. It doesn’t bother Python.

हमने पायथन को यह बताने के लिए एक निर्देशिका के अंदर एक __init__.py, फ़ाइल शामिल की है कि वर्तमान निर्देशिका एक पैकेज है। जब भी आप कोई पैकेज बनाना चाहते हैं तो आपको __init__.py फाइल को डायरेक्टरी में शामिल करना होगा। आप अंदर कोड लिख सकते हैं या अपनी इच्छानुसार इसे खाली छोड़ सकते हैं। यह पायथन को परेशान नहीं करता है।

Follow the below steps to create a package in Python

  • Create a directory and include a py file in it to tell Python that the current directory is a package.
  • Include other sub-packages or files you want.
  • Next, access them with the valid import

Let’s create a simple package that has the following structure.
Package (university)

  • py
  • py
  • py

Go to any directory in your laptop or desktop and create the above folder structure. After creating the above folder structure include the following code in respective files.

Example
#nstudent.py
class Student:
   def __init__(self, student):
      self.name = nstudent[‘name’]
      self.gender = nstudent[‘gender’]
      self.year = nstudent[‘year’]
   def get_nstudent_details(self):
      return f”Name: {self.name}\nGender: {self.gender}\nYear: {self.year}”
# nfaculty.py
class Faculty:
   def __init__(self, nfaculty):
      self.name = nfaculty[‘name’]
      self.subject = nfaculty[‘subject’]
   def get_nfaculty_details(self):
      return f”Name: {self.name}\nSubject: {self.subject}”

We have the above in the student.py and faculty.py files. Let’s create another file to access those classed inside it. Now, inside the package directory create a file named testing.py and include the following code.

Example
# testing.py
# importing the Student and Faculty classes from respective files
from student import Student
from faculty import Faculty
# creating dicts for student and faculty
student_dict = {‘name’ : ‘Gyancs’, ‘gender’: ‘Male’, ‘year’: ‘5’}
faculty_dict = {‘name’: ‘Integral’, ‘subject’: ‘Python’}
# creating instances of the Student and Faculty classes
student = Student(student_dict)
faculty = Faculty(faculty_dict)
# getting and printing the student and faculty details
print(student.get_student_details())
print()
print(faculty.get_faculty_details())

If you run the testing.py file, then you will get the following result.

Output
Name: Gyancs
Gender: Male
Year: 5
Name: Integral
Subject: Python

(B) निम्नलिखित की व्याख्या करें: Explain the following:
(i) लिस्ट स्लाइसिंग List Slicing

लिस्ट स्लाइसिंग
Slicing का हिंदी अर्थ होता है – टुकड़ा। python programming language में string का एक छोटा भाग slice कहलाता है। Slice operator का उपयोग करके string का एक भाग print करने की प्रक्रिया slicing कहलाती है। Slice operator को [: : :] से represent करते हैं। इसका syntax कुछ इस प्रकार लिखा जाता है।

The Hindi meaning of Slicing is – Piece. In the python programming language, a small part of a string is called a slice. The process of printing a part of a string using the slice operator is called slicing. Slice operator is represented by [: ::] . Its syntax is written something like this.

Syntax – strObj [ begin : end : step ]

किसी range value का प्रयोग करके string के एक part को print करने की प्रक्रिया को slicing कहते हैं।

Begin – Begin value यह specify करता है की string के किस index से slice का निर्माण शुरू होगा।

End – यह specify करता है की string के किस index तक slice का निर्माण बंद होगा।

Step – इसे increment value भी कहते हैं। इसकी आवश्यकता तब पड़ती है। जब हम begin और end value के अंदर भी कुछ index को छोड़कर slice को print करना चाहते है।

Example-
>>>a=’Gyancs’
>>>print(a[0:6])
‘Gyancs’
>>>print(a[0:6:2])
‘Gy’
(ii)लिस्ट एक्सेसिंग विधिय List Accessing Methods
Python List

Python has a set of built-in methods that you can use on lists/arrays.

MethodDescription
append()Adds an element at the end of the list
clear()Removes all the elements from the list
copy()Returns a copy of the list
count()Returns the number of elements with the specified value
extend()Add the elements of a list (or any iterable), to the end of the current list
index()Returns the index of the first element with the specified value
insert()Adds an element at the specified position
pop()Removes the element at the specified position
remove()Removes the first item with the specified value
reverse()Reverses the order of the list
sort()Sorts the list

Q.7.
(A) रिकर्शन का उपयोग करके किसी दी गई संख्या के फ़ैक्टोरियल की गणना करने के लिए एक पाइथन प्रोग्राम लिखें।
Write a Python program to compute the factorial of a given number using recursion.

# Factorial of a number using recursion
def recur_factorial(n):
   if n == 1:
       return n
   else:
       return n*recur_factorial(n-1)
num = 7
# check if the number is negative
if num < 0:
   print(“Sorry, factorial does not exist for negative numbers”)
elif num == 0:
   print(“The factorial of 0 is 1”)
else:
   print(“The factorial of”, num, “is”, recur_factorial(num))

(B) परिवर्तनीय और अपरिवर्तनीय डेटा प्रकार की परिभाषा दें। पाइथन प्रोग्राम के साथ लीनियर और बाइनरी सर्च की अवधारणा की व्याख्या करें।
Define mutable and immutable data type. Explain the concept of Linear and Binary search with Python program.

Mutable and Immutable Data Types in Python

  • Some of the mutable data types in Python are list, dictionary, set and user-defined classes.
  • On the other hand, some of the immutable data types are int, float, decimal, bool, string, tuple, and range.

It’s time for some examples. Let’s start by comparing the tuple (immutable) and list (mutable) data types. We can define a list using square brackets [] like this: numbers = [1, 2, 3]. To define a tuple, we just need to replace the brackets with parentheses () like this: numbers = (1, 2, 3). From both data types, we can access elements by index and we can iterate over them. The main difference is that a tuple cannot be changed once it’s defined.

Indexing lists and tuples

list_values = [1, 2, 3]
set_values = (10, 20, 30)
print(list_values[0])
print(set_values[0])

(C) टपल के एक्सेसिंग तत्वों के निष्पादन के लिए पाइथन में कोड स्निपेट्स लिखें।
Write code snippets in Python to perform Accessing Elements of a Tuple.

There are various ways in which we can access the elements of a tuple.

Indexing
We can use the index operator [] to access an item in a tuple, where the index starts from 0.

# Accessing tuple elements using indexing
my_tuple = (‘p’,’e’,’r’,’m’,’i’,’t’)
print(my_tuple[0])   # ‘p’
print(my_tuple[5])   # ‘t’
# nested tuple
n_tuple = (“mouse”, [8, 4, 6], (1, 2, 3))
# nested index
print(n_tuple[0][3])       # ‘s’
print(n_tuple[1][1])       # 4
Q.8.
(A) एक पाइथन प्रोग्राम को निष्पादित करने के लिए इंटरप्रेटर द्वारा अपेक्षित बेसिक स्टेप्स लिखें।
Write the basic steps required by the interpreter to execute a python program.

Go to python.org
Download the latest version
Install the setup
Click on the set path checkbox.
Once you complete the above steps, go to command prompt and run the following command.

Install the setup

Hello World Program
One of the salient features of python is its syntax and readability. It becomes extremely easy to write a code in python compared to other programming languages. Following is the simple code for printing hello world in python.

print(‘hello world’)

(B) निम्नलिखित प्रोग्राम के आउटपुट को प्रिडिक्ट और व्याख्या करें।
Predict and explain the output of following program
r = lambda q: q * 2
s = lambda q: q * 3
x = 2
x = r(x)
x = s(x)
x = r(x)
print (x)

Output:
24
Explanation:
In the above program r and s are lambda functions or anonymous functions and q is the argument to both of the functions. In first step we have initialized x to 2. In second step we have passed x as argument to the lambda function r, this will return x*2 which is stored in x. That is, x = 4 now. Similarly in third step we have passed x to lambda function s, So x = 4*3. i.e, x = 12 now. Again in the last step, x is multiplied by 2 by passing it to function r. Therefore, x = 24.

(C) पाइथन में मेमोरी का प्रबंधन कैसे किया जाता है? उस उपकरण का नाम दें जो बग्स का पता लगाने में मदद करता है या स्थैतिक विश्लेषण करता है।
How memory is managed in Python? Give the tools name that help to find bugs or perform static analysis?

Understanding Memory allocation is important to any software developer as writing efficient code means writing a memory-efficient code. Memory allocation can be defined as allocating a block of space in the computer memory to a program. In Python memory allocation and deallocation method is automatic as the Python developers created a garbage collector for Python so that the user does not have to do manual garbage collection.

Pychecker and Pylint are the static analysis tools that help to find bugs in python.

Pychecker is an opensource tool for static analysis that detects the bugs from source code and warns about the style and complexity of the bug.

Pylint is highly configurable and it acts like special programs to control warnings and errors, it is an extensive configuration file Pylint is also an opensource tool for static code analysis it looks for programming errors and is used for coding standard. it checks the length of each programming line. it checks the variable names according to the project style. it can also be used as a standalone program, it also integrates with python IDEs such as Pycharm, Spyder, Eclipse, and Jupyter

Pychecker can be simply installed by using pip package pip install Pychecker if suppose if you use python 3.6 version use upgrade pip install Pychecker –upgrade Pylint can be simply installed by using pip package

pip install Pylint

if suppose if you use python 3.6 version use upgrade

pip install Pylint –upgrade

Q.9.
(A) उपयुक्त आरेख की मदद से एल.ई.जी.बी. नियमों और उनके महत्व का वर्णन करें।
Illustrate the LEGB rules and its significance with help of suitable diagram.

Python Variable Scope Resolution Rules (LEGB)

Python variables are searched in the following order of namespaces.
Local -> Enclosed -> Global -> Built-in
This is also called LEGB rule for variable scope resolution.

Python Variable Scope Resolution Rules

Scope resolution via LEGB rule:

In Python, the LEGB rule is used to decide the order in which the namespaces are to be searched for scope resolution.

The scopes are listed below in terms of hierarchy (highest to lowest/narrowest to broadest):

  • Local(L): Defined inside function/class
  • Enclosed(E): Defined inside enclosing functions(Nested function concept)
  • Global(G): Defined at the uppermost level
  • Built-in(B): Reserved names in Python built-in modules

(B) पाइथन स्लाइस की व्याख्या करें। स्लाइस का सिन्टैक्स लिखें और इसके बारे में चर्चा करें।
Explain about Python slice. Write the syntax of slice and discuss about it.

Slicing in Python
String operations have never been easier, as Python has introduced multiple string operation methods that allow fetching a substring from a string. One of these operations is called Slice. This operator is so versatile and syntactically elegant, that with the help of just a few parameters you can fetch numerous substring combinations out of a string.

Python slice() function
Python slice() function returns a slice object.

A sequence of objects of any type(string, bytes, tuple, list or range) or the object which implements __getitem__() and __len__() method then this object can be sliced using slice() method.

Syntax:
slice(stop)
slice(start, stop, step)

Example 1: Python slice string

# Python program to demonstrate
# slice() operator
# String slicing
String = ‘Gyancs’
s1 = slice(3)
s2 = slice(1, 5, 2)
print(“String slicing”)
print(String[s1])
print(String[s2])

Output:
String slicing
Gya
yn
>>>