Python PF
Python PF
4. Write a program that return True or False depending on whether the given
number is a palindrome.
n=int(input("Enter number:"))
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("Palindrome = TRUE")
else:
print("Palindrome = FALSE")
3. Write a Python program to get a string made of the first 2 and the last 2
chars from a given a string.
str = input("Enter string:")
count=0
for i in str:
count=count+1
new=str[0:2]+str[count-2:count]
print("Newly formed string is:")
print(new)
4. Write a Python program to get a string from a given string where all
occurrences of its first char have been changed to '$', except the first char
itself.
def change_char(str1):
char = str1[0]
str1 = str1.replace(char, '$')
str1 = char + str1[1:]
return str1
print(change_char('restart'))
5. Write a Python program to get a single string from two given strings,
separated by a space and swap the first two characters of each string.
def chars_mix_up(a, b):
new_a = b[:2] + a[2:]
new_b = a[:2] + b[2:]
return new_a + ' ' + new_b
print(chars_mix_up('abc', 'xyz'))
6. Write a Python program to add 'ing' at the end of a given string (length
should be at least 3). If the given string already ends with 'ing' then add 'ly'
instead. If the string length of the given string is less than 3, leave it
unchanged.
def add_string(str1):
length = len(str1)
if length > 2:
if str1[-3:] == 'ing':
str1 += 'ly'
else:
str1 += 'ing'
return str1
print(add_string('ab'))
print(add_string('abc'))
print(add_string('string'))
7. Write a Python program to find the first appearance of the substring 'not'
and 'poor' from a given string, if 'not' follows the 'poor', replace the whole
'not'...'poor' substring with 'good'. Return the resulting string.
def not_poor(str1):
snot = str1.find('not')
spoor = str1.find('poor')
if spoor > snot and snot>0 and spoor>0:
str1 = str1.replace(str1[snot:(spoor+4)], 'good')
return str1
else:
return str1
print(not_poor('The lyrics is not that poor!'))
print(not_poor('The lyrics is poor!'))
8. Write a Python program that takes a list of words and returns the length of
the longest one.
def find_longest_word(words_list):
word_len = []
for n in words_list:
word_len.append((len(n), n))
word_len.sort()
return word_len[-1][0], word_len[-1][1]
result = find_longest_word(["PHP", "Exercises", "Backend"])
print("Longest word: ",result[1])
print("Length of the longest word: ",result[0])
9. Write a Python program to remove the nth index character from a nonempty
string.
def remove(str, n):
first = str[:n]
last = str[n+1:]
return first + last
str=input("Enter the sring:")
n=int(input("Enter the index of the character to remove:"))
print("Modified string:")
print(remove(str, n))
15.Write a Python program to display a number in left, right and center aligned
of width 10.
x = 22
print("Original Number: ", x)
print("Left aligned (width 10) :"+"{:< 10d}".format(x));
print("Right aligned (width 10) :"+"{:10d}".format(x));
print("Center aligned (width 10) :"+"{:^10d}".format(x));
20.Write a Python program to count and display the vowels of a given text.
def vowel(text):
vowels = "aeiuoAEIOU"
print(len([letter for letter in text if letter in vowels]))
print([letter for letter in text if letter in vowels])
vowel('HelloWorld');
22.Write a Python program to find the first repeated word in a given string.
def first_repeated_word(str1):
temp = set()
for word in str1.split():
if word in temp:
return word;
else:
temp.add(word)
return 'None'
print(first_repeated_word("ab ca bc ab"))
print(first_repeated_word("ab ca bc ab ca ab bc"))
print(first_repeated_word("ab ca bc ca ab bc"))
print(first_repeated_word("ab ca bc"))
23.Write a Python program to find the second most repeated word in a given
string.
def word_count(str):
counts = dict()
words = str.split()
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
counts_x = sorted(counts.items(), key=lambda kv: kv[1])
return counts_x[-2]
print(word_count("aa cc dd cc bb aa cc bb aa dd aa"))
25.Write a Python program to capitalize first and last letters of each word of a
given string.
def capitalize_first_last_letters(str1):
str1 = result = str1.title()
result = ""
for word in str1.split():
result += word[:-1] + word[-1].upper() + " "
return result[:-1]
print(capitalize_first_last_letters("hello world"))
27.Write a Python program to create two strings from a given string. Create the
first string using those character which occurs only once and create the
second string which consists of multi-time occurring characters in the said
string.
from collections import Counter
def generateStrings(input):
str_char_ctr = Counter(input)
part1 = [ key for (key,count) in str_char_ctr.items() if count==1]
part2 = [ key for (key,count) in str_char_ctr.items() if count>1]
part1.sort()
part2.sort()
return part1,part2
input = "aabbcceffgh"
s1, s2 = generateStrings(input)
print(''.join(s1))
print(''.join(s2))
29.Write a Python program to count Uppercase, Lowercase, special character
and numeric values in a given string.
def count_chars(str):
upper_ctr, lower_ctr, number_ctr, special_ctr = 0, 0, 0, 0
for i in range(len(str)):
if str[i] >= 'A' and str[i] <= 'Z': upper_ctr += 1
elif str[i] >= 'a' and str[i] <= 'z': lower_ctr += 1
elif str[i] >= '0' and str[i] <= '9': number_ctr += 1
else: special_ctr += 1
return upper_ctr, lower_ctr, number_ctr, special_ctr
str = "# He110 W0r1d @ H0w Are Y0u"
print("Original Substrings:",str)
u, l, n, s = count_chars(str)
print('Upper case characters: ',u)
print('Lower case characters: ',l)
print('Number case: ',n)
print('Special case characters: ',s)
1. Write a Python program to get the second largest number from a list.
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
a.sort()
print("Second largest element is:",a[n-2])
2. Write a Python program to count the number of strings where the string
length is 2 or more and the first and last character are same from a given list
of strings.
def match_words(words):
ctr = 0
for word in words:
if len(word) > 1 and word[0] == word[-1]:
ctr += 1
return ctr
print(match_words(['abc', 'xyz', 'aba', '1221']))
3. Write a Python program to remove duplicates from a list.
a = [10,20,30,20,10,50,60,40,80,50,40]
dup_items = set()
uniq_items = []
for x in a:
if x not in dup_items:
uniq_items.append(x)
dup_items.add(x)
print(dup_items)
4. Write a Python program to get the difference between the two lists.
list1 = [1, 3, 5, 7, 9]
list2=[1, 2, 4, 6, 7, 8]
diff_list1_list2 = list(set(list1) - set(list2))
diff_list2_list1 = list(set(list2) - set(list1))
total_diff = diff_list1_list2 + diff_list2_list1
print(total_diff)
13.Write a Python program to replace the last element in a list with another
list.
num1 = [1, 3, 5, 7, 9, 10]
num2 = [2, 4, 6, 8]
num1[-1:] = num2
print(num1)
14.Write a Python program to find the list in a list of lists whose sum of
elements is the highest.
num = [[1,2,3], [4,5,6], [10,11,12], [7,8,9]]
print(max(num, key=sum))
18.Write a Python program to remove the K'th element from a given list, print
the new list.
def remove_kth_element(n_list, L):
return n_list[:L-1] + n_list[L:]
n_list = [1,1,2,3,4,4,5,1]
print("Original list:")
print(n_list)
kth_position = 3
result = remove_kth_element(n_list, kth_position)
print("After removing an element at the kth position of the said list:")
print(result)
7. Write a Python program to remove the intersection of a 2nd set from the
1st set.
sn1 = {1,2,3,4,5}
sn2 = {4,5,6,7,8}
print("Original sets:")
print(sn1)
print(sn2)
print("Remove the intersection of a 2nd set from the 1st set")
sn1.difference_update(sn2)
print("sn1: ",sn1)
print("sn2: ",sn2)
PYTHON PROGRAMS ON DICTIONARY
7. Write a Python program to sum and multiply all the items in a dictionary.
my_dict = {'data1':100,'data2':-54,'data3':247}
result=0
for key in my_dict:
result=result + my_dict[key]
print("SUM = ", result)
result=1
for key in my_dict:
result=result * my_dict[key]
print("MULTIPLY = ",result)
2. Insert records in tables Hospital and Doctor by taking input from user.
import sqlite3
c=sqlite3.connect('Database')
cur=c.cursor()
ch='y'
while ch=='y':
hospid=int(input('enter the hospital id:'))
hospname=input('enter hospital name:')
beds=int(input('enter the bed count:'))
cur.execute('insert into Hospital
values(?,?,?)',(hospid,hospname,beds))
print('want to enter values?(y/n)')
ch=input()
ch='y'
while ch=='y':
docid=int(input('enter the doctor id:'))
docname=input('enter the doctor\'s name:')
hospid=int(input('enter the hospital id:'))
join=input('enter the joining date(dd-mm-yyyy)')
spec=input('enter the speciality:')
sal=int(input('enter the salary:'))
exp=int(input('enter the experience:'))
cur.execute('insert into Doctor
values(?,?,?,?,?,?,?)',(docid,docname,hospid,join,spec,sal,exp))
print('want to enter values?(y/n)')
ch=input()
c.commit()
c.close()
3. Fetch Hospital and Doctor Information using hospital Id and doctor Id
Implement the functionality to read the details of a given doctor from the
doctor table and Hospital from the hospital table. i.e., read records from
Hospital and Doctor Table as per given hospital Id and Doctor Id.
import sqlite3
c=sqlite3.connect("Database")
cur=c.cursor()
cur.execute('select * from Doctor ')
r=cur.fetchall()
for i in r:
print(i)
cur.execute('select * from Hospital')
r=cur.fetchall()
for i in r:
print(i)
c.close()
4. Get the list of doctors as per the given specialty and salary
Fetch all doctors whos salary higher than the input amount and specialty is
the same as the input specialty.
import sqlite3
c=sqlite3.connect('Database')
cur=c.cursor()
cur.execute('select * from Doctor where salary>45000 and
speciality="neurologist"')
r=cur.fetchall()
for i in r:
print(i)
c.close()