Python Important Questions AI and ML For Sem II Osmania University
Python Important Questions AI and ML For Sem II Osmania University
Introduction:
Python IDE,
Elements of Python,
Type Conversion.
Basics:
Expressions,
Assignment Statement,
Arithmetic Operators,
Operator Precedence,
Boolean Expression.
Conditionals:
Loops:
For Loop,
Nested Loops,
Function:
Parts of A Function,
Execution of A Function,
Scope Rules.
Strings :
Length of the string and perform Concatenation and Repeat operations in it,
Tuples,
Unpacking Sequences,
Lists,
Mutable Sequences,
List Comprehension,
Sets,
Dictionaries.
Lambda Expressions.
Sieve of Eratosthenes:
generate prime numbers with the help of an algorithm given by the Greek Mathematician named
Eratosthenes,
File I/O:
Classes:
Special Methods (such as init, str, comparison methods and Arithmetic methods etc.),
Class Example,
Inheritance,
Recursive Fibonacci,
Tower Of Hanoi.
Search :
Selection Sort,
Merge List,
Merge Sort,
Ans. Python is a high-level, interpreted, interactive and object-oriented scripting language. It is a highly readable
language. Unlike other programming languages, Python provides an interactive mode similar to that of a calculator.
Ans.
The syntax of Java is complex than Python. The syntax of Python is easier than Java
ed Java is statically typed programming, makes it faster Python is manually typed, makes it slower.
e Longer lines of code than python Shorter lines of code than Java.
1. The code written in Python is automatically compiled to byte code and executed.
2. Python can be used as a scripting language, as a language for implementing web applications, etc.
3. Python supports many features such as nested code blocks, functions, classes, modules and packages.
2. Using a graphical user interface (GUI) from an Integrated Development Environment (IDE),
Ans. Python is called an interpreted language because it goes through an interpreter, which turns the Python code
into the language understood by processor of the computer.
Ans. Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.
Ans. Type () function in Python programming language is a built-in function which returns the datatype of any
arbitrary object. The object is passed as an argument to the type() function. Type() function can take anything as an
argument and return its datatype, such as integers, strings, dictionaries, lists, classes, module, tuple, functions, etc.
Ans. Unary operators are operators with only one operand. These operators are basically used to provide sign to the
operand.
+, -, are some unary operators.
Ans: Binary operators are operators with two operands that are manipulated to get the result. They are also used to
compare numeric values and string values.
**, %, <<, >>, &, |, ^, <, >, <=, >=, ==, !=, <> are some binary operators.
Ans. Pythonpath has a role similar to PATH. This variable tells Python Interpreter where to locate the module files
imported into a program. It should include the Python source library directory and the directories containing Python
source code. PYTHONPATH is sometimes preset by Python Installer.
Q12. What is the difference between list and tuples in Python?
Ans.
List Tuples
Lists are mutable, i.e., they can be edited. Tuples are immutable (they are lists that cannot be edited).
Lists are usually slower than tuples. Tuples are faster than lists.
Syntax :list_ 1 [10, bachelorExam, 20] Syntax :tup 1 (10, bachelorExam, 20)
Ans
Arrays Lists
Arrays can only store homogeneous data (data of the same type). Lists can store heterogeneous and arbitrary d
Arrays use less memory to store data. Lists require more memory to store data.
The length of an array is pre-fixed while creating it, so more elements cannot The length of a list is not fixed, so more elem
be added. added.
Ans. Python does not have a specific syntax for including multiline comments like other programming languages.
However, programmers can use triple-quoted strings (docstrings) for making multiline comments as when a docstring
is not used as the first statement inside a method, it is ignored by Python parser.
Ans. No. Python is a dynamically typed language, i.e., Python Interpreter automatically identifies the data type of a
variable based on the type of value assigned to the variable.
Q16. In some languages, every statement ends with a semicolon (;). What happens if you put a semicolon at the
end of a Python statement ?
Ans. Python allows semicolon to use as a line terminator. So no error will occur if we put a semicolon; at the end of
python statement.
2. Most automation, data mining, and big data platforms depend on Python. This is because it is the ideal
language to work with for general purpose tasks.
Ans. Floor division returns the quotient in which the digits after the
decimal point are removed. But if one of the operands (dividend and divisor) is negative, then the result is floored,
i.e., rounded away from zero (means, towards the negative of infinity). It is denoted by “//”.
For example:
5.0 // 2
2.0
1. PyCharm
2. Spyder
3. PyDev
Ans.
1. and
2. false
3. is
4. pass 5. return
6. def
Ans.
>>> name2
‘Albert’ # Output
>>>
Ans.
>>> amount = 50
>>> amount
50 # Output
>>> amount
‘Fifty’ # Output
>>>
3. Operation on RHS
1. Arithmetic operators.
2. Assignment operators.
3. Bitwise operators.
4. Comparison operators.
5. Identity operators.
6. Logical operators.
7. Membership operators.
Q26. Name the tools that are used for static analysis.
Ans.
1. Pychecker
2. Pylint
Ans. Python has six basic data types which are as follows:
1. Numeric
2. String
3. List
4. Tuple
5. Dictionary
6. Boolean
Ans.
1. Associativity decides the order in which the operators with the same precedence are executed.
a. Left to right: In left-to-right associativity, the operator of the same precedence are executed from
the left side first.
b. Right to left: In right-to-left associativity, the operator of the same precedence are executed from
the right side first.
Ans.
1. Precedence: It is applied to two different class of operators. That is,+ and*, and *, AND & OR, etc.
2. Associativity: It is applied to operators of same class. That is, * and *,+ and -, * and /, etc.
3. Order: Precedence and associativity identify the operands for each operator. While evaluating an
assignment, the RHS is evaluated before LHS.
Ans. The range () function is a built-in function in Python that helps us to iterate over a sequence of numbers. It
produces an iterator that follows an arithmetic progression.
Ans.
>>> range (8)
[0, 1, 2, 3, 4, 5, 6, 7]
range (8) provides a sequence of number 0-7. That is to say range (n) generates a sequence of number that starts
with 0 and end with (n – 1).
Ans.
[3, 4, 5, 6, 7, 8]
We provided the begin index with 3 and the end index with 9. Hence, the range function generates a sequence
iterator of number that starts from 3 and ends at 8.
Ans. The alternative execution provides two possibilities and the condition determines which one is to be executed.
This is the second form of the if statement.
Ans. The intended statements that follow the conditional statements are called block. The first unintended statement
marks the end of the block.
Ans. ‘Hello’
Ans. A control statement is a statement that determines the control flow of a set of instructions. There are three
fundamental forms of control that programming languages provide: sequential control, selection control, and
iterative control.
Ans. In short-circuit (lazy) evaluation, the second operand of Boolean operators AND and OR is not evaluated if the
value of the Boolean expression can be determined from the first operand alone.
Ans. A header in Python starts with a keyword and ends with a colon. The group of statements following a header is
called a suite. A header and its associated suite are together referred to as a clause.
Q11. What do you mean by iterative control ?
Ans. An iterative control statement is a control statement providing the repeated execution of a set of instructions.
An iterative control structure is a set of instructions and the iterative control statement(s) controlling their execution.
Ans. A definite loop is a program loop in which the number of times the loop will iterate can be determined before
the loop is executed.
Ans. An indefinite loop is a program loop in which the number of times that the loop will iterate cannot be
determined before the loop is executed.
Ans. No indentation in Python is compulsory and is part of its syntax. Indentation is a way of defining the scope and
extent of the block of codes. Indentation provides better readability to the code.
Ans. If the break statement in a for loop is executed then the else part of that for loop is skipped.
Ans. Raw_input() takes the input from the user but it does not interpret the input and also it returns the input of the
user without doing any changes.
Ans. The main difference between void and fruitful functions in python is:
Ans. Traversal is a process in which we access all the elements of the string one by one using some conditional
statements such as for
loop, while loop, etc.
Ans. The backslash character (/) is used to escape characters. It converts difficult-to-type characters into a string. For
example, we need the escaping character concept when we want to print a string with double quotes or single
quotes. When single or double quotes are used with the string, Python normally neglects them and prints only the
string.
Ans. Tuple assignment allows the assignment of values to a tuple of variables on the left side of assignment from the
tuple of values on the right side of the assignment.
Ans. Lists are mutable means that we can change the value of any elements inside the list at any point of time. The
element inside the list are accessible with their index value. The index will always start with 0 and end with n-1, if the
list contains n elements.
Ans. Traversing of the list refers to accessing all the elements or items of the list. Traversing can be done using any
conditional statement of Python, but it is preferable to use for loop.
Q.6. What are the different methods used in deleting elements from dictionary?
1. pop(): pop() method removes that item from the dictionary for which the key is provided. It also returns
the value of the item.
2. popitem(): popitem() method is used to remove or delete and return an arbitrary item from the dictionary.
3. clear(): clear() method removes all the items or elements from a dictionary at the same time.
1. One key in a dictionary cannot have two values, i.e., duplicate keys are not allowed in the dictionary; they
must be unique.
2. Keys are immutable, i.e., we can use string, integers or tuples for dictionary keys, but cannot use
something like [‘key’].
Ans.
2. Solve each of the sub-problems separately as a function, and combine them together in another function.
Q9. What are mathematical functions? How are they used in Python?
Ans. Python provides us a math module containing most of the familiar and important mathematical functions. A
module is a file that contain some predefine Python codes. A module can define functions, classes and variables. It is
a collection of related functions grouped together.
Ans. Python also allows users to define their own functions. To use their own functions in Python, users have to
define the functions first; this is known as function definition. In a function definition, users have to define a name for
the new function and also the list of the statements that will execute when the function will be called.
Syntax :
Syntax;
return [expression]
Ans. The anonymous functions are the functions created using a lambda keyword.
Q13. You have been given a string ‘I live in Cochin. I love pets.’ Divide this string in such a very that the two
sentences in it are separated and stored in different variables. Print them.
Ans.
Q14. An email address is provided : hello@python. org. Using tuple assignment, split the username and domain
from the email address.
Ans.
Q15. Write a function called sumall that takes any number of arguments and returns their sum.
Ans.
Q16. Write a function called circleinfo which takes the radius of circle as argument and returns the area and
circumference of the circle.
Ans.
Ans.
Q.18. Give examples for all, any, len and sorted methods in
dictionary.
Ans.
Q.19. Give the syntax required to convert an integer number into string and a float to an integer.
Ans.
March 1991.
Ans.
their sum.
Ans.
Q22. What are the types of arguments used for calling a function?
i. Required argument
Q23. What is the output of print list[2] when list = [‘abcd’, 2.23,
john’] ?
Ans. john
Ans. In Python, we can extract a substring by using a colon inside the square bracket [:]. The resultant substring is a
part of the long string.
Ans. Docstring command is use to know about a function using triple- quoted string.
Ans.
i. Global variables:
1. Global variables are the variables that are defined outside a function body.
2. Global variables can be accessed throughout the program body by all functions.
1. Local variables are the variables that are defined inside a function body.
2. Local variables can be accessed only inside the function in which they are declared.
3. When we call a function, the variables declared inside it are brought into scope.
Ans. A variable that is defined in the class and can be used by all the instances of that class is called class variable.
Ans. A variable that is defined in the method; its scope is only within the object that defines it.
Q3. Define the term instance.
Ans. A function defined more than one time with different behaviours is called function overloading.
Ans. Methods are the functions defined in the definition of class and are used by various instances of the class.
Ans. Objects can be used to access the attributes of the class. The syntax for creating an object in Python is similar to
that for calling a
function.
Syntax :
obj_name = class_name()
For example:
Ans. Objects are mutable means that the state of an object can be changed at any point in time by making changes
to its attributes.
Ans. The instances of a class can also be returned by a function i.e., function can return the instances or objects.
Ans.
_bases__: It displays the tuple that contains the base classes, possibly empty. It displays them in the order in which
they occur in the base class list.
For example:
Ans. The main advantage of inheritance is that the code can be written once in the base class and then reused
repeatedly in the subclasses.
Ans. The class which inherits the feature of another class is called subclass.
1. Opening a file
3. Closing a file
i. r : It opens a file in reading mode. The file pointer is placed at the starting of the file.
ii. r + : It opens the file in both reading and writing mode. The file
iii. w: It opens the file in writing mode. If a file exists, it overwrites the existing file; otherwise, it creates a new file.
iv. w +: It opens the file in both reading and writing mode. If a file exists, it overwrites the existing file; otherwise, it
creates a new file.
Ans.
Attribute Description
file.closed It will return true if the file is closed; it will otherwise return false.
file.mode It will return the access mode with which the file is opened.
file.softspace It will return false if space explicitly required with print; otherwise it will return true.
Q16. Give the syntax for reading from a file. What is the work of the readline() function?
Ans. Syntax:
fileobject.read([size])
The count parameter size gives the number of bytes to be read from an opened file. It starts reading from the
beginning of the file until the size given. If no size is provided, it ends up reading until the end of the file.
Q17. How are renaming and deleting performed on a file ? Give the syntax for each.
Ans.
Renaming a file: Renaming a file in Python is done with the help of the rename() method. The rename() method is
passed with two argument, the current filename and the new filename.
Syntax :
os.rename(current_filename, new_filename)
Deleting a file: Deleting a file in Python is done with the help of the remove() method. The remove() method takes
the filename as an argument to be deleted.
Syntax :
os.remove(filename)
Ans. In Python, the tell() method tells us about the current position of the pointer. The current position tells us where
reading will starts from at present.
We can also change the position of the pointer with the help of the seek() method. We pass the number of bytes to
be moved by the pointer as arguments to the seek() method.
Ans. If there is a large number of files, then related files are placed in different directories. The directory can be said
to be a collection of files
and sub-directories. The module in Python enables us to use various methods to work with directories.
Q20. What are the basic methods performed on directories ?
Ans. Following are the four basic methods that are performed on directories:
Ans. Python allows users to define their own exceptions by creating a new class. Exception needs to be derived,
directly or indirectly from exception class.
For example:
Ans.
i. AssertionError
ii. FloatingPointError
iii. SystemError
iv. RunTimeError
v. ZeroDivisionError
but not how these operations will be implemented. It does not specify how data will be organized in memory and
what algorithms will be used for implementing the operations. It is called “abstract” because it gives an
implementation-independent view.
2. The change in arguments should be toward a case for which the solution is known and we call it as a base
case. There can be more than one base case.
2. The programs are easy to implement if the problem has a recursive definition.
Ans.
1. Debugging is difficult.
Ans.
2. There also exists a variant of this task called Tower of London for neuropsychological diagnosis and
treatment of executive functions.
3. The Tower of Hanoi is also used as a Backup rotation scheme when performing computer data Backups
where multiple tapes/media are involved.
4. The Tower of Hanoi is also used as a test by neuropsychologists trying to evaluate frontal lobe deficits.
Ans: Advantages:
2. In the best-case scenario, the item we are searching for may be at the start of the list in which case we get
it on the very first try.
Drawbacks :
1. Its drawback is that if our list is large, it may take time to go through the list.
2. In the worst-case scenario, the item we are searching for may not be in the list, or it may be at the
opposite end of the list.
Q6. Write algorithm of simple search.
Ans.
Ans
Ans.
3. Example of sorting in real world are: Contact list in mobile phones, ordering marks before assignment of
grades, etc.
Ans.
1. Insertion sort
2. Selection sort
3. Bubble sort
4. Merge sort
Ans. Binary search is a search algorithm that finds the position of a target value within a sorted list.
Table Of Contents
2 Q2. What is Python? How is Python interpreted? What are the tools that help to find bugs or perform static
analysis? What Are Python decorators?
3 Q3. What do you mean by data types? Explain numeric and string data type with examples.
5 Q5. What do you mean by Boolean expression?ORWrite short notes with example: The programming cycle for
Python, elements of Python, type conversion in Python, operator precedence, and Boolean expression.
6 Q5. How memory is managed in Python? Explain PEP 8. Write a Python program to print even length words in a
string.
Ans.
1. Python’s programming cycle is dramatically shorter than that of traditional programming cycle.
3. Python programs simply import modules at runtime and use the objects they contain.Because of this, Python
programs run immediately after changes are made.
4. In cases where dynamic module reloading can be used, it is even possible to change and reload parts of a
running program without stopping it at all.
Q2. What is Python? How is Python interpreted? What are the tools that help to find bugs or perform static
analysis? What Are Python decorators?
Ans.
Python: Python is a high-level, interpreted, interactive and object-oriented scripting language. It is a highly readable
language. Unlike other programming languages, Python provides an interactive mode similar to that of a calculator.
Interpretation of Python :
2. When we write Python programs, it converts source code written by the developer into an intermediate
language which is again translated into the machine language that is executed.
3. The python code we write is compiled into python bytecode, which creates a file with the extension .pyc.
4. The bytecode compilation happened internally and was almost completely hidden from the developer.
5. Compilation is simply a translation step, and byte code is a lower-level, and platform-independent,
representation of source code.
6. Each of the source statements is translated into a group of bytecode instructions. This bytecode translation
is performed to speed execution. Bytecode can be run much quicker than the original source code
statements.
7. The .pyc file, created in the compilation step, is then executed by appropriate virtual machines.
8. The Virtual Machine iterates through bytecode instructions, one by one, to carry out their operations.
9. The Virtual Machine is the runtime engine of Python and it is always present as part of the Python system,
and is the component that actually runs the Python scripts.
The following tools are the static analysis tools that help to find bugs in python :
1.Pychecker: Pychecker is an open source tool for static analysis that detects the bugs from source code and warns
about the style and complexity of the bug.
2. Pylint:
a.Pylint is highly configurable and it acts like special programs to control warnings and errors, it is an
extensive configuration file
b. It is an open source tool for static code analysis and it looks for programming errors and is used for coding
standard.
c. It also integrates with Python IDEs such as Pycharm, Spyder, Eclipse, and Jupyter.
Python decorators:
1. Decorators are very powerful and useful tool in Python since it allows programmers to modify the behavior
of function or class.
2. Decorators allow us to wrap another function in order to extend the behavior of wrapped function, without
permanently modifying it.
3. In decorators, functions are taken as the argument into another function and then called inside the wrapper
function.
4. Syntax :
@gfg_decorator
def hello_decorator():
print(“Gfg”)
5. gfg_decorator is a callable function, will add some code on the top of some another callable function,
hello_decorator function and return the wrapper function.
Q3. What do you mean by data types? Explain numeric and string data type with examples.
Ans.
Data types:
The data stored in the memory can be of many types. For example, a person’s name is stored as an
alphabetic value and his address is stored as an alphanumeric value.
Numeric
String
List
Tuple
Dictionary
Boolean
Numeric
Numeric data can be broadly divided into integers and real numbers (i.e., fractional numbers).
Integers can be positive or negative.
The real numbers or fractional numbers are called, floating point numbers in programming
languages. Such floating point numbers contain a decimal and a fractional part.
For example:
String
A string in Python can be a series or a sequence of alphabets, numerals and special characters.
For Example
Ans.
List:
4. To declare a list in Python, we need to separate the items using commas and enclose them within square
brackets ([ ]).
5. Operations such as concatenation, repetition and sub-list are done on list using plus (+), asterisk (*) and
slicing (:) operator.
Tuple:
3. Tuples are enclosed within parentheses rather than within square brackets.
Ans.
Python’s programming cycle is dramatically shorter than that of traditional programming cycle.
Python programs simply import modules at runtime and use the objects they contain.Because of this, Python
programs run immediately after changes are made.
In cases where dynamic module reloading can be used, it is even possible to change and reload parts of a
running program without stopping it at all.
Since Python is interpreted, there is a rapid turnaround after program changes. And because Python’s parser is
embedded in Python-based systems, it is easy to modify programs at runtime.
Elements of Python :
Data types:
The data stored in the memory can be of many types. For example, a person’s name is stored as an
alphabetic value and his address is stored as an alphanumeric value.
Numeric
String
List
Tuple
Dictionary
Boolean
Numeric
Numeric data can be broadly divided into integers and real numbers (i.e., fractional numbers).
Integers can be positive or negative.
The real numbers or fractional numbers are called, floating point numbers in programming
languages. Such floating point numbers contain a decimal and a fractional part.
For example:
String
A string in Python can be a series or a sequence of alphabets, numerals and special characters.
For Example
List:
9. To declare a list in Python, we need to separate the items using commas and enclose them within square
brackets ([ ]).
10. Operations such as concatenation, repetition and sub-list are done on list using plus (+), asterisk (*) and
slicing (:) operator.
Tuple:
6. Tuples are enclosed within parentheses rather than within square brackets.
Dictionary:
2. When we have the large amount of data, the dictionary data type is used.
4. Items in dictionary are enclosed in the curly-braces () and separated by the comma (,).
5. A colon (:) is used to separate key from value. A key inside the square bracket [ ] is used for accessing the
dictionary items.
6. For example:
Boolean :
1. In a programming language, mostly data is stored in the form of alphanumeric but sometimes we need to
store the data in the form of ‘Yes’ or ‘No’.
3. This True and False data is known as Boolean data and the data types which stores this Boolean data are
known as Boolean data types.
1. The process of converting one data type into another data type is known as type conversion.
Python handles the implicit data type conversion, so we do not have to explicitly convert the data type into
another data type
In the given example, we have taken two variables of integer and float data types and added them.
Further, we have declared another variable named ‘sum’ and stored the result of the addition in it.
When we checked the data type of the sum variable, we can see that the data type of the sum variable has
been automatically converted into the float data type by the Python compiler. This is called implicit type
conversion.
Explicit type conversion takes place when the programmer clearly and explicitly defines the variables in the
program.
For example:
In the given example, the variable a is of the number data type and variable b is of the string data type.
Operator precedence:
1. When an expression has two or more operator, we need to identify the correct sequence to evaluate these
operators. This is because result of the expression changes depending on the precedence.
For example : Consider a mathematical expression: 10+ 5/5
When the given expression is evaluated left to right, the final answer becomes 3.
2. However, if the expression is evaluated right to left, the final answer becomes 11. This shows that changing
the sequence in which the operators are evaluated in the given expression also changes the solution.
3. Precedence is the condition that specifies the importance of each operator relative to the other.
Boolean expression: A boolean expression may have only one of two values: True or False.
For example: In the given example comparison operator (==) is used which compares two operands and prints true if
they are equal otherwise print false :
>>> 5 == 5
True #Output
>>> 5 == 6
False #Output
Q5. How memory is managed in Python? Explain PEP 8. Write a Python program to print even length words in a
string.
1. Memory management in Python involves a private heap containing all Python objects and data structures.
2. The management of this private heap is ensured internally by the Python memory manager.
3. The Python memory manager has different components which deal with various dynamic storage
management aspects, like sharing, segmentation, preallocation or caching.
4. At the lowest level, a raw memory allocator ensures that there is enough room in the private heap for storing
all Python-related data by interacting with the memory manager of the operating system.
5. On top of the raw memory allocator, several object-specific allocators operate on the same heap and
implement distinct memory management policies adapted to the peculiarities of every object type.
6. For example, integer objects are managed differently within the heap than strings, tuples or dictionaries
because integers imply different storage requirements and speed/space tradeoffs.
7. Python memory manager thus delegates some of the work to the object-specific allocators, but ensures that
the latter operate within the bounds of the private heap.
PEP 8:
1. A PEP is a design document providing information to the Python community, or describing a new feature for
Python or its processes or environment.
4. PEP 8 is Python’s style guide. It is a set of rules for how to format the Python code to maximize its
readability.
5. A PEP is a design document providing information to the Python community, or describing a new feature for
Python or its processes or environment.
Search
Courses
Code World
Bachelor Exam
Youtube
Table Of Contents
1 Q1. Explain elif statements in Python.ORExplain all the conditional statement in Python using small code example?
2 Q2. Explain expression evaluation and float representation with example. Write a Python program for how to check
if a given number is Fibonacci number.
3 Q3. Explain the purpose and working of loops. Discuss break and continue with examples. Write a Python program
to convert time from 12 hour to 24-hour format.
5 Q5. Write a python program to print the numbers for a user provided range.
1. If statement:
1. An if statement consists of a Boolean expression followed by one or more statements.
2. With an if clause, a condition is provided; if the condition is true then the block of statement written in the if
clause will be executed, otherwise not.
3. Syntax:
If (Boolean expression): Block of code #Set of statements to execute if the condition is true
2. If else statement:
1.An if statement can be followed by an optional else statement, which executes when the Boolean expression is
False.
2. The else condition is used when we have to judge one statement on the
basis of other.
3. Syntax: If (Boolean expression): Block of code #Set of statements to execute – if condition is true
If the condition is true then the statements or program present inside the if block will be executed
If the condition is false then the statements or program present inside else block will be executed.
3.Nested-if statement:
Nested-if statements are nested inside other if statements. That is, a nested-if statement is the body of
another if statement.
We use nested if statements when we need to check secondary conditions only if the fist condition executes
as true.
4. Elif statement:
1. Elif stands for else if in Python.
2. We use elif statements when we need to check multiple conditions only if the given if condition executes as
false.
1. If the first if condition is true, the program will execute the body of the if statement. Otherwise, the
program will go to the elif block (else if in Python) which basically checks for another if statement.
2. Again, if the condition is true, the program will execute the body of the elif statement, and if the
condition is found to be false, the program will go to the next else block and execute the body of the
else block.
4. Syntax
Q2. Explain expression evaluation and float representation with example. Write a Python program for how to
check if a given number is Fibonacci number.
Expression evaluation,
Statement execution.
The key difference between these two forms is that expression evaluation returns a value whereas statement
execution does not return any value.
A Python program contains one or more statements. A statement contains zero or more expressions.
Python evaluates an expression by evaluating the sub-expressions and substituting their values.
For example:
An expression is not always a mathematical expression in Python. A value by itself is a simple expression, and
so is a variable.
In the given example, we assigned a value “Hello Python” to the variable program. Now, when we type only
program, we get the output ‘Hello Python’. This is the term we typed when we assigned a value to the
variable. When we use a print statement with program it gives the value of the variable i.e., the value after
removing quotes.
Float representation:
3. Float is used to represent real numbers and is written with a decimal point dividing the integer and fractional
parts.
4. For example: 97.98, 32.3+e18, -32.54e100 all are floating point numbers.
5. Python float values are represented as 64-bit double-precision values. The maximum value any floating-point
number can be is approx 1.8 × 10308
6. Any number greater than this will be indicated by the string inf in Python.
8. For example, the decimal fraction 0.125 has value 1/10+2/100+ 5/1000, and in the same way the binary
fraction 0.001 has value 0/2 + 0/4 + 1/8.
9. For example: # Python code to demonstrate float values.
Program:
Q3. Explain the purpose and working of loops. Discuss break and continue with examples. Write a Python program
to convert time from 12 hour to 24-hour format.
Ans.
A loop is a programming structure that repeats a sequence of instructions until a specific condition is met.
a. For
b. While
C.Nested
Python programming language provides following types of loops to handle looping requirements:
Purpose: The purpose of loops is to repeat the same, or similar, code a number of times. This number of
times could be specified to a certain number, or the number of times could be dictated by a certain condition
being met.
In the flow chart if the test condition is true, then the loop is executed, and if it is false then the
execution breaks out of the loop.
After the loop is successfully executed the execution again starts from the loop entry and again
checks for the test condition, and this keeps on repeating until the condition is false.
Break statement:
The break keyword terminates the loop and transfers the control to the end of the loop.
While loops, for loops can also be prematurely terminated using the break statement.
The break statement exits from the loop and transfers the execution from the loop to the statement that is
immediately following the loop.
For example:
Continue statement:
The continue statement causes execution to immediately continue at the start of the loop, it skips the
execution of the remaining body part of the loop.
The continue keyword terminates the ongoing iteration and transfers the control to the top of the loop and
the loop condition is evaluated again. If the condition is true, then the next iteration takes place.
Just as with while loops, the continue statement can also be used in Python for loops
For Example:
Output
2
4
6
8
Program:
Q4. Differentiate between for and while loop.
Ans.
The ‘For’ loop is used only when we already knew The ‘while’ loop is used only when the number of iterati
Use
the number of iterations exactly known.
If the condition is not given in the ‘for’ loop then If the condition is not given in the ‘while’ loop, it provide
Condition
the loop iterates infinite times. compilation error.
Initializatio In ‘for’ loop the initialization once done is never In the ‘while’ loop if initialization is done during conditio
n repeated. then initialization is done each time the loop iterates.
Q5. Write a python program to print the numbers for a user provided range.
Ans.
Unit3-FUNCTION AND STRINGS | Python programming Important Question with solution
Table Of Contents
1 Q1. Explain unpacking sequences, and mutable sequences, and list comprehension with examples. Write a program
to sort the list of dictionaries by values in Python – Using the lambda function.
2 Q2. Explain higher order function with respect to lambda expression. Write a Python code to count occurrences of
an element in a list
4 Q4. What do you mean by sets? Explain the operations performed on sets.
5 Q5. Define tuples. How are tuples created in Python?
Q1. Explain unpacking sequences, and mutable sequences, and list comprehension with examples. Write a
program to sort the list of dictionaries by values in Python – Using the lambda function.
Ans.
Unpacking sequences:
Unpacking allows us to extract the components of the sequence into individual variables.
We have multiple assignments in Python where we can have multiple LHS assigned from corresponding
values at the RHS. This is an example of unpacking sequences.
There is one restriction, the LHS and RHS must have equal length. That is, every value that is created at RHS
should be assigned to LHS.
Strings and tuples are examples of sequences. Operations applicable on sequences are: Indexing, repetition,
concatenation.
Since strings are also sequences, we can also get individual characters in the string using unpacking
operation.
Mutable sequences:
1. Python represents all its data as objects. Mutability of object is determined by its type.
2. Some of these objects like lists and dictionaries are mutable, meaning we can change their content without
changing their identity.
3. Other objects like integers, floats, strings and tuples are immutable, meaning we cannot change their
contents.
4. Dictionaries are mutable in Python :
3. If the key is present in the dictionary, then the associated value with that key is updated or changed;
otherwise a new key: value pair is added.
For example:
4. In the given example, we tried to reassign the value ’30’ to the key ‘age’, Python interpreter first searches the
key in the dictionary and then updates it. Hence, the value of ‘age’ is updated to 30. However, in the next
statement, it does not find the key ‘address’; hence, the key: value ‘address’: ‘Alaska’ is added to the
dictionary.
1. String are immutable which means that we cannot change any element of a string.
3. For example:
4.
5. Output:
In the given example, we cut the slice from the original string and concatenate it with the character we want to insert
in the string. It does not have any effect on the original string.
2. The elements of the list are accessible with their index value.
3. The index always starts with 0 and ends with n – 1, if the list contains n elements.
4. The syntax for accessing the elements of a list is the same as in the case of a string. We use square
brackets around the variable and index number.
5. For example:
In the given example, we access the 2nd element of the list that has 1 as index number and the
interpreter prints 20.
Now, if we want to change a value in the list given in the example:
List comprehension :
3. Using list comprehension, we can replace the loop with a single expression that produces the same result.
5. Set builder notation is a notation is a mathematical notation for describing a set by stating the property that
its members should satisfy. The syntax is
6. In the given example, the output for both without list comprehension and using list comprehension is the
same.
7. The use of list comprehension requires lesser code and also runs faster.
1. An input sequence
3. An optional expression
Ans.
2. Lambda definition does not include a “return” statement, it always contains an expression which is returned.
3. We can also put a lambda definition anywhere a function is expected, and we do not have to assign it to a
variable at all.
4. Lambda functions can be used along with built-in higher order functions like filter(), map() and reduce().
2. This function helps to filter out all the elements of a sequence “sequence”, for which the function returns
true.
1. For example: Python program that returns the odd numbers from an input list:
2. The function is called with a lambda function and a list and a new reduced result is returned. This performs a
repetitive operation over the pairs of the list.
For example:
Here the results of previous two elements are added to the next element and this goes on till the end of the list like
(((((5+8)+10)+20)+50)+100).
Ans.
2. The anonymous functions are the functions created using a lambda keyword.
3. They are not defined by using the def keyword. For this reason, they are called anonymous functions.
4. We can pass any number of arguments to a lambda form functions, but still they return only one value in the
form of expression.
5. An anonymous function cannot directly call print command as the lambda needs an expression.
6. It cannot access the parameters that are not defined in its own namespace.
8. Syntax :
9. In the given example, the lambda function is defined with two arguments vall and val2. The expression
val1*va12 does the multiplication of the two values. Now, in function call, we can directly call the mult
function with two valid values as arguments and produce the output as shown in given example.
Q4. What do you mean by sets? Explain the operations performed on sets.
Ans.
1. In Python we also have one data type which is an unordered collection of data known as set.
i.Union: Union operation performed on two sets returns all the elements from both the sets. It is performed
by using and operator.
ii. Intersection: Intersection operation performed on two sets returns all the elements which are common or
in both the sets. It is performed by using ‘|’ operator.
iii. Difference: Difference operation performed on two sets set1 and set2 returns the elements which are
present on set1 but not in set2. It is performed by using the ‘-‘ operator.
iv. Symmetric difference: Symmetric difference operation performed on two sets returns the element which
are present in either set1 or set2 but not in both. It is performed by using an operator.
Ans.
1. Tuples are the sequence or series values of different types separated by commas (,).
2. Values in tuples can also be accessed by their index values, which are integers starting from 0.
For example:
>>> months = (‘January’, February’, March’, April’, ‘May’, ‘June’, ‘July’, ‘August’, ‘September’, ‘October’, ‘November’,
‘December’)
1. To create a tuple, all the items or elements are placed inside parentheses separated by commas and assigned to a
variable.
2. Tuples can have any number of different data items (that is, integer, float, string, list, etc.).
For examples:
(4, 2, 9, 1) # Output
>>>print tuple_mix
3. Nested tuple:
>>>print tuple
UNIT-4: SIEVE OF ERATOSTHENES & FILE I/O | Python programming Important questions with solution
Table Of Contents
1 Q1. Discuss file I/O in Python. How to perform open, read, write, and close into a file? Write a Python program to
read a file line-by-line store it into a variable.
Q1. Discuss file I/O in Python. How to perform open, read, write, and close into a file? Write a Python program to
read a file line-by-line store it into a variable.
Ans.
File I/O:
3. The files are used to store data permanently on to a non-volatile memory (such as hard disks).
4. As we know, the Random Access Memory (RAM) is a volatile memory type because the data in it is lost when
we turn off the computer. Hence, we use files for storing of useful information or data for future reference.
1. Python has a built-in open() function to open files from the directory.
2. Two arguments that are mainly needed by the open() function are:
1. File name: It contains a string type value containing the name of the file which we want to access.
2. Access_mode: The value of access_mode specifies the mode in which we want to open the file, i.e.,
read, write, append etc.
3. Syntax:
1.
1. When the operations that are to be performed on an opened file are finished, we have to close the file in
order to release the resources.
2. Python comes with a garbage collector responsible for cleaning up the unreferenced objects from the
memory, we must not rely on it to close a file.
3. Proper closing of a file frees up the resources held with the file.
1. After opening a file, we have to perform some operations on the file. Here we will perform the write
operation.
2. In order to write into a file, we have to open it with w mode or a mode, on any writing-enabling mode.
3. We should be careful when using the w mode because in this mode overwriting persists in case the file
already exists.
4. For example:
The given example creates a file named test.txt if it does not exist, and overwrites into it if it exists. If we
open the file, we will find the following content in it.
Output:
Writing to the file line 1
Writing to the file line 2
Writing to the file line 3
Writing to the file line 4
1. In order to read from a file, we must open the file in the reading mode (r mode).
2. We can use read (size) method to read the data specified by size.
4. The read() method enables us to read the strings from an opened file.
5. Syntax :
file object. read ([size])
For example:
# open the file
handle exceptions with try-finally? Explain five built-in exceptions with example?
Ans.
Exception:
1. While writing a program, we often end up making some errors. There are many types of error that can occur
in a program.
2. The error caused by writing an improper syntax is termed syntax error or parsing error; these are also called
compile time errors.
3. Errors can also occur at runtime and these runtime errors are known as exceptions.
5. For example, when a file we try to open does not exist, we get a FileNotFoundError. When a division by zero
happens, we get a ZeroDivisionError. When the module we are trying to import does not exist, we get an
ImportError.
6. Python creates an exception object for every occurrence of these run- time errors.
7. The user must write a piece of code that can handle the error.
8. If it is not capable of handling the error, the program prints a trace back to that error along with the details of
why the error has occurred.
Assertions:
1. An assertion is a sanity-check that we can turn on or turn off when we are done with our testing of the
program. An expression is tested, and if the result is false, an exception is raised.
3. Programmers often place assertions at the start of a function to check for valid input, and after a function call
to check for valid output.
6. If the assertion fails, Python uses ArgumentExpression as the argument for the AssertionError.
Handle exceptions:
1. Whenever an exception occurs in Python, it stops the current process and passes it to the calling process
until it is handled.
2. If there is no piece of code in our program that can handle the exception, then the program will crash.
3. For example, assume that a function X calls the function Y, which in turn calls the function Z, and an
exception occurs in Z. If this exception is not handled in Z itself, then the exception is passed to Y and then to
X. If this exception is not handled, then an error message will be displayed and our program will suddenly
halt.
1. Try…except:
2. An operation in the program that can cause the exception is placed in the try clause while
the block of code that handles the exception is placed in the except clause.
3. The block of code for handling the exception is written by the user and it is for him to decide
which operation he wants to perform after the exception has been identified.
4. Syntax:
2. Try finally :
1. The try statement in Python has an optional finally clause that can be associated with it.
2. The statements written in the finally clause will always be executed by the interpreter,
whether the try statement raises an exception or not.
3. With the try clause, we can use either except or finally, but not both.
4. We cannot use the else clause along with the final clause.
1. exception LookupError: This is the base class for those exceptions that are raised when a key or index used
on a mapping or sequence is invalid or not found. The exceptions raised are:
1. KeyError
2. IndexError
2. TypeError: TypeError is thrown when an operation or function is applied to an object of an inappropriate
type.
3. exception ArithmeticError: This class is the base class for those built-in exceptions that are raised for various
arithmetic errors such as:
1. OverflowError
2. ZeroDivisionError
3. Floating PointError
4. For example:
5. exception AttributeError: An AttributeError is raised when an attribute reference or assignment fails such as
when a non-existent attribute is referenced.
Ans.
Class:
1. A class can be defined as a blue print or a previously defined structure from which objects are made.
2. Classes are defined by the user; the class provides the basic structure for an object.
3. It consists of data members and method members that are used by the instances of the class.
6. For example: Fruit is a class, and apple, mango and banana are its objects. Attribute of these objects are
color, taste, etc.
In the given example, we have created a class Student that contains two methods: fill_details and print_details. The
first method fill_details takes four arguments: self, name, branch and year. The second method print_details takes
exactly one argument: self.
Objects:
4. The syntax of creating an object in Python is similar to that for calling a function.
5. Syntax :
obj_name = class_name()
For example:
s1 = Student ()
In the given example, Python will create an object s1 of the class student.
Q4. Explain data encapsulation with example.
Ans.
1. In Python programming language, encapsulation is a process to restrict the access of data members. This
means that the internal details of an object may not be visible from outside of the object definition.
2. The members in a class can be assigned in three ways i.e., public, protected and private.
_varname Protected They are like the public member buy they cannot be directly accessed from outside
__varname Private They cannot be seen and accessed from outside the class
Q5. What do you mean by multiple inheritance? Explain in detail.
Ans.
1. In multiple inheritance, a subclass is derived from more than one base class.
Table Of Contents
1 Q1. Explain Tower of Hanoi problem in detail OR Explain iterator. Write a program to demonstrate the Tower of
Hanoi using function.
2 Q2.Differentiate between recursion and iteration. OR Discuss and differentiate iterators and recursion. Write a
program for recursive Fibonacci series.
4 Q4. Discuss sorting and merging. Explain different types of sorting with example. Write a Python program for Sieve
of Eratosthenes.]
Q1. Explain Tower of Hanoi problem in detail OR Explain iterator. Write a program to demonstrate the Tower of
Hanoi using function.
Ans.
Iterator:
2. An iterator is an object that can be iterated upon, meaning that we can traverse through all the values.
3. Python iterator, implicitly implemented in constructs like for-loops, comprehensions, and python generators.
4. Python lists, tuples, dictionary and sets are all examples of in-built iterators.
1. __iter: This method is called on initialization of an iterator. This should return an object that has a
next() method.
2. next() (or_next_): The iterator next method should return the next value for the iterable. When an
iterator is used with a ‘for in’ loop, the for loop implicitly calls next() on the iterator object. This
method should raise a StopIteration to signal the end of the iteration.
3. For example:
1. Tower of Hanoi is a mathematical puzzle which consists of three rods and a number of disks of different sizes,
which can slide onto any rod.
2. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top,
thus making a conical shape.
3. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:
2. Each move consists of taking the upper disk from one of the stacks and placing it on top of another
stack.
4.
Q2.Differentiate between recursion and iteration. OR Discuss and differentiate iterators and recursion. Write a
program for recursive Fibonacci series.
Ans.
Used when code size need to be small and time complexity is Used when time complexity needs to be
Usage
not an issue against an expanded code size
The stack is used to store the set of new local variables and
Stack Does not use stack
parameters each time the function is called.
Overhead Recursion possesses the overhead of repeated function calls No overhead of repeated function call
Answer
3. Recursion is the property how we write a function. A function which performs the same task can be written
either in a recursive form or in an iterative form.
5. For example:
Q4. Discuss sorting and merging. Explain different types of sorting with example. Write a Python program for Sieve
of Eratosthenes.]
Ans.
Sorting:
3. The importance of sorting lies in the fact that data searching can be optimized to a very high level, if data is
stored in a sorted manner.
Merging:
1. Merging is defined as the process of creating a sorted list/array of data items from two other sorted array/list
of data items.
2. Merge list means to merge two sorted list into one list.
a=[ ]
c=[ ]
Different types of sorting are:
Bubble sort: It is a comparison-based algorithm in which each pair of adjacent elements is compared and the
elements are swapped if they are not in order.
Merge sort:
Merge sort is a divide and conquer algorithm. It divides input array in two halves, calls itself for the
two halves and then merges the two sorted halves.
The merge(arr, l, m, r) is key process that assumes that arr[l..m] and arr[m+1..r] are sorted and
merges the two sorted sub-arrays into one.
Selection sort:
The selection sort algorithm sorts an array by repeatedly finding the smallest element (considering
ascending order) from unsorted list and swapping it with the first element of the list.
In every iteration of selection sort, the smallest element from the unsorted sub-array is picked and
moved to the sorted sub-array.
Python also supports higher order functions, meaning that functions can accept other functions as
arguments and return functions to the caller.
In order to defined non-default sorting in Python, both the sorted() function and .sort()
method accept a key argument.
The value passed to this argument needs to be a function object that returns the sorting key
for any item in the list or iterable.
For example: Consider the given list of tuples, Python will sort by default on the first value in each
tuple. In order to sort on a different element from each tuple, a function can be passed that returns
that element.
Insertion sort:
Insertion sort involves finding the right place for a given element in a sorted list. So in beginning we
compare the first two elements and sort them by comparing them.
Then we pick the third element and find its proper position among the previous two sorted
elements.
This way we gradually go on adding more elements to the already sorted list by putting them in their
proper position.
Program:
Q5. Discuss binary search in Python.
Ans.
1. Binary search follows a divide and conquer approach. It is faster than linear search but requires that the array
be sorted before the algorithm is executed.
2. Binary search looks for a particular item by comparing the middle most item of the collection. If a match
occurs, then the index of item is returned.
3. If the middle item is greater than the item, then the item is searched in the sub-array to the left of the middle
item.
4. Otherwise, the item is searched for in the sub-array to the right of the middle item.
5. This process continues on the sub-array as well until the size of the sub-array reduces to zero.
6. Code:
Table Of Contents
1. Python’s programming cycle is dramatically shorter than that of traditional programming Cycle.
3. Python programs simply import modules at runtime and use the objects they contain. Because of this,
Python programs run immediately after changes are made.
4. In cases where dynamic module reloading can be used, it is even possible to change and reload parts of a
running program without stopping it at all.
5. Since Python is interpreted, there is a rapid turnaround after program changes. And because Python’s parser
is embedded in Python-based systems, it is easy to modify programs at runtime.
6. Fig. 1.1.1 shows Python’s impact on the programming cycle. Python’s programming cycle
def cube(x):
return x * x * x
× = cube(3)
print(x)
Ans. Output: 27
Qd. How do we define an Interface for an ADT? OR Explain ADT interface in Python programming?
Ans:
1. ADT only defines as what operations are to be performed but not how these operations will be implemented.
2. It does not specify how data will be organized in memory and what algorithms will be used for implementing
the operations.
4. The process of providing only the essentials and hiding the details is known as abstraction.
5. The user of data type does not need to know how that data type is implemented, for example, we have been
using primitive values like int, float, char data types only with the knowledge that these data type can
operate and be performed on without any idea of how they are implemented.
6. So, a user only needs to know what a data type can do, but not how it will be implemented.
Qe. How do you perform a search in Python?
1. Linear search
2. Binary search
Ans:
1. IDE is a software package that consists of several tools for developing and testing the software.
1. PyCharm: PyCharm assists the developers to be more productive and provides smart suggestions. It saves
time by taking care of routine tasks, hence increases productivity.
1. Features of PyCharm:
1. It has smart code navigation, good code editor, a function for quick refactoring.
2. The integrated activities with PyCharm are profiling, testing, debugging, remote
development, and deployments.
3. PyCharm supports Python web development frameworks, Angular JS, JavaScript, CSS, HTML
and live editing functions.
2. Spyder: Spyder is widely used for data science works. It is mostly used to create a secure and scientific
environment for Python. Spyder Python uses PyQt (Python plug-in) which a developer can add as an
extension.
1. Features of Spyder:
3. PyDev: It is an external plug-in for Eclipse and is very popular as a Python interpreter.
1. Features of PyDev:
1. PyDev has strong parameters like refactoring, debugging, type hinting, code analysis, and
code coverage function.
2. PyDev supports tokens browser, PyLint integration, interactive console, remote debugger,
Unittest integration, etc.
1. IDLE Python is a cross-platform IDE, hence it increases the flexibility for users.
3. GUI toolkit.
4. The feature of multi-window text editor in IDLE has some great functions like smart indentation, call
tips, Python colorizing, and undo option.
5. It also comes with a strong debugger along with continuous breakpoints, local spaces, and global
view.
5. Visual studio: It enables development for various platforms and has its own marketplace for extensions.
2. It has both paid and free versions in the market with great features.
Qb. How can you randomize the items of a list in place in Python ?
Ans: The method shuffle() can be used to randomize the items of a list in place However, this function is not
accessible directly and therefore we need to import or call this function using a random static object.
Here. ‘list name’ is passed as a parameter which could be a list or tuple. The shuffle() returns a reshuffled list of
items.
For example:
import random
random.shuffle(list)
Output :
Ans:
1. Tuples are the sequence or series values of different types separated by commas (,).
2. Values in tuples can also be accessed by their index values, which are integers starting from 0.
For example:
1. To create a tuple, all the items or elements are placed inside parentheses separated by commas and assigned
to a variable.
2. Tuples can have any number of different data items (that is, integer, float, string, list, etc.).
For examples:
(4, 2, 9, 1) # Output
>>>print tuple_mix
3. Nested tuple:
>>>print tuple
(4.9, 6, house’)
# Output
Unpacking sequences:
1. Unpacking allows to extract the components of the sequence into individual variables.
4. There is one restriction, the LHS and RHS must have equal length. That is, every value that is created at RHS
should be assigned to LHS.
5. Strings and tuples are example of sequences. Operations applicable on sequences are: Indexing, repetition,
concatenation.
For example:
>>> student
>>> name
Output: Aditya
>>> roll
27
>>> redcourse
6. Since strings are also sequences, we can also get individual characters in the string using unpacking
operation.
For example:
Abha
Qd. What are file input and output operations in Python Programming?
A. Open operation:
1. Python has a built-in open () function to open files from the directory.
2. Two arguments that are mainly needed by the open () function are:.
1. File name: It contains a string type value containing the name of the file which we want to access.
2. Access_mode: The value of access_mode specifies the mode in which we want to open the file, i.e.,
read, write, append etc.
3. Syntax:
For example:
>>>f
#Output
B. Close operation:
1. ‘When the operations that are to be performed on an opened file are finished, we have to close the file in
order to release the resources.
2. Python comes with a garbage collector responsible for cleaning up the unreferenced objects from the
memory, we must not rely on it to close a file.
3. Proper closing of a file frees up the resources held with the file.
5. Syntax:
fileObject. close ()
For example:
# open a file
C. Write operation :
1. After opening a file, we have to perform some operations on the file. Here we will perform the write
operation.
2. In order to write into a file, we have to open it with w mode or a mode, on any writing-enabling mode.
3. We should be careful when using the w mode because in this mode overwriting persists in case the file
already exists.
For example:
>>> f.close ()
The given example creates a file named test. txt if it does not exist, and overwrites into it if it exists. If we open the
file, we will find the following content in it.
Output :
D. Read operation:
1. In order to read from a file, we must open the file in the reading mode (r mode).
2. We can use the read (size) method to read the data specified by size.
4. The read() method enables us to read the strings from an opened file.
5. Syntax:
For example:
‘writing’ # Output
# Output
Qe. Solve the Tower of Hanoi problem for n= 3 disk and show all the steps.
Ans: Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to
move the entire stack to another rod, obeying the following rules:
Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e.,
a disk can only be moved if it is the uppermost disk on a stack.
Ans.
1. The selection sort algorithm sorts an array by repeatedly finding the smallest element (considering ascending
order) from an unsorted list and swapping it with the first element of the list.
4. Code:
Def slectionSort(nlist):
maxpos = 0
maxpos = location
nlist[fillslot] = nlist[maxpos]
nlist = [14, 46, 43, 27, 57, 41, 45, 21, 70]
selectionSort(nlist)
print (nlist)
Output :
Output : [14, 21, 27, 41, 43, 45, 46, 57, 70]
5. Time complexity:
Ans. 1. Python is called an interpreted language because it goes through an interpreter, which turns code we write
into the language understood by computer’s processor.
2. Python is an interpreted language, which means the source code of a Python program is converted into bytecode
that is then executed by the Python virtual machine.
a. Python code is fast to develop: As the code is not needed to be compiled and built, Python code can be readily
changed and executed .This makes for a fast development cycle.
b. Python code is not as fast in execution: Since the code is not directly compiled and executed and an additional
layer of the Python virtual machine is responsible for execution, Python code runs a little slow as compared to
conventional languages like C, C++, etc.
4a. Write a Python program to construct the following pattern, using a nested for loop.
*
**
***
****
*****
****
***
**
Ans. Program :
n=5
for i in range(n):
print(“*”,end=””)
print()
print(“*”,end=””)
print()
>>> number = int (input ("Enter the value for × (where x > 2) ?")
>>> x1 = 0
>>> x2 = 1
>>> count = 2
elif numbers == 1:
print (x1)
else:
xth = x1 + x2
print (xth)
#update values
xl = x2
×2 = xth
count + = 1
Output :
Fibonacci sequence:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34
5a. Write a Python program to change a given string to a new string where the first and last chars have been
exchanged.
Ans:
defchange_sring(str1):
print(change_sring(abed’))
Output : dbca
1. To create a tuple, all the items or elements are placed inside parentheses separated by commas and assigned
to a variable.
2. Tuples can have any number of different data items (that is, integer, float, string, list, etc.).
For examples:
3. Nested tuple:
>>>print nested_tuple
Ans.
Create a Module:To create a module just save the code we want in a file with the file extension .py.
For example:
print(“Hello,” + name)
Importing a module: Now we can use the newly created module or built-in module, by using the import statement:
For example:
Import the module named mymodule, and call the greeting function:
importmymodule
mymodule.greeting(“Aditya Kumar”)
Ans:
1. Sieve of Eratosthenes is a simple and ingenious ancient algorithm for finding all prime numbers up to any
given limit.
2. It does so by iteratively marking as composite (i.e., not prime) the multiples of each prime, starting with the
first prime number, 2.
3. The multiples of a given prime are generated as a sequence of numbers starting from that prime, with
constant difference between them that is equal to that prime.
4. Following is the algorithm to find all the prime numbers less than or equal to a given integer n by
Eratosthenes’ method:
4. Find the first number greater than p in the list that is not marked. If there was no such number, stop.
Otherwise, let p now equal this number (which is the next prime), and repeat from step c.
7a. Write a Recursive function in python Binary Search (Arr, I, R, X to search the given element X to be searched
from the List Arr having R elements, where 1 represent lower bound and R represents the upper bound.
Ans:
1. Binary search follows a divide and conquer approach. It is faster than linear search but requires that the array
be sorted before the algorithm is executed.
2. Binary search looks for a particular item by comparing the middle most item of the collection. If a match
occurs, then the index of item is returned.
3. If the middle item is greater than the item, then the item is searched in the sub-array to the left of the middle
item.
4. Otherwise, the item is searched for in the sub-array to the right of the middle item.
5. This process continues on the sub-array as well until the size of the sub-array reduces to zero.
6. Code:
def binarysearch(arr, 1, r, x) :
while 1 <=r:
mid = 1 + (r - 1)/2;
if arr [mid] == x:
return mid
1= mid + 1
else:
r = mid - 1
return - 1
# Test array
X = 10
# Function call
else:
Output:
7b. Explain the terms Merge List and Merge Sort in Python Programming.
Ans.
Merge List:
1. Merging is defined as the process of creating a sorted list/array of data items from two other sorted array/list of
data items.
2. Merge list means to merge two sorted list into one list.
a=[]
c=[]
a.append(b)
d=int(input("Enter element:"))
c.append(d)
new=a+c
new.sort()
Merge Sort :
1. Merge sort is a divide and conquer algorithm. It divides input array in two halves, calls itself for the two
halves and then merges the two sorted halves.
3. The merge(arr, I, m, r) is key process that assumes that arr[l..m] and arr [m + 1 ..r] are sorted and merges the
two sorted sub-arrays into one.
4. Code:
5.Time Complexity
Recurrence relation of merge sort is given by
k = log2n
Time complexity of Merge sort is On log n) in all three cases (worst, average and best) as merge sort always divides
the array into two halves and take linear time to merge two halves.