Ge3151 16marks QB
Ge3151 16marks QB
Ge3151 16marks QB
UNIT I
PART B (16 MARKS)
1 The process is repeated until the The function calls itself until the base condition is
condition fails. satisfied.
3 It is faster It is slower
factorial(n)
Step 1: Initialize f=1,i=1
Step 2: Repeat step 2.1 and 2.2 until i<=nStep
2.1: f= f*i
Step 2.2: Increment i by 1 (i=i+1)
Step 3: Return f
factorial(n)
Step 1: If n==1 then return 1
Step 2: Else
f=n*factorial(n-1)
Step 3: Return f
Algorithm:
Step 1: Start
Step 2: Initialize the value of result, r=1.
Step 3: Repeat step4 for 4 times
Step 4: calculate r=r*2
Step 5: Print the value of r
Step 6: Stop
Flowchart:
ENDFOR
SET maximum = numlist[0]FOR i in
numlist
IF (n > maximum)
maximum = n
ENDIF
ENDFOR
PRINT maximum
END
Pseudocode
START
Procedure Hanoi(disk, source, dest, aux)
IF disk = = 0, THEN
move disk from source to dest
ELSE
Hanoi(disk - 1, source, aux, dest)
move disk from source to dest
Hanoi(disk - 1, aux, dest, source)
END IF
END Procedure
6. a) What is flowchart?
Flowchart is a diagrammatic representation of the logic for solving a task. A flowchart is drawn using
boxes of different shapes with lines connecting them to show the flow of control. Thepurpose of drawing a
flowchart is to make the logic of the program clearer in a visual form.
b) List down symbols and rules for writing flowchart.
c) Draw a flowchart to count and print from1 to 10.
7. a) Write an algorithm and give the flowchart to find the net salary of an employee.
Algorithm:
Step 1: Start
Step 2 : Read the basic salary
Step 3 : IF the basic is greater than or equal to 4000 ELSE Goto Step 4
Step 3.1 : DA= 0.32 * basic (Dearness Allowance)
Step 3.2: HRA= 0.15*basic (House Rent Allowance)
Step 3.3: CCA = 325 (City Compensatory Allowance)
Step 3.4: Net Salary = basic+DA+HRA+CCA
Step 4 : Print the Net Salary
Step 5 : Stop
b) Write an algorithm and give the pseudo code to guess an integer number in a range.
Algorithm:
step 1: Start the program
step 2: Read an 'n' number
step 3: Read an Guess number
step 4: if Guess> n; print "Your Guess too high"
Step 5: elif Guess <n ; print "Your Guess too low"
step 6: elif Guess = = n; print "Good job"
Step 7: else print"Nope "
Step :8 Stop the program
Pseudocode: BEGIN
READ n
READ
Guess = 20
IF Guess> n
print"Your Guess too High" elif Guess< n
print "Your Guess too low" elif Guess = = 20
print "Good Job"
ELSE
print"Nope"
8. a) Write an algorithm to insert a card in a list of sorted cards.
ALGORITHM:
Step 1: Start
Step 2: Declare the variables N, List[],I and X
Step 3: READ Number of element in sorted list as N
Step 4: SET i=0
Step 5: IF i<N THEN go to step 6 ELSE go to step 9
Step 6: READ Sorted list element as List[i]
Step 7: i=i+1
Step 8: go to step 5
Step 9: READ Element to be insert as X
Step 10: SET i=N-1
Step 11: IF i>0 AND X<List[i] THEN go to step 12 ELSE go to step 15
Step 13: i=i-1
Step 14: go to step 11
Step 15: List[i+1]=X
Step 16: Stop
b) Write an algorithm to find the minimum number in a list.
Algorithm:
Step 1 : Start
Step 2 : Initialize the value of minimum = 0
Step 3 : Enter the input number (n) of items in a list.
Step 4 : Get all the elements using for loop and store it in a list.
Step 5: Assign the first element in a list as minimum.
Step 6: Compare maximum with the first element in a list,n.
Step 7: Repeat step 8,9 until list becomes empty.
Step 8 : If n is less than the minimum
Step 9 : Assign minimum = n
Step 10 : Displa y minimum
Pseudocode:
BEGIN
SET numlist=[ ]
GET n
FOR i=1 to n
GET numlist elements
ENDFOR
SET minimum = numlist[0]FOR i in
numlist
IF (n < minimum)
minimum = n
END IFEND
FOR
PRINT minimum
END
UNIT II
PART B (16 MARKS)
1. What is the role of an interpreter? Give a detailed note on python interpreter andinteractive mode
of operation.
$ python
>>>
Once the Python interpreter is started, you can issue any command at the command prompt ">>>".For
example,let us print the "Hello World" statement:
>>> print "Hello World"
Hello World
In the interactive Python interpreter the print is not necessary:
2. (a) List down the rules for naming the variable with example.
A variable is a name that refers to a value. An assignment statement creates new variables andgives them
values:
Variable names can be arbitrarily long. They can contain both letters and numbers, but theyhave to
begin with a letter. It is legal to use uppercase letters, but it is a good idea to
begin variable names with a lowercase letter .
The underscore character, _, can appear in a name. It is often used in names with multiplewords, such
as my_name or variable_name.
If you give a variable an illegal name, you get a syntax error:
3. What do you mean by rule of precedence? List out the order of precedence and demonstrate in detail
with example.
When more than one operator appears in an expression, the order of evaluation depends on the rules of
precedence. For mathematical operators, Python follows mathematical convention. The acronym PEMDAS is a
useful way to remember the rules,
• Parentheses have the highest precedence and can be used to force an expression to evaluate in theorder you
want. Since expressions in parentheses are evaluated first,
2 * (3-1) is 4, and (1+1)**(5-2) is 8.
You can also use parentheses to make an expression easier to read, as in (minute * 100) / 60, even ifit doesn’t
change the result.
• Exponentiation has the next highest precedence, so 2**1+1 is 3, not 4 and 3*1**3 is 3, not 27.
• Multiplication and Division have the same precedence, which is higher than Addition and
Subtraction, which also have the same precedence. So 2*3-1 is 5, not 4, and 6+4/2 is 8, not 5.
• Operators with the same precedence are evaluated from left to right (except exponentiation).
So in the expression degrees / 2 * pi, the division happens first and the result is multiplied by pi. Todivide by 2π,
you can use parentheses or write degrees / 2 / pi.
4. Explain the role of function call and function definition with example.
A function is a named sequence of statements that performs a computation. When you define a
function, you specify the name and the sequence of statements. Later, you can “call” the function by
name.
>>> type(32)
<type 'int'>
The name of the function is type. The expression in parentheses is called the argument of the function.
The result, for this function, is the type of the argument. A function “takes” an argument and “returns” a
result. The result is called the return value.
Type conversion functions
Python provides built-in functions that convert values from one type to another. The int function takes any
value and converts it to an integer, if it can, or complains otherwise:
>>> int('32')
32
>>> int('Hello')
int can convert floating-point values to integers, but it doesn’t round off; it chops off thefraction
part:
>>> int(3.99999)3
>>> int(-2.3)
-2
This statement creates a module object named math. If you print the module object, youget some
information about it:
The module object contains the functions and variables defined in the module. To accessone of the
functions,specify the name of the module and the name of the
function, separated by a dot (also known as a period). This format is called dot notation.
>>> ratio = signal_power / noise_power
>>> decibels = 10 * math.log10(ratio)
>>> radians = 0.7
>>> height = math.sin(radians)
The first example uses log10 to compute a signal-to-noise ratio in decibels (assuming that
computes logarithms base e.
The second example finds the sine of radians. The name of the variable is a hint that sin
and the other trigonometric functions (cos, tan, etc.) take arguments in radians. To convertfrom
degrees to radians, divide by 360 and multiply by 2π:
>>> degrees = 45
>>> radians = degrees / 360.0 * 2 * math.pi
>>> math.sin(radians)0.707106781187
The expression math.pi gets the variable pi from the math module. The value of thisvariable is an
approximation of π, accurate to about 15 digits.
7. Write a Python program to check whether a given year is a leap year ornot. #
To get year (integer input) from the user
year = int(input("Enter a year"))
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("%d is a leap year"%year)
else:
print("%d is not a leap year"%d)
else:
print("%d is a leap year"%year)
else:
print("%d is not a leap year"%year)
# calculate Fahrenheit
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit))
The boolean expression after ‘if’ is called the condition. If it is true, then the indented statement gets
executed. If not, nothing happens. if statements have the same structure as function definitions: a header
followed by an indented body. Statements like this are called compound statements. There is no limit on
the number of statements that can appear in the body, but there has to be at least one. Occasionally, it is
useful to have a body with no statements .In that case, you can use the pass statement, which does
nothing.
if x < 0:
pass # need to handle negative values!
Alternative execution (if-else):
A second form of if statement is alternative execution, in which there are two possibilities and the
condition determines which one gets executed. The syntax looks like this:
Eg:
if x%2 == 0:
print 'x is even'
else:
print 'x is odd'
If the remainder when x is divided by 2 is 0, then we know that x is even, and the program displays a message to
that effect. If the condition is false, the second set of statements is executed. Since the condition must be true or
false, exactly one of the alternatives will be executed. The alternatives are called branches, because they are
branches in the flow of execution.
Chained conditionals(if-elif-else):
Sometimes there are more than two possibilities and we need more than two branches. One way to
express a computation like that is a chained conditional:
Eg: if x < y:
print 'x is less than y'elif
x > y:
print 'x is greater than y'
else:
print 'x and y are equal'
elif is an abbreviation of “else if.” Again, exactly one branch will be executed. There is no limit on the
number of elif statements. If there is an else clause, it has to be at the end, but there doesn’t have to be one.
Eg:
if choice == 'a':
draw_a()
approx = 0.5 * n
better = 0.5 * (approx + n/approx)
while better != approx:
approx = better
better = 0.5 * (approx + n/approx)
print(approx)
4. Explain RECURSION.
The process in which a function calls itself directly or indirectly is called recursion and the corresponding
function is called as recursive function. Using recursive algorithm, certain problems can be solved quite
easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree
Traversals, DFS of Graph, etc.
5. Explain string slices and string immutability.
String slices
A segment of a string is called a slice . Selecting a slice is similar to selecting a character:
>>> s ='Monty Python'
>>> print s[0:5]
Monty
>>> print s[6:12]
The operator [n:m]returns the part of the string from the “n-eth” character to the “m-eth” character,
including the first but excluding the last. If you omit the first index (before the colon), the slice starts at the
beginning of the string. If you omit the second index, the slice goes to the end ofthe string:
>>> fruit = 'banana'
>>> fruit[:3]'ban'
>>> fruit[3:]'ana'
If the first index is greater than or equal to the second the result is an empty string, represented by
two quotation marks:
>>> fruit ='banana'
>>> fruit[3:3]
An empty string contains no characters and has length 0, but other than that, it is the same as anyother string.
String immutability.
Python strings are immutable. ‘a’ is not a string. It is a variable with string value. You can’t mutatethe string
but can change what value of the variable to a new string.
Eg:
a = “foo”
# a now points to foob=a
# b now points to the same foo that a points to
a=a+a
# a points to the new string “foofoo”, but b points to the same old “foo”print a
print b
# Output
#foofoo
#foo
It is observed that b hasn’t changed even though ‘a’ has changed the value.
6. Explain string functions and methods.
There are a number of useful operations that can be performed with string. One of the most useful
of these is the function split. This function takes a string (typically a line of input from the user)and splits it
into individual words.
Another useful function is lower, which converts text into lower case.Eg:
>>> line = input(“What is your name?”)
What is your name? Timothy Alan Budd
>>> lowname = line.lower()
>>> print lowname.split()
[‘timothy’, ‘alan’, ‘budd’]
Other useful functions will search a string for a given text value, or strip leading or trailing white space
from a string. An alternative version of split takes as argument the separator string. The string is broken
into a list using the separator as a division. This can be useful, for example, for breaking a file path name
into parts:
Eg:
>>> pathname = ‘/usr/local/bin/ls’
>>> pathname.split(‘/’)
[‘usr’, ‘local’, ‘bin’, ‘ls’]
The inverse of split is the function join. The argument to join is a list of strings. The value to theleft of the
dot is the separator that will be placed between each element. Often this is simply an empty string. The values
in the list are laminated along with the separator to produce the result string.
>>> lst = [‘abc’,’pdq’,’xyz’]
>>> pri
nt ‘::’.join(lst)
abc::pdq::xyz String
methods
A method is similar to a function—it takes arguments and returns a value—but the syntax is different. For
example, the method upper takes a string and returns a new string with all uppercase letters:
Instead of the function syntax upper(word), it uses the method syntax word.upper()
.>>> word = 'banana'
>>> new_word = word.upper()
>>> print new_word
BANANA
This form of dot notation specifies the name of the method, upper, and the name of the string to apply the
method to, word. The empty parentheses indicate that this method takes no argument. A method call is called
an invocation ; in this case, we would say that we are invoking upper on the word. As it turns out, there is a
string method named find that is remarkably similar to the function we wrote:
>>> word = 'banana'
>>> index = word.find('a')
>>> print index1
In this example, we invoke find on word and pass the letter we are looking for as a parameter. Actually, the
find method is more general than our function; it can find substrings, not just characters:
>>> word.find('na')2
It can take as a second argument the index where it should start:
>>> word.find('n', 3)
4
And as a third argument the index where it should stop:
>>> name ='bob'
>>> name.find('b', 1, 2)
-1
This search fails because b does not appear in the index range from 1 to 2 (not including 2).
print(powered)
The following list contains a string, a float, an integer, and (mirabile dictu) another list:
A list within another list is said to be nested. Lists that contain consecutive integers are common, so Python
provides a simple way to create them:
LIST OPERATIONS
The + operator concatenates lists
: >>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print c [1, 2, 3, 4, 5, 6]
Similarly, the * operator repeats a list a given number of times:
LIST SLICES
If we omit the first index, the slice starts at the beginning. If we omit the second, the slice goes to the end.
So if we omit both, the slice is a copy of the whole list.
>>> list[1] = 17
>>> list
[2, 17, 'usurp', 9.0, 'n']
We can assign new values to slices of the lists, which don't even have to be the same length:
It's even possible to append items onto the start of lists by assigning to an empty slice:
Similarly, you can append to the end of the list by specifying an empty slice after the end:
>>> list[len(list):] = ['four', 'score']
>>> list
The right-hand side of a list assignment statement can be any iterable type:
Note, however, that this is a shallow copy and contains references to elements from the original list, so be
careful with mutable types:
>>> list_copy[2].append('something')
>>> original
[1, 'element', ['something']]
Non-Continuous slices
It is also possible to get non-continuous parts of an array. If one wanted to get every n-th occurrence of a
list, one would use the :: operator. The syntax is a:b:n where a and b are the start and end of the slice to be
operated upon.
>>> list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list[::2]
[0, 2, 4, 6, 8]
>>> list[1:7:2]
[1, 3, 5]
2. Explain in detail about list methods and list loops with examples.
Python provides methods that operate on lists. Some of the methods are
• Append()
• Extend()
• Sort()
• Pop()
>>> t.append('d')
>>> print t ['a', 'b', 'c', 'd']
>>> t1.extend(t2)
This example leaves t2 unmodified. sort arranges the elements of the list from low to high:
>>> t.sort()
Remove the item in the list at the index i and return it. If i is not given, remove the the last item in the list and
return it.
>>> list = [1, 2, 3, 4]
>>> a = list.pop(0)
>>>
list [2,
3, 4]
>>> a
List methods are all void; they modify the list and return None.
LIST LOOPS
Here are two functions that both generate ten million random numbers, and return the sum of the numbers.
They both work.
import random
joe = random.Random()
def sum1():
""" Build a list of random numbers, then sum them """ # Generate one random ˓→number
xs = []
for i in range(10000000):
num = joe.randrange(1000 )
xs.append(num) # Save it in our list
tot = sum(xs)
return tot
def sum2():
""" Sum the random numbers as we generate them """
tot = 0
for i in range(10000000):
num = joe.randrange(1000)
tot += num
return tot
print(sum1())
print(sum2())
Unlike strings, lists are mutable, which means we can change their elements. Using the bracket operator on
the left side of an assignment, we can update one of the elements:
We can also remove elements from a list by assigning the empty list to them:
>>> list[1:3] = []
And we can add elements to a list by squeezing them into an empty slice at the desired location:
Tuple assignment
It is often useful to swap the values of two variables. With conventional assignments, you have to use a
temporary variable. For example, to swap a and b:
>>> temp = a
>>> a = b
>>> b = temp
>>> a, b = b, a
The left side is a tuple of variables; the right side is a tuple of expressions. Each value is assigned to its
respective variable. All the expressions on the right side are evaluated before any of the assignments. The
number of variables on the left and the number of values on the right have to be the same:
>>> a, b = 1, 2, 3
ValueError: too many values to unpack More generally, the right side can be any kind of sequence (string,
list or tuple). For example, to split an email address into a user name and a domain, you could write:
The return value from split is a list with two elements; the first element is assigned to uname, the second to
domain.
>>> temp = a
>>> a = b
>>> b = temp
>>> a, b = b, a
The left side is a tuple of variables; the right side is a tuple of expressions. Each value is assigned to its
respective variable. All the expressions on the right side are evaluated before any of the assignments. The
number of variables on the left and the number of values on the right have to be the same:
>>> a, b = 1, 2, 3
ValueError: too many values to unpack More generally, the right side can be any kind of sequence (string,
list or tuple). For example, to split an email address into a user name and a domain, you could write:
The return value from split is a list with two elements; the first element is assigned to uname, the second to
domain.
return y, x
Then we can assign the return value to a tuple with two variables:
a, b = swap(a, b)
In this case, there is no great advantage in making swap a function. In fact, there is a danger in trying to
encapsulate swap, which is the following tempting mistake:
x, y = y, x
If we call this function like this: swap(a, b) then a and x are aliases for the same value. Changing x inside
swap makes x refer to a different value, but it has no effect on a in main. Similarly, changing y has no effect
on b. This function runs without producing an error message, but it doesn’t do what we intended. This is an
example of a semantic error.
The built-in function divmod takes two arguments and returns a tuple of two values, the quotient and
remainder. You can store the result as a tuple:
>>> t = divmod(7, 3)
Here is an example of a function that returns a tuple: def min_max(t): return min(t), max(t) max and min are
built-in functions that find the largest and smallest elements of a sequence. min_max computes both and
returns a tuple of two values.
The function dict creates a new dictionary with no items. Because dict is the name of a built-in function,
you should avoid using it as a variable name.
The squiggly-brackets, {}, represent an empty dictionary. To add items to the dictionary, you can use
square brackets: >>> eng2sp['one'] = 'uno' This line creates an item that maps from the key 'one' to the value
'uno'. If we print the dictionary again, we see a key-value pair with a colon between the key and value:
This output format is also an input format. For example, you can create a new dictionary with three items:
The order of the key-value pairs is not the same. In fact, if you type the same example on your computer,
you might get a different result. In general, the order of items in a dictionary is unpredictable. But that’s not
a problem because the elements of a dictionary are never indexed with integer indices. Instead, you use the
keys to look up the corresponding values:
The key 'two' always maps to the value 'dos' so the order of the items doesn’t matter. If the key isn’t in the
dictionary, you get an exception:
The len function works on dictionaries; it returns the number of key-value pairs:
>>> len(eng2sp)
The in operator works on dictionaries; it tells you whether something appears as a key in the dictionary
(appearing as a value is not good enough).
To see whether something appears as a value in a dictionary, you can use the method values, which returns
the values as a list, and then use the in operator:
True
The in operator uses different algorithms for lists and dictionaries. For lists, it uses a search algorithm, as in
Section 8.6. As the list gets longer, the search time gets longer in direct proportion. For dictionaries, Python
uses an algorithm called a hashtable that has a remarkable property: the in operator takes about the same
amount of time no matter how many items there are in a dictionary
Dictionary operations
The del statement removes a key-value pair from a dictionary. For example, the following dictionary
contains the names of various fruits and the number of each fruit in stock:
>>> inventory = {’apples’: 430, ’bananas’: 312, ’oranges’: 525, ’pears’: 217}
>>> print inventory {’oranges’: 525, ’apples’: 430, ’pears’: 217, ’bananas’: 312}
If someone buys all of the pears, we can remove the entry from the dictionary:
Or if we’re expecting more pears soon, we might just change the value associated with pears:
>>> inventory[’pears’] = 0
>>> print inventory {’oranges’: 525, ’apples’: 430, ’pears’: 0, ’bananas’: 312}
The len function also works on dictionaries; it returns the number of key-value pairs:
>>> len(inventory) 4
A method is similar to a function—it takes arguments and returns a value— but the syntax is different. For
example, the keys method takes a dictionary and returns a list of the keys that appear, but instead of the
function syntax keys(eng2sp), we use the method syntax eng2sp.keys().
This form of dot notation specifies the name of the function, keys, and the name of the object to apply the
function to, eng2sp. The parentheses indicate that this method has no parameters. A method call is called an
invocation; in this case, we would say that we are invoking keys on the object eng2sp.
The values method is similar; it returns a list of the values in the dictionary:
The items method returns both, in the form of a list of tuples—one for each key-value pair:
>>> eng2sp.items() [(’one’,’uno’), (’three’, ’tres’), (’two’, ’dos’)]
The syntax provides useful type information. The square brackets indicate that this is a list. The parentheses
indicate that the elements of the list are tuples. If a method takes an argument, it uses the same syntax as a
function call. For example, the method has key takes a key and returns true (1) if the key appears in the
dictionary:
>>> eng2sp.has_key(’one’)
True
>>> eng2sp.has_key(’deux’)
False
If you try to call a method without specifying an object, you get an error. In this case, the error message is
not very helpful:
List comprehensions
List comprehensions provide a concise way to create lists. It consists of brackets containing an expression
followed by a for clause, then zero or more for or if clauses. The expressions can be anything, i.e., all kinds
of objects can be in lists. The result will be a new list resulting from evaluating the expression in the context
of the for and if clauses which follow it. The list comprehension always returns a result list.
Syntax
The list comprehension starts with a '[' and ']', to help you remember that the result is going to be a list.
List comprehension is a method to describe the process using which the list should be created. To do that, the
list is broken into two pieces. The first is a picture of what each element will look like, and the second is what
is done to get it.
For instance, let's say we have a list of words:
listOfWords = ["this","is","a","list","of","words"]
To take the first letter of each word and make a list out of it using list comprehension:
>>> listOfWords = ["this","is","a","list","of","words"]
>>> items = [ word[0] for word in listOfWords ]
>>> print items
['t', 'i', 'a', 'l', 'o', 'w']
List comprehension supports more than one for statement. It will evaluate the items in all of the objects
sequentially and will loop over the shorter objects if one object is longer than the rest.
List comprehension supports an if statement, to only include members into the list that fulfill a certain
condition:
PROGRAM:
least = i
least = k
def swap( A, x, y ):
tmp = A[x]
A[x] = A[y]
A[y] = tmp
aList = [54,26,93,17,77,31,44,55,20]
selectionsort(aList)
print(aList)
Insertion sort:
def insertionSort(alist):
currentvalue = alist[index]
position = index
alist[position]=alist[position-1]
position = position-1
alist[position]=currentvalue
alist = [54,26,93,17,77,31,44,55,20]
insertionSort(alist)
print(alist)
def mergeSort(alist):
print("Splitting
",alist) if
len(alist)>1:
mid = len(alist)//2
lefthalf =
alist[:mid]
righthalf =
alist[mid:]
mergeSort(lefthalf)
mergeSort(righthal
f) i=0
j=0
k=
0
while i < len(lefthalf) and j <
len(righthalf): if lefthalf[i] <
righthalf[j]:
alist[k]=lefthalf
[i] i=i+1
else:
alist[k]=righthalf
[j] j=j+1
k=k+1
while i <
len(lefthalf):
alist[k]=lefthalf[i
] i=i+1
k=k+1
while j <
len(righthalf):
alist[k]=righthalf[j
] j=j+1
k=k+1
print("Merging ",alist)
alist = [54,26,93,17,77,31,44,55,20]
mergeSort(alis
t) print(alist)
Quicksort:
from random import randrange
store_index = start
store_index += 1
return store_index
return lst
def sort(lst):
quick_sort(lst, 0, len(lst) - 1)
return lst
3. Write a python program to count number of lines, words and characters in a text file. def
wordCount():
cl=0
cw=0
cc=0
f=open("ex88.txt","r")for
line in f:
words=line.split()cl
+=1
cw +=len(words)cc
+=len(line)
print('No. of lines:',cl)
print('No. of words:',cw)
print('No. of characters:',cc)
f.close()
5. Mention the commands and their syntax for the following: get current directory, changing
directory, list, directories and files, make a new directory, renaming and removing directory.
(a) Get current directory: getcwd()
Syntax : import os
os.getcwd()
(a) Changing directory: chdir()
Syntax: os.chdir(‘C:\\Users’)
os.getcwd()
(b) List directories and files: listdir()
Syntax: os.listdir()
(c) Making a new directory: mkdir()
Syntax: os.mkdir(‘Newdir’)
(d) Renaming a directory: rename()
os.rename(‘Newdir’,’Newname’)
os.listdir()
(e) Removing a directory: remove()
os.remove(‘NewName’)
def getStack():
return[]
def isempty(s):if
s==[]:
return True
else:
return Falsedef
top(s):
if isempty(s):
return None
else:
return s[len(s)-1]
def push(s,item):
s.append(item)
def pop(s):
if isempty(s):
return None
else:
item=s[len(s)-1]
del s[len(s)-1]
return item
import stackdef
today():
mystack=stack.getStack()
for item in range(1,7):
stack.push(mystack,item)
print('Pushing',item,'to stack')print
('Stack items')
while not stack.isempty(mystack):
item=stack.pop(mystack)
print('Poping',item,'from stack')
def test():
wordcount.wordCount()
def test2():
ex12.inputNumber()
def test3():
ex97.fun()
ex97.py:
def fun():try:
x = float(raw_input("Your number: "))
inverse = 1.0 / x
except ValueError:
print "You should have given either an int or a float"
except ZeroDivisionError:
print "Infinity"
ex12.py:
def inputNumber () :
x = input ('Pick a number: ')if
x == 17 :
raise ValueError, '17 is a bad number'
return x
wordcount.py:
def wordCount():
cl=0
cw=0
cc=0
f=open("ex88.txt","r")for
line in f:
words=line.split()cl
+=1
cw +=len(words)
cc +=len(line)
print('No. of lines:',cl)
print('No. of words:',cw)
print('No. of characters:',cc)
f.close()