0% found this document useful (0 votes)
177 views39 pages

Python PF

The document contains 23 Python programs related to loops and strings. The programs include: 1) calculating the sum of natural numbers using a while loop, 2) printing multiplication tables from 1 to 10 using a for loop, and 3) determining if a number is a perfect number by calculating the sum of its factors. Other programs manipulate strings by counting characters, reversing words, encrypting/decrypting text, and analyzing substrings. The programs demonstrate a variety of common string and loop operations in Python.

Uploaded by

aces thala
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)
177 views39 pages

Python PF

The document contains 23 Python programs related to loops and strings. The programs include: 1) calculating the sum of natural numbers using a while loop, 2) printing multiplication tables from 1 to 10 using a for loop, and 3) determining if a number is a perfect number by calculating the sum of its factors. Other programs manipulate strings by counting characters, reversing words, encrypting/decrypting text, and analyzing substrings. The programs demonstrate a variety of common string and loop operations in Python.

Uploaded by

aces thala
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/ 39

PYTHON PROGRAMS ON LOOP

1. Write a program to find the sum of natural numbers.


 num = int(input("Enter a number: "))
if num < 0:
print("Enter a positive number")
else:
sum = 0
while(num > 0):
sum += num
num -= 1
print("The sum is",sum)

2. Write a program to print the table from 1 to 10 in the following format :


 for i in range(1,11):
print("1x%d=%d 2x%d=%d 3x%d=%d 4x%d=%d 5x%d=%d 6x%d=%d 7x%d=
%d 8x%d=%d 9x%d=%d 10x%d=%d" %
(i,1*i,i,2*i,i,3*i,i,4*i,i,5*i,i,6*i,i,7*i,i,8*i,i,9*i,i,10*i,))

3. Write a program to determine whether a given natural number is a perfect


number.
 n = int(input("Enter any number: "))
sum1 = 0
for i in range(1, n):
if(n % i == 0):
sum1 = sum1 + i
if (sum1 == n):
print("The number is a Perfect number!")
else:
print("The number is not a Perfect number!")

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")

5. Write a program that prints Armstrong numbers in the range 1 to 1000.


 lower = 1
upper = 1000
for num in range(lower,upper + 1):
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
if num == sum:
print(num)

PYTHON PROGRAMS ON STRINGS

1. Write a Python program to calculate the length of a string.


 str = input("Enter a string: ")
counter = 0
for s in str:
counter = counter+1
print("Length of the input string is:", counter)

2. Write a Python program to count the number of characters (character


frequency) in a string.
 string = input("Enter some text: ")
frequency_dict = {}
for character in string:
if character in frequency_dict:
frequency_dict[character] += 1
else:
frequency_dict[character] = 1
print("Character Frequency")
for character, frequency in frequency_dict.items():
print("%5c\t %5d" %(character, frequency))

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))

10.Write a Python program that accepts a comma separated sequence of


words as input and prints the unique words in sorted form
(alphanumerically).
 items = input("Input comma separated sequence of words \n")
words = [word for word in items.split(",")]
print(",".join(sorted(list(set(words)))))

11.Write a Python program to reverses a string if it's length is a multiple of 4.


 def reverse_string(str1):
if len(str1) % 4 == 0:
return ''.join(reversed(str1))
return str1
print(reverse_string('abcd'))
print(reverse_string('python'))

12.Write a Python function to convert a given string to all uppercase if it
contains at least 2 uppercase characters in the first 4 characters.
 def to_uppercase(str1):
num_upper = 0
for letter in str1[:4]:
if letter.upper() == letter:
num_upper += 1
if num_upper >= 2:
return str1.upper()
return str1
print(to_uppercase('Python'))
print(to_uppercase('PyThon'))

13.Write a Python program to check whether a string starts with specified


characters.
 string = "HelloWorld.com"
print(string.startswith("Hell"))

14.Write a Python program to create a Caesar encryption.


 def caesar_encrypt(realText, step):
outText = []
cryptText = []
uppercase = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
lowercase = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
for eachLetter in realText:
if eachLetter in uppercase:
index = uppercase.index(eachLetter)
crypting = (index + step) % 26
cryptText.append(crypting)
newLetter = uppercase[crypting]
outText.append(newLetter)
elif eachLetter in lowercase:
index = lowercase.index(eachLetter)
crypting = (index + step) % 26
cryptText.append(crypting)
newLetter = lowercase[crypting]
outText.append(newLetter)
return outText
Code = caesar_encrypt('HelloWorld', 3)
print(code)

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));

16.Write a Python program to reverse a string.


 txt = "Hello World"[::-1]
print(txt)

17.Write a Python program to reverse words in a string.
 string = "I am a python programmer"
words = string.split()
words = list(reversed(words))
print(" ".join(words))

18.Write a Python program to count repeated characters in a string.


 import collections
str1 = 'thequickbrownfoxjumpsoverthelazydog'
d = collections.defaultdict(int)
for c in str1:
d[c] += 1
for c in sorted(d, key=d.get, reverse=True):
if d[c] > 1:
print('%s-%d' % (c, d[c]),end=",")

19.Write a Python program to check if a string contains all letters of the


alphabet.
 import string
alphabet = set(string.ascii_lowercase)
input_string = 'The quick brown fox jumps over the lazy dog'
print(set(input_string.lower()) >= alphabet)
input_string = 'The quick brown fox jumps over the lazy cat'
print(set(input_string.lower()) >= alphabet)

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');

21.Write a Python program to find the first non-repeating character in given


string.
 def first_non_repeating_character(str1):
char_order = []
ctr = {}
for c in str1:
if c in ctr:
ctr[c] += 1
else:
ctr[c] = 1
char_order.append(c)
for c in char_order:
if ctr[c] == 1:
return c
return None
print(first_non_repeating_character('abcdef'))
print(first_non_repeating_character('abcabcdef'))
print(first_non_repeating_character('aabbcc'))

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"))

24.Write a Python program to remove spaces from a given string.


 def remove_spaces(str1):
str1 = str1.replace(' ','')
return str1
print(remove_spaces("H el l oW o r ld"))
print(remove_spaces("a b c"))

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"))

26.Write a Python program to remove duplicate characters of a given string.


 from collections import OrderedDict
def remove_duplicate(str1):
return "".join(OrderedDict.fromkeys(str1))
print(remove_duplicate("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))

28.Write a Python program to create a string from two given strings


concatenating uncommon characters of the said strings.
 def uncommon_chars_concat(s1, s2):
set1 = set(s1)
set2 = set(s2)
common_chars = list(set1 & set2)
result = [ch for ch in s1 if ch not in common_chars] + [ch for ch in s2 if ch
not incommon_chars]
return(''.join(result))
s1 = 'abcdpqr'
s2 = 'xyzabcd'
print("Original Substrings:\n",s1+"\n",s2)
print("After concatenating uncommon characters:")
print(uncommon_chars_concat(s1, 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)

30.Write a Python program to swap cases of a given string.


 def swap_case_string(str1):
result_str = ""
for item in str1:
if item.isupper():
result_str += item.lower()
else:
result_str += item.upper()
return result_str
print(swap_case_string("Python Exercises"))
print(swap_case_string("Java"))

PYTHON PROGRAMS ON LIST

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)

5. Write a Python program to convert a list of characters into a string.


 s = ['a', 'b', 'c', 'd']
str1 = ''.join(s)
print(str1)

6. Write a Python program to find the index of an item in a specified list.


 num =[10, 30, 4, -6]
print(num.index(30))

7. Write a Python program to append a list to the second list.


 list1 = [1, 2, 3, 0]
list2 = ['Red', 'Green', 'Black']
final_list = list1 + list2
print(final_list)

8. Write a Python program to get unique values from a list.


 my_list = [10, 20, 30, 40, 20, 50, 60, 40]
print("Original List : ",my_list)
my_set = set(my_list)
my_new_list = list(my_set)
print("List of unique numbers : ",my_new_list)

9. Write a Python program to get the frequency of the elements in a list.


 import collections
my_list = [10,10,10,10,20,20,20,20,40,40,50,50,30]
print("Original List : ",my_list)
ctr = collections.Counter(my_list)
print("Frequency of the elements in the List : \n",ctr)

10.Write a Python program to check whether a list contains a sublist.


 def is_Sublist(l, s):
sub_set = False
if s == []:
sub_set = True
elif s == l:
sub_set = True
elif len(s) > len(l):
sub_set = False
else:
for i in range(len(l)):
if l[i] == s[0]:
n=1
while (n < len(s)) and (l[i+n] == s[n]):
n += 1
if n == len(s):
sub_set = True
return sub_set
a = [2,4,3,5,7]
b = [4,3]
c = [3,7]
print(is_Sublist(a, b))
print(is_Sublist(a, c))

11.Write a Python program to find common items from two lists.


 color1 = "Red", "Green", "Orange", "White"
color2 = "Black", "Green", "White", "Pink"
print(set(color1) & set(color2))

12.Write a Python program to convert a list of multiple integers into a single
integer.
 L = [11, 33, 50]
print("Original List: ",L)
x = int("".join(map(str, L)))
print("Single Integer: ",x)

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))

15.Write a Python program to remove duplicates from a list of lists.


 import itertools
num = [[10, 20], [40], [30, 56, 25], [10, 20], [33], [40]]
print("Original List", num)
num.sort()
new_num = list(num for num,_ in itertools.groupby(num))
print("New List", new_num)

16.Write a Python program to flatten a given nested list structure.
 def flatten_list(n_list):
result_list = []
if not n_list: return result_list
stack = [list(n_list)]
while stack:
c_num = stack.pop()
next = c_num.pop()
if c_num: stack.append(c_num)
if isinstance(next, list):
if next: stack.append(list(next))
else: result_list.append(next)
result_list.reverse()
return result_list
n_list = [0, 10, [20, 30], 40, 50, [60, 70, 80], [90, 100, 110, 120]]
print("Original list:")
print(n_list)
print("Flatten list:")
print(flatten_list(n_list))

17.Write a Python program to remove consecutive duplicates of a given list.


 from itertools import groupby
def compress(l_nums):
return [key for key, group in groupby(l_nums)]
n_list = [0, 0, 1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 8, 9, 4, 4 ]
print("Original list:")
print(n_list)
print("After removing consecutive duplicates:")
print(compress(n_list))

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)

PYTHON PROGRAMS ON TUPLE

1. Write a Python program to calculate the average value of the numbers in a


given tuple of tuples.
 def average_tuple(nums):
result = [sum(x) / len(x) for x in zip(*nums)]
return result
nums = ((10, 10, 10, 12), (30, 45, 56, 45), (81, 80, 39, 32), (1, 2, 3, 4))
print ("Original Tuple: ")
print(nums)
print("Average value of the numbers of the said tuple of tuples:\
n",average_tuple(nums))

2. Write a Python program to convert a given tuple of positive integers into an


integer.
 def tuple_to_int(nums):
result = int(''.join(map(str,nums)))
return result
nums = (10,20,40,5,70)
print("Original tuple: ")
print(nums)
print("Convert the said tuple of positive integers into an integer:")
print(tuple_to_int(nums))

3. Write a Python program to check if a specified element presents in a tuple


of tuples.
 def check_in_tuples(colors, c):
result = any(c in tu for tu in colors)
return result
colors = (('Red', 'White', 'Blue'),('Green', 'Pink', 'Purple'),('Orange', 'Yellow',
'Lime'),)
print("Original list:")
print(colors)
c1 = 'White'
print("Check if",c1,"presenet in said tuple of tuples!")
print(check_in_tuples(colors, c1))
c1 = 'Olive'
print("Check if",c1,"presenet in said tuple of tuples!")
print(check_in_tuples(colors, c1))

4. Write a Python program to convert a given list of tuples to a list of lists.


 def test(lst_tuples):
result = [list(el) for el in lst_tuples]
return result
lst_tuples = [(1,2), (2,3,5), (3,4), (2,3,4,2)]
print("Original list of tuples:")
print(lst_tuples)
print("Convert the said list of tuples to a list of lists:")
print(test(lst_tuples))

5. Swap the following two tuples


t1=(1,2)
t2=(3,4)
 t1=(1,2)
t2=(3,4)
print ("Before SWAPPING")
print ("First Tuple",t1)
print ("Second Tuple",t2)
t1,t2=t2,t1
print ("AFTER SWAPPING")
print ("First Tuple",t1)
print ("Second Tuple",t2)

6. Sort a tuple of tuples by 2nd item


 tuple = [(200, 6), (100, 3), (400, 12), (300, 9)]
print("Orignal Tuple List :" ,tuple)
def Sort(tuple):
tuple.sort(key = lambda a: a[1])
return tuple
print("Sorted Tuple List:" ,Sort(tuple))

7. Check if all items in the following tuple are the same


 List = ['Mon','Mon','Mon','Mon']
result = List.count(List[0]) == len(List)
if (result):
print("All the elements are Equal")
else:
print("Elements are not equal")

PYTHON PROGRAMS ON SETS


1. Write a Python program to add member(s) in a set and iterate over it.
 num_set = set([0, 1, 2, 3, 4, 5])
for n in num_set:
print(n, end=' ')

2. Write a Python program to remove an item from a set if it is present in the


set.
 num_set = set([0, 1, 3, 4, 5])
print("Original set:")
print(num_set)
num_set.pop()
print("After removing the first element from the said set:")
print(num_set)

3. Write a Python program to apply union, intersection, difference, symmetric


difference operators on sets.
 A = {0, 2, 4, 6, 8};
B = {1, 2, 3, 4, 5};
print("Union :", A | B)
print("Intersection :", A & B)
print("Difference :", A - B)
print("Symmetric difference :", A ^ B)

4. Write a Python program to check if a set is a subset of another set.
 setx = set(["apple", "mango"])
sety = set(["mango", "orange"])
setz = set(["mango"])
print("x: ",setx)
print("y: ",sety)
print("z: ",setz)
print("If x is subset of y")
print(setx <= sety)
print(setx.issubset(sety))
print("If y is subset of x")
print(sety <= setx)
print(sety.issubset(setx))
print("If y is subset of z")
print(sety <= setz)
print(sety.issubset(setz))
print("If z is subset of y")
print(setz <= sety)
print(setz.issubset(sety))

5. Write a Python program to clear a set.


 setc = {"Red", "Green", "Black", "White"}
print("Original set elements:")
print(setc)
print("After removing all elements of the said set.")
setc.clear()
print(setc)

6. Write a Python program to check if two given sets have no elements in


common.
 x = {1,2,3,4}
y = {4,5,6,7}
print("Compare x and y:")
print(x.isdisjoint(y))

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

1. Write a Python script to sort (ascending and descending) a dictionary by


value.
 import operator
d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
print('Original dictionary : \n',d)
sorted_d = sorted(d.items(), key=operator.itemgetter(1))
print('Dictionary in ascending order by value : \n',sorted_d)
sorted_d = dict( sorted(d.items(), key=operator.itemgetter(1),reverse=True))
print('Dictionary in descending order by value : \n',sorted_d)

2. Write a Python script to add a key to a dictionary.


 d = {0:10, 1:20}
print(d)
d.update({2:30})
print(d)

3. Write a Python script to concatenate following dictionaries to create a new


one.
 dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
dic4 = {}
for d in (dic1, dic2, dic3): dic4.update(d)
print(dic4)

4. Write a Python script to check whether a given key already exists in a


dictionary.
 d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
def is_key_present(x):
if x in d:
print('Key is present in the dictionary')
else:
print('Key is not present in the dictionary')
is_key_present(5)
is_key_present(9)

5. Write a Python script to generate and print a dictionary that contains a


number (between 1 and n) in the form (x, x*x).
 n=int(input("Input a number "))
d = dict()
for x in range(1,n+1):
d[x]=x*x
print(d)

6. Write a Python script to merge two Python dictionaries.


 d1 = {'a': 100, 'b': 200}
d2 = {'x': 300, 'y': 200}
d = d1.copy()
d.update(d2)
print(d)

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)

8. Write a Python program to sort a dictionary by key.


 color_dict =
{'red':'#FF0000','green':'#008000','black':'#000000','white':'#FFFFFF'}
for key in sorted(color_dict):
print("%s: %s " % (key, color_dict[key]), end="")

9. Write a Python program to combine two dictionary adding values for


common keys.
 from collections import Counter
d1 = {'a': 100, 'b': 200, 'c':300}
d2 = {'a': 300, 'b': 200, 'd':400}
d = Counter(d1) + Counter(d2)
print(d)

10.Write a Python program to find the highest 3 values in a dictionary.
 from heapq import nlargest
my_dict = {'a':500, 'b':5874, 'c': 560,'d':400, 'e':5874, 'f': 20}
three_largest = nlargest(3, my_dict, key=my_dict.get)
print(three_largest)

11.Write a Python program to get the top three items in a shop.


 from heapq import nlargest
from operator import itemgetter
items = {'item1': 45.50, 'item2':35, 'item3': 41.30, 'item4':55, 'item5': 24}
for name, value in nlargest(3, items.items(), key=itemgetter(1)):
print(name, value)

12.Write a Python program to filter a dictionary based on values.


 marks = {'Cierra Vega': 175, 'Alden Cantrell': 180, 'Kierra Gentry': 165}
print("Original Dictionary:")
print(marks)
print("Marks greater than 170:")
result = {key:value for (key, value) in marks.items() if value >= 170}
print(result)

PYTHON PROGRAMS ON USER DEFINED FUNCTIONS

1. Write a Python function to sum all the numbers in a list.


 def sum(numbers):
total = 0
for x in numbers:
total += x
return total
print(sum((8, 2, 3, 0, 7)))

2. Write a Python program to reverse a string.


 def my_function(x):
return x[::-1]
mytxt = my_function("I wonder how this text looks like backwards")
print(mytxt)

3. Write a Python function to calculate the factorial of a number (a non-


negative integer). The function accepts the number as an argument.
 def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
n=int(input("Input a number to compute the factiorial : "))
print(factorial(n))

4. Write a Python function that accepts a string and calculate the number of
upper case letters and lower case letters.
 def string_test(s):
d={"UPPER_CASE":0, "LOWER_CASE":0}
for c in s:
if c.isupper():
d["UPPER_CASE"]+=1
elif c.islower():
d["LOWER_CASE"]+=1
else:
pass
print ("Original String : ", s)
print ("No. of Upper case characters : ", d["UPPER_CASE"])
print ("No. of Lower case Characters : ", d["LOWER_CASE"])
string_test('The quick Brown Fox')

5. Write a Python function to check whether a number is perfect or not.


 def perfect_number(n):
sum = 0
for x in range(1, n):
if n % x == 0:
sum += x
return sum == n
print(perfect_number(6))

6. Write a Python function to check whether a string is a pangram or not.


 import string, sys
def ispangram(str1, alphabet=string.ascii_lowercase):
alphaset = set(alphabet)
return alphaset <= set(str1.lower())
print ( ispangram('The quick brown fox jumps over the lazy dog'))

PYTHON PROGRAMS ON SQLite

Write a program to perform the following queries :

1. Create tables Hospital and Doctor


 import sqlite3
c=sqlite3.connect('Database')
cur=c.cursor()
cur.execute('create table Hospital(Hospital_Idint primary
key,Hospital_Namevarchar(10),Bed_Countint)')
cur.execute('create table Doctor(Doctor_Idint primary
key,Doctor_Namevarchar(10),Hospital_Idint,Joining_Datevarchar(10),\
Specialityvarchar(20),Salary int,Experienceint,constraint F foreign
key(Hospital_Id) references Hospital(Hospital_Id))')
c.commit()
c.close()

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()

5. Get a list of doctors from a given hospital


Implement the functionality to fetch all the doctors as per the given Hospital
Id. You must display the hospital name of a doctor.
 import sqlite3
c=sqlite3.connect('Database')
cur=c.cursor()
cur.execute('select Hospital_name,Doctor_name from Hospital h, Doctor d
where h.Hospital_Id=d.Hospital_Id')
r=cur.fetchall()
for i in r:
print(i)
c.close()

6. Update doctor experience in years
The value of the experience column for each doctor is null. Implement the
functionality to update the
experience of a given doctor in years.
 import sqlite3
c=sqlite3.connect('Database')
cur=c.cursor()
cur.execute('update Doctor set Experience=null')
cur.execute('update Doctor set Experience=12 where Doctor_Id=1')
c.commit()
cur.execute('select * from Doctor')
r=cur.fetchall()
for i in r:
print(i)
c.close()

You might also like