You are on page 1of 17

EXCEL ENGINEERING COLLEGE

(Autonomous)
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Accredited by NBA, NAAC with “A+” and Recognised by UGC (2f &12B)
KOMARAPALAYAM – 637303.

Department of Computer Science and Engineering


20CS201 - Problem Solving using Python
Unit-IV
1. What is the use of * and + operators in string?
 The * operator performs repetition on strings and the + operator performs
concatenation on strings.
 Example:>>> 'Hello'*3
Output:HelloHelloHello
>>>'Hello'+'World'
Output:HelloWorld .

2. Mention a few string functions.


 captilize() – Capitalizes first character of string
 lower() – converts a string to lower case
 split() – returns a list of words in string

3. Define string immutability.


 Python strings are immutable. a‘ is not a string. It is a variable with string value.
 You can‘t mutate the string but can change value of the variable to a new string.

4. What is string module?


 The string module contains number of useful constants and classes, as well as some
deprecated legacy functions that are also available as methods on strings.

5. Compare string and string slices.


A string is a sequence of character.
Eg: fruit = ‗banana‘
String Slices :
A segment of a string is called string slice, selecting a slice is similar to selecting a
character.
Eg:>>> s ='Monty Python'
>>> print (s[0:5])
Monty
>>> print( s[6:12])
Python

6. What are 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()

7. Define String.
 A string is a sequence of characters.
 Strings can be created by enclosing characters inside a single quote or double-quotes.

8. How to Assign a string to a variable?


 Assign a string to a variable, we can use the variable name and “=”
 Str= “ Welcome to python programming”

9. Write a python program to find index value of any string.


Str= “ Welcome to python programming”
print(str[2])
print(str[6])
Output
l
e

10. Write a python program to a word in a given string.


Str1= “Hello_World”
x=input(“Enter a character to update”)
str2=x+str1
print(str2)
output
Enter a character to update
Z
ZHello_Wordl

11. What is a list?


 A list is an ordered set of values, where each value is identified by an index. The
values that make up a list are called its elements
 Elements are represented by square bracket[].

12. Relate String and List.


 String: String is a sequence of characters and it is represented within double quotes
or single quotes. Strings are immutable.
 List: A list is an ordered set of values, where each value is identified by an index.
Elements are represented by square bracket [].List is mutable.

13. Mention any 5 list methods.


 append()
 extend ()
 sort()
 pop()
 remove()

14. What is aliasing in list? Give an example.


 An object with more than one reference has more than one name, then the object is
said to be aliased.
 Example:If a refers to an object and we assign b = a, then both variables refer to the
same object:
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True

15. What is List mutability in Python? Give an example.


 The content can be changed without changing their identity. Other objects like
integers, floats, strings and tuples are objects that cannot be changed.
Example:
>>> numbers = [17, 123]
>>> numbers[1] = 5
>>> print( numbers)
[17, 5]

16. Solve a)[0] * 4 and b) [1, 2, 3] * 3.


>>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]

17. Mention the list looping in python.


There are two types of looping in list
 Normal for-in loop
 For in range loop

18. Define the features of pop method in list.


 Remove and return the element at the given index from the list
 Syntax pop(index)
 List1=[10,20,30,40]
 List1.pop(1)
 List1=[10,30,40]

19. What is list cloning?


 Cloning create a new list with same value under another name.
 Changes made in cloned list will not affect the original list.

20. Define List comprehension.


 List comprehension is used to construct list in a simpler manner by reducing the
lines of code.
 List comprehension execute much faster than for loop

PART B
1. Explain in detail about basic string operations.
Strings:

 Strings in python are surrounded by either single quotation marks, or double quotation
marks.
 'hello' is the same as "hello".
 You can display a string literal with the print() function:

Example:
print("Hello")
print('Hello')

 Assign String to a Variable


 Assigning a string to a variable is done with the variable name followed by an equal sign
and the string:

a = "Hello"
print(a)

Multiline Strings

 You can assign a multiline string to a variable by using three quotes:

a = """Welcome to Excel Engineering College.


We are aiming at Excellence in professional education"""
print(a)
 Or three single quotes:

a = ‘’’Welcome to Excel Engineering College.


We are aiming at Excellence in professional education’’’
print(a)

Strings are Arrays

 Strings in Python are arrays of bytes representing unicode characters.

 Square brackets can be used to access elements of the string.

a = "Hello, World!"
print(a[1])

Looping Through a String

 Since strings are arrays, we can loop through the characters in a string, with a for loop.

for x in "banana":
print(x)

String Length
 To get the length of a string, use the len() function.

a = "Hello, World!"
print(len(a))

Check String
 To check if a certain phrase or character is present in a string, we can use the keyword in.

txt = "The best things in life are free!"


print("free" in txt)

 Use it in an if statement:

txt = "The best things in life are free!"


if "free" in txt:
print("Yes, 'free' is present.")
2. Illustrate string operations in detail with examples (8 marks). Explain built-in
methods for modifying strings with example (8 marks).

Operator Description

+ It is known as concatenation operator used to join the strings given either side of
the operator.

* It is known as repetition operator. It concatenates the multiple copies of the same


string.

[] It is known as slice operator. It is used to access the sub-strings of a particular


string.

[:] It is known as range slice operator. It is used to access the characters from the
specified range.

In It is known as membership operator. It returns if a particular sub-string is present


in the specified string.

not in It is also a membership operator and does the exact reverse of in. It returns true if
a particular substring is not present in the specified string.

r/R It is used to specify the raw string.

% It is used to perform string formatting.

Python - Modify Strings


Python has a set of built-in methods that you can use on strings.
Upper Case
 The upper() method returns the string in upper case:

a = "Hello, World!"
print(a.upper())
Output: HELLO, WORLD!

Lower Case
 The lower() method returns the string in lower case:

a = "Hello, World!"
print(a.lower())
Output: hello, world!

Remove Whitespace
 The strip() method removes any whitespace from the beginning or the end:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
Output: Hello, World!

Replace String
 The replace() method replaces a string with another string:

a = "Hello, World!"
print(a.replace("H", "J"))
Output: Jello, World!

Split String
 The split() method splits the string into substrings if it finds instances of the separator:

a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
Output: ['Hello', ' World!']

3. Discuss in detail about String indexing and splitting (8 marks). Explain the usage of
escape sequences in strings (8 marks).
 The indexing of the Python strings starts from 0.
 For example, The string "HELLO" is indexed as given in the below figure.

Example:
str = "HELLO"
print(str[0])
print(str[1])
# It returns the IndexError because 6th index doesn't exist
print(str[6])

Output:
H
E
IndexError: string index out of range

 In Python, the slice operator [] is used to access the individual characters of the string.
However, we can use the : (colon) operator in Python to access the substring from the given
string.

Example:
# Given String
str = "JAVATPOINT"
# Start Oth index to end
print(str[0:])
# Starts 1th index to 4th index
print(str[1:5])
# Starts 2nd index to 3rd index
print(str[:3])

Output:
JAVATPOINT
AVAT
JAV

 We can do the negative slicing in the string; it starts from the rightmost character, which is
indicated as -1.
 The second rightmost index indicates -2, and so on. Consider the following image.

Example:
str = 'JAVATPOINT'
print(str[-1])
print(str[-2:])
print(str[-4:-1])

Output:
T
NT
OIN

Escape Sequence
 The backslash(/) symbol denotes the escape sequence.
 The backslash can be followed by a special character and it interpreted differently.
 The single quotes inside the string must be escaped.
 We can apply the same as in the double quotes.

r. Escape Sequence Description Example

1. \newline It ignores the new line. print("Python1 \


Python2 \
Python3")
Output:
Python1 Python2 Python3

2. \\ Backslash print("\\")
Output:
\

3. \' Single Quotes print('\'')


Output:
'

4. \\'' Double Quotes print("\"")


Output:
"

5. \n ASCII Linefeed print("Hello \n World!")


Output:
Hello
World!

4. Describe the working of built-in methods used on Strings.

Method Description
capitalize() Converts the first character to upper case

casefold() Converts string into lower case


center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
find() Searches the string for a specified value and returns the position of where it was
found

format() Formats specified values in a string


index() Searches the string for a specified value and returns the position of where it was
found
isalnum() Returns True if all characters in the string are alphanumeric

isalpha() Returns True if all characters in the string are in the alphabet
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
join() Joins the elements of an iterable to the end of the string

lower() Converts a string into lower case


partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
split() Splits the string at the specified separator, and returns a list
strip() Returns a trimmed version of the string
upper() Converts a string into upper case

zfill() Fills the string with a specified number of 0 values at the beginning

5. Describe the working of built-in methods used on lists.

Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
append()
fruits = ['apple', 'banana', 'cherry']
fruits.append("orange")
print(fruits)
Output: ['apple', 'banana', 'cherry', 'orange']

clear():
fruits = ['apple', 'banana', 'cherry', 'orange']
fruits.clear()
print(fruits)
Output: []

6. Explain in detail about basic list operations.

 A list in Python is used to store the sequence of various types of data.


 Python lists are mutable type its mean we can modify its element after it created.
 A list can be defined as a collection of values or items of different types.
 The items in the list are separated with the comma (,) and enclosed with the square
brackets [].

Characteristics of Lists
 The lists are ordered.
 The element of the list can access by index.
 The lists are mutable types.
 A list can store the number of various elements.

Example:
emp = ["John", 102, "USA"]
Dep1 = ["CS",10]
Dep2 = ["IT",11]
HOD_CS = [10,"Mr. Holding"]
HOD_IT = [11, "Mr. Bewon"]
print("printing employee data...")
print("Name : %s, ID: %d, Country: %s"%(emp[0],emp[1],emp[2]))
print("printing departments...")
print("Department 1:\nName: %s, ID: %d\nDepartment 2:\nName: %s, ID: %s"%(Dep1[0],Dep2[1],
Dep2[0],Dep2[1]))
print("HOD Details ....")
print("CS HOD Name: %s, Id: %d"%(HOD_CS[1],HOD_CS[0]))
print("IT HOD Name: %s, Id: %d"%(HOD_IT[1],HOD_IT[0]))
print(type(emp),type(Dep1),type(Dep2),type(HOD_CS),type(HOD_IT))

Output:
printing employee data...
Name : John, ID: 102, Country: USA
printing departments...
Department 1:
Name: CS, ID: 11
Department 2:
Name: IT, ID: 11
HOD Details ....
CS HOD Name: Mr. Holding, Id: 10
IT HOD Name: Mr. Bewon, Id: 11
<

7. Discuss in detail about List indexing and splitting (8 marks). Explain the working of
list operations using examples (8 marks).
 The indexing is processed in the same way as it happens with the strings.
 The elements of the list can be accessed by using the slice operator [].
Example:
list = [1,2,3,4,5,6,7]
print(list[0])
print(list[1])
print(list[2])
print(list[3])
# Slicing the elements
print(list[0:6])
# By default the index value is 0 so its starts from the 0th element and go for index -1.
print(list[:])
print(list[2:5])
print(list[1:6:2])

Output:
1
2
3
4
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[3, 4, 5]
[2, 4, 6]

Python List Operations


 The concatenation (+) and repetition (*) operators work in the same way as they were
working with the strings.
 Consider a Lists l1 = [1, 2, 3, 4], and l2 = [5, 6, 7, 8] to perform operation.

Operator Description Example

Repetition The repetition operator enables the list elements to be L1*2 = [1, 2, 3, 4, 1,
repeated multiple times. 2, 3, 4]

Concatenation It concatenates the list mentioned on either side of the l1+l2 = [1, 2, 3, 4, 5,
operator. 6, 7, 8]

Membership It returns true if a particular item exists in a particular print(2 in l1) prints
list otherwise false. True.

Iteration The for loop is used to iterate over the list elements. for i in l1:
print(i)
Output
1
2
3
4

Length It is used to get the length of the list len(l1) = 4

8. Write the program to implement a binary search in python (10 marks). Write the
program to find the lists consist of at least one common element (6 marks).

Write the program to implement a binary search in python.


# Iterative Binary Search Function method Python Implementation
# It returns index of n in given list1 if present,
# else returns -1
def binary_search(list1, n):
low = 0
high = len(list1) - 1
mid = 0

while low <= high:


# for get integer result
mid = (high + low) // 2

# Check if n is present at mid


if list1[mid] < n:
low = mid + 1
# If n is greater, compare to the right of mid
elif list1[mid] > n:
high = mid - 1

# If n is smaller, compared to the left of mid


else:
return mid

# element was not present in the list, return -1


return -1

# Initial list1
list1 = [12, 24, 32, 39, 45, 50, 54]
n = 45

# Function call
result = binary_search(list1, n)

if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in list1")

Output: Element is present at index 4

Write the program to find the lists consist of at least one common element.
list1 = [1,2,3,4,5,6]
list2 = [7,8,9,2,10]
for x in list1:
for y in list2:
if x == y:
print("The common element is:",x)
Output:
The common element is: 2

9. Write the program for bubble sort and merge sort algorithms.
 Sorting refers to arranging data in a particular format.
 Sorting algorithm specifies the way to arrange data in a particular order.
 Most common orders are in numerical or lexicographical order.

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.
Example:
def bubblesort(list):

# Swap the elements to arrange in order


for iter_num in range(len(list)-1,0,-1):
for idx in range(iter_num):
if list[idx]>list[idx+1]:
temp = list[idx]
list[idx] = list[idx+1]
list[idx+1] = temp
list = [19,2,31,45,6,11,121,27]
bubblesort(list)
print(list)
Output: [2, 6, 11, 19, 27, 31, 45, 121]

Merge Sort

 Merge sort first divides the array into equal halves and then combines them in a sorted
manner.

Example:

def merge_sort(unsorted_list):
if len(unsorted_list) <= 1:
return unsorted_list
# Find the middle point and devide it
middle = len(unsorted_list) // 2
left_list = unsorted_list[:middle]
right_list = unsorted_list[middle:]
left_list = merge_sort(left_list)
right_list = merge_sort(right_list)
return list(merge(left_list, right_list))

# Merge the sorted halves


def merge(left_half,right_half):
res = []
while len(left_half) != 0 and len(right_half) != 0:
if left_half[0] < right_half[0]:
res.append(left_half[0])
left_half.remove(left_half[0])
else:
res.append(right_half[0])
right_half.remove(right_half[0])
if len(left_half) == 0:
res = res + right_half
else:
res = res + left_half
return res
unsorted_list = [64, 34, 25, 12, 22, 11, 90]
print(merge_sort(unsorted_list))

Output: [11, 12, 22, 25, 34, 64, 90]

10. Write the program for selection sort and linear search algorithms.

Selection Sort
 In selection sort we start by finding the minimum value in a given list and move it to a
sorted list.
 Then we repeat the process for each of the remaining elements in the unsorted list.
 The next element entering the sorted list is compared with the existing elements and
placed at its correct position.
 So, at the end all the elements from the unsorted list are sorted.

Example:
def selection_sort(input_list):
for idx in range(len(input_list)):
min_idx = idx
for j in range( idx +1, len(input_list)):
if input_list[min_idx] > input_list[j]:
min_idx = j
# Swap the minimum value with the compared value
input_list[idx], input_list[min_idx] = input_list[min_idx], input_list[idx]
l = [19,2,31,45,30,11,121,27]
selection_sort(l)
print(l)

Output: [2, 11, 19, 27, 30, 31, 45, 121]

Linear search:
 In this type of search, a sequential search is made over all items one by one.
 Every item is checked and if a match is found then that particular item is returned,
otherwise the search continues till the end of the data structure.

Example:
def linear_search(values, search_for):
search_at = 0
search_res = False
# Match the value with each data element
while search_at < len(values) and search_res is False:
if values[search_at] == search_for:
search_res = True
else:
search_at = search_at + 1
return search_res
l = [64, 34, 25, 12, 22, 11, 90]
print(linear_search(l, 12))
print(linear_search(l, 91))

Output:
True
False

You might also like