Python | All in One Program By. Shivansh Sir
PYTHON PROGRAMMING
PYTHON | MISCELLANEOUS PROGRAM
Program 1. Write a Python function to find the maximum of three numbers.
Source Code
def max_of_two( x, y ):
if x > y:
return x
return y
def max_of_three( x, y, z ):
return max_of_two( x, max_of_two( y, z ) )
print(max_of_three(3, 6, -5))
Output
6
Program 2. Input age and check eligibility for voting
# input age
age = int(input("Enter Age : "))
# condition to check voting eligibility
if age>=18:
status="Eligible"
else:
status="Not Eligible"
print("You are ",status," for Vote.")
Output
Enter Age = 15
You are Not Eligible for Vote.
Program 3. Write a Python program to find the number of notes (Samples of notes: 10, 20, 50, 100, 200, 500) against an amount.
Source Code
def no_notes(a):
Q = [500, 200, 100, 50, 20, 10]
x = 0
for i in range(6):
q = Q[i]
x += int(a / q)
a = int(a % q)
if a > 0:
x = -1
return x
print(no_notes(880))
print(no_notes(1000))
Output
6
2
Program 4. Write a Python program that computes the greatest common divisor (GCD) of two positive integers using while loop.
Source Code
def gcd(x, y):
z = x % y
while z:
x = y
y = z
z = x % y
return y
print("GCD of 12 & 17 =",gcd(12, 17))
print("GCD of 4 & 6 =",gcd(4, 6))
print("GCD of 336 & 360 =",gcd(336, 360))
Output
GCD of 12 & 17 = 1
GCD of 4 & 6 = 2
GCD of 336 & 360 = 24
Program 5. Write a Python program that computes the greatest common divisor (GCD) of two positive integers using for loop.
Source Code
def gcd(x, y):
gcd = 1
if x % y == 0:
return y
for k in range(int(y / 2), 0, -1):
if x % k == 0 and y % k == 0:
gcd = k
break
return gcd
print("GCD of 12 & 17 =",gcd(12, 17))
print("GCD of 4 & 6 =",gcd(4, 6))
print("GCD of 336 & 360 =",gcd(336, 360))
Output
GCD of 12 & 17 = 1
GCD of 4 & 6 = 2
GCD of 336 & 360 = 24
Program 6. Write a Python program to convert the distance (in feet) to inches, yards, and miles.
d_ft = int(input("Input distance in feet: "))
d_inches = d_ft * 12
d_yards = d_ft / 3.0
d_miles = d_ft / 5280.0
print("The distance in inches is %i inches." % d_inches)
print("The distance in yards is %.2f yards." % d_yards)
print("The distance in miles is %.2f miles." % d_miles)
Output
Input distance in feet: 100
The distance in inches is 1200 inches.
The distance in yards is 33.33 yards.
The distance in miles is 0.02 miles.
Program 7. Write a Python function that prints out the first n rows of Pascal's triangle.
![]() |
Pascal's triangle is an arithmetic and geometric figure first imagined by Blaise Pascal. |
Source Code
def pascal_triangle(n):
trow = [1]
y = [0]
for x in range(max(n,0)):
print(trow)
trow=[l+r for l,r in zip(trow+y, y+trow)]
return n>=1
pascal_triangle(5)
Output
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
Program 8. Write a Python function that checks whether a passed string is a palindrome or not.
Note: A palindrome is a word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run.
Source Code
def isPalindrome(string):
left_pos = 0
right_pos = len(string) - 1
while right_pos >= left_pos:
if not string[left_pos] == string[right_pos]:
return False
left_pos += 1
right_pos -= 1
return True
print(isPalindrome('aza'))
Output
True
Program 9. Write a Python function to sum all the numbers in a list.
Source Code
def sum(numbers):
total = 0
for x in numbers:
total += x
return total
print(sum((8, 2, 3, 0, 7)
Output
20
Program 10. Write a Python function to check whether a number is "Perfect" or not.
Perfect Number a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Example : The first perfect number is 6, because 1, 2, and 3 are its proper positive divisors, and 1 + 2 + 3 = 6. Equivalently, the number 6 is equal to half the sum of all its positive divisors: ( 1 + 2 + 3 + 6 ) / 2 = 6. The next perfect number is 28 = 1 + 2 + 4 + 7 + 14. This is followed by the perfect numbers 496 and 8128.
Source Code
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))
print(perfect_number(58))
Output
True
False
Program 11. Write a Python function that takes a number as a parameter and checks whether the number is prime or not.
Source Code
def check_prime(n):
if (n==1):
return False
elif (n==2):
return True;
else:
for x in range(2,n):
if(n % x==0):
return False
return True
print(check_prime(9))
Output
False
Program 12. Write a Python function that accepts a string and counts the number of upper and lower case letters.
Source Code
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('Sunrise is the Best in feild of Computer Education')
Output
Original String : Sunrise is the Best in field of Computer Education.
No. of Upper case characters : 4
No. of Lower case Characters : 39
Program 13. Write a Python function to check whether a number falls within a given range.
Source Code
def check_range(n):
if n in range(15,45):
print( " %s is in the range"%str(n))
else :
print("The number is outside the given range.")
check_range(25)
check_range(55)
Output
25 is in the range.
The number is outside the given range.
Program 14. Write a Python function to calculate the factorial of a number.
Source Code
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
n=int(input("Input a number to compute the factorial : "))
print(factorial(n))
Output
Input a number to compute the factorial : 5
Result:- 120
Program 15. Write a Python program to reverse a string.
Source Code
def string_reverse(str1):
rstr1 = ''
index = len(str1)
while index > 0:
rstr1 += str1[ index - 1 ]
index = index - 1
return rstr1
print(string_reverse('sunrise_computer'))
Output
retupmoc_esirnus
Method - 2
Source Code
def reverse(itr):
return itr[::-1]
str1 = 'Sunrise'
print("Original string:",str1)
print("Reverse string:",reverse('Sunrise'))
str1 = 'Computer'
print("\nOriginal string:",str1)
print("Reverse string:",reverse(str1))
Output
esirnus
retupmoc
PYTHON | LIST PROGRAMS
Program 1. Write a Python program to sum all the items in a list.
Source Code
def sum_list(items):
sum_numbers = 0
for x in items:
sum_numbers += x
return sum_numbers
print(sum_list([1,2,-8]))
Output
-5
Program 2. Write a Python program to Multiply all the items in a list.
Source code
def multiply_list(items):
tot = 1
for x in items:
tot *= x
return tot
print(multiply_list([1,2,-8]))
Output
-16
Program 3. Write a Python program to get the largest number from a list.
Source Code
def max_num_in_list( list ):
max = list[ 0 ]
for a in list:
if a > max:
max = a
return max
print(max_num_in_list([1, 2, -8, 0]))
Output
2
Program 4. Write a Python program to get the smallest number from a list.
Source Code
def smallest_num_in_list( list ):
min = list[ 0 ]
for a in list:
if a < min:
min = a
return min
print(smallest_num_in_list([1, 2, -8, 0]))
Output
-8
Program 5. Write a Python program to get a list, sorted in increasing order by the last element in each tuple from a given list of non-empty tuples.
Source Code
def last(n): return n[-1]
def sort_list_last(tuples):
return sorted(tuples, key=last)
print(sort_list_last([(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]))
Output
[(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]
Program 6. Write a Python program to remove duplicates from a list.
Source Code
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)
Output
{40, 10, 80, 50, 20, 60, 30}
Program 7. Write a Python program to find the list of words that are longer than n from a given list of words.
Source Code
def long_words(n, str):
word_len = []
txt = str.split(" ")
for x in txt:
if len(x) > n:
word_len.append(x)
return word_len
print(long_words(3, "The quick brown fox jumps over the lazy dog"))
Output
['quick', 'brown', 'jumps', 'over', 'lazy']
Program 8. Write a Python program to replace the last element in a list with another list.
Source Code
num1 = [1, 3, 5, 7, 9, 10]
num2 = [2, 4, 6, 8]
num1[-1:] = num2
print(num1)
Output
[1, 3, 5, 7, 9, 2, 4, 6, 8]
Program 9. Write a Python program to iterate over two lists simultaneously.
Source Code
num = [1001, 1002, 1003]
color = ['raghu', 'sonal', 'Preet']
for (a,b) in zip(num, color):
print(a, b)
Output
1001 raghu
1002 sonal
1003 Preet
PYTHON | TUPLE
Program 1. Write a Python program to create a tuple.
Source Code
#Create an empty tuple
x = ()
print(x)
#Create an empty tuple with tuple() function built-in Python
tuplex = tuple()
print(tuplex)
Output
()
()
Program 2. Write a Python program to create a tuple with different data types.
Source Code
#Create a tuple with different data types
tuplex = ("tuple", False, 3.2, 1)
print(tuplex)
Output
('tuple', False, 3.2, 1)
Program 3. Write a Python program to unpack a tuple into several variables.
Source Code
#create a tuple
tuplex = 4, 8, 3
print(tuplex)
n1, n2, n3 = tuplex
#unpack a tuple in variables
print(n1 + n2 + n3)
#the number of variables must be equal to the number of items of the tuple
n1, n2, n3, n4= tuplex
Output
(4, 8, 3)
15
Traceback (most recent call last):
File "C:/Users/shiva/Desktop/Python/Shiva.py", line 16, in <module>
n1, n2, n3, n4= tuplex
ValueError: not enough values to unpack (expected 4, got 3)
Program 4. Write a Python program to add an item to a tuple.
Source Code
#create a tuple
tuplex = (4, 6, 2, 8, 3, 1)
print(tuplex)
#tuples are immutable, so you can not add new elements
#using merge of tuples with the + operator you can add an element and it will create a new tuple
tuplex = tuplex + (9,)
print(tuplex)
#adding items in a specific index
tuplex = tuplex[:5] + (15, 20, 25) + tuplex[:5]
print(tuplex)
#converting the tuple to list
listx = list(tuplex)
#use different ways to add items in list
listx.append(30)
tuplex = tuple(listx)
print(tuplex)
Output
(4, 6, 2, 8, 3, 1)
(4, 6, 2, 8, 3, 1, 9)
(4, 6, 2, 8, 3, 15, 20, 25, 4, 6, 2, 8, 3)
(4, 6, 2, 8, 3, 15, 20, 25, 4, 6, 2, 8, 3, 30)
Program 5. Write a Python program to convert a tuple to a string
Source Code
tup = ('s', 'u', 'n', 'r', 'i', 's', 'e')
str = ''.join(tup)
print(str)
Output
sunrise
Program 6. Write a Python program to find repeated items in a tuple.
Source Code
#create a tuple
tuplex = 2, 4, 5, 6, 2, 3, 4, 4, 7
print(tuplex)
#return the number of times it appears in the tuple.
count = tuplex.count(4)
print(count)
Output
(2, 4, 5, 6, 2, 3, 4, 4, 7)
3
Program 7. Write a Python program to check whether an element exists within a tuple.
Source Code
tuplex = ("s", "u", "n", "r", "i", "s", "e", 1, 5)
print("r" in tuplex)
print(5 in tuplex)
print(7 in tuplex)
Output
True
True
False
Program 8. Write a Python program to convert a list to a tuple.
Source Code
#Convert list to tuple
listx = [5, 10, 7, 4, 15, 3]
print(listx)
#use the tuple() function built-in Python, passing as parameter the list
tuplex = tuple(listx)
print(tuplex)
Output
[5, 10, 7, 4, 15, 3]
(5, 10, 7, 4, 15, 3)
Program 9. Write a Python program to remove an item from a tuple.
Source Code
#create a tuple
tuplex = "w", 3, "r", "s", "o", "u", "r", "c", "e"
print(tuplex)
#tuples are immutable, so you can not remove elements
#using merge of tuples with the + operator you can remove an item and it will create a new tuple
tuplex = tuplex[:2] + tuplex[3:]
print(tuplex)
#converting the tuple to list
listx = list(tuplex)
#use different ways to remove an item of the list
listx.remove("c")
#converting the tuple to list
tuplex = tuple(listx)
print(tuplex)
Program 10. Write a Python program to slice a tuple
Source Code
#create a tuple
tuplex = (2, 4, 3, 5, 4, 6, 7, 8, 6, 1)
#used tuple[start:stop] the start index is inclusive and the stop index
_slice = tuplex[3:5]
#is exclusive
print(_slice)
#if the start index isn't defined, is taken from the beg inning of the tuple
_slice = tuplex[:6]
print(_slice)
#if the end index isn't defined, is taken until the end of the tuple
_slice = tuplex[5:]
print(_slice)
#if neither is defined, returns the full tuple
_slice = tuplex[:]
print(_slice)
#The indexes can be defined with negative values
_slice = tuplex[-8:-4]
print(_slice)
#create another tuple
tuplex = tuple("HELLO WORLD")
print(tuplex)
#step specify an increment between the elements to cut of the tuple
#tuple[start:stop:step]
_slice = tuplex[2:9:2]
print(_slice)
#returns a tuple with a jump every 3 items
_slice = tuplex[::4]
print(_slice)
#when step is negative the jump is made back
_slice = tuplex[9:2:-4]
print(_slice)
Output
(5, 4)
(2, 4, 3, 5, 4, 6)
(6, 7, 8, 6, 1)
(2, 4, 3, 5, 4, 6, 7, 8, 6, 1)
(3, 5, 4, 6)
('H', 'E', 'L', 'L', 'O', ' ', 'W', 'O', 'R', 'L', 'D')
('L', 'O', 'W', 'R')
('H', 'O', 'R')
('L', ' ')
Program 11. Write a Python program to reverse a tuple.
Source Code
#create a tuple
x = ("Sunrise Computer")
# Reversed the tuple
y = reversed(x)
print(tuple(y))
#create another tuple
x = (5, 10, 15, 20)
# Reversed the tuple
y = reversed(x)
print(tuple(y))
Output
('r', 'e', 't', 'u', 'p', 'm', 'o', 'C', ' ', 'e', 's', 'i', 'r', 'n', 'u', 'S')
(20, 15, 10, 5)
Program 12. Write a Python program to replace the last value of tuples in a list.
Source Code
l = [(10, 20, 40), (40, 50, 60), (70, 80, 90)]
print([t[:-1] + (100,) for t in l])
Output
[(10, 20, 100), (40, 50, 100), (70, 80, 100)]
Program 13. Write a Python program to sort a tuple by its float element.
price = [('item1', '12.20'), ('item2', '15.10'), ('item3', '24.5')]
print( sorted(price, key=lambda x: float(x[1]), reverse=True))
Output
[('item3', '24.5'), ('item2', '15.10'), ('item1', '12.20')]
Program 14. Write a Python program to compute the element-wise sum of given tuples.
Source Code
x = (1,2,3,4)
y = (3,5,2,1)
z = (2,2,3,1)
print("Original lists:")
print(x)
print(y)
print(z)
print("\nElement-wise sum of the said tuples:")
result = tuple(map(sum, zip(x, y, z)))
print(result)
Output
Original lists:
(1, 2, 3, 4)
(3, 5, 2, 1)
(2, 2, 3, 1)
Element-wise sum of the said tuples:
(6, 9, 8, 6)
PYTHON | SETS
Program 1. Write a Python program to create a set.
Source Code
print("Create a new set:")
x = set()
print(x)
print(type(x))
print("\nCreate a non empty set:")
n = set([0, 1, 2, 3, 4])
print(n)
print(type(n))
print("\nUsing a literal:")
a = {1,2,3,'foo','bar'}
print(type(a))
print(a)
Output
Create a new set:
set()
<class 'set'>
Create a non empty set:
{0, 1, 2, 3, 4}
<class 'set'>
Using a literal:
<class 'set'>
{1, 2, 3, 'bar', 'foo'}
Program 2. Write a Python program to iterate over sets.
Source Code
#Create a set
num_set = set([0, 1, 2, 3, 4, 5])
for n in num_set:
print(n, end=' ')
print("\n\nCreating a set using string:")
char_set = set("sunrise")
# Iterating using for loop
for val in char_set:
print(val, end=' ')
Output
0 1 2 3 4 5
Creating a set using string:
euSnirs
Program 3. Write a Python program to add member(s) to a set.
Source Code
#A new empty set
color_set = set()
print(color_set)
print("\nAdd single element:")
color_set.add("Red")
print(color_set)
print("\nAdd multiple items:")
color_set.update(["Blue", "Green"])
print(color_set)
Output
set()
Add single element:
{'Red'}
Add multiple items:
{'Green', 'Red', 'Blue'}
Program 4. Write a Python program to remove item(s) from a given set.
Source Code
num_set = set([0, 1, 3, 4, 5])
print("Original set:")
print(num_set)
num_set.pop()
print("\nAfter removing the first element from the said set:")
print(num_set)
Output
Original set:
{0, 1, 3, 4, 5}
After removing the first element from the said set:
{1, 3, 4, 5}
Program 5. Write a Python program to remove an item from a set if it is present in the set.
Source Code
#Create a new set
num_set = set([0, 1, 2, 3, 4, 5])
print("Original set elements:")
print(num_set)
print("\nRemove 0 from the said set:")
num_set.discard(4)
print(num_set)
print("\nRemove 5 from the said set:")
num_set.discard(5)
print(num_set)
print("\nRemove 2 from the said set:")
num_set.discard(5)
print(num_set)
print("\nRemove 7 from the said set:")
num_set.discard(15)
print(num_set)
Output
Original set elements:
{0, 1, 2, 3, 4, 5}
Remove 0 from the said set:
{0, 1, 2, 3, 5}
Remove 5 from the said set:
{0, 1, 2, 3}
Remove 2 from the said set:
{0, 1, 2, 3}
Remove 7 from the said set:
{0, 1, 2, 3}
Program 6. Write a Python program to create an intersection of sets.
Source Code
setx = set(["green", "blue"])
sety = set(["blue", "yellow"])
print("Original set elements:")
print(setx)
print(sety)
print("\nIntersection of two said sets:")
setz = setx & sety
print(setz)
Output
Original set elements:
{'green', 'blue'}
{'blue', 'yellow'}
Intersection of two said sets:
{'blue'}
Program 7. Write a Python program to create a union of sets.
Source Code
setc1 = set(["green", "blue"])
setc2 = set(["blue", "yellow"])
print("Original sets:")
print(setc1)
print(setc2)
setc = setc1.union(setc2)
print("\nUnion of above sets:")
print(setc)
setn1 = set([1, 1, 2, 3, 4, 5])
setn2 = set([1, 5, 6, 7, 8, 9])
print("\nOriginal sets:")
print(setn1)
print(setn2)
print("\nUnion of above sets:")
setn = setn1.union(setn2)
print(setn)
Output
Original sets:
{'blue', 'green'}
{'blue', 'yellow'}
Union of above sets:
{'blue', 'yellow', 'green'}
Original sets:
{1, 2, 3, 4, 5}
{1, 5, 6, 7, 8, 9}
Union of above sets:
{1, 2, 3, 4, 5, 6, 7, 8, 9}
Program 8. Write a Python program to create set difference.
Source Code
setc1 = set(["green", "blue"])
setc2 = set(["blue", "yellow"])
print("Original sets:")
print(setc1)
print(setc2)
r1 = setc1.difference(setc2)
print("\nDifference of setc1 - setc2:")
print(r1)
r2 = setc2.difference(setc1)
print("\nDifference of setc2 - setc1:")
print(r2)
setn1 = set([1, 1, 2, 3, 4, 5])
setn2 = set([1, 5, 6, 7, 8, 9])
print("\nOriginal sets:")
print(setn1)
print(setn2)
r1 = setn1.difference(setn2)
print("\nDifference of setn1 - setn2:")
print(r1)
r2 = setn2.difference(setn1)
print("\nDifference of setn2 - setn1:")
print(r2)
Output
Original sets:
{'green', 'blue'}
{'yellow', 'blue'}
Difference of setc1 - setc2:
{'green'}
Difference of setc2 - setc1:
{'yellow'}
Original sets:
{1, 2, 3, 4, 5}
{1, 5, 6, 7, 8, 9}
Difference of setn1 - setn2:
{2, 3, 4}
Difference of setn2 - setn1:
{8, 9, 6, 7}
Program 9. Write a Python program to remove all elements from a given set.
Source Code
setc = {"Red", "Green", "Black", "White"}
print("Original set elements:")
print(setc)
print("\nAfter removing all elements of the said set.")
setc.clear()
print(setc)
Output
Original set elements:
{'Green', 'Black', 'Red', 'White'}
After removing all elements of the said set.
set()
Program 10. Write a Python program to find the maximum and minimum values in a set.
Source Code
#Create a set
setn = {5, 10, 3, 15, 2, 20}
print("Original set elements:")
print(setn)
print(type(setn))
print("\nMaximum value of the said set:")
print(max(setn))
print("\nMinimum value of the said set:")
print(min(setn))
Output
Original set elements:
{2, 3, 5, 10, 15, 20}
<class 'set'>
Maximum value of the said set:
20
Minimum value of the said set:
2
Program 11. Write a Python program to find the length of a set.
Source Code
#Create a set
setn = {5, 10, 3, 15, 2, 20}
print("Original set elements:")
print(setn)
print(type(setn))
print("\nLength of the said set:")
print(len(setn))
setn = {5, 5, 5, 5, 5, 5}
print("Original set elements:")
print(setn)
print(type(setn))
print("\nLength of the said set:")
print(len(setn))
setn = {5, 5, 5, 5, 5, 5, 7}
print("Original set elements:")
print(setn)
print(type(setn))
print("\nLength of the said set:")
print(len(setn))
Output
Original set elements:
{2, 3, 5, 10, 15, 20}
<class 'set'>
Length of the said set:
6
Original set elements:
{5}
<class 'set'>
Length of the said set:
1
Original set elements:
{5, 7}
<class 'set'>
Length of the said set:
2
Program 12. Write a Python program to check if a given value is present in a set or not.
Source Code
nums = {1, 3, 5, 7, 9, 11}
print("Original sets(nums): ",nums,"\n")
print("Test if 6 exists in nums:")
print(6 in nums)
print("Test if 7 exists in nums:")
print(7 in nums)
print("Test if 11 exists in nums:")
print(11 in nums)
print("Test if 0 exists in nums:")
print(0 in nums)
print("\nTest if 6 is not in nums")
print(6 not in nums)
print("Test if 7 is not in nums")
print(7 not in nums)
print("Test if 11 is not in nums")
print(11 not in nums)
print("Test if 0 is not in nums")
print(0 not in nums)
Output
Original sets(nums): {1, 3, 5, 7, 9, 11}
Test if 6 exists in nums:
False
Test if 7 exists in nums:
True
Test if 11 exists in nums:
True
Test if 0 exists in nums:
False
Test if 6 is not in nums
True
Test if 7 is not in nums
False
Test if 11 is not in nums
False
Test if 0 is not in nums
True
PYTHON | STRING
Program 1. Write a Python program to calculate the length of a string.
Source Code
def string_length(str1):
count = 0
for char in str1:
count += 1
return count
print(string_length('Sunrise Computer Classes'))
Output
24
Program 2. Write a Python program to count the number of characters (character frequency) in a string.
Source Code
def char_frequency(str1):
dict = {}
for n in str1:
keys = dict.keys()
if n in keys:
dict[n] += 1
else:
dict[n] = 1
return dict
print(char_frequency('sunrisecomputerclasses.com'))
Output
{'s': 5, 'u': 2, 'n': 1, 'r': 2, 'i': 1, 'e': 3, 'c': 3, 'o': 2, 'm': 2, 'p': 1, 't': 1, 'l': 1, 'a': 1, '.': 1}
Program 3. 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.
Source Code
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'))
Output
CONRISE SUMPUTER
Program 4. Write a Python function that takes a list of words and return the longest word and the length of the longest one.
Source Code
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(["Python", "Sunrise", "Backend", "Computer"])
print("\nLongest word: ",result[1])
print("Length of the longest word: ",result[0])
Output
8
Program 5. Write a Python program to change a given string to a newly string where the first and last chars have been exchanged.
Source Code
def change_sring(str1):
return str1[-1:] + str1[1:-1] + str1[:1]
print(change_sring('Sunrise'))
print(change_sring('Shivansh'))
print(change_sring('123456'))
Output
eunrisS
hhivansS
623451
Program 6. Write a Python program to remove the nth index character from a nonempty string.
Source Code
def remove_char(str, n):
first_part = str[:n]
last_part = str[n+1:]
return first_part + last_part
print(remove_char('Sunrise', 0))
print(remove_char('Computer', 3))
print(remove_char('Classes', 5))
Output
unrise
Comuter
Classs
Program 7. Write a Python program to remove characters that have odd index values in a given string.
Source Code
def odd_values_string(str):
result = ""
for i in range(len(str)):
if i % 2 == 0:
result = result + str[i]
return result
print(odd_values_string('Python Language'))
print(odd_values_string('Sunrise Computer'))
print(odd_values_string('National Institute of Electronic & Information Technology'))
Output
Pto agae
SnieCmue
Ntoa nttt fEetoi nomto ehooy
Program 8. Write a Python program to count the occurrences of each word in a given sentence.
Source Code
def word_count(str):
counts = dict()
words = str.split()
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
return counts
print( word_count('Video provides a powerful way to help you prove your point. When you click Online Video, you can paste in the embed code for the video you want to add. You can also type a keyword to search online for the video that best fits your document.'))
Output
{'Video': 1, 'provides': 1, 'a': 2, 'powerful': 1, 'way': 1, 'to': 3, 'help': 1, 'you': 4, 'prove': 1, 'your': 2, 'point.': 1, 'When': 1, 'click': 1, 'Online': 1, 'Video,': 1, 'can': 2, 'paste': 1, 'in': 1, 'the': 3, 'embed': 1, 'code': 1, 'for': 2, 'video': 2, 'want': 1, 'add.': 1, 'You': 1, 'also': 1, 'type': 1, 'keyword': 1, 'search': 1, 'online': 1, 'that': 1, 'best': 1, 'fits': 1, 'document.': 1}
Program 9. Write a Python function to reverse a string if its length is a multiple of 4.
Source Code
def reverse_string(str1):
if len(str1) % 4 == 0:
return ''.join(reversed(str1))
return str1
print(reverse_string('Sunrise'))
print(reverse_string('Computer'))
Output
Sunrise
retupmoC
Program 10. Write a Python program to display formatted text (width=50) as output.
Source Code
import textwrap
sample_text = '''
Python is a widely used high-level, general-purpose, interpreted,
dynamic programming language. Its design philosophy emphasizes
code readability, and its syntax allows programmers to express
concepts in fewer lines of code than possible in languages such
as C++ or Java.
'''
print()
print(textwrap.fill(sample_text, width=50))
print()
Output
Python is a widely used high-level, general-
purpose, interpreted, dynamic programming
language. Its design philosophy emphasizes code
readability, and its syntax allows programmers to
express concepts in fewer lines of code than
possible in languages such as C++ or Java.
PYTHON | DICTIONARY
Program 1. Write a Python script to sort (ascending and descending) a dictionary by value.
Source Code
import operator
d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
print('Original dictionary : ',d)
sorted_d = sorted(d.items(), key=operator.itemgetter(1))
print('Dictionary in ascending order by value : ',sorted_d)
sorted_d = dict( sorted(d.items(), key=operator.itemgetter(1),reverse=True))
print('Dictionary in descending order by value : ',sorted_d)
Output
Original dictionary : {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
Dictionary in ascending order by value : [(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
Dictionary in descending order by value : {3: 4, 4: 3, 1: 2, 2: 1, 0: 0}
Program 2. Write a Python script to add a key to a dictionary.
Source Code
d = {0:10, 1:20}
print(d)
d.update({2:30})
print(d)
Output
{0: 10, 1: 20}
{0: 10, 1: 20, 2: 30}
Program 3. Write a Python script to concatenate the following dictionaries to create a new one.
Source Code
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)
Output
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
Program 4. Write a Python script to check whether a given key already exists in a dictionary.
Source Code
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)
Output
Key is present in the dictionary
Key is not present in the dictionary
Program 5. Write a Python program to iterate over dictionaries using for loops.
Source Code
d = {'x': 10, 'y': 20, 'z': 30}
for dict_key, dict_value in d.items():
print(dict_key,'->',dict_value)
Output
x -> 10
y -> 20
z -> 30
Program 6. Write a Python script to generate and print a dictionary that contains a number (between 1 and n) in the form (x, x*x).
Source Code
n=int(input("Input a number "))
d = dict()
for x in range(1,n+1):
d[x]=x*x
print(d)
Output
10
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}
Program 7. Write a Python script to print a dictionary where the keys are numbers between 1 and 15 (both included) and the values are the square of the keys.
Source Code
d=dict()
for x in range(1,16):
d[x]=x**2
print(d)
Output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225}
Program 8. Write a Python script to merge two Python dictionaries.
Source Code
d1 = {'a': 100, 'b': 200}
d2 = {'x': 300, 'y': 200}
d = d1.copy()
d.update(d2)
print(d)
Output
{'x': 300, 'y': 200, 'a': 100, 'b': 200}
Program 9. Write a Python program to iterate over dictionaries using for loops.
Source Code
d = {'Red': 1, 'Green': 2, 'Blue': 3}
for color_key, value in d.items():
print(color_key, 'corresponds to ', d[color_key])
Output
Red corresponds to 1
Green corresponds to 2
Blue corresponds to 3
Program 10. Write a Python program to sum all the items in a dictionary.
Source Code
my_dict = {'data1':100,'data2':-54,'data3':247}
print(sum(my_dict.values()))
Output
293
Program 11. Write a Python program to multiply all the items in a dictionary.
Source Code
my_dict = {'data1':100,'data2':-54,'data3':247}
result=1
for key in my_dict:
result=result * my_dict[key]
print(result)
Output
-1333800
Program 12. Write a Python program to remove a key from a dictionary.
Source Code
myDict = {'a':1,'b':2,'c':3,'d':4}
print(myDict)
if 'a' in myDict:
del myDict['a']
print(myDict)
Output
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
{'b': 2, 'c': 3, 'd': 4}
Program 13. Write a Python program to map two lists into a dictionary.
Source Code
keys = ['red', 'green', 'blue']
values = ['#FF0000','#008000', '#0000FF']
color_dictionary = dict(zip(keys, values))
print(color_dictionary)
Output
{'red': '#FF0000', 'green': '#008000', 'blue': '#0000FF'}
Program 14. Write a Python program to sort a given dictionary by key.
Source Code
color_dict = {'red':'#FF0000',
'green':'#008000',
'black':'#000000',
'white':'#FFFFFF'}
for key in sorted(color_dict):
print("%s: %s" % (key, color_dict[key]))
Output
black: #000000
green: #008000
red: #FF0000
white: #FFFFFF
Program 15. Write a Python program to get the maximum and minimum values of a dictionary.
Source Code
my_dict = {'x':500, 'y':5874, 'z': 560}
key_max = max(my_dict.keys(), key=(lambda k: my_dict[k]))
key_min = min(my_dict.keys(), key=(lambda k: my_dict[k]))
print('Maximum Value: ',my_dict[key_max])
print('Minimum Value: ',my_dict[key_min])
Output
Maximum Value: 5874
Minimum Value: 500
For Any Doubt Clear on Telegram Discussion Group
Comments
Post a Comment