0% found this document useful (0 votes)
9 views

Univ Impt Flowchart, Algorithm, Programs in Python

This contains important flowcharts programs from problem solving and Python programming subject

Uploaded by

Anisha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Univ Impt Flowchart, Algorithm, Programs in Python

This contains important flowcharts programs from problem solving and Python programming subject

Uploaded by

Anisha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

UNIT 1

1.Explain with an example the basic building blocks of algorithms. (refer notes)
2.Outline the Towers of Hanoi problem. Suggest a solution to the Towers of Hanoi problem with
relevant diagrams. (refer notes)

3. i)Write an algorithm and draw a flowchart to accept three distinct numbers, find
the greatest, and print the result. (5)
ALGORITHM to find the greatest of three numbers:
• Algorithm is a step-by-step instructions to solve a particular problem.

1. Start .
2. Input A,B,C
3.If (A>B) and (A>C) then print “A is greater”.
Else if (B>A) and (B>C) then print “B is greater”.
Else print “C is greater”.
4.Stop

FLOWCHART to find the greatest of three numbers:


• Flowchart is a pictorial representation of an algorithm.
(ii)Write an algorithm and draw a flowchart to find the sum of series
1+2+3+4+5+.......+100.(5)
ALGORITHM to find the sum of series 1+2+3+4+5+.......+100

1.Start
2.Initialize the variables i=1,sum=0
3.Do the following until i<=100:
3(a). Calculate sum=sum+i
3(b) Increment i value by 1(i=i+1)
4.Print the Sum value as the output .
5.Stop

FLOWCHART to find the sum of series 1+2+3+4+5+.......+100


(iii)Write an algorithm to insert card into a list of sorted cards(6)

Insert a Card in a List of Sorted Cards


Algorithm:
Step 1 : Start
Step 2 : Read the list of sorted cards.
Step 3 : If it is the first card, it is already sorted. return 1;
Step 4 : Pick next card
Step 5 : Compare with all cards in the sorted sub-list
Step 6 : Shift all the cards in the sorted sub-list that is greater than the value of the card to be
inserted.
Step 7 : Insert the card
Step 8 : Repeat until list is sorted.
Step 9: Stop

FLOWCHART:
4.i)What is an Algorithm? Summarize the good characteristics of good algorithm. (8)
(refer notes , write at least 10 characteristics )

(ii)Outline the algorithm, Pseudocode, and flowchart for displaying the first n odd numbers(8)
UNIT 2:

1. Explain in detail about operator precedence and associativity with relevant examples.(notes)

2. Explain in detail about the types of operators supported by Python with relevant examples and
code.(notes)

3. (i))Write a Python program to exchange the values of two variables


using a third variable.(4)
Python program to exchange the values of two variables using a third
variable:
Algorithm:
1.Start
2.Get the values of x and y .
3.Print x and y value before swapping process.
4.Introduce a third variable temp.
5.Assign the following for swapping x and y value.
temp =x
x=y
y=temp
6.Print x and y values after swapping process.
7.Stop

#Python program :

x=int(input(“Enter the value of x:”))


y=int(input(“Enter the value of y:”))
print(“Before Swapping x and y:”,x,y)
#swap x and y values using a third variable temp
temp=x
x=y
y=temp
print(“After Swapping x and y:”,x,y)

OUTPUT:

Enter the value of x:3


Enter the value of y:4
Before Swapping x and y: 3 4
After Swapping x and y: 4 3
ii)Write a Python program to exchange the values of two variables
without using a third variable.(4)

Python program to exchange the values of two variables without using


a third variable:
Algorithm:
1.Start
2.Get the values of x and y .
3.Print x and y value before swapping process.
4.Swap a and y value using tuple assignment concept as follows:

x,y=y,x
6.Print x and y values after swapping process.
7.Stop

#Python program :

x=int(input(“Enter the value of x:”))


y=int(input(“Enter the value of y:”))
print(“Before Swapping x and y:”,x,y)
#swap x and y values without using a third variable

x,y=y,x #using tuple assignment concept

print(“After Swapping x and y:”,x,y)

OUTPUT:

Enter the value of x:3


Enter the value of y:4
Before Swapping x and y: 3 4
After Swapping x and y: 4 3
ii)Write a Python program to find the sum of the first n even numbers
and print the result. (8)
Python program to find the sum of the first n even numbers and print
the result:
Algorithm:
1.Start
2.Get the values of n from the user.
3.Initialize the variables, sum=0 ,i=1.
4..Repeat the following until i<=n using for or while loop:
4(a). Add i value to sum only if i is a even number.
if((i % 2) == 0):
sum= sum + i

5.Print the value of sum as a output which returens the sum of the first n even numbers ,
6.Stop

#Python program :

# Take input from user.


n= int(input("Enter the value of n "))

sum = 0

for i in range(1, n + 1):

# Check for even or not.


if((i % 2) == 0):
sum= sum + i

print("\nSum of even numbers from 1 to", n, "is :", sum)

OUTPUT:

Enter the value of n 4


Sum of even numbers from 1 to 4 is : 6

Program Logic:
First, we declare one variable ”sum ”with value 0, and then we are going to use this variable
to store sum of all even numbers between 1 to n. Now after taking input (n) from user, we have to
check if the current variable “i”is even or not inside the loop . If it is even we have to add it to
variable ” sum ” otherwise continue with the loop.
Once the loop is completed we have to print the variable ”sum “containing the sum of all even
numbers up to n.
4. i)Sketch the structures of the interpreter and compiler.Detail the differences between them.
Explain how python works in interactive mode and script mode with examples.(2+2+4)
ii)Outline the data types supported by Python with examples.(8)
(refer notes , write examples)

UNIT 3
1.Outline the iteration statements in Python. Also, explain the working of break,continue and pass
statements in python.(notes , flowchart is must)
2. Outline the conditional branching statements in Python with examples.(notes,flowchart must))

3. i)Explain the string methods with example.


Python strings are immutable. Justify with an example.(8)
ii)Write a Python code to perform a binary search. Trace it with an example of your choice.(8)
(NOTES)

4. i)Analyse string slicing.Illustrate how it is done in python with example. (8)


ii)Write a Python code to Search a string in a given list.(8) (NOTES)

UNIT 4
1.What is a Python dictionary?Give an example.Appraise the operations for dynamically
manipulating dictionaries.(NOTES)
2. Name the operations that can be performed on a list and outline the same with an example.
(NOTES)
3. i)Write a separate Python program to create, access, concatenate and delete operations in a tuple.
(10)
ii)Write a Python program to create a dictionary and sort the content of a dictionary based on values
in reverse order.(6) (NOTES)

4.Write a Python Program (NOTES)


i)Merge sort
ii)To create a Students marks statement
iii)Retail bill preparation.
UNIT 5
1.Tabulate the different modes for opening a file and explain the same with relevant examples.
(Refer notes and write the below examples )

EXAMPLE 1:

file1 = open("py.txt",”r”) # read in text mode


file1 = open("py.txt",'w') # write in text mode
file1 = open("py.txt",'w+') # write and read in text mode
file1 = open("py.txt",'a') # append in text mode
file1 = open("py.txt",'a+') # write and read in text mode
file1 = open("img.bmp",'r+b') # read and write in binary mode

EXAMPLE 2:

# open a file
file1 = open("py.txt", "r")

# read the file


read_content = file1.read()
print(read_content)

#write the file


file1 = open("py.txt", “w+")
write_content=file1.write(“Python program”) #overwrite the file content
print(write_content)

#write using append mode


file1 = open("py.txt", “w+")
write_content=file1.write(“for everyone”) #add content to the end of file
print(write_content)

file1.close()

Output:

This is a test file.


Hello from the test file.
Python program
Python program for everyone
2.What is an exception?Elaborate exception handling in Python with
relevant Python code. (notes)

3. i)Write a program to concatenate the contents of two files into a single file.
Get the input for two files from the user and concatenate it.(8)
• To merge the content of two files into a third file using a Python program.
Then, first of all, we need to create two files in the current directory, the directory
where the Python source code is saved.

• Therefore, let's create two files namely one.txt and two.txt with
some contents. And a third file named three.txt with or without
any content. Here is the snapshot of the current directory,
along with all these three files, opened:
• Now let's create the program, to merge the content of two text files into the
third. It is not compulsory to create the third file, because while writing the content
using w mode, the file automatically gets created, if not available.
# Python Program to merge two files into a third file:

print("Enter the Name of First File: ", end="")


fileOne = input()
print("Enter the Name of Second File: ", end="")
fileTwo = input()
print("Enter the Name of Third File: ", end="")
fileThree = input()

content = ""
fh = open(fileOne, "r")
for line in fh:
content = content + line + '\n'
fh.close()

fh = open(fileTwo, "r")
for line in fh:
content = content + line + '\n'
fh.close()

fh = open(fileThree, "w")
fh.write(content)

print("\nFile merged successfully!")

SAMPLE OUTPUT:
Three text files, after executing the above program:

ii)Write a program that reads a file and builds a histogram of the


words in the file.(8)

import string

def process_file(filename):
hist = dict()
fp = open(filename)
for line in fp:
process_line(line, hist)
return hist

def process_line(line, hist):


line = line.replace('-', ' ')

for word in line.split():


word = word.strip(string.punctuation + string.whitespace)
word = word.lower()

hist[word] = hist.get(word, 0) + 1
#DRIVER CODE
hist = process_file('python.txt')

This program reads python.txt, which contains the text of Welcome to Python Programming.

2 user defined functions:


• process_file loops through the lines of the file, passing them one at a time to process_line.
The histogram hist is being used as an accumulator.

• process_line uses the string method replace to replace hyphens with spaces before
using split to break the line into a list of strings. It traverses the list of words and uses
strip and lower to remove punctuation and convert to lower case. (It is a shorthand to say
that strings are “converted;” remember that string are immutable, so methods like strip and
lower return new strings.)

Finally, process_line updates the histogram by creating a new item or incrementing an


existing one.

• To count the total number of words in the file, we can add up the frequencies in the
histogram:

def total_words(hist):
return sum(hist.values())

• The number of different words is just the number of items in the dictionary:

def different_words(hist):
return len(hist)

• Here is some code to print the results:

print 'Total number of words:', total_words(hist)


print 'Number of different words:', different_words(hist)
OUTPUT:

Total number of words: 4


Number of different words: 4
4.i)Explain in detail about command line arguments. Write a Python code to
Count the number of words in a Python file using a command line argument. (8)

COMMAND LINE ARGUMENTS


 Command-line arguments are the arguments passed into the program from the
command line.
 While executing the program, command line arguments are given along with
program name.
 In Python, function supporting command line arguments are placed in sys module.
 While using command line arguments, sys module should be imported.
 import sys
 sys.argv is a list in sys module, which contains the command line arguments passed
to the program.
 The number of arguments passed in command line can be counted using built-in
len() function
 Syntax
len(sys.argv)

Program:
To find the occurrence of each word(word count) in a text file using command line
arguments.
wc. py
print("Finding word count using Command line Arguments")
import sys
if len(sys.argv)!=2:
print(' Error:filename missing')
sys.exit()
filename=sys.argv[1]
file=open(filename,"r")
wordcount={}
for word in file.read().split():
if word not in wordcount:
wordcount[word]=1
else:
wordcount[word] += 1
for k,v in wordcount.items():
print (k,v)

sample.txt
This is Python Program
Output:
Open the command prompt(start->cmd).
>python wc.py sample.txt
Finding word count using Command line Arguments
This 1
is 1
Python 1
Program 1
ii)Discuss the use of format operators in file processing.(8) (refer class notes
also)

FORMAT OPERATOR
The write() accept only string as arguments. To give other values in write(), the
values must be converted to string.
i) The built-in function str() is used to convert other values to strings.
Syntax:
fileobject.write(str(variablename))
Example:
>>>fout = open('output.txt', 'w')
>>> x = 52
>>> fout.write(str(x))
ii) Format operator
An alternative is to use the format operator, %.
The first operand contains one or more format sequences, which specify how the
second operand is formatted. The result is a string.
Format sequences
%d - To format an integer
%g - To format a floating point number
%s - To format a string
The format sequence '%d' means that the second operand should be formatted as a
decimal integer.
Example:
>>> x = 15
>>> '%d' % x
'15'
The result is the string '15'.
A format sequence can appear anywhere in the string.
Example:
>>>a=30
>>>print(“The bag contains %d apples”%a)
“The bag contains 30 apples”
If there is more than one format sequence in the string, the second argument has to
be a tuple. Each format sequence is matched with an element of the tuple, in order.

Example:
>>> "Ram scored %g %s in sem %d."%(9.2,"GPA",1)
'Ram scored 9.2 GPA in sem 1.'

You might also like