# 1.
Write a Pythhon program to print all Armstrong
# numbers in a given range.
start=int(input("Enter start value of the range "))
end=int(input("Enter last value of the range "))
print("Armstron numbers between",start,"to",end,"are")
for n in range(start,end+1):
m=n
s=0
num_digits=len(str(n))
while m!=0:
d=m%10
q=m//10
s=s+d**num_digits
m=q
if s==n:
print(n)
# 2. Write a function that will accept a string as parameter and returns
# a string with every swccessive repetitive character replaced by "!".
def substitute(s):
#string to list
l=list(s)
#replace successive repetitive character
i=1
while i<len(l):
if l[i]==l[i-1]:
l[i]='!'
i+=1
#create result string
sep=''
s1=sep.join(l)
return s1
#Function calling
s=input("Enter a string ")
s1=substitute(s)
print("Result string=",s1)
# 3(i) Write a program to check if an integer exist in list. If
# the element dows not exist in list then add it to the list.
l=[5,7,2,1,3,4,8]
n=int(input("Enter an integer to check "))
if n in l:
print("The element exist in the list")
else:
l.append(n)
print("Result list=",l)
# 3(ii) Write a program to check if duplicate element oresents in a list.
# If that is present in the list then remove it from the list.
l=[2,7,9,2,3,4,5,3,3]
for x in l:
if l.count(x)>1:
l.remove(x)
print("Result list=",l)
# 1. Write a program to compute the wages of a daily laborer as per the following rules :-
# Hours Worked Rate Applicable Upto first 8 hrs Rs100/-
# a) For next 4 hrs Rs30/- per hr extra
# b) For next 4 hrs Rs40/- per hr extra
# c) For next 4 hrs Rs50/- per hr extra
# d) For rest Rs60/- per hr extra
hrs=eval(input("Enter number of hours worked "))
amt=0
if hrs<0:
print("Invalid hours of work")
exit()
if hrs<=8:
amt=100*hrs
elif hrs<=12:
amt=(100*8)+(30*(hrs-8))
elif hrs<=16:
amt=(100*8)+(30*4)+(40*(hrs-12))
elif hrs<=20:
amt=(100*8)+(30*4)+(40*4)+(50*(hrs-16))
else:
amt=(100*8)+(30*4)+(40*4)+(50*4)+(60*(hrs-20))
print("Total wages for {0} hours is Rs. {1} ".format(hrs,amt))
# 2. Create a list variable l and ask user to input 10 integer elements into
# it. Write Python code to perform following operations on the list (Do
# use built-in list functions):
# a) Create a new list l1 by adding a number 10 with every element of the
# list using list comprehension. Say l contains [5,1,5,2,5] then l1
# containts [15,11,15,12,15].
# b) Find total number of positive and negetive integersin the list.
# c) Count the elements that are disible by 5.
# d) Remove all the repetitive elements from the list by storing
# each unique element into a new list.
# e) Create a new dictionary by counting the frequency of each value
# in the list. Store the element of the list as keys of the dictionary
# and frequencies as values.
l=[]
print("Enter 10 integers")
for i in range(10):
x=int(input())
l.append(x)
#ans. of a
l1=[x+10 for x in l ]
print("New list=",l1)
#ans. of b
cp=0
cn=0
for x in l:
if x>0:
cp+=1
elif x<0:
cn+=1
print("Total positive numbers=",cp,"Total negetive numbers=",cn)
#ans. of c
c=0
for x in l:
if x%5==0:
c+=1
print("Count=",c)
#ans. of d
l2=[]
for x in l:
if x not in l2:
l2.append(x)
print("Unique list=",l2)
#ans. of e
freq={}
for x in l:
if x in freq:
freq[x]+=1
else:
freq[x]=1
print("Frequencies are",freq)
# 3(i) Write Python program to show Fibonacci Series (for 20 terms) using recursion.
def fibo(n):
if n==1:
return 0
if n==2:
return 1
x=fibo(n-2)+fibo(n-1)
return x
#Function calling
for i in range(1,21):
a=fibo(i)
print(a, end=' ')
print()
# 3(ii) Write a Python program to calculate factorial of an
# integer using recursion.
def factorial(n):
if n==0:
return 1
x=factorial(n-1) #recursive call
f=n*x
return f
#function calling
n=int(input("Enter an integer "))
f=factorial(n)
print("Factorial=",f)
# 2. Create a dictionary consisting of student's name as kay and
# student's marks as value (store 10 elements for this question).
# Perform following operations on dictionary:
# a) Calculate sum of values of the dictionary.
# b) Display all values where student's marks is greater
# than 50.
# c) Display all keys where student's name begins with the
# letter 'A' or 'S'.
# d) Create a function to display marks i.e. dictionary vale for a
# given key.
# e) Create a function that asks a student name to remove. It the
# student exists in the dictionary then remove it otherwise print
# a message "Student name doesn't exist" .
student={
'Sushanta' : 70,
'Asish' : 35,
'Goutam' : 86,
'Indrani' : 35,
'Sangita' : 49,
'Debasis' : 95,
'Amit' : 20,
'Bappa' : 51,
'Amitava' : 64,
'Moumita' : 59
}
#ans of a)
total=sum(student.values())
print("Sum of values=",total)
#ans of b)
for x in student.values():
if x>50:
print(x)
#ans of c)
print("Names with A or S")
for name in student.keys():
if name[0]=='A' or name[0]=='S':
print(name)
#ans of d)
def display(key):
marks=student.get(key)
print("Marks=",marks)
#Function call
display("Amitava")
#ans of e)
def remove(name):
if name in student:
del student[name]
else:
print(name,"Student dows not exist")
#function call
remove("Amit")
remove("pqr")
# 3. Write a program to find the mean of values of a dictionary ? For
# example, input: test_dict={"Sachin" : 5, "is" : 4, "Best" : 4,
# "Player" : 3, "Indian" : 4} then the mean of the values is 4
# as output.
test_dict={
"Sachin" : 5,
"is" : 4,
"Best" : 4,
"Player" : 3,
"Indian" : 4
}
vals=list(test_dict.values())
mean=sum(vals)/len(vals)
print("Mean of dictionary values=",mean)
#1. Write a Python function with name "dividebyfive" which generate
# and print a random number from the range 0 to 100 and then returns True
# if the randomly generated number is divisible by 5 and Flasw otherwise.
import random
def dividebyfive():
x=random.randint(0,100)
print("Random number=",x)
if x%5==0:
return True
else:
return False
#Function calling
y=dividebyfive()
print("Function returns=",y)
# 2. Create a numpy array having two dimensionsa shape (3,3) and
# perform following operations on array elements.
# a) Calculate sum of all the columns of the array.
# b) Calculate product of all the rows of the array.
# c) Retive the last two columns and last two rows from the array.
# d) Create another two dimensional array having same shape and carray
# out the element wise sum two arrays and display the result.
# e) Create a new array by multipling every element of the original
# array with value 2 and display the new array.
import numpy as np
a=np.array([[1,2,3],[4,5,6],[7,8,9]])
#ans. of 2(a)
col_sum=np.sum(a,axis=0)
print("Column wise sum=",col_sum)
#ans. of 2(b)
row_prod=np.prod(a,axis=1)
print("Row wise product=",row_prod)
#ans. of 2(c)
cols=a[...,1:]
print("Last 2 columns=\n",cols)
rows=a[1:,:]
print("Last 2 rows=\n",rows)
#ans. of 2(d)
b=np.array([[10,11,12],[13,14,15],[16,17,18]])
c=a+b
print("Sum of elements=\n",c)
#ans. of 2(e)
d=a*2
print("Result array=\n",d)
# 3. Write a Python program to create intersection of two array.
# For example, sample input: arr1=[1 3 4 5 7] and arr2=[2 3 5 6], the
# intersection is [3 5].
import numpy as np
a=np.array([1,3,4,5,7])
b=np.array([2,3,5,6])
c=[]
for x in b:
if x in a:
c.append(x)
d=np.array(c)
print("Result array=\n",d)
#1. Write a Python program to sort Python dictionay by key or value.
#Creating a dictonary
d={
'name' : 'Manas',
'email':'
[email protected]',
'address' : ' 123 ABC Road',
'phone' : '9988776655'
}
#Sorting by keys
#Getting all keys from the dictionary
keys=d.keys()
#Convert all keys to list
s_keys=list(keys)
#sort the list
s_keys.sort()
#create a dictionary with sorted keys
d1={}
for k in s_keys:
d1[k]=d[k]
print("Result dictionary sorted by keys=",d1)
#Sorting by values
#Getting all values from the dictionary
all_val=d.values()
#Convert all vslues to list
s_val=list(all_val)
#sort the list
s_val.sort()
#create a dictionary with sorted values
d2={}
for v in s_val:
for k in d:
if d[k]==v:
d2[k]=d[k]
break
print("Result dictionary sorted by values=",d2)
# 2. Write a Python program to find power of a number using recursion.
#define power function
def power(x,y):
if y==0:
return 1
else:
z=x*power(x,y-1)
return z
#power() function calling
a=eval(input("Enter base number "))
b=int(input("Enter power value "))
c=power(a,b)
print("Result=",c)
# 3. Write a Python proram to multiply two numbers by repeated addition.
# For example 6*3=6+6+6
a=int(input("Enter 1st number "))
b=int(input("Enter 2nd number "))
c=0
for i in range(1, b+1):
c=c+a
print("Multiplication result=",c)
# 23 Write a Python program that takes a sentence as input and display the number of words, the number of
# capital letters, the number of smatt letters and number of special symbols present in the inputed sentence.
s=input("Enter a sentence ")
wc=uc=lc=spc=0
#Finding words count
words=s.split(' ')
wc=len(words)
print("Number of words=",wc)
#Finding number of capital letters, small letters and special symbols
for x in s:
if x.isalpha():
if x.isupper():
uc=uc+1
else:
lc=lc+1
elif x.isdigit():
continue
else:
spc=spc+1
print("Number of capital letters=",uc)
print("Number of small letters=",lc)
print("Number of special symbols=",spc)
# 3. Write a Python function that takes two lists and return True if there is atleast one common item.
#define a function
def check(l1,l2):
for x in l1:
if x in l2:
return True
return False #if two lists have no common item
#Function calling
l1=[5,10,20,7,3]
l2=[1,2,3,7]
res=check(l1,l2)
print("Checking result=",res)
# 1. Write a NumPy program to find most frequent value in a list.
import numpy as np
import numpy.random
#Create a list and populate it with random numbers.
l=list(np.random.randint(1,6,10))
#Creating numpy array from a list
a=np.array(l)
#Count frequency of each value
b=np.bincount(a)
#Find value having largest frequency
c=np.argmax(b)
print("Original list=",l)
print("Frequency array=",b)
print("Most frequent value=",c)
# 2. Write a Python program that accepts hyphen separated sequence of words as inputand prints them as hyphen
# separated sequence of words after sirting them alphabbetically.
# Hints:
# Input: gaurav-ram-yashir-bittu-wrong
# Output: bittu-gaurav-ram-wrong-yashir
s=input("Enter hyphen separated sequence of words ")
#Split words into a list
l=s.split('-')
#Sort the list alphabetically
l.sort()
#Convert items of list into hyphen separated string
# 1. Write a Python function that will accept a string and counts number of capital letters and small letters
sep='-'
# present in the string.
s1=sep.join(l)
print("Result string=",s1)
#define function
def count_lower_upper(s):
lc=uc=0
#Finding number of capital letters, small letters and special symbols
for x in s:
if x.isalpha():
if x.isupper():
uc=uc+1
else:
lc=lc+1
return lc,uc
#Function calling
s=input("Enter a string ")
lc,uc=count_lower_upper(s)
print("No. of capital letter=",uc)
print("No. of small letter=",lc)
# 2. Write a Python function to check whether a password string is palindrome or not.
from getpass import getpass
#define function
def chk_palindrome(pwd):
rev_pwd=pwd[::-1]
if pwd==rev_pwd:
return True
else:
return False
#Function calling
passwd=input("Enter your password ")
x=chk_palindrome(passwd)
if x==True:
print("Your password is palindrome string")
else:
print("Your password is not palindrome string")
# 3. Write a Python program to find those numbers which are divisible by 7 and multiple of 5 bwtween1500 and
# 2700 (both inclusive).
i t("N b ")