You are on page 1of 25

INDEX

S.No Programs Page No.


1 Programs on Loops 2-4
2 Programs on Strings 5-6
3 Programs on Lists 7-12
4 Programs on Sets 13-14
5 Programs on Dictionary 15-18
6 Programs on Functions 19-20
7 Programs on Lambda and 21-22
Map functions

8 Programs on Sorting 23-25


Techniques

1
Programs on Loops
1) Wap to find the sum of a number.
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) Wap to print the table from 1 to 10 in the following format

2
for i in range(1, 10+1):

for j in range(i, (i*10)+1, i):

print(j, end="\t")

print()

3) Write a program to determine whether a given natural


number is a perfect no. A natural no. is said to be a perfect no.
if it is the sum of its divisors.

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

3
4) Wap that return true or false depending on whether the given no.
is palindrome. A palindromic is a no. (such as 16461) that remains the
same when its digits are reversed.

n=int(input("Enter number:"))
temp=n
rev=0
while(n>0):
digit=n%10
rev=rev*10+digit
n=n//10
if(temp==rev):
print("The number is a palindrome!")

Programs on Strings
4
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 reverse a string if its length is a multiple


of 4.

a=input(“enter the string: “)

if len(a)%4==0:

print(‘’.join(reversed(a)))

else:

print(“The length is not the multiple of 4”)

3) Write a python program to reverse words in a string.

x=input(“enter the sentence: “)


5
for line in x.split(‘\n’)

reverse=’’.join(line.split()[::-1])

print(reverse)

4) Write a python program to count and display the vowels of a given


text.

x=input("enter the string: ")

vowels="aeiouAEIOU"

print(len([letter for letter in x if letter in vowels]))

print([letter for letter in x if letter in vowels])

Programs on lists

6
1)Write a python program to get the largest and second largest
number from a list.

x=[‘21’, ‘11’, ‘15’, ‘51’]

y=max(x)

print(“the largest no. is”,y)

x.remove(y)

z=max(x)

print(“the second largest no, is “, z)

2) Write a python program to get the difference between the two


strings.

lst1=['21', '15', '17', '35']

lst2=['23', '14', '21', '11', '15']

diff12=list(set(lst1)-set(lst2))

diff21=list(set(lst2)-set(lst1))

print(diff12+diff21)

3) Write a python program to convert a list of characters into a string.

lst=[‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’]


7
x=””.join(lst)

print(x)

4) Write a python program to find the index of an item in a specified


set.

lst=['21', '15', '17', '35']

lst.index(‘35’)

5) Write a python program to append a list to the second list.

lst1=['21', '15', '17', '35']

lst2=['23', '14', '21', '11', '15']

append=lst1+lst2

print(append)

6) Write a python program to get unique values from a list.

lst=[‘13’, ‘15’, ‘17’, ‘34’, ‘11’, ‘15’, ‘17’]


8
my_set=set(lst)

my_newlist=list(my_set)

print(my_newlist)

7) Write a python program to get the frequency of the elements in a


list.

mylist=['23', '14', '21', '11', '15', '23', '11']

res={}

for I in mylist:

if (I in res):

res[i]+=1

else:

res[i]=1

for key, value in res.items():

print(key,”:“,value)

8) Write a python program to find common items from the two lists.

color1=[“Red”, “Blue”, “Pink”, “Green”]


9
color2=[“Yellow”, “White”, “Blue”, “Red”]

print(set(color1) & set(color2))

9) Write a python program to convert a list of multiple integers into a


single string.

mylist=['23', '14', '21', '11', '15', '23', '11']

y=””.join(mylist)

print(y)

10) Write a python program to replace last element in a list with


another element.

lst1=['1', '3', '5', '7', '9', '10']

lst2=['2', '4', '6', '8']

y=lst1.remove(lst1[-1])

new_list=lst1+lst2

print(new_list)

11)Write a python program to find the list in a list whose sum of the
elements is the highest.

10
num=[[1, 2, 3], [4, 5, 6], [10, 11, 12], [7, 8, 9]]

print(max(num, key=sum))

12)Write a python program to remove duplicates from a list of lists.

num=[[‘10’, ‘20’],[‘40’], [‘30’, ‘56’, ‘25’], [‘10’, ‘20’], [‘33’], [‘40’]]

new_num=[]

for elem in num:

if elem not in new-num:

new_num.append(elem)

num=new_num

print(new_num)

13)write a python program to remove consecutive duplicates of a


given list.

lis=[‘0’, ‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘4’, ‘5’, ‘6’, ‘6’, ‘7’, ‘8’, ‘9’, ‘4’, ‘4’]

11
i=0

while i<len(lis)-1:

if lis[i]==lis[i+1]:

del lis[i]

else:

i+=1

print(lis)

14)Write a python program to remove the Kth element from a given


list, print the new list.

lis=[‘1’, ‘1’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’]

k=4

result=lis[:k-1] + lis[k:]

print(result)

Programs on Sets
1) Write a python program to add members in a set and iterate over
it.

12
num_set=set(['0', '1', '2', '3', '4'])

num_set.update(['python', 'anaconda', 'jupyter'])

for n in num_set:

print(n, end=' ')

2) Write a python program to remove item from a set if it is present


in the set.

vowels={'a', 'e', 'i', 'o', 'u'}

vowels.remove('a')

print(vowels)

3) Write the python program to clear a set.

my_set={'a', 'b', 'c', 'd', 'e'}

my_set.clear()

print(my_set)

4) Write a python program to check if two given sets have no


elements in common.

n=set(input("enter the first set").split())

13
m=set(input("enter the second set").split())

if n.isdisjoint(m):

print("no in the two sets none of the elements are common")

else:

print("yes in the two sets some of the elements are common")

5) Write a python program to remove intersection of a second set


from the first set.

n=set(input("enter the first set").split())

m=set(input("enter the second set").split())

n.difference_update(m)

print("the first set is ", n)

print("the second set is ", m)

Programs on Dictionary
1) Write a python script to sort (ascending and descending) a
dictionary by value.

14
import operator
d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
s= sorted(d.items(), key=operator.itemgetter(1))
print('ascending order : ',s)
s1= dict( sorted(d.items(),
key=operator.itemgetter(1),reverse=True))
print('descending order : ',s1)

2) Write a python program to add a key to a dictionary.

my_dict={0:10, 1:20}

my_dict[2]=30

print(my_dict)

3) Write a python program to check whether a given key already


exists in a dictionary.

my_dict={1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}

x=int(input("enter the key you want to check"))

if x in my_dict:
15
print("key is present in the dictionary")

else:

print("key is not present in the dictionary")

4) Write a python program to print a dictionary where the keys are


numbers between 1 and 15(both included) and the values are the
squares of keys.

d=dict()

for x in range(1, 16):

d[x]=x*x

print(d)

5) Write a python program to merge two python dictionaries.

d1={1:'Jan', 2:'Feb'}

d2={3:'Mar', 4:'Apr'}

d1.update(d2)

print(d1)

16
6) Write a python program to sum and multiply all the items in a
dictionary.

my_dict={'data1': 100, 'data2': 200, 'data3':300}

print(sum(my_dict.values()))

my_dict={'data1': 100, 'data2': 200, 'data3':300}

result=1

for key in my_dict:

result=result*my_dict[key]

print(result)

7) Write a python program to sort a dictionary by key.

my_dict={'data2': 100, 'data3': 200, 'data1':300}

print(sorted(my_dict.keys()))

17
8) Write a python program to remove the duplicate values from
dictionary.

my_dict={'data2': 100, 'data3': 200, 'data1':300, 'data4':100}

uniq=dict()

for key, value in my_dict.items():

if value not in uniq.values():

uniq[key]=value

print(uniq)

9) Write a python program to filter a dictionary based on values.

my_dict={'data2': 100, 'data1': 200, 'data3':300, 'data4':500}

result={key:value for (key, value) in my_dict.items() ifvalue>=250}

print("data greater than 250", result)

Programs on Functions

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

lst=[1, 3, 4, 6, 11, 12]

18
def list_sum(lst):

add_items=sum(lst)

return add_items

print("the sum of all the no. of the list is", list_sum(lst))

2) Write a python function to reverse a string.

str1=input("enter the string:")

def reverse(str1):

return str1[::-1]

print("the reverse of the said string is: ", reverse(str1))

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

if x==1:

return 1

19
else:

fact=x*factorial(x-1)

return(fact)

n=int(input("enter the no. "))

print("the factorial of the given no. is ", factorial(n))

4) Write a python function to check whether a string is a pangram or


not.

import string

def ispangram(str1):

alpha=set(string.ascii_lowercase);

return alpha<=set(x.lower());

x=input("enter the string: ");

print(ispangram(x))

Programs on Lambda and Map Functions


1) Write a python program to square and cube every number in a
given list of integers using lambda.

lst=[2, 4, 6, 8, 9]

y=map(lambda x:x**2, lst)

20
z=map(lambda x:x**3, lst)

print("The square of the no. in the list: ", list(y))

print("The cube of the no. in the list: ", list(z))

2) Write a python program to find if a given string starts with a given


character using lambda.

str1=input("enter the string: ")

c=input("enter the character you want to check ")

z=(lambda x,e:True if x.startswith(e) else False)

print(z(str1, c))

3) Write a python program to count the even, odd numbers in a given


array of integers using lambda.

lst=[2, 4, 6, 8, 9, 11, 15]

print("the original list is ", lst)

odd_ctr=len(list(filter(lambda x:(x%2!=0), lst)))

even_ctr=len(list(filter(lambda x:(x%2==0), lst)))

21
print("the no. of even numbers in the list is ", even_ctr)

print("the no. of odd numbers in the list is ", odd_ctr)

4) Write a python program to add two given lists using map and
lambda.

lst1=[2, 4, 6, 8, 9, 11, 15]

lst2=[3, 6, 7, 8, 3, 2, 1]

print("the first list is: ", lst1)

print("the second list is: ", lst2)

add_list=map(lambda x, y:x+y, lst1, lst2)

print("the sum of the two given lists are ", list(add_list))

Programs on Sorting Techniques


1) Write a python program to sort a list of elements using the bubble
sort algorithm.

a=[16,19,11,15,10,12,14]

print("the original list ",a)

22
for j in range(len(a)):

swapped=False

i=0

while i<len(a)-1:

if a[i]>a[i+1]:

a[i],a[i+1]=a[i+1],a[i]

swapped=True

i=i+1

if swapped==False:

break

print("the sorted list using bubble sort ", a)

2) Write a python program to sort a list of elements using the


selection sort algorithm.

a=[18,10,11,15,60,56,14]

print("the original list ",a)

i=0

while i<len(a):
23
smallest=min(a[i:])

index_of_smallest=a.index(smallest)

a[i],a[index_of_smallest]=a[index_of_smallest],a[i]

i=i+1

print("the sorted list using selection sort ", a)

3) Write a python program to sort a list of elements using the linear


search algorithm.

lst = []

num = int(input("Enter size of list :- "))

for n in range(num):

numbers = int(input("Enter the array of %d element :- " %n))

lst.append(numbers)

24
x = int(input("Enter number to search in list :- "))

i=0

flag = False

for i in range(len(lst)):

if lst[i] == x:

flag = True

break;

if flag == 1:

print('{} was found at index {}.'.format(x, i))

else:

print('{} was not found.'.format(x))

25

You might also like