GE8151 Python Programming - Question Bank and Example Programs

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13
At a glance
Powered by AI
Key takeaways from the document are definitions of algorithms, control flow statements, recursion and examples of programs to find sum, factorial, binary search etc.

An algorithm is a set of steps to solve a problem or achieve a goal. Examples mentioned are algorithms to find sum of two numbers, factorial of a number and convert temperature.

Control flow statements control the order of execution of program like conditional statements(if-else) and loops. If-else statement is given as an example.

GE8151 Problem Solving and Python Programming - 2017 Regulations ()

( www.edunotes.in )

Q.No. Topic Question Answer


An algorithm is a finite sequence of well-
defined, computer-implementable
instructions, typically to solve a class of
1 Algorithm Define Algorithm problems or to perform a computation.
Algorithms re unambiguous specifications
for performing calculation, data processing,
automated reasoning, and other tasks.

A program's control flow is the order in


which the program's code executes. The
control flow of a Python program is
regulated by conditional statements, loops,
Define Control flow and function calls. ... Raising and handling
Control
2 statement with an exceptions also affects control flow;
Flow
example.
Control flow example
if x < 0: print "x is negative"
elif x % 2: print "x is positive and odd"
else: print "x is even and non-negative

A recursive function is a function defined in


terms of itself via self-referential
expressions. This means that the function
will continue to call itself and repeat its
behavior until some condition is met to
return a result.
3 Recursion Define Recursion
def factorial(x):
if x==1:
return 1
else:
return x*factorial(x-1)
f=factorial(5)
print ("factorial of 5 is ",f)
The result is
factorial of 5 is 120

a = int(input("enter first number: "))


Write an algorithm to b = int(input("enter second number: "))
accept two numbers,
4 Procedure
compute the sum = a + b
sum and print the result.
print("sum:", sum)

# Python Program to convert temperature in


celsius to fahrenheit
Develop an algorithm
to convert Temperature
# change this value for a different result
5 Code in Celsius
celsius = 37.5
to Fahrenheit and vice
versa.
# calculate fahrenheit
fahrenheit = (celsius * 1.8) + 32

# Sum of natural numbers up to 50

num = 50

Examine a simple if num < 0:


program print("Enter a positive number")
6 Code to print the integer else:
number sum = 0
from 1 to 50. # use while loop to iterate until zero
while(num > 0):
sum += num
num -= 1
print("The sum is", sum)

Discuss with suitable


examples: def smallest_num_in_list( list ):
i) Find minimum in a min = list[ 0 ]
7 Code
list for a in list:
ii) Find maximum in a if a < min:
list min = a
return min
print(smallest_num_in_list([1, 2, -8, 0]))
Sample Output:
-8
i) Find maximum in a list

def max_num_in_list( list ):


max = list[ 0 ]
for a in list:
if a > max:
max = a
return max
print(max_num_in_list([1, 2, -8, 0]))

Function call with arguments

# A simple Python function to check


# whether x is even or odd
def evenOdd( x ):
if (x % 2 == 0):
print "even"
else:
8 CODE
print "odd"

# Driver code
evenOdd(2)
evenOdd(3)
Output:
even
odd

The special syntax *args in function


definitions in python is used to pass a
variable number of arguments to a
function. It is used to pass a non-
Define the special keyworded, variable-length argument list.
9 CODE syntax *args for passing
arguments • Example for usage of *arg:

# Python program to illustrate


# *args with first extra argument
def myFun(arg1, *argv):
print ("First argument :", arg1)
for arg in argv:
print("Next argument through *argv :", arg)

myFun('Hello', 'Welcome', 'to', 'World of


Python')
Output:
First argument : Hello
Next argument through *argv : Welcome
Next argument through *argv : to
Next argument through *argv : World of
Python

'''Function definition and invocation.'''

def happyBirthdayEmily():
print("Happy Birthday to you!")
What are the two parts
print("Happy Birthday to you!")
10 CODE of function definition.
print("Happy Birthday, dear Emily.")
Give its syntax.
print("Happy Birthday to you!")

happyBirthdayEmily()
happyBirthdayEmily()

'''Function with parameter called in main'''

def happyBirthday(person):
print("Happy Birthday to you!")
print("Happy Birthday to you!")
print("Happy Birthday, dear " + person +
Explain a Python
".")
11 CODE function with arguments
print("Happy Birthday to you!")
with an example.
def main():
happyBirthday('Emily')
happyBirthday('Andre')

main()

Point out the difference Iterative Approach


12 CODE
between recursive and
iterative technique with # iterative Function (Returns the result of:
examples 1 +2+3+4+5+...+n)
def iterativeSum(n):
total=0
for i in range(1,n+1):
total += i
return total
The Recursive Approach
The following code uses a function that
calls itself. This is the main characteristic
of a recursive approach.

# Recursive Function (Returns the result of:


1 +2+3+4+5+...+n)
def recursiveSum(n):
if (n > 1):
return n + recursiveSum(n - 1)
else:
return n

OUTPUT
Using an interative approach
1+2+3+4+...+99+100=
5050

Using a recursive approach


1+2+3+4+...+99+100=
5050

Python *args
Python has *args which allow us to pass
the variable number of non keyword
arguments to function.
Give the syntax for
In the function, we should use an asterisk *
13 CODE variable length
before the parameter name to pass variable
arguments.
length arguments.The arguments are passed
as a tuple and these passed arguments make
tuple inside the function with same name as
the parameter excluding asterisk *.
Example : Using *args to pass the variable
length arguments to the function

1. def adder(*num):
2. sum = 0
3.
4. for n in num:
5. sum = sum + n
6.
7. print("Sum:",sum)
8.
9. adder(3,5)
10. adder(4,5,6,7)
11. adder(1,2,3,5,6)

When we run the above program, the


output will be
Sum: 8
Sum: 22
Sum: 17

append(): Used for appending and adding


elements to List.It is used to add elements
to the last position of List.
Syntax:
list.append (element)

extend(): Adds contents to List2 to the end


of List1.
Syntax:
Differentiate append() List1.extend(List2)
and extend() operations
14 CODE
of a List. Explain with # Adds List Element as value of List.
sntax and examples List = ['Mathematics', 'chemistry', 1997,
2000]
List.append(20544)
print(List)
Output:
['Mathematics', 'chemistry', 1997, 2000,
20544]

List1 = [1, 2, 3]
List2 = [2, 3, 4, 5]
# Add List2 to List1
List1.extend(List2)
print(List1)

#Add List1 to List2 now


List2.extend(List1)
print(List2)
Output:
[1, 2, 3, 2, 3, 4, 5]
[2, 3, 4, 5, 1, 2, 3, 2, 3, 4, 5]

# Python program to get average of a list


# Using reduce() and lambda

# importing reduce()
from functools import reduce

def Average(lst):
return reduce(lambda a, b: a + b, lst) /
i) Write a function which len(lst)
15 CODE returns the average of
given list of numbers # Driver Code
lst = [15, 9, 55, 41, 35, 20, 62, 49]
average = Average(lst)

# Printing average of the list


print("Average of the list =",
round(average, 2))
Output:
Average of the list = 35.75

1. # Python program to swap two variables


ii) Write a Python 2.
16 CODE program to exchange the 3. x = 5
value of two variables 4. y = 10
5.
6. # To take inputs from the user
7. #x = input('Enter value of x: ')
8. #y = input('Enter value of y: ')
9.
10. # create a temporary variable and swap
the values
11. temp = x
12. x = y
13. y = temp
14.
15. print('The value of x after swapping:
{}'.format(x))
16. print('The value of y after swapping:
{}'.format(y))

#sum of Even numbers in python


#Python program to get input n and
calculate the sum of even numbers till n
ii) Write a Python Solution
17 CODE function to find the sum n=int(input("Enter n value:"))
of first ‘n’ even numbers. sum=0
for i in range(2,n+1,2):
sum+=i
print(sum)

>>> languages = ["C", "C++", "Perl",


"Python"]
>>> for x in languages:
... print(x)
Give syntax and an
...
18 CODE example of for loop in
C
Python
C++
Perl
Python
>>>

Write a Python program


to accept two numbers,
19 CODE 1. a = int(input("enter first number: "))
multiply them and print
2. b = int(input("enter second number: "))
the result.
3. result = a * b.
4. print("result :", result)
OUTPUT
enter first number: 4
enter second number: 5
result : 20

We use indices to access elements of an


array:
1. import array as arr
2. a = arr.array('i', [2, 4, 6, 8])
How to access the 3.
elements of an array 4. print("First element:", a[0])
20 CODE using index. 5. print("Second element:", a[1])
How to access array 6. print("Last element:", a[-1])
elements?

OUTPUT
First element: 2
Second element: 4
Last element: 8

The pass Statement:


The pass statement in Python is used when
a statement is required syntactically but
you do not want any command or code to
execute.
The pass statement is a null operation;
nothing happens when it executes. The pass
is also useful in places where your code
What is the use of pass
will eventually go, but has not been written
21 CODE statement? Illustrate with
yet (e.g., in stubs for example):
an example.
Example:
#!/usr/bin/python

for letter in 'Python':


if letter == 'h':
pass
print 'This is pass block'
print 'Current Letter :', letter
print "Good bye!"
OUTPUT
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!

Python Program for Binary Search


(Recursive and Iterative)
We basically ignore half of the elements
just after one comparison.
1. Compare x with the middle element.
2. If x matches with middle element, we
return the mid index.
3. Else If x is greater than the mid element,
then x can only lie in right half subarray
after the mid element. So we recur for right
half.
4. Else (x is smaller) recur for the left half.
Iterative:
Write a program for # Iterative Binary Search Function
22 CODE binary search using # It returns location of x in given array arr
Arrays. if present,
# else returns -1
def binarySearch(arr, l, r, x):

while l <= r:

mid = l + (r - l)/2;

# Check if x is present at mid


if arr[mid] == x:
return mid

# If x is greater, ignore left half


elif arr[mid] < x:
l = mid + 1
# If x is smaller, ignore right half
else:
r = mid - 1

# If we reach here, then the element was


not present
return -1

# Test array
arr = [ 2, 3, 4, 10, 40 ]
x = 10

# Function call
result = binarySearch(arr, 0, len(arr)-1, x)

if result != -1:
print "Element is present at index %d" %
result
else:
print "Element is not present in array"

# Python code to count and display number


of vowels
# Simply using for and comparing it with a
# string containg all vowels
def Check_Vow(string, vowels):
final = [each for each in string if each in
vowels]
Write a Python program
print(len(final))
to count the number of
23 CODE print(final)
vowels in a string
provided by the user.
# Driver Code
string = "I wandered lonely as a cloud"
vowels = "AaeEeIiOoUu"
Check_Vow(string, vowels);
Output:
10
['I', 'a', 'e', 'e', 'o', 'e', 'a', 'a', 'o', 'u']
# Syntax of while Loop in Python

while test_expression:
Body of while

# Example: Python while Loop


# Program to add natural numbers upto n
# sum = 1+2+3+...+n
# To take input from the user,
Write syntax for while # n = int(input("Enter n: "))
24 CODE loop in python and give n = 10
an example # initialize sum and counter
sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
print("The sum is", sum)
OUTPUT
Enter n: 10
The sum is 55

# Python program to check if year is a leap


year or not.

# To get year (integer input) from the user.


year = int(input("Enter a year: "))

if (year % 4) == 0:
Create a Python program if (year % 100) == 0:
25 CODE to find the given year is if (year % 400) == 0:
leap year or not. print("{0} is a leap year". format(year))
if (year % 4) is not 0:
print("{0} is NOT a leap year".
format(year))

OUTPUT
Enter a year: 2019
2019 is NOT a leap year
Enter a year: 2000
2000 is a leap year

You might also like