Write Python Script For Following: Practical:Set - 3
Write Python Script For Following: Practical:Set - 3
Write Python Script For Following: Practical:Set - 3
Practical :Set -3
1. Given a string of odd length greater 7, return a string made of the middle three
chars of a given String .
Program:
def getMiddleThreeChars(sampleStr):
middleIndex = int(len(sampleStr) /2)
print("Original String is", sampleStr)
middleThree = sampleStr[middleIndex-1:middleIndex+2]
print("Middle three chars are", middleThree)
getMiddleThreeChars("nencyahir")
getMiddleThreeChars("ahirnencyy")
Output:
Output
Original String is nencyahir
2. Given 2 strings, s1 and s2, create a new string by appending s2 in the middle of s1
1
PDS_3 190170107147
appendMiddle("ahir", "nency")
Output
Original Strings are ahir nency
3. Given 2 strings, s1, and s2 return a new string made of the first, middle and last
char each input string
Program:
def mix_string(s1, s2):
first_char = s1[:1] + s2[:1]
middle_char = s1[int(len(s1) / 2):int(len(s1) / 2) + 1] + s2[int(len(s2)
/ 2):int(len(s2) / 2) + 1]
last_char = s1[len(s1) - 1] + s2[len(s2) - 1]
res = first_char + middle_char + last_char
print("Mix String is ", res)
s1 = "vaghamshi"
s2 = "nency"
mix_string(s1, s2)
2
PDS_3 190170107147
Output:
Output
Mix String is vnaniy
Program:
inputString = "Welcome to USA. usa awesome, isn't it?"
substring = "USA"
tempString = inputString.lower()
count = tempString.count(substring.lower())
print("The USA count is:", count)
Output:
Output
The USA count is: 2
5. Given a two list. Create a third list by picking an odd-index element from the
first list and even index elements from second.
Program:
listOne = [7, 6, 9, 56, 15, 18, 21]
listTwo = [6, 8, 12, 16, 60, 24, 28]
listThree = list()
3
PDS_3 190170107147
oddElements = listOne[1::2]
print("Element at odd-index positions from list one")
print(oddElements)
EvenElement = listTwo[0::2]
print("Element at even-index positions from list two")
print(EvenElement)
Output:
Output
Element at odd-index positions from list one
6. Given a list iterate it and count the occurrence of each element and create a
dictionary to show the count of each element
Program:
4
PDS_3 190170107147
countDict = dict()
for item in sampleList:
if(item in countDict):
countDict[item] += 1
else:
countDict[item] = 1
Output
Original list [11, 45, 8, 11, 23, 45, 23, 45, 89]
7. Given a two list of equal size create a set such that it shows the element from
both lists in the pair
Program:
firstList = [2, 3, 4, 5, 6, 7, 8]
print("First List ", firstList)
5
PDS_3 190170107147
Output:
Output
First List [2, 3, 4, 5, 6, 7, 8]
{(6, 36), (8, 64), (4, 16), (5, 25), (3, 9), (7, 49), (2, 4)}
8. Iterate a given list and Check if a given element already exists in a dictionary as
a key’s value if not delete it from the list
Program:
Output:
Output
List - [37, 64, 69, 37, 76, 83, 95, 97]
after removing unwanted elemnts from list [37, 69, 37, 76, 97]
6
PDS_3 190170107147