SE Computer Engineering practical 4 solution

SE Computer Engineering practical 4 solution

Question:

Write a Python program to compute following operations on String:
a) To display word with the longest length
b) To determines the frequency of occurrence of a particular character in the string
c) To check whether given string is palindrome or not
d) To display index of first appearance of the substring
e) To count the occurrences of each word in a given string

Code:

sentence = input("Enter sentence: ")
longest = max(sentence.split(), key=len)

print("Longest word is: ", longest)
print("And its length is: ", len(longest))

# b) To determines the frequency of occurrence of particular character in the string

# using naive method to get count of each element in string
all_freq = {}

for i in sentence:
   if i in all_freq:
       all_freq[i] += 1
   else:
       all_freq[i] = 1

# printing result
print("Count of all characters in sentence is :\n "
     + str(all_freq))
# c) To check whether given string is palindrome or not

text = sentence
print("Given text is " + text)
rev = reversed(text)
if list(text) == list(rev):
   print("its a palindrome")
else:
   print("its not a palindrome")

# d) To display index of first appearance of the substring


sub_str1 = str(input("Enter word"))
print("index of first appearance of the substring " + sub_str1 + " is")
print(sentence.find(sub_str1))

# check if Substring found or not.
if sentence.find(sub_str1) == -1:
   print("Substring Not Found")
else:
   print("Substring found")

#  e) To count the occurrences of each word in a given string.

print("Following are the count the frequency of each word in a given string")


def freq(sentence):
   # break the string into list of words
   sentence = sentence.split()
   str2 = []

   # loop till string values present in list str
   for i in sentence:

       # checking for the duplicacy
       if i not in str2:
           # insert value in str2
           str2.append(i)

   for i in range(0, len(str2)):
       # count the frequency of each word(present in str2) in sentence and print
       print('count of frequency', str2[i], 'is :', sentence.count(str2[i]))


def main():
   # call freq function
   freq(sentence)


main()

Output:

Enter sentence: They speak English at work.
Longest word is:  English
And its length is:  7
Count of all characters in sentence is :
 {'T': 1, 'h': 2, 'e': 2, 'y': 1, ' ': 4, 's': 2, 'p': 1, 'a': 2, 'k': 2, 'E': 1, 'n': 1, 'g': 1, 'l': 1, 'i': 1, 't': 1, 'w': 1, 'o': 1, 'r': 1, '.': 1}
Given text is : They speak English at work.
String is not palindrome
Enter word : speak
index of first appearance of the substring 'speak' is 5
Substring found
Following are the count the frequency of each word in a given string
count of frequency They is : 1
count of frequency speak is : 1
count of frequency English is : 1
count of frequency at is : 1
count of frequency work. is : 1

Process finished with exit code 0
Tech Amplifier Final Logo