[go: up one dir, main page]

0% found this document useful (0 votes)
43 views18 pages

Tutorial 2 Solution

The document discusses various Python list and dictionary concepts like their differences, traversing dictionaries using for loops, adding and removing values from lists, finding values in lists, sorting lists, shallow and deep copying, dictionary methods like get, items, keys and values, list slicing, negative indexing, append, remove, pop, insert and sort.

Uploaded by

Adarsha M R
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views18 pages

Tutorial 2 Solution

The document discusses various Python list and dictionary concepts like their differences, traversing dictionaries using for loops, adding and removing values from lists, finding values in lists, sorting lists, shallow and deep copying, dictionary methods like get, items, keys and values, list slicing, negative indexing, append, remove, pop, insert and sort.

Uploaded by

Adarsha M R
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Assignment-2 Solution

Module-2
1. What is Dictionary in Python? How is it different from List data type? Explain how a
for loop can be used to traverse the keys of the Dictionary with an example.

Dictionary: A dictionary is a collection of many values. Indexes for dictionaries can use
many different data types, not just integers. Indexes for dictionaries are called keys, and a key
with its associated value is called a key-value pair. A dictionary is typed with braces, {}.
The dictionary is different from list data type:
• In lists the items are ordered and in dictionaries the items are unordered.
• The first item in a list exists. But there is no “first” item in a dictionary.
• The order of items matters for determining whether two lists are the same, it does
not matter in what order the key-value pairs are typed in a dictionary.
• Trying to access a key that does not exist in a dictionary will result in a KeyError
error message, in list “out-of-range” IndexError error message.

Traversing using for loop:

2. Explain the methods of List data type in Python for the following operations with
suitable code snippets for each.
(i) Adding values to a list ii) Removing values from a list
(iii) Finding a value in a list iv) Sorting the values in a list

i) Adding values to a list:


ü To add new values to a list, the append() and insert() methods can be used.
ü The append() method adds the argument to the end of the list.

The insert() method insert a value at any index in the list.


ü The first argument to insert() is the index for the new value, and the second argument is the
new value to be inserted.
ii) Removing values from a list:
• To remove values from a list, the remove( ) and del( ) methods can be used.
• The del statement is used when we know the index of the value we want to remove
from the list.
• The remove() method is used when we know the value we want to remove from the
list.

• Attempting to delete a value that does not exist in the list will result in a ValueError
error.
• If the value appears multiple times in the list, only the first instance of the value will
be removed

iii) Finding a value in a list:


• To find a value in a list we can use index value.
• The first value in the list is at index 0, the second value is at index 1, and the third
value is at index 2, and so on. The negative indexes can also be used.
• Example:

• The expression 'Hello ' + spam[0] evaluates to 'Hello ' + 'cat' because spam[0]
evaluates to the string 'cat'. This expression in turn evaluates to the string value 'Hello
cat'.
• Negative index à spam[-1] à Retrieves last value.
iv) Sorting the values in a list
• Lists of number values or lists of strings can be sorted with the sort() method.

3. What is the difference between copy.copy( ) and copy.deepcopy( ) functions applicable


to a List or Dictionary in Python? Give suitable examples for each.

Copy module must be imported and can be used to make a duplicate copy of a mutable value
like a list or dictionary, not just a copy of a reference.
copy.copy( ): A shallow copy creates a new object which stores the reference of the original
elements.So, a shallow copy doesn't create a copy of nested objects, instead it just copies the
reference of nested objects. This means, a copy process does not create copies of nested
objects itself.
Example:
import copy
old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
new_list = copy.copy(old_list)
old_list[1][1] = 'AA'
print("Old list:", old_list)
print("New list:", new_list)
Output:
Old list: [[1, 1, 1], [2, 'AA', 2], [3, 3, 3]]
New list: [[1, 1, 1], [2, 'AA', 2], [3, 3, 3]]

copy.deepcopy( ): A deep copy creates a new object and recursively adds the copies of
nested objects present in the original elements.
Example:
import copy
old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
new_list = copy.deepcopy(old_list)
old_list[1][0] = 'BB'
print("Old list:", old_list)
print("New list:", new_list)
Output:
Old list: [[1, 1, 1], ['BB', 2, 2], [3, 3, 3]]
New list: [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
4. Discuss the following Dictionary methods in Python with examples.
(i) get( ) (ii) items( ) (iii) keys( ) (iv) values( )
(i) get( ): Dictionaries have a get() method that takes two arguments:
Ø The key of the value to retrieve
Ø A fallback value to return if that key does not exist.

(ii) items( ): This method returns the dictionary values and keys in the form of tuples.
Ex: spam = {‘color’ : ‘red’ , ‘age’ : 27}
for i in spam.items( ):
print(i)
Output: (‘color’, ‘red’)
(‘age’, 27)
(iii) keys( ): This method returns the dictionary keys.
Ex: spam = {‘color’ : ‘red’ , ‘age’ : 27}
for i in spam.keys( ):
print(i)

Output: color
age
iv) values( ): This method returns the dictionary values.
Ex: spam = {‘color’ : ‘red’ , ‘age’ : 27}
for i in spam.values( ):
print(i)
Output: red
27
5. What is list? Explain the concept of list slicing with example.
List: A list is a value that contains multiple values in an ordered sequence.
Slicing: Extracting a substring from a string is called substring.
Ex.
6. Explain references with example.
ü Reference: A reference is a value that points to some bit of data, and a list reference is a
value that points to a list.

Here, the list is created, and assigned reference to it in the spam variable.
• In the next line copies only the list reference in spam to cheese, not the list value itself.
This means the values stored in spam and cheese now both refer to the same list.
• When a function is called, the values of the arguments are copied to the parameter
variables.

• when eggs() is called, a return value is not used to assign a new value to spam.
• Even though spam and someParameter contain separate references, they both refer to
the same list.
• This is why the append('Hello') method call inside the function affects the list even
after the function call has returned.

7. What is dictionary? How it is different from list? Write a program to count the
number of occurrences of character in a string.
Dictionary: A dictionary is a collection of many values. Indexes for dictionaries can use
many different data types, not just integers. Indexes for dictionaries are called keys, and a key
with its associated value is called a key-value pair. A dictionary is typed with braces, {}. The
dictionary is different from list data type:
• In lists the items are ordered and in dictionaries the items are unordered.
• The first item in a list exists. But there is no “first” item in a dictionary.
• The order of items matters for determining whether two lists are the same, it does
not matter in what order the key-value pairs are typed in a dictionary.
• Trying to access a key that does not exist in a dictionary will result in a KeyError
error message, in list “out-of-range” IndexError error message.
import pprint
x = input("Enter a String")
count = {}
for character in x:
count.setdefault(character, 0)
count[character] = count[character] + 1
pprint.pprint(count)

8. You are creating a fantasy video game. The data structure to model the player’s
inventory will be a dictionary where the keys are string values describing the item in the
inventory and the value is an integer value detailing how many of that item the player
has. For example, the dictionary value {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1,
'arrow': 12} means the player has 1 rope, 6 torches, 42 gold coins, and so on. Write a
function named displayInventory() that would take any possible “inventory” and
display it like the following:
Inventory: 12 arrow , 42 gold coin , 1 rope , 6 torch , 1 dagger , Total number of items:
63

stuff = {'arrow':12, 'gold coin':42, 'rope':1, 'torch':6, 'dagger':1}


def displayInventory(inventory):
print('Inventory:')
item_total = 0
for k, v in inventory.items():
print(str(v) + ' ' + str(k))
item_total += v
print('Total number of items: ' +
str(item_total))
displayInventory(stuff)

9. Explain negative indexing, slicing, index( ), append( ), remove( ), pop( ), insert( ) and
sort( ) with suitable examples.

(i) Negative indexing: While indexes start at 0 and go up, you can also use negative integers
for the index. The integer value -1 refers to the last index in a list, the value -2 refers to the
second-to-last index in a list, and so on.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[-1]
'elephant'
>>> spam[-3]
'bat'
>>> 'The ' + spam[-1] + ' is afraid of the ' + spam[-3] + '.'
'The elephant is afraid of the bat.’

(ii) Slicing: A slice is typed between square brackets, like an index, but it has two integers
separated by a colon.
• spam[2] is a list with an index (one integer).
• spam[1:4] is a list with a slice (two integers).
In a slice, the first integer is the index where the slice starts. The second integer is the index
where the slice ends.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[0:4]
['cat', 'bat', 'rat', 'elephant']
>>> spam[1:3]
['bat', 'rat']
>>> spam[0:-1]
['cat', 'bat', ‘rat']

(iii) Index( ): List values have an index() method that can be passed a value, and if that value
exists in the list, the index of the value is returned. If the value is not in the list, then Python
produces a ValueError error.
>>> spam = ['hello', 'hi', 'howdy', 'heyas']
>>> spam.index('hello')
0
>>> spam.index('heyas')
3

(iv) Append( ): The append() method call adds the argument to the end of the list.
>>> spam = ['cat', 'dog', 'bat']
>>> spam.append('moose')
>>> spam
['cat', 'dog', 'bat', ‘moose']

(v) Remove( ): The remove() method is passed the value to be removed from the list it is
called on.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam.remove('bat')
>>> spam
['cat', 'rat', ‘elephant’]

(vi) Pop( ): The pop() method removes the element at the specified position.
>>> fruits = ['apple', 'banana', ‘cherry']
>>> x = fruits.pop(1)
>>> print(x)
banana
>>> fruits = ['apple', 'banana', 'cherry']
>>> fruits.pop(1)
>>> print(fruits)
['apple', 'cherry']

(vii) Insert( ): The insert() method can insert a value at any index in the list. The first
argument to insert() is the index for the new value, and the second argument is the new value
to be inserted.
>>> spam = ['cat', 'dog', 'bat']
>>> spam.insert(1, 'chicken')
>>> spam
['cat', 'chicken', 'dog', ‘bat']

(viii) Sort( ): Lists of number values or lists of strings can be sorted with the sort() method.
>>> spam = [2, 5, 3.14, 1, -7]
>>> spam.sort()
>>> spam
[-7, 1, 2, 3.14, 5]

>>> spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']


>>> spam.sort()
>>> spam
['ants', 'badgers', 'cats', 'dogs', ‘elephants']

10. Explain the use of in and not in operators in list with suitable examples.
It can be determined whether a value is or is not in a list with the in and not in operators.
In and not in are used in expressions and connect two values: a value to look for in a list and
the list where it may be found. These expressions will evaluate to a Boolean value.

>>> 'howdy' in ['hello', 'hi', 'howdy', 'heyas']


True
>>> spam = ['hello', 'hi', 'howdy', 'heyas']
>>> 'cat' in spam
False
>>> 'howdy' not in spam
False
>>> 'cat' not in spam
True

11. Develop a program to find mean, variance and standard deviation.


from math import sqrt
myList = []
num = int(input("Enter the number of elements in your list : "))
for i in range(num):
val = int(input("Enter the element : "))
myList.append(val)
print('The length of list1 is', len(myList))
print('List Contents', myList)
total = 0
for elem in myList:
total += elem
mean = total / num
total = 0
for elem in myList:
total += (elem - mean) * (elem - mean)
variance = total / num
stdDev = sqrt(variance)
print("Mean =", mean)
print("Variance =", variance)
print("Standard Deviation =", "%.2f"%stdDev)

12. Explain the following methods in list with examples.


(i) len( ) (ii) sum( ) (iii) max( ) (iv) min( )
(i) len( ): The len() function will return the number of values that are in a list value passed to
it, just like it can count the number of characters in a string value.
>>> spam = ['cat', 'dog', 'moose']
>>> len(spam)
3

(ii) sum( ): Python provides an inbuilt function sum() which sums up the numbers in the list.
numbers = [1,2,3,4,5,1,4,5]
Sum = sum(numbers)
print(Sum)
Sum = sum(numbers, 10)
print(Sum)
Output: 25
35

(iii) max( ): Python list method max returns the elements from the list with maximum value.
list1= [456, 700, 200]
print ("Max value element : ", max(list1))
Output: Max value element : 700

(iv) min( ): Python min() function returns the smallest of the values or the smallest item in an
iterable passed as its parameter.
print(min([1,2,3]))
Output: 1
13. Explain set( ) and setdefault( ) method in dictionary.
(i) set( ): The set() function creates a set object.
The items in a set list are unordered, so it will appear in random order
>>> x = set(("apple", "banana", "cherry"))
>>> print(x)
# Note: the set list is unordered, so the result will display the items in a random order.
Output: {‘banana', 'cherry', 'apple'}

(ii) setdefault( ): A value has to be set in a dictionary for a certain key only if that key does
not have a value.
spam = {'name': 'Pooka', 'age': 5}
if 'color' not in spam:
spam['color'] = 'black'

The setdefault() method offers a way to do this in one line of code. The first argument passed
to the method is the key to check for, and the second argument is the value to set at that key if
the key does not exist. If the key does exist, the setdefault() method returns the key’s value.
>>> spam = {'name': 'Pooka', 'age': 5}
>>> spam.setdefault('color', 'black')
'black'
>>> spam
{'color': 'black', 'age': 5, 'name': 'Pooka'}
>>> spam.setdefault('color', 'white')
'black'
>>> spam
{'color': 'black', 'age': 5, 'name': 'Pooka'}

Module-3 solution
1. Explain the various string methods for the following operations with examples.
(i) Removing whitespace characters from the beginning, end or both sides of a string.
(ii) To right-justify, left-justify, and center a string.
i) Removing whitespace characters from the beginning, end or both sides of a string.
• The strip() string method will return a new string without any whitespace
characters at the beginning or end.
• The lstrip() and rstrip() methods will remove whitespace characters from the left
and right ends, respectively.
ii) To right-justify, left-justify, and center a string.
• The rjust() and ljust() string methods return a padded version of the string they are
called on, with spaces inserted to justify the text.
• The first argument to both methods is an integer length for the justified string.

An optional second argument to rjust() and ljust() will specify a fill character other than a
space character.

The center() string method works like ljust() and rjust() but centers the text rather than
justifying it to the left or right.

2. Write a Python program that accepts a sentence and find the number of words,
digits, uppercase letters and lowercase letters.

print("Enter a sentence: ")


str = input()
up, low, num, spl = 0, 0, 0, 0
for i in range(len(str)):
if str[i] >= 'A' and str[i] <= 'Z':
up += 1
elif str[i] >= 'a' and str[i] <= 'z':
low += 1
elif str[i] >= '0' and str[i] <= '9':
num += 1
else:
spl += 1

print("UpperCase : ",up)
print("LowerCase : ",low)
print("NumberCase : ",num)
print("SpecialCase : “,spl)

3. List any six methods associated with string and explain each of them with
example.

i) upper( ): This method is used to convert lower case characters into upper case characters.

Ex: x = ‘Python’
x = x.upper( )
PYTHON
ii) lower( ): This method is used to convert upper case characters into lower case characters.

Ex: x = ‘Python’
x = x.lower( )
python

iii) isupper( ): This method is used to check whether a string has at least one letter or
complete string is upper or not. It returns Boolean value.

Ex: x = ‘Python’
x = x.isupper( )
TRUE
Ex: y = ‘python’
y = y.isupper( )
FALSE
iv) islower( ): This method is used to check whether a string has at least one letter or
complete string is lower or not. It returns Boolean value.
Ex: x = ‘Python’
x = x.islower( )
TRUE
Ex: y = ‘PYTHON’
y = y.isupper( )
FALSE
v) isspace( ): Returns True if the string consists only of spaces, tabs, and newlines and is not
blank.

Ex: ‘ ‘.isspace( )
TRUE
vi) isalnum( ): Returns True if the string consists only of letters and numbers and is not
blank.

Ex: ‘hello123’.isalnum( )
TRUE
Ex: ‘ ‘.isalnum( )
FALSE
4. Write a Python program to swap cases of a given string. Input: Java , Output: jAVA
def swapcase(string):
result_str = ""
for item in string:
if item.isupper():
result_str += item.lower()
else:
result_str += item.upper()
return result_str
string = input("Enter a String:")
print(swapcase(string))

5. Describe the difference between Python os and os.path modules. Also, discuss the
following methods of os module
a) chdir() b) rmdir() c) walk() d) listdir() e) getcwd()

os module àIt is from the standard library and it provides a portable way of accessing and
using operating system dependent functionality.
os.path module à It is used to manipulate the file and directory paths and path names.
a) chdir( ): This method is used to change from current working directory to the required
directory.
Ex: import os
os.chdir(“C:\\Windows\\System”)

b) rmdir( ) : This method is used to delete the folder at path. This folder must not contain
any files or folders.

c) walk( ) : This method is used to access or do any operation on each file in a folder.
Ex: import os
for foldername, subfolder, filenames in os.walk(“C:\\Windows\\System”)
print(“The current folder is “+foldername)

d) listdir( ) : This method returns a list containing the names of the entries in the directory
given by path.
e) getcwd( ) : This method is used to get the current working directory.
Ex: import os
os.getcwd( )

6. Explain the concept of file handling. Also explain file Reading/Writing process
with suitable example.

Reading File: read( ) and readlines( ) methods are used to read the contents of a file. read( )
method reads the contents of a file as a single string value whereas readlines( ) method reads
each line as a string value.
Ex.

Writing File: The file must be opened in order to write the contents to a file. It can be done
in two ways: wither in write mode or append mode. In write mode the contents of the existing
file will be overwritten whereas in append mode the contents will be added at the end of
existing file.
Ex: In the below example bacon.txt file is opened in write mode hence, all the contents will
be deleted and Hello world! Will be written.

Ex: In the below example bacon.txt file is opened in append mode hence, the contents will be
added after Hello world!

• The files must be closed after once it is read or written.

7. Explain saving of variables using shelve module.


• The variables can be saved in Python programs to binary shelf files using the shelve
module.
• This helps the program to restore data to variables from the hard drive.
• The shelve module will let us add Save and Open features to your program.
• Example:
8. How do we specify and handle absolute, relative paths?
There are two ways to specify a file path.
1. An absolute path, which always begins with the root folder
2. A relative path, which is relative to the program’s current working directory
• The os.path module provides functions for returning the absolute path of a relative
path and for checking whether a given path is an absolute path.
1. Calling os.path.abspath(path) will return a string of the absolute path of the argument. This
is an easy way to convert a relative path into an absolute one.
2. Calling os.path.isabs(path) will return True if the argument is an absolute path and False if
it is a relative path.
3. Calling os.path.relpath(path, start) will return a string of a relative path from the start path
to path. If start is not provided, the current working directory is used as the start path.

Since C:\Python34 was the working directory when os.path.abspath() was called, the “single-
dot” folder represents the absolute path 'C:\\Python34'.

Calling os.path.dirname(path) will return a string of everything that comes before the last
slash in the path argument.
ü Calling os.path.basename(path) will return a string of everything that comes after the last
slash in the path argument.
Ex.

9. Explain join( ) and split( ) method with examples.

join(): The join() method is used to join together a list of strings into a single string value.
The join() method is called on a string, gets passed a list of strings, and returns a string. The
returned string is the concatenation of each string in the passed-in list.

>>> ', '.join(['cats', 'rats', 'bats'])


'cats, rats, bats'
>>> ' '.join(['My', 'name', 'is', 'Simon'])
'My name is Simon'
>>> 'ABC'.join(['My', 'name', 'is', 'Simon'])
'MyABCnameABCisABCSimon'

split(): The split() method is called on a string value and returns a list of strings.
>>> 'My name is Simon'.split()
['My', 'name', 'is', 'Simon']
By default, the string 'My name is Simon' is split wherever whitespace characters such as the
space, tab, or newline characters are found. These whitespace characters are not included in
the strings in the returned list.
A delimiter string can be passed to the split() method to specify a different string to split
upon.
>>> 'MyABCnameABCisABCSimon'.split('ABC')
['My', 'name', 'is', 'Simon']
>>> 'My name is Simon'.split('m')
['My na', 'e is Si', 'on']

10. Explain with examples : (i) isalpha( ) (ii) isalnum( ) (iii) isspace( )
isalpha(): Returns True if the string consists only of letters and is not blank
>>> ‘hello'.isalpha()
TRUE
>>> ‘hello123'.isalpha()
FALSE
isalnum(): Returns True if the string consists only of letters and numbers and is not blank
>>> ‘hello123'.isalnum()
TRUE
>>> ‘hello'.isalnum()
TRUE
isspace(): Returns True if the string consists only of spaces, tabs, and newlines and is not
blank
>>> ' ‘.isspace()
TRUE

11. Develop a python code to determine whether the given string is a palindrome or
not a palindrome.
str1=input("enter a string:")
str2=""
i=len(str1)-1
while i>=0:
str2=str2+str1[i]
i-=1
print("reverse of",str1,"=",str2)
if str1 in str2:
print("given string is palindrome")
else:
print('given string is not palindrome’)

12. Explain the concept of file path. Also discuss absolute and relative file path.
A file has two key properties: a filename and a path. The path specifies the location of a file
on the computer. For example, there is a file on my Windows laptop with the
filename project.docx in the path C:\Users\Al\Documents. The part of the filename after the
last period is called the file’s extension and tells you a file’s type. The filename project.docx
is a Word document, and Users, Al, and Documents all refer to folders (directories).
There are two ways to specify a file path.
1. An absolute path, which always begins with the root folder
2. A relative path, which is relative to the program’s current working directory
• The os.path module provides functions for returning the absolute path of a relative
path and for checking whether a given path is an absolute path.
1. Calling os.path.abspath(path) will return a string of the absolute path of the argument. This
is an easy way to convert a relative path into an absolute one.
2. Calling os.path.isabs(path) will return True if the argument is an absolute path and False if
it is a relative path.
3. Calling os.path.relpath(path, start) will return a string of a relative path from the start path
to path. If start is not provided, the current working directory is used as the start path.

Since C:\Python34 was the working directory when os.path.abspath() was called, the “single-
dot” folder represents the absolute path 'C:\\Python34'.

Calling os.path.dirname(path) will return a string of everything that comes before the last
slash in the path argument.
ü Calling os.path.basename(path) will return a string of everything that comes after the last
slash in the path argument.

Ex.

You might also like