0% found this document useful (0 votes)
388 views

Assignment 2: # Even # Odd

The document contains 19 Python programs related to string operations and manipulations. Some of the programs included: 1. A program to enter a string and print it. 2. A program to check if a string is symmetrical or a palindrome. 3. Programs to reverse words in a string, find the length of a string, avoid spaces in string length calculation, and print even length words in a string. 4. Other programs include uppercase half a string, capitalize the first and last characters of each word, check for letters and numbers, accept strings with all vowels, and count matching characters between two strings.

Uploaded by

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

Assignment 2: # Even # Odd

The document contains 19 Python programs related to string operations and manipulations. Some of the programs included: 1. A program to enter a string and print it. 2. A program to check if a string is symmetrical or a palindrome. 3. Programs to reverse words in a string, find the length of a string, avoid spaces in string length calculation, and print even length words in a string. 4. Other programs include uppercase half a string, capitalize the first and last characters of each word, check for letters and numbers, accept strings with all vowels, and count matching characters between two strings.

Uploaded by

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

Assignment 2

1. Python program to enter a String and print the string.

Solution:

str=input(“Enter a string”)
print(str)

Output:

2. Python program to check whether the string is Symmetrical or Palindrome.

Solution:
string = input('Enter the string ')
half = int(len(string) / 2)
 
if len(string) % 2 == 0:  # even
    first_str = string[:half]
    second_str = string[half:]
else:   # odd
    first_str = string[:half]
    second_str = string[half+1:]
 
# symmetric
if first_str == second_str:
    print(string, 'string is symmertical')
else:
    print(string, 'string is not symmertical')
 
# palindrome
if first_str == second_str[::-1]:  # ''.join(reversed(second_str)) [slower]
    print(string, 'string is palindrome')
else:
    print(string, 'string is not palindrome')

Output:
3. Reverse words in a given String in Python

Solution:
# Function to reverse words of string

def rev_sentence(sentence):

# first split the string into words


words = sentence.split(' ')
# then reverse the split string list and join using space
reverse_sentence = ' '.join(reversed(words))

# finally return the joined string


return reverse_sentence

if __name__ == "__main__":
input = 'Aman Mohanty'
print (rev_sentence(input))

Output:

4. Find length of a string in python


Solution:
# Python code to demonstrate string length 
# using for loop
  
# Returns length of string
def findLen(str):
    counter = 0    
    for i in str:
        counter += 1
    return counter
  
  
str = "Aman Mohanty"
print(findLen(str))

Output:
5. Python – Avoid Spaces in string length

Solution:

# Python3 code to demonstrate working of 
# Avoid Spaces in Characters Frequency
# Using sum() + len() + map() + split()
  
# initializing string
test_str = 'Pakistan defeated India by 10 wickets'
  
# printing original string
print("The original string is : " ,test_str)
  
# len() finds individual word Frequency 
# sum() extracts final Frequency
res = sum(map(len, test_str.split()))
      
# printing result 
print("The Characters Frequency avoiding spaces : ",res)

Output:

6. Python program to print even length words in a string

Solution:
# Python3 program to print 
#  even length words in a string 
  
def printWords(s):
      
    # split the string 
    s = s.split(' ') 
      
    # iterate in words of string 
    for word in s: 
          
        # if length is even 
        if len(word)%2==0:
            print(word) 
  
  
# Driver Code 
s = "Pakistan defeated India by 10 wickets" 
printWords(s) 

Output:

7. Python – Uppercase Half String


Solution:
# Python3 code to demonstrate working of 
# Uppercase Half String
# Using upper() + loop + len()
  
# initializing string
test_str = 'Aman Mohanty'
  
# printing original string
print("The original string is : ",test_str)
  
# computing half index
hlf_idx = len(test_str) // 2
  
res = ''
for idx in range(len(test_str)):
      
    # uppercasing later half
    if idx >= hlf_idx:
      res += test_str[idx].upper()
    else :
      res += test_str[idx]
      
      # printing result 
print("The resultant string : ",res)

Output:

8. Python program to capitalize the first and last character of each word in a string

Solution:

# Python program to capitalize
# first and last character of 
# each word of a String
  
  
# Function to do the same
def word_both_cap(str):
      
    #lamda function for capitalizing the
    # first and last letter of words in 
    # the string
    return ' '.join(map(lambda s: s[:-1]+s[-1].upper(), 
                        s.title().split()))
      
      
# Driver's code
s = "Pakistan defeated India by ten wickets"
print("String before:", s)
print("String after:", word_both_cap(str))

Output:

9. Python program to check if a string has at least one letter and one number

Solution:

def checkString(str):
    
    # intializing flag variable
    flag_l = False
    flag_n = False
      
    # checking for letter and numbers in 
    # given string
    for i in str:
        
        # if string has letter
        if i.isalpha():
            flag_l = True
  
        # if string has number
        if i.isdigit():
            flag_n = True

             # returning and of flag
    # for checking required condition
    return flag_l and flag_n
  
  
# driver code
print(checkString('Pakistan defeated India by 10 wickets'))
print(checkString('Aman Mohanty'))

Output:

10. Python | Program to accept the strings which contains all vowels

Solution:

def check(string):
    string = string.replace(' ', '')
    string = string.lower()
    vowel = [string.count('a'), string.count('e'), string.count(
        'i'), string.count('o'), string.count('u')]
 
    # If 0 is present int vowel count array
    if vowel.count(0) > 0:
        return('not accepted')
    else:
        return('accepted')
 
 
# Driver code
if __name__ == "__main__":
 
    string = "abcdefghijklmnpqrstuvwxyz"
 
    print(check(string))

Output:

11. Python | Count the Number of matching characters in a pair of string

Solution:

def count(s1, s2):
    c=0 #counter variable
    j=0
    for i in s1:
        if s2.find(i)>=0 and j==s1.find(i):
            c=c+1
        j=j+1
    print("Matching char: ",c)

s1="England"
s2="New Zealand"
count(s1,s2)

Output:

12. Python program to count number of vowels using sets in given string

Solution:

def vowel_count(str):

# Initializing count variable to 0


count = 0

# Creating a set of vowels


vowel = set("aeiouAEIOU")

# Loop to traverse the alphabet


# in the given string
for alphabet in str:
# If alphabet is present
# in set vowel
if alphabet in vowel:
count = count + 1

print("No. of vowels :", count)

# Driver code
str = "Good Morning India. Have a good day"

# Function Call
vowel_count(str)

Output:

13. Python Program to remove all duplicates from a given string

Solution:

from collections import OrderedDict

def remove_duplicate(s):
return "".join(OrderedDict.fromkeys(s))

# test
s="aman mohanty"
print(s)
print("After removing duplicates: ",remove_duplicate(s))

Output:

14. Python – Least Frequent Character in String

Solution:

# initializing string
test_str = "amanmohanty"

# printing original string


print ("The original string is : " + test_str)

# using naive method to get


# Least Frequent Character in String
all_freq = {}
for i in test_str:
if i in all_freq:
all_freq[i] += 1
else:
all_freq[i] = 1
res = min(all_freq, key = all_freq.get)

# printing result
print ("The minimum of all characters in amanmohanty is : " +res)

Output:

15. Python | Maximum frequency character in String

Solution:

# initializing string
test_str = "AMANMOHANTY"

# printing original string


print ("The original string is : " + test_str)

# using naive method to get


# Least Frequent Character in String
all_freq = {}
for i in test_str:
if i in all_freq:
all_freq[i] += 1
else:
all_freq[i] = 1
res = max(all_freq, key = all_freq.get)

# printing result
print ("The minimum of all characters in AMANMOHANTY is : " +res)

Output:
16. Python – Odd Frequency Characters

Solution:

from collections import defaultdict

# helper_function
def hlper_fnc(test_str):
cntr = defaultdict(int)
for ele in test_str:
cntr[ele] += 1
return [val for val, chr in cntr.items() if chr % 2 != 0]

# initializing string
test_str = 'Chennai super kings'

# printing original string


print("The original string is : " + test_str)

# Odd Frequency Characters


# Using list comprehension + defaultdict()
res = hlper_fnc(test_str)

# printing result
print("The Odd Frequency Characters are : " + str(res))

Output:

17. Python – Specific Characters Frequency in String List

Solution:

# Python3 code to demonstrate working of


# Specific Characters Frequency in String List
# Using join() + Counter()
from collections import Counter

# initializing lists
test_list = ["chennai super kings"]
# printing original list
print("The original list : " + str(test_list))

# char list
chr_list = ['c', 's', 'k']

# dict comprehension to retrieve on certain Frequencies


res = {key:val for key, val in dict(Counter("".join(test_list))).items() if key in chr_list}

# printing result
print("Specific Characters Frequencies : " + str(res))
Output:

18. Python | Frequency of numbers in String

Solution:

import re

# initializing string
test_str = "fgtdg5 3 5 3 5 4 6 7 2 3 "

# printing original string


print("The original string is : " + test_str)

# Frequency of numbers in String


# Using re.findall() + len()
res = len(re.findall(r'\d+', test_str))

# printing result
print("Count of numerics in string : " +str(res))

Output:

19. Python | Program to check if a string contains any special character

Solution:

# Python program to check special character
# import required package
import re

# take inputs
string = input('Enter any string: ')
 
# special characters
special_char = re.compile('[@_!#$%^&*()<>?/\|}{~:]')

# check string contains special characters or not
if(special_char.search(string) == None):
    print('String does not contain any special characters.')
else:
    print('The string contains special characters.')

Output:

20. Generating random strings until a given string is generated

Solution:

import string
import random
import time

possibleCharacters = string.ascii_lowercase + string.digits + string.ascii_uppercase +


' ., !?;:'

t = input("Enter your target text: ")

attemptThis = ''.join(random.choice(possibleCharacters)
for i in range(len(t)))
attemptNext = ''

completed = False
iteration = 0

# Iterate while completed is false


while completed == False:
print(attemptThis)
attemptNext = ''
completed = True

# Fix the index if matches with


# the strings to be generated
for i in range(len(t)):
if attemptThis[i] != t[i]:
completed = False
attemptNext += random.choice(possibleCharacters)
else:
attemptNext += t[i]

# increment the iteration


iteration += 1
attemptThis = attemptNext
time.sleep(0.1)

# Driver Code
print("Target matched after " + str(iteration) + " iterations")

Output:

21.

Find words which are greater than


given length k

Solution:

# Python program to find all string


# which are greater than given length k

# function find string greater than length k


def string_k(k, str):
# create the empty string
string = []

# split the string where space is comes


text = str.split(" ")

# iterate the loop till every substring


for x in text:

# if length of current sub string


# is greater than k then
if len(x) > k:

# append this sub string in


# string list
string.append(x)

# return string list


return string

# Driver Program
k=3
str ="Chennai super kings"
print(string_k(k, str))

Output:

22. Python program for removing i-th character from a string

Solution:

# Python3 program for removing i-th 
# indexed character from a string
  
# Removes character at index i
def remove(string, i): 
  
    # Characters before the i-th indexed
    # is stored in a variable a
    a = string[ : i] 
      
    # Characters after the nth indexed
    # is stored in a variable b
    b = string[i + 1: ]
      
    # Returning string after removing
    # nth indexed character.
    return a + b
      
# Driver Code
if __name__ == '__main__':
      
    string = "Chennai Super kings"

    # Remove nth index element
    i = 5
    
    # Print the new string
    print(remove(string, i))

Output:

23. Python program to split and join a string

Solution:

# Python program to split a string and  
# join it using different delimiter
  
def split_string(string):
  
    # Split the string based on space delimiter
    list_string = string.split(' ')
      
    return list_string
  
def join_string(list_string):
  
    # Join the string based on '-' delimiter
    string = '-'.join(list_string)
      
    return string
  
# Driver Function
if __name__ == '__main__':
    string = 'Chennai super kings'
      
    # Splitting a string
    list_string = split_string(string)
    print(list_string)
  
     # Join list of strings into one
    new_string = join_string(list_string)
    print(new_string)

Output:

24. Python | Check if a given string is binary string or not

Solution:

def check(string) :

# set function convert string


# into set of characters .
p = set(string)

# declare set of '0', '1' .


s = {'0', '1'}

# check set p is same as set s


# or set p contains only '0'
# or set p contains only '1'
# or not, if any one condition
# is true then string is accepted
# otherwise not .
if s == p or p == {'0'} or p == {'1'}:
print("Yes")
else :
print("No")

# driver code
if __name__ == "__main__" :

string = "101010101010101010"

# function calling
check(string)

Output:

25. Python | Find all close matches of input string from a list

Solution:

strings = ["Lion", "Li", "Tiger", "Tig"]


element = "Lion"
for string in strings:
## checking for the condition mentioned above
if string.startswith(element) or element.startswith(string):
## printing the eligible string
print(string, end = " ")
print()

Output:

26. Python program to find uncommon words from two Strings

Solution:

def uncommon(a,b):
a=a.split()
b=b.split()
k=set(a).symmetric_difference(set(b))
return k

#Driver code
if __name__=="__main__":
a="Virat Rohit Rahul"
b="Shikhar Rishabh Rohit"
print(list(uncommon(a,b)))

Output:
27. Python | Swap commas and dots in a String

Solution:

def Replace(str1):
str1 = str1.replace(', ', 'third')
str1 = str1.replace('.', ', ')
str1 = str1.replace('third', '.')
return str1

string = "C++, Java, C, Python, HTML."


print(Replace(string))

Output:

28. Python | Permutation of a given string using inbuilt function

Solution:

from itertools import permutations

def allPermutations(str):

# Get all permutations of string 'ABC'


permList = permutations(str)

# print all permutations


for perm in list(permList):
print (''.join(perm))

# Driver program
if __name__ == "__main__":
str = 'ABC'
allPermutations(str)

Output:
29. Python | Check for URL in a String

Solution:

import re

def Find(string):

# findall() has been used


# with valid conditions for urls in string
regex = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\
(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]
{};:'\".,<>?«»“”‘’]))"
url = re.findall(regex,string)
return [x[0] for x in url]

# Driver Code
string = 'My Profile: http://www.facebook.com'
print("Urls: ", Find(string))

Output:

30. Execute a String of Code in Python

Solution:

def exec_code():
LOC = """
def reverse_string(str):
str1 = "" # Declaring empty string to store the reversed string
for i in str:
str1 = i + str1
return str1 # It will return the reverse string to the caller function

str = "Aman Mohanty" # Given String


print("The original string is: ",str)
print("The reverse string is",reverse_string(str))
"""
exec(LOC)

# Driver Code
exec_code()
Output:

You might also like