Assignment 2: # Even # Odd
Assignment 2: # Even # Odd
Solution:
str=input(“Enter a string”)
print(str)
Output:
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):
if __name__ == "__main__":
input = 'Aman Mohanty'
print (rev_sentence(input))
Output:
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:
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:
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:
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):
# Driver code
str = "Good Morning India. Have a good day"
# Function Call
vowel_count(str)
Output:
Solution:
def remove_duplicate(s):
return "".join(OrderedDict.fromkeys(s))
# test
s="aman mohanty"
print(s)
print("After removing duplicates: ",remove_duplicate(s))
Output:
Solution:
# initializing string
test_str = "amanmohanty"
# printing result
print ("The minimum of all characters in amanmohanty is : " +res)
Output:
Solution:
# initializing string
test_str = "AMANMOHANTY"
# printing result
print ("The minimum of all characters in AMANMOHANTY is : " +res)
Output:
16. Python – Odd Frequency Characters
Solution:
# 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 result
print("The Odd Frequency Characters are : " + str(res))
Output:
Solution:
# initializing lists
test_list = ["chennai super kings"]
# printing original list
print("The original list : " + str(test_list))
# char list
chr_list = ['c', 's', 'k']
# printing result
print("Specific Characters Frequencies : " + str(res))
Output:
Solution:
import re
# initializing string
test_str = "fgtdg5 3 5 3 5 4 6 7 2 3 "
# printing result
print("Count of numerics in string : " +str(res))
Output:
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:
Solution:
import string
import random
import time
attemptThis = ''.join(random.choice(possibleCharacters)
for i in range(len(t)))
attemptNext = ''
completed = False
iteration = 0
# Driver Code
print("Target matched after " + str(iteration) + " iterations")
Output:
21.
Solution:
# Driver Program
k=3
str ="Chennai super kings"
print(string_k(k, str))
Output:
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:
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:
Solution:
def check(string) :
# 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:
Output:
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
Output:
Solution:
def allPermutations(str):
# Driver program
if __name__ == "__main__":
str = 'ABC'
allPermutations(str)
Output:
29. Python | Check for URL in a String
Solution:
import re
def Find(string):
# Driver Code
string = 'My Profile: http://www.facebook.com'
print("Urls: ", Find(string))
Output:
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
# Driver Code
exec_code()
Output: