UNIT 3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

VELAMMAL ENGINEERING COLLEGE

Department of Computer Science and Engineering


19CS103T /Programming for Problem Solving using Python
19CS105T/Python Programming
UNIT-III STRINGS and LISTS
Strings-String slices, immutability, string methods and operations
-Lists-creating lists, list operations, list methods, mutability,
aliasing, cloning lists, list traversal, list processing
list comprehension. Illustrative programs: String palindrome,
linear search, binary search.
1. Strings:
❖ String is a sequence which is made up of one or more UNICODE
characters.
❖ The character can be a letter,digit, whitespace or any
other symbol.
❖ Python has a built-in string class named "str" that has many useful
features.
❖ A string can be created by enclosing one or more characters in
single,double or triple quote.
❖ To declare and define a string by creating a variable of string type:
>>> name = "India"
>>> graduate = 'N’
>>> str3 = """Hello World!"""
>>> str4 = '''Hello World!'''
>>>country = name nationality = str("Indian")
2. Accessing Characters in a String - Index:
❖ Individual characters in a string are accessed using the subscript ([])
operator. The expression in brackets is called an index.
❖ The index specifies a member of an ordered set and in this case it
specifies the character to be accessed from the given set of characters
in the string.
l=[1, 'a', 'abc',[40,50,60,70],2.5]
print(l[3][1])
Output:
50
#1: Using For loop
list = [1, 3, 5, 7, 9]
for i in list:
print(i)
Output :
1
3
5
7
9
#2: For loop and range()
list = [1, 3, 5, 7, 9]
length = len(list)
for i in range(length):
print(list[i])
Output :
1
3
5
7
`
9
#3: Using while loop
list = [1, 3, 5, 7, 9]
length = len(list) i = 0
while i < length:
print(list[i])
i += 1
Output :
1
3
5
7
9
x = [5, 2, 3]
y = [7, 9, 10]

print("Concatenation of list x and y :", x + y)


print("Repetition of list y :", y *3)
print("3 in x :", x + y)
print(x>y, x!=y)
print(len(x))
print("Maximum in list x :", max(x))
print("Minimum in list x :", min(x))
print("Sum of list x :", sum(x))
print("all fn using y :", all(y))
print("any fn using y :", any(y))
print("sorting list x :", sorted(x))
print("Converting string to list :", list("abcd"))
Output :
Concatenation of list x and y : [5, 2, 3, 7, 9, 10]
Repetition of list y : [7, 9, 10, 7, 9, 10, 7, 9, 10]
3 in x : [5, 2, 3, 7, 9, 10]
False True
3
Maximum in list x : 5
Minimum in list x : 2
Sum of list x : 10
all fn using y : True
any fn using y : True
sorting list x : [2, 3, 5]
Converting string to list : ['a', 'b', 'c', 'd']

n=[6,0,1,2,9,3,2,0,3]
print(n.index(9))
print(n.index(10))
Output :
4
Traceback (most recent call last):
File "<string>", line 3, in <module>
ValueError: 10 is not in list

n=[6,0,1,2,9]
n.append(10)
print(n)
n.append([11,12,13])
print(n)
Output :
[6, 0, 1, 2, 9, 10]
[6, 0, 1, 2, 9, 10, [11, 12, 13]]
n=[6,0,1,2,9,3,2,0,3]
print(n.count(3))
Output :
2

n=[6,0,1,2,9]
n.remove(1)
n=[6,0,1,2,9]
n.insert(2,50)
print(n)
Output :
[6, 0, 50, 1, 2, 9]
n=[6,0,1,2,9]
n.pop(1)
print(n)
n.pop()
print(n)
Output :
[6, 1, 2, 9]
[6, 1, 2]

print(n)
n.remove(10)
print(n)
Output :
[6, 0, 2, 9]
Traceback (most recent call last):
File "<string>", line 4, in <module>
ValueError: list.remove(x): x not in list

n=[6,0,1,2,9]
n.reverse()
print(n)
Output :
[9, 2, 1, 0, 6]

n=[6,0,1,2,9]
n.sort()
print(n)
Output :
[0, 1, 2, 6, 9]

n=[6,0,1,2,9]
n.extend([11,12,13])
print(n)
Output :
[6, 0, 1, 2, 9, 11, 12, 13]

x=[10,20,30,40]
y=x
print(id(x))
print(id(y))
Output:
139985896812096
139985896812096

n=[6,0,1,2,9]
n.clear()
print(n)
Output :
[ ]

n=[6,0,1,2,9]
a=n.copy()
print(n)
print(a)
Output :
[6, 0, 1, 2, 9]
[6, 0, 1, 2, 9]

Ex:
x=[10,20,30,40]
y=x[:]
y[1]=777
print(x)
print(y)
Output :
[10,20,30,40]
[10,777,30,40]

def Cloning(li1):
li_copy = list(li1)
return li_copy
li1 = [4, 8, 2, 10, 15, 18]
li2 = Cloning(li1)
print("Original List:", li1)
print("After Cloning:", li2)
Output :
Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]

def Cloning(li1):
li_copy =[]
li_copy = li1.copy()
return li_copy
# Driver Code
li1 = [4, 8, 2, 10, 15, 18]
li2 = Cloning(li1)
print("Original List:", li1)
print("After Cloning:", li2)
Output :
Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]

def Cloning(li1):
li_copy =[]
for item in li1:
li_copy.append(item)
return li_copy
li1 = [4, 8, 2, 10, 15, 18]
li2 = Cloning(li1)
print("Original List:", li1)
print("After Cloning:", li2)
Output :
Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


squares = [x**2 for x in lst]
print(squares)
for i in range(10):
if i % 2 ==0:
print(i)
Output
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[0, 2, 4, 6, 8]

21. Illustrative programs


1. Write a Python program to find String palindrome
Program:
a=input("Enter a string:")
b=a.lower()
c=b[::-1]
if b==c:
print(a,"is a palindrome")
else:
print(a,"is not a palindrome")
Output:
Enter a string: Radar
Radar is a palindrome

2. Write a Python program to perform linear search using list


Program:
def linear(lst,sval):
for i in range(len(lst)):
if lst[i]==sval:
return(i)
return -1
n=int(input("Enter no. of elements:"))
l=[]
for i in range(n):
val=int(input("enter value:"))
l.append(val)
print(l)
searchval= int(input("enter value to be searched:"))
a=linear(l,searchval)
if a==-1:
print("Element not found")
else:
print("Element found at index",a)
Output:
Enter no. of elements:5
enter value:23
enter value:45
enter value:67
enter value:89
enter value:100
[23,45,67,89,100]
enter value to be searched:67
Element found at index 2

3.Write a Python program to perform binary search using list


Program:
def binsearch(lst,sval):
low,high=0,(len(lst)-1)
while (low<high):
mid=(low+high)//2
if lst[mid]<sval:
low=mid+1
elif lst[mid]>sval:
high=mid-1
else:
return(mid)
return -1
n=int(input("Enter the no of elements in list:"))
l =[]
for i in range(n):
ele=int(input("Enter the list elements:"))
l.append(ele)
x = int(input("Enter the element to search:"))
a=binsearch(l,x)
if a==-1:
print("Element not found")
else:
print("Element found at index",a)
Output:
Enter the no of elements in list:5
Enter the list elements:2
Enter the list elements:3
Enter the list elements:4
Enter the list elements:5
Enter the list elements:6
Enter the element to search:8
Element not found

5. Implement python script to perform the following on matrix:


i.Add matrices
#i) MATRIX MULTIPLICATION
A=[[1,2,3],
[1,2,3],
[1,2,3]]
B=[[2,3,1],
[2,3,1],
[2,3,1]]
C=[[0,0,0],
[0,0,0],
[0,0,0]]
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
C[i][j]+=A[i][k]*B[k][j]
for r in C:
print(r)
Output :
[12, 18, 6]
[12, 18, 6]
[12, 18, 6]
ii.Multiply matrices
#ii) MATRIX ADDITION
A=[[3,3,3],
[2,2,2],
[1,1,1]]
B=[[1,1,1],
[2,2,2],
[3,3,3]]
C=[[0,0,0],
[0,0,0],
[0,0,0]]
for i in range(len(A)):
for j in range(len(A[0])):
C[i][j]=A[i][j]+B[i][j]
for r in C:
print(r)
Output :
[4, 4, 4]
[4, 4, 4]
[4, 4, 4]
iii.Find Transpose of a matrix
#iii) TRANSPOSE OF MATRIX
A=[[1,2,3],
[4,5,6]]
B=[[0,0],
[0,0],
[0,0]]
for i in range(len(A)):
for j in range(len(A[0])):
B[j][i] = A[i][j]
for r in B:
print(r)
Output :
[1, 4]
[2, 5]
[3, 6]

5. Write a Python Program to Remove the Duplicate Items from a List.


Program:
list1=[2,8,4,5]
list2=[4,7,8,9]
list_intersection = list(set(list1) ^ set(list2))
print("Intersection of {} and {} is : {}".format(list1, list2,
list_intersection))
Output:
Intersection of [2, 8, 4, 5] and [4, 7, 8, 9] is : [2, 5, 7, 9]

6. Write a function called is_anagram that takes two strings and returns True
if they are anagrams.
Program:
def is_anagram(s1,s2):
s1=sorted(s1)
s2=sorted(s2)
if(s1==s2):
return True
else:
return False
a=input("enter 1st string:")
b=input("enter 2nd string:")
print("Is Anagram:",is_anagram(a.lower(),b.lower()))
Output:
enter 1st string:Ajax
enter 2nd string:Jaxa
Is Anagram: True

7. Write a function deleteChar() which takes two parameters one is a string


and other is a
character. The function should create a new string after deleting all
occurrences of the character
from the string and return the new string.
Program:
def delchar(string,char):
str=" "
for i in string:
if i==char:
str=string.replace(i, '')
return str
a=input("enter string:")
b=input("enter char to be deleted:")
print("the string:", delchar(a, b))
Output :
enter string:abcdxyzd
enter char to be deleted:d
the string: abcxyz

8. Write a Python program to count Uppercase, Lowercase, special character and


numeric
values in a given string.
Programs:
v='Shop open@3pm'
s=v.replace(" ","")
a=0
b=0
c=0
d=0
for i in s:
if i.isdigit()==True:
a+=1
elif i.isupper()==True:
b+=1
elif i.islower()==True:
c+=1
else:
d+=1
print('digit values:',a)
print('uppercase letters:',b)
print('lower case letters:',c)
print('special char:',d)
Output:
digit values: 1
uppercase letters: 1
lower case letters: 9
special charc: 1

9.Count no. of vowels and consonants in string


Program:
str=input("Enter string:")
str1="".join(str.split())
vowel="aeiou"
vcount=0
ccount=0
for i in str1:
if i.lower() in vowel:
vcount+=1
else:
ccount+=1
print("No. of vowels in string ",str ,vcount)
print("No. of consonents in string ",str ,ccount)
Output
Enter string:python program
No. of vowels in string python program 3
No. of consonents in string python program 10

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy