[Go to site: main page, start]

0% found this document useful (0 votes)
16 views96 pages

Basic Python Programs

The document contains a collection of over 140 basic Python programs designed to assist users in preparing for programming interviews. Each program demonstrates fundamental concepts such as arithmetic operations, variable swapping, random number generation, temperature conversion, and more. The examples are structured to be easily understood and executed in a Jupyter Notebook environment.

Uploaded by

Radhika Kumari
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
16 views96 pages

Basic Python Programs

The document contains a collection of over 140 basic Python programs designed to assist users in preparing for programming interviews. Each program demonstrates fundamental concepts such as arithmetic operations, variable swapping, random number generation, temperature conversion, and more. The examples are structured to be easily understood and executed in a Jupyter Notebook environment.

Uploaded by

Radhika Kumari
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
140+ BASIC PYTHON PROGRAMS Thiy resource can assist you Ww preparing for your Wnterview- 11126023, 453 AM Basic Python Program - Jupyter Notebook Program 1 Write a Python program to print "H lo Python”. 1 print("Hello Python") Hello Python Program 2 Write a Python program to do arithmetical operations addi In [2] 1 # Addition 2 num1 = float(input("Enter the first number for addition: 3 num2 = float(input("Enter the second number for addition 4 sum_result = num1 + num2 5 print(#"sum: {num} + {num} = {sumresult}") Enter the first number for addition: 5 Enter the second number for addition: 6 sum: 5.@ + 6.0 = 11.0 In [3]: 1 # Division 2 num3 = float(input("Enter the dividend for division: d 3 num4 = float(input("Enter the divisor for division: ")) 4 if muna == 0: 5 print("Error: Division by zero is not allowed.") 6 else: 7 div_result = num3 / num4 8 print(f"Division: {num3} / {num4} = {div_result}") Enter the dividend for division: 25 Enter the divisor for division: 5 Division: 25.0 / 5.8 = 5. Program 3 Write a Python program to find the area of a triangle. In [4]; # Input the base and height from the user 1 2 base = float(input("Enter the length of the base of the triangle: ")) 3 height = float(input("Enter the height of the triangle: ")) 4 # Calculate the area of the triangle 5 area = 0.5 * base * height 6 # Display the result 7 print(f"The area of the triangle 4: {area}" Enter the length of the base of the triangle: 1¢ Enter the height of the triangle: 15 The area of the triangle is: 75.0 localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 1195: 11126023, 4:53AM In [6]: Basic Python Program -Jupyter Notebook Program 4 Write a Python program to swap two variables. 1 # Input two variables 2 a= input("Enter the value of the first variable (a): 3b = input("Enter the value of the second variable (b) 4 # Display the original values 5 print(#"Original values: a = {a}, b = {b}") 6 # Swap the values using a temporary variable 7 temp =a 8 a=b 9 b= temp 1@ # Display the swapped values 11 print(f"Swapped values: a = {a}, b = {b}") Enter the value of the first variable (a): 5 Enter the value of the second variable (b): 9 Original values: a = 5, b= 9 Swapped values: a= 9, b= 5 Program 5 Write a Python program to generate a random number. 1 import random 2 print(f"Random number: {[Link](1, 100)}") Random number: 89 Program 6 Write a Python program to convert kilometers to miles. kilometers = float(input("Enter distance in kilometers: ")) # Conversion factor: 1 kilometer = 0.621371 miles conversion _factor = 0.621371 1 2 3 4 5 6 miles = kilometers * conversion_factor 7 8 print(#"{kilometers} kilometers is equal to {miles} miles") Enter distance in kilometers: 100 100.@ kilometers is equal to 62.137100000000004 miles Program 7 Write a Python program to convert Celsius to Fahrenheit. localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 2105 11126023, 4:53AM In [8. In [9]: Basic Python Program -Jupyter Notebook celsius = Float(input("Enter temperature in Celsius: “)) 4 Conversion formula: Fahrenheit = (Celsius * 9/5) + 32 fahrenheit = (celsius * 9/5) + 32 print(f"{celsius} degrees Celsius is equal to {fahrenheit} degrees Fahr Enter temperature in Celsius: 37 37.0 degrees Celsius is equal to 98.6 degrees Fahrenheit Program 8 Write a Python program to display calendar. import calendar 1 2 3 year = int(input("enter year: ")) 4 month = int(input("Enter month: ")) 5 6 7 cal = [Link](year, month) print(cal) Enter year: 2023 Enter month: 11 November 2023 Mo Tu We Th Fr Sa Su dss 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 Program 9 Wr a Python program to solve quadratic equation. The standard form of a quadratic equation is: axe +bx+e=0 where a, band care real numbers and a#0 The solutions of this quadratic equation is given by: (-b + ( — 4ac)!”\/(2a) localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 3195 11726023, 4:53 AM In [10, 15, 16 7 18 19 20 21 22 23 24 25 26 27 28 Basic Python Program - Jupyter Notebook import math # Input coefficients a = float(input("Enter coefficient a: ")) b = float(input("Enter coefficient b: ")) ¢ = Float(input("Enter coefficient ¢: ")) # Calculate the discriminant discriminant = b**2 - 4*a*c # Check if the discriminant is positive, negative, or zero if discriminant > 0: # Two real and distinct roots root = (-b + [Link](discriminant)) / (2*a) root2 = (-b - [Link](discriminant)) / (2*a) print(#"Root 1: {root1}") print(#"Root 2: {root2}") elif discriminant == 0: # One real root (repeated) root = -b / (2*a) print(#"Root: {root}") elsi # Complex roots real_part = -b / (2*a) imaginary_part = [Link](abs(discriminant)) / (2*a) print(#"Root 1: {real_part} + {imaginary_part}i") print(f"Root 2: {real_part} - {imaginary_part}i") Enter coefficient a: 1 Enter coefficient b: 4 Enter coefficient c: 8 Root 1: -2.0 + 2.01 Root 2: -2.0 - 2.04 Program 10 a Python program to swap two vai bles without temp variable. a b 10 # Swapping without a temporary variable a, b=b,a print("After swapping:") print("a =", a) print("b =", b) After swapping: a=10 localhost: 8888/nolebooksPiush Kumar Sharma/Basic Python [Link] 4195 11126023, 4:53AM In [12] In [13]: In [14]: Basie Python Program -Jupyter Notebook Program 11 Write a Python Program to Check if a Number is Positive, Negative or Zero. 1 num = float(input("Enter a number: ")) 2 if num > @: 3 print("Positive number") 4 elif num == 0: 5 6 7 print("Zero") else: print("Negative number”) Enter a number: 6.4 Positive number Program 12 co a Python Program to Check if a Number is Odd or Even. num = int(input ("Enter a number: *)) 1 2 3 if numk2 == @: 4 print("This is a even number”) 5 6 else: print("This is a odd number”) Enter a number: 3 This is a odd number Program 13 Write a Python Program to Check Leap Yet year = int(input("enter @ year: ")) 1 2 3 # divided by 100 means century year (ending with 0) 4 # century year divided by 490 is Leap year 5 if (year % 400 == 0) and (year % 100 == 0): 6 print("{@} is a leap year".format(year)) 7 8 # not divided by 100 means not a century year 9 |# year divided by 4 is a Leap year 16 elif (year % 4 ==@) and (year % 100 I= @): 1 print("{@} is a leap year". format (year)) 13 # if not divided by both 400 (century year) and 4 (not century year) 14 # year is not Leap year 15 else: 16 print("{@} is not a leap year".format(year)) Enter a year: 2024 2024 is a leap year localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 5/95 11126023, 4:53AM In [15]: Basie Python Program - Jupyter Notebook Program 14 Write a Python Program to Check Prime Number. Prime Numbers: ‘Aprime number is a whole number that cannot be evenly divided by any other number except for 1 and itself. For example, 2, 3, 5, 7, 11, and 13 are prime numbers because they cannot be divided by any other positive integer except for 1 and their own value. 1 num = int(input("enter a number: ")) 2 3. # define a flag variable 4 flag = False 5 6 if num == 1: 7 print(#"{num}, is not a prime number") 8 elif num > 1: 9 # check for factors 16 for i in range(2, num): n if (num % i) == 0: 2 flag = True —# if factor is found, set flag to True 2B # break out of Loop 14 break 15 16 # check if flag is True 17 if Flag: 18 print(#"{num}, is nota prime number") 19 else: 26 print(#"{num}, is a prime number") Enter a number: 27 27, is not a prime number Program15 { Wr a Python Program to Print all Prime Numbers in an Interval of 1-10. localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 11126023, 4:53AM In [20, 15, Basie Python Program - Jupyter Notebook # Python program to display all the prime numbers within an interval. lower = 1 upper = 10 print("Prime numbers between", lower, “and”, upper, “are:") for num in range(lower, upper + 1): # all prime numbers are greater than 1 if num > 1: for i in range(2, num): if (num % i) == 0: break else: print (num) Prime numbers between 1 and 10 are: 2 3 5 7 Program 16 In [21] a Python Program to Find the Factorial of a Number. num = int(input("Enter a number: ")) factorial = 1 if num <@: print("Factirial does not exist for negative numbers") elif num == 0: print("Factorial of @ is 1") else: for i in range(1, num+1): factorial = factorial*i print(f'The factorial of {num} is {factorial}') Enter a number: 4 The factorial of 4 is 24 Program 17 me a Python Program to Display the multi localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 7195 11126023, 4:53 AM Basic Python Program -Jupyter Notebook In [22]: 1 num = int(input("Display multiplication table of: ")) 2 3. for i in range(1, 11): 4 print(f"{num} x {4} = {num*d Display multiplication table of: 19 19 X1=19 19 X 2 = 38 19 x3 19 x4 19 X5 19 X6 19 X7 19 X8 19 x9 19 x 1 Program 18 Write a Python Program to Print the Fibonacci sequence. Fibonacci sequence: ‘The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, typically starting with 0 and 1. So, the sequence begins with 0 and 1, and the next number is obtained by adding the previous two numbers. This pattern continues indefinitely, generating a sequence that looks like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, and so on. Mathematically, the Fibonacci sequence can be defined using the following recurrence relation’ F(0) = 0 F(1) = 1 F(n) = F(n— 1) + F(n—2)forn> 1 localhost 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 8195 11126023, 4:53AM In [23 Basie Python Program -Jupyter Notebook nterms = int(input("How many terms? ")) # first two terms mi, n2= 0,1 count = @ # check if the number of terms is valid if nterms <= 0: 9 print("Please enter a positive integer") 1@ # if there is only one term, return ni 11 elif nterms == 1: 2 print("Fibonacci sequence upto” nterms," 2B print(nd) 14 # generate fibonacci sequence 15 else: 16 print("Fibonacci sequence:") v7 while count < nterms: 18 print(na) 19 nth = nl + n2 26 # update values 21 nd = n2 22 n2 = nth 23 count += 1 How many terms? 10 Fibonacci sequence: Program 19 Write a Python Program to Check Armstrong Number? ‘Armstrong Number: Itis a number that is equal to the sum of its own digits, each raised to a power equal to the number of digits in the number. For example, let's consider the number 153: + Ithas three digits (1, 5, and 3). + Ifwe calculate 1° + 5° + 3°, we get 1 + 125 +27, which is equal to 153. ‘So, 153 is an Armstrong number because it equals the sum of its digits raised to the power of the number of digits in the number. Another example is 9474: + Ithas four digits (9, 4, 7, and 4), localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] ‘wesi23, 4:53.00 Basic Python Program -Jupyter Notebook + Ifwe calculate 9* + 4* + 7* + 4%, we get 6561 + 256 + 2401 + 256, which is also equal to 9474. ‘Therefore, 9474 is an Armstrong number as well. In [25]: 1 num = int(input("Enter a number: ")) 2 3 # Calculate the number of digits in num 4 num_str = str(num) 5 num_digits = len(num_str) 6 7 8 # Initialize variables sum_of_powers = @ 9 temp_num = num 16 11 # Calculate the sum of digits raised to the power of numdigits 2 13 while temp_num > 0: 14 digit = temp_num % 10 15 sum_of_powers += digit ** num_digits 16 temp_num //= 10 v7 18 # Check if it’s an Armstrong number 19 if sum_of_powers == num: 26 print(#"{num} is an Armstrong number.) 21 else: 2 print(#"{num} is not an Armstrong number. 23 Enter a number: 9474 9474 is an Armstrong number. Program 20 Write a Python Program to Find Armstrong Number in an Interval. localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 11126023, 4:53AM In [26]: | 1 2 3 4 15 16 7 18 Basic Python Program - Jupyter Notebook # Input the interval from the user lower = int(input("Enter the lower limit of the interval: ")) upper = int(input("Enter the upper limit of the interval: “)) for num in range(lower, upper + 1): # Iterate through the numbers 4 order = len(str(num)) # Find the number of digits in ‘num’ temp_num = num sum = @ while temp_num > 0: digit = temp_num % 10 sum += digit ** order temp_num //= 10 # Check if ‘num’ is an Armstrong number if num == sum: print (num) Enter the lower limit of the interval: 10 Enter the upper limit of the interval: 1000 153 378 371 407 Program 21 Wr a Python Program to Find the Sum of Natural Numbers. Natural numbers are a set of positive integers that are used to count and order objects. They are the numbers that typically start from 1 and continue indefinitely, including all the whole numbers greater than 0. In mathematical notation, the set of natural numbers is often denoted as "N" and can be expressed as: In [27]: 1 2 5 4 5 6 7 8 9 e 1 Enter the limi The N =1,2,3,4,5,6,7,8, Limit = int(input("Enter the limit: ")) # Initialize the sum sum = @ # Use a for Loop to calculate the sum of natural numbers for i in range(1, limit + 1): sum 42 4 # Print the sum print("The sum of natural numbers up to", limit, “is:", sum) 10 sum of natural numbers up to 1@ is: 55 localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 11195 11126023, 4:53AM Basic Python Program - Jupyter Notebook Program 22 Write a Python Program to Find LCM. Least Common Multiple (LCM): LCM, or Least Common Multiple, is the smallest multiple that is exactly divisible by two or more numbers. Formula: For two numbers a and b, the LCM can be found using the formula: lab LOM.) = Gora For more than two numbers, you can find the LCM step by step, taking the LCM of pairs of numbers at a time until you reach the last pair. Note: GCD stands for Greatest Common Divisor. 1 # Python Program to find the L.C.M,-of two input number 2 3 def compute_lem(x, y): 4 if x>y: # choose the greater number 5 greater = x 6 else: 7 greater = y 8 while(True) : 9 if((greater % x == @) and (greater % y == 0): 16 lem = greater n break 2 greater += 1 2B return lem 14 15 numi = int(input(’enter the number: ')) 16 num2 = int(input(‘Enter the number: *)) 7 18 print("The L.C.M. is", compute_lem(num1, num2)) Enter the number: 54 Enter the number: 24 The L.C.M. is 216 Program 23 Write a Python Program to Find HCF. Highest Common Factor(HCF): HCF, or Highest Common Factor, is the largest positive integer that divides two or more numbers without leaving a remainder. Formula: localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 12105 11126023, 4:53AM In [2]: Basic Python Program -Jupyter Notebook For two numbers a and b, the HCF can be found using the formula: HCF(a, b) = GCD(a, 6) For more than two numbers, you can find the HCF by taking the GCD of pairs of numbers at a time until you reach the last pair. Note: GCD stands for Greatest Common Divisor. 1 # Python program to find H.C.F of two numbers 2 3. # define a function 4 def compute_hcf(x, y): 5 6 # choose the smaller number 7 if x>y: 8 smaller = y 9 else: 16 smaller = x 1 for i in range(1, smaller+1): 2 if((x % i == 0) and (y % 4 == 0): 2B hef 14 return hef 15 16 numi = int(input(‘Enter the number: ')) 17 num2 = int(input(‘Enter the number: *)) 18 19 print("The H.C.F. is", compute_hef(numi, num2)) Enter the number: 54 Enter the number: 24 The H.C.F. is 6 Program 24 Write a Python Program to Convert Decimal to Binary, Octal and Hexadecimal. How can we manually convert a decimal number to binary, octal and hexadecimal? Converting a decimal number to binary, octal, and hexadecimal involves dividing the decimal number by the base repeatedly and noting the remainders at each step. Here's a simple example: Let's convert the decimal number 27 to binary, octal, and hexadecimal. 4. Binary: Divide 27 by 2. Quotient is 13, remainder is 1. Note the remainder. Divide 13 by 2. Quotient is 6, remainder is 1. Note the remainder. Divide 6 by 2. Quotient is 3, remainder is 0. Note the remainder. Divide 3 by 2. Quotient is 1, remainder is 1. Note the remainder. Divide 1 by 2. Quotient is 0, remainder is 1. Note the remainder. Reading the remainders from bottom to top, the binary representation of 27 is 11011. 2. Octal: localhost 8888/nolebooks/Piush Kumar Sharma/Basie Python [Link] 13105 11126023, 4:53 AM Basic Python Program - Jupyter Notebook + Divide 27 by 8. Quotient is 3, remainder is 3. Note the remainder. + Divide 3 by 8. Quotient is 0, remainder is 3. Note the remainder. Reading the remainders from bottom to top, the octal representation of 27 is 33. 3, Hexadecimal: + Divide 27 by 16. Quotient is 1, remainder is 11 (B in hexadecimal). Note the remainder. Reading the remainders, the hexadecimal representation of 27 is 18. So, in summary: + Binary: 27 in decimal is 11011 in binary. Octal: 27 in decimal is 33 in octal. Hexadecimal: 27 in decimal is 1B in hexadecimal. In [3] dec_num = int(input(‘Enter a decimal number: *)) a 2 3 print("The decimal value of", dec_num, "is:") 4 print(bin(dec_num), “in binary.") 5 print(oct(dec_num), "in octal.") 6 print(hex(dec_num), “in hexadecimal.") Enter a decimal number: 27 The decimal value of 27 is: @b11@11 in binary. @033 in octal. @xib in hexadecimal. Program 25 Write a Python Program To Find ASCII value of a character. ASCII value: ASCII, or American Standard Code for Information Interchange, is a character encoding standard that uses numeric values to represent characters. Each ASCII character is assigned a unique 7-bit or 8-bit binary number, allowing computers to exchange information ‘and display text in a consistent way. The ASCII values range from 0 to 127 (for 7-bit ASCII) 0F 0 to 255 (for 8-bit ASCII), with each value corresponding to a specific character, such as letters, digits, punctuation marks, and control characters. In [4]: 1 \char = str(input("Enter the character: ")) 2. print("The ASCII value of '" + char + "' is", ord(char)) Enter the character: P The ASCII value of 'P’ is 80 Program 26 Write a Python Program to Make a Simple Calculator with 4 basic mathematical operations. localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 14905 11126023, 4:53AM In [5]: 25 26 27 28 29 30 31 32 33 34 35, 36 37 38 39 40 a a2 43 45 46 47 48 49 50 51 52 53 54 55 Basic Python Program - Jupyter Notebook # This function adds two numbers def add(x, y): return x + y 4# This function subtracts two numbers def subtract(x, y): return x - y ' # This function multiplies two numbers def multiply(x, y): return x * y # This function divides two numbers def divide(x, y): return x / y print("Select operation.") print("[Link]") print("[Link]") print("[Link]") print("[Link]") while True: # take input from the user choice = input("Enter choice(1/2/3/4): ") # check if choice is one of the four options if choice in (11, '2', 3") '4"): try: num = float(input("Enter first number: num2 = Flosewnune"ereer second inusbens except ValueError: print("Invalid input. Please enter a number. continue if choice ‘1 print (num, add(num1, num2)) elif choice print(num, subtract(num1, num2)) elif choice print (num, , num2, "=", multiply(numi, num2)) elif choice == print (num, > num, divide(num1, num2)) # check if user wants another calculation # break the while Loop if answer is no next_calculation = input("Let's do next calculation? (yes/no): if next_calculation == “no’ break else: print("Invalid Input") localhost: 8888/notebooks/Piush Kumar SharmalBasic Python [Link] 15105 11126023, 4:53AM Basic Python Program - Jupyter Notebook Select operation. [Link] [Link] [Link] [Link] Enter choice(1/2/3/4): 1 Enter first number: 5 Enter second number: 6 5.0 + 6.0 = 11.0 Let's do next calculation? (yes/no): yes Enter choice(1/2/3/4): 2 Enter first number: 5@ Enter second number: 5 50.0 - 5.0 = 45.0 Let's do next calculation? (yes/no): yes Enter choice(1/2/3/4): 3 Enter first number: 22 Enter second number: 2 22.0 * 2.0 = 44.0 Let's do next calculation? (yes/no): yes Enter choice(1/2/3/4): 4 Enter first number: 99 Enter second number: 9 99.0 / 9.0 = 11.0 Let's do next calculation? (yes/no): no Program 27 Write a Python Program to Display Fibonacci Sequence Using Recursion. Fibonacci sequence: The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. In mathematical terms, itis defined by the recurrence relation ( F(n) = F(n-1) + F(n-2) ), with initial conditions ( F(0) = 0 ) and ( F(1) ). The sequence begins: 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on. The Fibonacci sequence has widespread applications in mathematics, computer science, nature, and art. localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 16195 11126023, 4:53 AM Basie Python Program -Jupyter Notebook In [9. # Python program to display the Fibonacci sequence def recur_Fibo(n): if nti: return n else: return(recur_ ibo(n-1) + recur_fibo(n-2)) 9 nterms = int(input("Enter the number of terms (greater than @):°")) 11 # check if the number of terms is valid 12 if nterms < 2B print("Plese enter a positive integer") 14 else: 15 print("Fibonacci sequence 16 for i in range(nterms): v print (recur_fibo(i)) Enter the number of terms (greater than 8): 8 Fibonacci sequence: ° Program 28 Write a Python Program to Find Factorial of Number Using Recursion. The factorial of a non-negative integer ( n ) is the product of all positive integers less than or equal to (n ). Itis denoted by (n! ) and is defined as: nl =nx(n—1)x(n-2)x...X3xX2x1 For example: + S1=5x4x3x2x1= 120 + Otis defined to be 1. Factorials are commonly used in mathematics, especially in combinatorics and probability, to count the number of ways a set of elements can be arranged or selected. localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 17195 11126023, 4:53AM In [11 Basic Python Program - Jupyter Notebook 1 # Factorial of a number using recursion 2 3. def recur_factorial(n): 4 ifn == 1: 5 return n 6 else: 7 return n*recur_factorial(n-1) 8 9 num = int(input("Enter the number: ")) 11 # check if the number is negative 12 if num < @: 23 print("Sorry, factorial does not exist for negative numbers") 14 elif num == 0: 15 print("The factorial of @ is 1") 16 else: v7 print("The factorial of", num, is", recur_factorial(num)) Enter the number: 7 The factorial of 7 is 5040 Program 29 Write a Python Program to calculate your Body Mass Index. Body Mass Index (BMI) is a measure of body fat based on an individual's weight and height. It is commonly used as a screening tool to categorize individuals into different weight status categories, such as underweight, normal weight, overweight, and obesity. The BM1 is calculated using the following formula: pea = Weight) Height (m)* Alternatively, in the imperial system: Weight (1b) Weight (Ib) BM 5 Height (in)? 703 BMI provides a general indication of body fatness but does not directly measure body fat or largest_element: un largest_elenent = element 2 13. return largest_elenent 1a 15 # Example usage: 16 my_array = [10, 20, 30, 99] 17 result = find_largest_element(my_array) 18 print(f"The largest element in the array is: {result}") 19 The largest element in the array is: 99 localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 21195 11126023, 4:53 AM In [19] Basic Python Program - Jupyter Notebook Program 34 Write a Python Program for array rotation. def rotate_array(arr, d): n= len(arr) 1 2 3 4 # Check if 'd’ is valid, it should be within the range of array Ler 5 if d <0 or d >= n: 6 7 8 return "Invalid rotation valu # Create a new array to store the rotated elements. 9 rotated_arr = [0] * n 16 n # Perform the rotation. 2 for i in range(n): 2B rotated_arr[i] = arr[(i + d) % n] 14 15 return rotated_arr 16 17 # Input array 18 arr = [1, 2, 3, 4, 5] 19 26 # Number of positions to rotate 21d=2 2 23 # Call the rotate_array function 24 result = rotate_array(arr, d) 25 26 # Print the rotated array 27 print(“Original array:",. arr) 28 print("Rotated Array:", result) 29 Original Array: [1, 2, 3, 4, 5] Rotated Array: [3, 4, 5, 1, 2] Program 35 Write a Python Program to Split the array and add the first part to the end? localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 22195 11126023, 453 AM Basie Python Program -Jupyter Notebook In [20]: 1 def split_and_add(arr, k): 2 if k <= @ or k >= len(arr): 3 return arr 4 5 # Split the array into two parts 6 first_part = arr[:k] 7 second_part = arr[k:] 8 9 # Add the first part to the end of the second part 16 result = second_part + first_part 1 2 return result 2B 14 # Test the function 15 arr = [1, 2, 3, 4, 5] 16 k= 3 17 result = split_and_add(arr, k) 18 print(“Original Array:", arr) 19 print("Array after splitting and adding:", result) Original Array: [1, 2, 3, 4, 5] Array after splitting and adding: [4, 5, 1, 2, 3] Program 36 Write a Python Program to check if given array is Monotonic. + Amonotonic array is one that is entirely non-increasing or non-decreasing, In [21]: 1 def is_monotonic(arr): 2 increasing = decreasing = True 3 4 for i in range(1, len(arr)): 5 if arr[i] > arr[i - 1]: 6 decreasing = False 7 elif arr[i] < arr[i - 1]: 8 increasing = False 8 16 return increasing or decreasing 1 12 # Test the function 13 /arri.= [1, 2, 2, 3] # Monotonic (non-decreasing) 14 arr2 = [3, 2, 1] __ # Monotonic (non-increasing) 45 arr3 = [1, 3, 2, 4] # Not monotonic 16 17 print("arr1 is monotonic:", is_monotonic(arr1)) 18 print("arr2 is monotonic:", is_monotonic(arr2)) 19 print("arr3 is monotonic:", is_monotonic(arr3)) arr1 is monotonic: True arr2 is monotonic: True arr3 is monotonic: False localhost: 8888/nolebooksiPiush Kumar Sharma/Basic Python [Link] 23195 11126023, 4:53AM In [4]: Basic Python Program - Jupyter Notebook Program 37 Write a Python Program to Add Two Matrices. 1 # Function to add two matrices 2 def add_matrices(mat1, mat2): 3 # Check if the matrices have the same dimensions 4 if len(mat1) != len(mat2) or len(mati[0]) != len(mat2[@]): 5 return "Matrices must have the same dimensions for addition 6 7 # Initialize an empty result matrix with the same dimensions 8 result = [] 9 for i in range(len(mati)): 16 row = [] n for j in range(len(mat1[0])): 2 [Link](mati[i}[j] + mat2[i}[J]) 2B result. append(row) 14 15 return result 16 17 # Input matrices 38 matrixi = [ 19 (1, 2, 31, 20 [4 5, 6], a (7, 8, 9] 2] 23 24 matrix2 = [ 25 (9, 8, 7], 26 [s, 5, 4], 27 (3; 2, 4) 23] 29 30 # Call the add matrices function 31 result_matrix = add_matrices(matrix1, matrix2) 33 # Display the result 34 if isinstance(result_matrix, str): 35 print(result_matrix) 36 else: 37 print("Sum of matrices:") 38 for row in result_matrix: 39 print(row) 40 Sum of matrices: [1e, 10, 10] [2@, 10, 10] [18, 10, 10] Program 38 vie localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] a Python Program to Multiply Two Matrices. 24195 11126023, 4:53AM Basic Python Program - Jupyter Notebook In [2]: 1 # Function to multiply two matrices 2 def multiply _matrices(mati, mat2): 3 # Determine the dimensions of the input matrices 4 rows1 = len(mat1) 5 cols1 = len(mat1[0]) 6 rows2 = len(mat2) 7 cols2 = len(mat2[0]) 8 9 # Check if multiplication is possible 10 if cols1 != rows2: 1 return "Matrix multiplication is not possible. Number of columr 2 2B # Initialize the result matrix with zeros 14 result = [[@ for _ in range(cols2)] for _ in range(rows1)] 15 16 # Perform matrix multiplication Vv for i in range(rows1): 18 for j in range(cols2): 19 for k in range(cols1): 26 result[i][J] += mata[i][k] * mat2[k][3] 21 2 return result 23 24 # Example matrices 25 matrixt = [[1, 2, 3], 26 [4, 5, 6]] 27 28 matrix2 = [[7, 8], 28 [9, 10], 36 (11, 12]] 31 32 # Multiply the matrices 33 result_matrix = multiply _matrices(matrix1, matrix2) 34 35 # Display the result 36 if isinstance(result_matrix, str): 37 print(result_matrix) 38 else: 39 print("Result of matrix multiplication: 40 for row in result_matrix: a print (row) Zz: » Result of matrix multiplication: [58, 64] (239, 154) Program 39 Write a Python Program to Transpose a Matrix. localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 25195 11126023, 4:53 AM In [3 Basic Python Program - Jupyter Notebook 1 # Function to transpose a matrix 2. def transpose_matrix(matrix): 3 rows, cols = len(matrix), len(matrix[@]) 4 # Create an empty matrix to store the transposed data 5 result = [[@ for _ in range(rows)] for _ in range(cols)] 6 7 8 for i in range(rows): for j in range(cols): 9 result[j][i] = matrix[i}(3] 16 1 return result 2 13 # Input matrix a4 matrix = [ a5 (1, 2, 3], 16 [4, 5, 6] vi] 18 19 # Transpose the matrix 26 transposed_matrix = transpose_matrix(matrix) 22 # Print the transposed matrix 23 for row in transposed_matrix: 24 print (row) (1, 4] (2, 5] (3, 6] Program 40 Write a Python Program to Sort Words in Alphabetic Order. localhost: 8888/notebooks/Piush Kumar Sharma/Basic Python [Link] 26195 11726023, 4:53 AM In [4]: In [5 Basic Python Program - Jupyter Notebook # Program to sort alphabetically the words forma string provided by th my_str = input(“Enter a string: ") # breakdown the string into a List of words words = [[Link]() for word in my_str.split()] # sort the List 9 words. sort() 11 # display the sorted words 13 print("The sorted words are: 14 for word in words: 15 print (word) Enter a string: suresh ramesh vibhuti gulgule raji ram shyam ajay The sorted words are: Ajay Gulgule Raji Ram Ramesh Shyam Suresh Vibhuti Program 41 Write a Python Program to Remove Punctuation From a String. # define punctuation punctuations = '''!()-[]{}5 2 PERRO - # To take input from the user my_str = input("Enter a string: ) # remove punctuation from the string 9 no_punct 1@ for char in my_str: Fey if char not in punctuations: 12 o_punct = no_punct + char 14 # display the unpunctuated string 15) print(no_punct) Enter a string: Hello! Hello he said and went » he said ---and went Program 42 localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 27195 11126023, 4:53AM Basie Python Program - Jupyter Notebook Int 1 Inf]: 1 Program 43 Write a Python program to check if the given number is a Disarium Number. A Disarium number is a number that is equal to the sum of its digits each raised to the power of its respective position. For example, 89 is a Disarium number because 8149 =8+81 = 89. In [1]: 15 16 7 18 19 20 21 def is_disarium(number): # Convert the number to a string to iterate over its digits num_str = ste(number) # Calculate the sum of digits raised to their respective positions digit_sum = sum(int(i) ** (index + 1) for index, i in enumerate(nun # Check if the sum is equal to the original number return digit_sum == number # Input a number from the user try: num = int(input("Enter a number: ")) # Check if it's a Disarium number if is_disarium(num): print(#"{num} is a Disarium number.” else: print(#"{num} is not a Disarium number.") except ValueError: print("Invalid input. Please enter a valid number. Enter a number: 89 89 is a Disarium number. Program 44 Write a Python program to print all disarium numbers between 1 to 100. localhost 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 28195 11126023, 4:53AM In [2 In [3 Basic Python Program - Jupyter Notebook def is_disarium(num): num_str = str(num) digit_sum = sum(int(i) ** (index + 1) for index, i in enumerate(nun return num == digit_sum disarium_numbers = [num for num in range(1, 101) if is_disarium(num)] print("Disarium numbers between 1 and 10 for num in disarium_numbers: 1e print(num, end=" | “) oy Disarium numbers between 1 and 100: a/21314isl6l718i9| as] Program 45 Write a Python program to check if the given number is Happy Number. Happy Number: A Happy Number is a positive integer that, when you repeatedly replace the number by the sum of the squares of its digits and continue the process, eventually reaches 1. If the process never reaches 1 but instead loops endlessly in a cycle, the number is not a Happy Number. For example’ 19 is a Happy Number because: P+9 =82 P42 = 68 @ +8 = 100 P+P +051 The process reaches 1, so 19 is a Happy Number. 1 def is_happy_number(num): 2 seen = set() # To store previously seen numbers 3 4 while num != 1 and num not in seen: 5 [Link](num) 6 num = sum(int(i) ** 2 for 4 in str(num)) 7 8 return num == 1 9 1@ # Test the function with a number 11 num = int(input("Enter a number: ")) 12 if is_happy_number(num) : 13 print(#"{num} is a Happy Number”) 14 else: 15 print(#"{num} is not a Happy Number") Enter a number: 23 23 is a Happy Number localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 20195 11126023, 4:53AM Basic Python Program - Jupyter Notebook Program 46 Write a Python program to print all happy numbers between 1 and 100. def is_happy_nunber(num): seen = set() 1 2 3 4 while num != 1 and num not in seen: 5 [Link](num) 6 7 8 num = sum(int(i) ** 2 for 4 in str(num)) return num == 1 9 16 happy_numbers = [] n 12 for num in range(1, 101): 2B if is_happy_number (num) : 14 happy_numbers.. append(num) 15 16 print("Happy Numbers between 1 and 100:") 17 print(happy_numbers) Happy Numbers between 1 and 100: [2, 7, 18, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97, 108) Program 47 Write a Python program to determine whether the aHarshad Number. ‘AHarshad number (or Niven number) is an integer that is divisible by the sum of its digits. In other words, a number is considered a Harshad number if it can be evenly divided by the ‘sum of its own digits. For example: + 18is a Harshad number because 1 + 8 = 9, and 18s divisible by 9 + 42/is not a Harshad number because 4 + 2 = 6, and 42 is not divisible by 6. localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 30195 11126023, 453 AM Basie Python Program -Jupyter Notebook In [5]: 1 def is_harshad_number (num): 2 # Calculate the sum of the digits of the number 3 digit_sum = sum(int(i) for i in ste(num)) 4 5 # Check if the number is divisible by the sum of its digits 6 return num % digit_sum 7 8 # Input a number 9 num = int(input("Enter a number: ")) 16 11 # Check if it's a Harshad Number 12 if is_harshad_number (num): 2B print(#"{num} is a Harshad Number.") 14 else: 15 print(#"{num} is not a Harshad Number.") Enter a number: 18 18 is a Harshad Number. Program 48 writ a Python program to print all pronic numbers between 1 and 100. Apronic number, also known as an oblong number or rectangular number, is a type of figurate number that represents a rectangle. It is the product of two consecutive integers, n ‘and (n +1). Mathematically, a pronic number can be expressed as: P, =n (n+1) For example, the first few pronic numbers are: + Pale(lt=2 + Pp=2#Q41=6 +P =3*G4D=12 + P=48441)=20 In [6]: def is_pronic_number(num): for n in range(1, int(num**0.5) + 1): ifn * (n + 1) == num: return True return False print("Pronic numbers between 1 and 100 ar for i in range(1, 101): if is_pronic_number(i): print(i, end=" | * Pronic numbers between 1 and 160 are: 2/6 | 12 | 2¢ | 3@| 42 | 56 | 72 | 98 | Program 49 localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 31195 11126023, 4:53 AM In [7]: In [8]: In [9]: Basic Python Program - Jupyter Notebook # Sample List of numbers numbers = [10, 20, 30, 40, 50] # Initialize a variable to store the sum sum_of_numbers = 0 # Iterate through the List and accumulate the sum for i in numbers: sum_of_numbers += i # Print the sum print("Sum of elements in the list:", sum_of_numbers) of elements in the list: 150 Program 50 Write a Python program to Multiply all numbers in the list. # Sample List of numbers numbers = [10, 20, 30, 40, 50] # Initialize a variable to store the product product_of_nunbers = 1 # Iterate through the List and accumulate the product for i in numbers: product_of_numbers *= i # Print the product print("Product of elements in the list:", product_of_numbers) Product of elements in the list: 12000000 Program 51 Write a Python program to find smallest number in a list. # Sample List of numbers numbers = [30, 10, -45, 5, 20] # Initialize a variable to store the minimum value, initially set to th minimum = numbers[@] # Iterate through the List and update the minimum value if a smaller nu for i in numbers: if i < minimum: minimum = i # Print the minimum value print("The smallest number in the list is: smallest number in the list is: -45 localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 32195 11126023, 453 AM Basie Python Program -Jupyter Notebook Program 52 Write a Python program to find largest number in a list. In [10] # Sample List of numbers numbers = [3@, 10, -45, 5, 20] 1 2 3 4 # Initialize a variable to store the minimum value, initially set to th 5 minimum = numbers[@] 6 7 8 # Iterate through the List and update the minimum value tf a smaller nu for i in numbers: 9 if i> minimum: 16 minimum = i 12. # Print the minimum value 13 print("The largest number in the list is:", minimum) The largest number in the list is: 30 Program 53 Write a Python program to find second largest number ina list. In [11]: # Sample List of numbers nunbers = [30, 10, 45, 5, 20] # Sort the List in descending order numbers . sort (reverse=True) # Check if there are at Least two elements in the List if len(numbers) >= 2: 9 second_largest = numbers[1] 16 print("The second largest number in the list is:", second_largest) 11 else: 2 print("The list does not contain a second largest nunber.") The second largest number in the list is: 3@ Program 54 Write a Python program to find N largest elements from a list. localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 30195 11726023, 4:53 AM In [12]: The Basic Python Program -Jupyter Notebook def find_n_largest_elenents(1st, n): # Sort the List in descending order sorted_Ist = sorted(Ist, reverse=True) # Get the first N elements largest_elements = sorted_Ist[:n] return largest_elements # Sample List of numbers numbers = [30, 10, 45, 5, 20, 50, 15, 3, 345, 54, 67, 87, 98, 100, 34, # Number of Largest elements to find N= int(input("N =" )) # Find the N Largest elements from the List result = find_n_largest_elements (numbers, N) # Print the N Largest elements print(#"The {N} largest elements in the list are: » result) 3 3 largest elements in the list are: [345, 100, 98] Program 55 Wr In [13] 1 2 3 4 5 6 a 8 a Python program to print even numbers in a Ii # Sample List of numbers numbers = [1, 2, 3, 4,5, 6, 7, 8 9, 10] # Using a List comprehension to filter even numbers even_numbers = [num for num in numbers if num % 2 == @] # Print the even numbers print("Even numbers in the list:", even_numbers) Even numbers in the list: [2, 4, 6, 8, 10] Program 56 Write a Python program to print odd numbers in a List. In [14] odd # Sample List of numbers numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Using a List comprehension to filter even numbers even_numbers = [num for num in numbers if num % 2 != 0] # Print the even numbers print("Odd numbers in the list:", even_numbers) numbers in the list: [1, 3, 5, 7, 9] localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 3495 11126023, 4:53 AM Basic Python Program - Jupyter Notebook Program 57 Write a Python program to Remove empty List from List. In [15] # Sample List containing Lists list_of_lists = [[1, 2, 3], [], [4, 5], [1, [6 7, 8], [1] # Using a List comprehension to remove empty Lists filtered_list = [i for i in list_of_lists if i] # Print the filtered List print("List after removing empty lists: » filtered_list) List after removing empty lists: [[1, 2, 3], [4 5], [6 7) 8]] Program 58 In [16]: In [17]: In [18]: Ia a Python program to Cloning or Copying a # 1, Using Using the Slice Operator original_list = [1, 2, 3, 4, 5] cloned_list = original_list[:] print(cloned_list) 2, 3, 4, 5] # 2. Using the List() constructor original_list = [1, 2, 3, 4, 5] cloned_list = list(original_list) print(cloned_list) 2, 3, 4, 5] # 3. Using List Comprehension original_list = [1, 2, 3, 4, 5] cloned_list = [item for item in original_list] print(cloned_list) 2, 3, 4, 5] Program 59 Write a Python program to Count occurrences of an element in a list. localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 35195 11126023, 4:53AM In [19, In [20]: Basie Python Program - Jupyter Notebook def count_occurrences(1, element): count = [Link](element) return count # Example usage: my_list = [1, 2, 3, 4, 2, 5, 2, 3, 4, 6, 5] element_to_count = 2 occurrences = count_occurrences(my_list, element_to_count) 16 print(f"The element {element_to_count} appears {occurrences} times in t The element 2 appears 3 times in the list. Program 60 a Python program to find words which are greater than given length k. 1 def Find_words(words, k): 2 4 Create an empty List to store words greater than k 3 result = [] 4 5 # Iterate through each word in the List 6 for i in words: 7 # Check if the Length of the i is greater than k 8 if len(i) > k: 8 # If yes, append it to the result List 16 result. append(i) 1 2 return result 2B 14 # Example usage 15 word_list = ["apple", “banana”, “cherry”, “date”, “elderberry we k=5 17 long_words = find_words(word_list, k) 18 19 print(f"Words longer than {k} characters: {long_words}") iragor Words longer than 5 characters: [‘banana', ‘cherry’, ‘elderberry', ‘dragon fruit’] Program 61 Wr a Python program for removing i” character from a string. localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 36195 11126023, 4:53AM In [21 In [22] Basic Python Program - Jupyter Notebook 1 def remove_char(input_str, i): 2 # Check if i is a valid index 3 if 1 <0 or i >= len(input_str): 4 print(#"Invalid index {i}. The string remains unchanged.” 5 return input_str 6 7 # Remove the i-th character using slicing 8 result_str = input_str[:i] + input_str[i + 1:] 9 16 return result_str 1 12 # Input string 13 input_str = "Hello, wiorld!” 14 i= 7 # Index of the character to remove 15 16 # Remove the i-th character 17 new_str = remove_char(input_str, i) 18 19 print(f"Original String: {input_str}") 26 print(f"String after removing {i}th character : {new_str}") Original String: Hello, wWorld! String after removing 7th character : Hello, World! Program 62 a Python program to sp! and join a string. # Split a string into a List. of words input_str = "Python program to split and join a string” word list = input_str.split() # By default, split on whitespace 1 2 3 4 5 # Join the List of words into a string 6 separator = "" # specify the separator between words 7 output_str = separator. join(word_list) 8 9 # Print the results 1@ print("Original String:", input_str) 11 print("List of split Words:", word_list) 12 print("Joined String:", output_str) Original String: Python program to split and join a string List of split Words: ['Python’, ‘program’, ‘to’, ‘split’, ‘and', ‘join', ta’, ‘string’ ] Joined String: Python program to split and join a string Program 63 Write a Python program to check if a given string is binary string or not. localhost: 8888/nolebooksPiush Kumar Sharma/Basic Python [Link] 37195 11126023, 4:53 AM In [23]: 15 16 Basic Python Program - Jupyter Notebook def is_binary_str(input_str): # Iterate through each character in the input string for i in input_str: # Check if the t is not '@' or ‘1° if i not in ‘a1: return False # If any character is not '@' or ‘'1', it's nc return True # If all characters are ‘9’ or '1', it's a binary stri # Input string to check | input_str = "1001110" # Check if the input string is a binary string if is_binary_str(input_str): print(#""{input_str}' is a binary string.") else: print(#"'{input_str}' is not a binary string.") "1901110" is a binary string. Program 64 Write a Python program to find uncommon words from two Strings. In [24]: 1 a 3 4 5 6 7 8 14 15, 16 7 18 19 20 21 22 def uncommon_words(str1, str2): # Split the strings into words and convert them to sets words1 = set([Link]()) words2 = set([Link]()) # Find uncommon words by taking the set difference uncommon_words_set = words1.synmetric_difference(words2) # Convert the set of uncommon words back to a List uncommon_words_list = list(uncommon_words_set) return uncommon_words_list # Input two strings stringl = "This is the first string" string2 = "This is the second string” # Find uncommon words between the two strings uncommon = unconmon_words(stringi, string2) # Print the uncommon words print("Uncommon words:", uncommon) Uncommon words: ['second', ‘first'] Program 65 Write a Python program to find all duplicate characters in string. localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 30195 11726023, 4:53AM In [25]: Basic Python Program - Jupyter Notebook 1 def find_duplicates(input_str): 2 # Create an empty dictionary to store character counts 3 char_count = {} 4 5 # Initialize a List to store duplicate characters 6 duplicates = [] 7 8 # Iterate through each character in the input string 9 for i in input_str: 16 # If the character is already in the dictionary, increment its 1 if i in char_count: 2 char_count[i] 1 2B else: 14 char_count[i] = 1 15 16 # Iterate through the dictionary and add characters with count > 1 v7 for i, count in char_count. items(): 18 if count > 1: 19 duplicates. append(i) 26 21 return duplicates 2 23. # Input a string 24 input_string = “piyush sharma” 25 26 # Find duplicate characters in the string 27 duplicate_chars = find_duplicates (input_string) 28 29 # Print the List of duplicate characters 3@ print("Duplicate characters:", duplicate_chars) Duplicate characters: Program 66 Write a Python Program to check if a string contains any special character. localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 30195 11126023, 4:53 AM In [26]: 15 16 7 18 19 20 21 22 23 Basic Python Program - Jupyter Notebook import re def check_special_char(in_str): # Define a regular expression pattern to match special characters pattern = r'[!@#$%°8*()_+{}\[\]50,-2\\V/\"\-=]" # Use [Link] to find a match in the input string if [Link](pattern, in_str): return True else: return False # Input a string input_string = str(input("Enter a string: *)) # Check if the string contains any special characters contains_special = check_special_char(input_string) # Print the result if contains_special: print("The string contains special characters.") els print("The string does not contain special characters. Enter a string: "Hello, World!" The string contains special characters. Program 67 Write a Python program to Extract Unique dictionary values. In [27 # Sample dictionary my_dict = { # Initialize an enpty set to store unique values uni_val = set() # Iterate through the values of the dictionary for i in my [Link](): # Add each value to the set uni_val add(i) # Convert the set of unique values back to a List (if needed) unique_values_list = list(uni_val) # Print the unique values print("Unique values in the dictionary:", unique_values_list) Unique values in the dictionary: [1@, 20, 30] localhost: 8888/nolebooksPiush Kumar Sharma/Basic Python [Link] 40195 11126023, 4:53 AM Basic Python Program - Jupyter Notebook Program 68 Write a Python program to find the sum of all items in a dictionary. In [28]: 1 2 sum # Sample dictionary my_dict = { ta’: 10, “bt: 20, 4 Initialize a variable to store the sum total_sum = @ # Iterate through the values of the dictionary and add them to the totc for i in my [Link](): total_sum += 4 # Print the sum of all items in the dictionary print("Sum of all items in the dictionary:", total_sum) of all items in the dictionary: 150 Program 69 Write a Python program to Merging two Dictionaries. In [29]: 1 2 3 4 5 6 7 8 9 Merged Dictionary (using update()): {'a': 1, In [30]: a 2 3 4 5 6 7 8 9 18 Merged Dictionary (using dictionary unpacking): {'a": 1, 14} “at # 1. Using the update() method: dicta dict2 [Link](dict2) # The merged dictionary is now in dicta print("Merged Dictionary (using update()):", dict1) bi: 2, # 2, Using dictionary unpacking dict = {'a" 1, ‘b's 2} dict2 = ('c': 3 td's a} # Merge dict2 into dicti using dictionary unpacking merged_dict = {**dicti, **dict2} # The merged dictionary is now in merged dict print("Merged Dictionary (using dictionary unpacking):", merged_dict) localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 41195 11126023, 4:53AM In [34] In [32] Basie Python Program - Jupyter Notebook Program 70 Write a Python program to convert key-values list to flat dictionary. Flat Dictionary: {'a': 1, "b': key_values_list = [(‘a', 1), (‘b', 2), (‘c's 3), (d's 4)] # Initialize an empty dictionary flat_dict = {} # Iterate through the List and add key-value pairs to the dictionary for key, value in key_values_list: flat_dict[key] = value # Print the resulting flat dictionary print("Flat Dictionary:", flat_dict) Program 71 OrderedDict. from collections import OrderedDict # Create an Orderedpict ordered_dict = OrderedDict([('b', 2), ('c', 3), ('d', 4)]) # Item to insert at the beginning new_item = ('a', 1) # Create a new OrderedDict with the new item as the first element new_ordered_dict = OrderedDict([new_item]) # Merge the new OrderedDict with the original Orderedbict new_ordered_dict update(ordered_dict) # Print the updated OrderedDict print("Updated OrderedDict:", new_ordered_dict) Updated OrderedDict: OrderedDict([(‘a', 1), (‘b's 2), (‘c's 3), (‘d's 4)]) Program 72 Write a Python program to check order of character in string using OrderedDict(). localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 42195 11126023, 4:53 AM In [33 The Basic Python Program - Jupyter Notebook from collections import OrderedDict def check_order(string, reference): # Create Orderedbicts for both strings string dict = [Link](string) reference_dict = [Link] (reference) # Check if the Orderedbict for the string matches the Orderedpict 4 return string dict == reference_dict # Input strings input_string = "hello world” reference_string = "helo wrd” # Check if the order of characters in input_string matches reference_st if check_order(input_string, reference_string): print("The order of characters in the input string matches the refe else: print("The order of characters in the input string does not match t order of characters in the input string matches the reference string. Program 73 Write a Python program to sort Python Dictionaries by Key or Value. In [34]: 1 2 3 4 5 6 7 8 9 # Sort by Keys: sample_dict = ‘apple’: 3, ‘banana’: 1, ‘cherry’: 2, ‘date’: 4} sorted_dict_by_keys = dict(sorted(sample_dict.items())) print("Sorted by keys:") for key, value in sorted_dict_by_keys print(#"{key}: {value}") items(): Sorted by keys: apple: 3 banana, 1 cherry: 2 date: 4 localhost 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 43195 11126023, 4:53AM In [35]: Basi Python Program - Jupyter Notebook # Sort by values sample_dict = {‘apple': 3, ‘banana': 1, ‘cherry': 2, ‘date’: 4} a 2 3 4 5 sorted_dict_by values = dict(sorted(sample_dict.items(), key=lambda ite 6 7 print("Sorted by values:") 8 for key, value in sorted dict_by_values.items(): 9 print(#"{key}: {value}") Sorted by values: banana: 1 cherry: 2 apple: 3 date: 4 Program 74 writ a program that calculates and prints the value according to the given formula: Q = Square root of 252 Following are the fixed values of C and H: Cis 50. His 30, Dis the variable whose values should be input to your program in a comma- separated sequence, Example Let us assume the following comma separated input sequence is given to the program: 100,150,180 The output of the program should be: 18,22,24 localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 4495 11126023, 4:59AM In [36, In [37]: Basic Python Program - Jupyter Notebook import math # Fixed values 1 2 3 4 c= 50 5 H= 30 6 Zz 8 # Function to calculate Q def calculate_Q(0): 8 return int([Link]((2 * ¢ * D) / H)) 11 # Input comma-separated sequence of D values 12 Anput_sequence = input("Enter comma-separated values of D: “ 13 Dvalues = input_sequence.split(",") 15 # Calculate and print Q for each D value 16 result = [calculate_Q(int(D)) for D in D_values] 17 print(','.join(map(str, result))) Enter comma-separated values of D: 100,150,186 18,22,24 Program 75 Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The element value in the i-th row and j-th column of the array should be i Note: Nan, XA; J=0,1 5-4. Example ‘Suppose the following inputs are given to the program: 35 Then, the output of the program should be: [[0, 0, 0, 0, 0}, [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]] # Input two digits, x and Y X, Y =map(int, input("Enter two digits (x, Y): " -split(’,")) array = [[@ for j in range(Y)] for i in range(x)] # Fill the array with values i * j 1 2 3 4 # Initialize a 20 array filled with zeros 5 6 7 8 for i in range(x): 8 for j in range(Y) 16 arrayli][i] = i * J 1 12 # Print the 20 array 13. for row in array: 14 print(row) Enter two digits (x, Y): 3,5 [2, ®, 8, 0, 2] [e, 1, 2, 3, 4] [@, 2, 4, 6, 8] localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 45195 11126023, 4:53AM In [38]: Basic Python Program - Jupyter Notebook Program 76 Write a program that accepts a comma separated sequence of words as input and prints the words in a comma-separated sequence after sorting them alphabetically. Suppose the following input is supplied to the program: without hello,bag,world Then, the output should b bag,hello,without, world # Accept input from the user input_sequence = input("Enter a comma-separated sequence of words: 1 2 3 4 # Split the input into a List of words 5 words = input_sequence.split(',') 6 7 8 9 # Sort the words alphabetically sorted words = sorted(words) 1@ # Join the sorted words into a comma-separated sequence 11 sorted_sequence = ','.join(sorted_words) 13. # Print the sorted sequence 14 print("Sorted words:", sorted_sequence) Enter a comma-separated sequence of words: without, hello, bag, world Sorted words: bag, hello, world,without Program 77 program that accepts a sequence of whitespace separated words as input 1g all duplicate words and sorting them writ and prints the words after remo alphanumerically. ‘Suppose the following input is supplied to the program: hello world and practice makes perfect and hello world again Then, the output should be: again and hello makes perfect practice world localhost: 8888/nolebooksPiush Kumar Sharma/Basic Python [Link] 46195 11126023, 4:53AM In [39, In [40] Basie Python Program - Jupyter Notebook # Accept input from the user input_sequence = input("Enter a sequence of whitespace-separated words: 1 2 3 4 # Split the input into words and convert it into a set to remove duplic 5 words = set(input_sequence.split()) 6 7 8 9 4 Sort the unique words alphanumerically sorted_words = sorted(words) 1@ # Join the sorted words into a string with whitespace separation 11 result = ' '.join(sorted_words) 2 13. # Print the result 14 print("Result:", result) Enter a sequence of whitespace-separated words: hello world and practice m akes perfect and hello world again Result: again and hello makes perfect practice world Program 79 Write a program that accepts a sentence and calculate the number of letters and digits. Suppose the following input is supplied to the program: hello world! 123 Then, the output should be: LETTERS 10 DIGITS 3 1 # Accept input from the user 2 sentence = input(“Enter a sentence: ") 3 4 # Initialize counters for Letters and digits 5 letter_count = 0 6 digit_count = 7 8 # Iterate through each character in the sentence 9 for char in sentence: 16 if. [Link]() 1 letter_count += 1 2 elif [Link]() 2B digit_count +> 1 14. 15 |# Print the results 16 print("LETTERS", letter_count) 17 print("DIGITS", digit_count) Enter a sentence: hello world! 123 LETTERS 10 DIGITS 3 localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 47195, 11726723, 4:53AM Basic Python Program - Jupyter Notebook Program 80 Awebsite requires the users to input username and password to register. Write a program to check the validity of password input by users. Following are the criteria for checking the password: 1. At least 1 letter between [2-2] 2. At least 1 number between [0-9] 1. Atleast 1 letter between [A-Z] 3. Atleast 1 character from [S#@] 4. Minimum length of transaction password: 6 5. Maximum length of transaction password: 12 Your program should accept a sequence of comma separated passwords and will check them according to the above criteria. Passwords that match the criteria are to be printed, each separated by a comma. Example If the following passwords are given as input to the program: ABd1234@1,a F1#,2w3E*,2We3345 Then, the output of the program should be: ABd1234@1 localhost: 8888/nolebooksPiush Kumar Sharma/Basic Python [Link] 48195 11126023, 4:53 AM Basic Python Program - Jupyter Notebook In [41]: 1 import re 2 3 # Function to check if a password is valid 4 def is_valid_password(password): 5 # Check the Length of the password 6 if 6 <= len(password) <= 12: 7 # Check if the password matches all the criteria using regular 8 Af [Link](r"*(?=.*[a-z])(?=.*[A-Z]) (?=.*[0-9]) (?=.*[$8@])", & 9 return True 10 return False 1 12 # Accept input from the user as comma-separated passwords 13 passwords = input("Enter passwords separated by commas: ").split(',") 15 # Initialize a List to store valid passwords 16 valid_passwords = [] 18 # Iterate through the passwords and check their validity 19 for psw in passwords: 26 if is_valid_password(psw): 2 valid_passwords . append(psw) 2 23 # Print the valid passwords separated by commas 24 print(’,'.join(valid_passwords) ) Enter passwords separated by commas: ABd1234@1,a Fit, 23E*,2We3345 ABd1234@1 Program 81 Define a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n. In [42]: class DivisibleBySeven: def _init_(self,n): self.n=n def generate_divisible_by_seven(self): for num in range(self.n + 1): if num? 1 2 3 4 5 6 7 2 8 yield num localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 49195 11726728, 4:53. AM Basic Python Program -Jupyter Notebook In [43]: | 1 = int(input("Enter your desired range: ")) 2 3 divisible by_seven_generator = DivisibleBySeven(n).generate_divisible_t 4 5 for num in divisible by seven_generator: 6 print (num) Enter your desired range: 50 e 7 14 2a 28 35 a2 49 Program 82 Write a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically. Suppose the following input is supplied to the program: New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3. Then, the output should be: 22 34 374 New:4 Python:5, Read:1 and:t betwee! choosing:1 or: to:t localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 50195 11726023, 4:53 AM In [44, Basic Python Program - Jupyter Notebook input_sentence = input("Enter a sentence: ") # Split the sentence into words words = input_sentence.split() # Create a dictionary to store word frequencies word_freq = {} 9 # Count word frequencies 1@ for word in words: 1 # Remove punctuation (., ?) from the word 2 word = [Link]('.,?') 2B # Convert the word to Lowercase to ensure case-insensitive counting 14 word = word. lower() 15 # Update the word frequency in the dictionary 16 if word in word_freq: v7 word_freq[word] += 1 18 else: 19 word_freq{word] = 1 26 21 # Sort the words alphanumerically 22 sorted_words = sorted(word_freq.items()) 23 24 # Print the word frequencies 25 for word, frequency in sorted_words: 26 print (#" {word}: {frequency}") Enter a sentence: New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3. 2:2 3 and:1 between:1 choosing:1 new:1 or:2 python: read:1 to: Program 83 Define a class Person and its two child classes: Male and Female. All classes have a method "getGender” which can print "Male" for Male class and “Female” for Female class. localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 51195 11126023, 4:53AM In [45 In [46]: In [47] 1 2 3 4 5 6 7 Basic Python Program - Jupyter Notebook class Person: def getGender(self): return “Unknown” class Male(Person): def getGender(self): return "Male" class Female(Person): def getGender(self): return "Female" person = Person() male = Male() female = Female() print([Link]()) print([Link]()) print([Link]()) Unknown Male Female Program 84 Please write a program to generate all sentences where subject is in ["I", "You"] and verb is in ["Play" 9 18 1 12 13 14 ‘Love"] and the object is in ["Hockey","Football”}. subjects = ["I", "You"] verbs = ["Play", “Love"] objects jockey", “Football"] sentences = [] for sub in subjects: for vrb in verbs: for obj in objects: sentence = f"{sub} {vrb} {obj} sentences .append (sentence) for sentence in sentences: print(sentence) T Play Hockey. I Play Football. T Love Hockey. I Love Football. You You You You Play Hockey. Play Football. Love Hockey. Love Football. localhost: 8888/nolebooks Piush Kumar Sharma/Basic Python [Link] 52195 11126023, 4:53AM In [48] Basic Python Program - Jupyter Notebook Program 85 Please write a program to compress and decompress the string "hello world!hello world!hello worldthello world!" import zlib string = "hello world!hello world!hello world!hello world # Compress the string compressed_string = [Link]([Link]()) # Decompress the string decompressed_string = [Link](compressed_string) .decode() print("Original String:", string) print("Compressed String:", compressed_string) print("Oecompressed String:", decompressed_string) Original String: hello world!hello world!hello world!hello world! Compressed String: b’x\x9c\xcbH\xcd\xc9\xcOW(\xcf/\xcaTQ\xcc \xB2\r\xe@\xd of \xa1\x#5" Decompressed String: hello world!hello world!hello world!hello world! Program 86 Please write a binary search function which searches an item in a sorted list. The function should return the index of element to be searched in the list. localhost 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 53195 11126023, 4:53AM In [49, In [50] In [51] Basic Python Program -Jupyter Notebook 1 def binary_search(arr, target): 2 left, right = @, len(arr) - 1 3 4 while left <= right: 5 mid = (left + right) // 2 6 7 if arr[mid] == target: 8 return mid # Element found, return its index 9 elif arr[mid] < target: 10 left = mid +1 # Target is in the right half 1 else: 2 right = mid - 1 # Target is in the Left half 2B 14 return -1 # Element not found in the List 15 16 # Example usage: 17 sorted_list = [1, 2, 3, 4, 5, 6 7, 8) 9] 18 target_element = 4 19 26 result = binary_search(sorted_list, target_element) 21 22 if result != -1: 23 print(f"Element {target_element} found at index {result}") 24 else: 25 print(f"Element {target_element} not found in the list") Element 4 found at index 3 Program 87 Please write a program using generator to print the numbers which can be divisible by 5 and 7 between 0 and n in comma separated form while n is input by console. Example: If the following n is given as input to the program: 100 Then, the output of the program should be: 0,35,70 def divisible_by_5_and_7(n): for num in range(n + 1): if num % 5 == @ and num % 7 == @: yield num try: n= int(input(“Enter a value for result = divisible_by_S_and_7(n) print(','.join(map(str, result))) except ValueError: print("Invalid input. Please enter a valid integer for n.") Enter a value for n: 100 0,35, 70 localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 54195 11726723, 4:53AM In [52]: In [53] localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] Basic Python Program - Jupyter Notebook Program 88 Please write a program using generator to print the even numbers between 0 and n in comma separated form while n is input by console. Example: If the following n is given as input to the program: 10 Then, the output of the program should be: 8,10 def even_numbers(n): for num in range(n + 1): if num % 2 == @: yield num try: n= int(input("Enter a value for result = even_numbers(n) print(’,'.join(map(str, result))) except ValueError: print("Invalid input. Please enter a valid integer for n.") Enter a value for n: 10 0,2,4,6,8,10 Program 89 The Fibonacci Sequencé ‘computed based on the following formula: #(n)=0 if n=0 f(n)=1 if n=2 #(n)=F(n-1)4#(n-2) if n>. Please write a program using list comprehension to print the Fibonacci Sequence in comma separated form with a given n input by console. Example: If the following n is given as input to the program: 8 Then, the output of the program should be: 0,4,1,2,3,5,8,13 55195 11126023, 4:53 AM In [55 In [56]: In [57]: In [58]: Basic Python Program - Jupyter Notebook 1. def Fibonacci(n): 2 sequence = [0, 1] # Initializing the sequence with the first two F 3 [[Link](sequence[-1] + sequence[-2]) for _ in range(2, n)_ 4 return sequence try: n= int(input("Enter a value for n: ")) result = fibonacci(n) print(’,'.join(map(str, result))) except ValueError: print("Invalid input. Please enter a valid integer for/n. Enter a value for n: 8 0,1,1,2,3,5,8,13 Program 90 Assuming that we have some email addresses in the 'username@[Link] ([Link]" format, please write program to print the user name of a given email address. Both user names and company names are composed of letters only. Example: If the following email address is given as input to the program: ighn@[Link] ([Link] Then, the output of the program should be: John 1 def extract_username(email): 2 # Split the email address at '@’ to separate the username and domai 3 parts = [Link]('@") 4 5 # Check if the email address has the expected format 6 if len(parts) == 2: 7 return parts[@] # The username is the first part 8 else: 9 return "Invalid email format” 1 try: 2 email = input("Enter an email address: ") 3 username = extract_username(email) 4 print (username) 5 except ValueError: 6 print("Invalid input. Please enter a valid email address.") Enter an email address: john@[Link] john localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 56195 11126023, 4:53AM In [59] In [60] Basic Python Program - Jupyter Notebook Program 91 Define a class named Shape and its subclass Square. The Square class has an init function which takes a length as argument. Both classes have an area function which can print the area of the shape where Shape's area is 0 by default. class Shape: def _init_(self): pass # Default constructor, no need to initialize anything al 2 3 4 5 def area(self): 6 return @ # Shape's area is @ by default 7 8 9 class Square(Shape): 16 def _init_(self, length): ary Super()._init_() # Call the constructor of the parent class 2 [Link] = length B 14 def area(self): 35 return [Link] ** 2 # Calculate the area of the square 1 # Create instances of the classes 2 shape = Shape() 3. square = Square(float(input("Enter the shape of the square: "))) 4 5 # Calculate and print the areas 6 print("Shape's area by default:", [Link]()) 7 print("Area of the square:", [Link]()) Enter the shape of the square: 5 Shape's area by default: @ Area of the square: 25.0 Program 92 Write a function that stutters a word as if someone is struggling to read it. The first two letters are repeated twice with an ellipsis ... and space after each, and then the word is pronounced with a question mark ?. Examples stutter("“incredible") + "in. incredible?" stutter(“enthusiastic") + "en... en... enthusiastic?” stutter(“outstanding") ~ “ou... ou... outstanding?" Hint :- Assume all i in lower case and at least two characters long. localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 87195 11126023, 4:53AM In [61] In [62]: In [63] In [64]: Basic Python Program - Jupyter Notebook def stutter(word): if len(word) < 2: return “Word must be at least two characters long.” stuttered_word = f"{word[:2]}... {word[:2]}... {word}?" return stuttered_word # Test cases print(stutter("incredible")) print(stutter("enthusiastic”)) print(stutter("outstanding")) in... in... incredible? en... en... enthusiastic? Ou... Ou... outstanding? Program 93 Create a function that takes an angle in radians and returns the corresponding angle in degrees rounded to one decimal place. Examples radians_to_degrees(1) + 57.3 radians_to_degrees(20) + 1145.9 radians_to_degrees(50) + 2864.8 import math def radians_to_degrees (radians): degrees = radians * (180 / [Link]) return round(degrees, 1) # Test cases print(radians_to_degrees(1)) print(radians_to_degrees(20)) print(radians_to_degrees(5@)) 57.3 1145.9 2864.8 Program 94 In this challenge, establish if a given integer num is a Curzon number. If 1 plus 2 elevated to num is exactly divisible by 1 plus 2 multiplied by num, then num is a Curzon number. \n that returns True if num Given a non-negative integer num, Curzon number, or False otherwise. plement a fun Examples localhost 8888inotebooksPiush Kumar Sharma/Basic Python [Link] 58195 11126023, 4:53AM In [65] In [66] Basic Python Program -Jupytr Notebook is_curzon(5) + True #2** 544533 #2*54.511 # 33 is a multiple of 11 s_curzon(10) ~+ False #2** 10 +1 = 1025 #2*10+4=21 # 1025 is not a multiple of 21 is_curzon(14) — True #2 1441 = 16385 #2144129 # 16385 is a multiple of 29 Curzon Number: Itis defined based on a specific mathematical relationship involving powers of 2. An integer ‘n'is considered a Curzon number if it satisfies the following condition: If (2'n + 1) is divisible by (2n + 1), then 'n'is a Curzon number. For example: on =5:2°5 +1 Curzon number. # In = 10: 20+ Curzon number. 33, and 2°6 + 1 = 11. Since 33 is divisible by 11 (33 % 11 = 0), Sisa = 1025, and 2°10 + 1 = 21. 1025 is not divisible by 21, so 10 is nota Curzon numbers are a specific subset of integers with this unique mathematical property. def is_curzon(num): numerator = 2 ** num + 1 denominator = 2 * num + 1 return numerator % denominator # Test cases print (is_curzon(5)) print(is_curzon(10)) print (is_curzon(14)) True False True localhost 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 50195 11726728, 4:53AM In [67] In [68]: Basic Python Program - Jupyter Notebook Program 95 Given the side length x find the area of a hexagon. Examples area_of_hexagon(1) — 2.6 area_of_hexagon(2) — 10.4 area_of_hexagon(3) + 23.4 import math def area_of_hexagon(x): area = (3 * [Link](3) * x*#2) / 2 return round(area, 1) # Example usage: print(area_of_hexagon(1)) print (area_of_hexagon(2)) print (area_of hexagon(3)) 10.4 23.4 Program 96 Create a function that returns a base-2 (binary) representation of a base-10 (decimal) string number. To convert is simple: ((2) means base-2 and (10) means base-10) 010101001(2) = 1 +8 + 32+ 128, Going from right to left, the value of the most right bit is 1, now from that every bit to the left will be x2 the value, value of an 8 bit binary numbers are (256, 128, 64, 32, 16, 8,4,2,1). Examples, binary(1) + "1 atte binary(5) + "101" #11 +14 =s binary(10) + 1010 #192 4+ 1%8 = 10 localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 60195 11726723, 4:53 AM Basie Python Program -Jupyte Notebook In [69]: 1 def binary(decimal): 2 binary_str = 3 while decimal > 0: 4 remainder = decimal % 2 5 6 7 binary_str = str(remainder) + binary_str decimal = decimal // 2 return binary_str if binary_str else In [70]: 1 print(binary(1)) 2. print(binary(5)) 3 print(binary(1@)) 101 1010 Program 97 Create a function that takes three arguments a, b, c and returns the sum of the numbers that are evenly divided by c from the range a, b inclusive. Examples evenly_divisible(1, 10, 20) + 0 #/No number between 1 and 1@ can be evenly divided by 20. evenly_divisible(1, 10, 2) + 30 #2+4464+8+4 10 = 30 evenly_divisible(1, 10, 3) + 18 #34+64+9- 11 In [71]: 1 def evenly_divisible(a, b, c): 2 total = @ 3 for num in range(a, b + 1): 4 if num %c e: 5 total += num 6 return total In [72] 1 print(evenly_divisible(1, 10, 2@)) 2 print(evenly_divisible(1, 10, 2)) 3 print(evenly_divisible(1, 10, 3)) e 30 18 Program 98 Create a function that returns True if a given inequality expression is correct and False otherwise localhost 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 61195 11126023, 4:53AM In [74] In [75] In [76] In v7) Basic Python Program - Jupyter Notebook Examples correct_signs("3 <7 < 11") + True correct_signs("13 > 44 > 33 < correct_signs("1 <2<6<9>3" 1 def correct_signs (expression): 2 try: 3 return eval (expression) 4 except: 5 return False print(correct_signs("3 < 7 < 11")) print(correct_signs("13 > 44 > 33 < 1")) print(correct_signs("1 < 2 <6 <9 > 3")) True False True Program 99 Create a function that replaces all the vowels in a string with a specified character. Examples replace_vowels("the aardvark”, "#") > "thi ##irdvitrk" replace_vowels("minnie mouse", "2") + "m?nn?? m??s?" replace_vowels("shakespeare”, "*") + "shkspr™" 1 def replace_vowels(string, char): 2 vowels = "AEIQUaeiou" # List of vowels to be replaced 3 for vowel in vowels: 4 5 string = [Link](vowel, char) # Replace each vowel with return string print(replace_vowels("the aardvark print(replace_vowels("minnie mouse”, print(replace_vowels("shakespeare", ‘thi #erdvitrk monn?? m2?s? shitksprr* Program 100 Write a function that calculates the factorial of a number recursively. Examples factorial(5) — 120 localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 62195 11726728, 4:53AM Basic Python Program - Jupyter Notebook factorial(3) + 6 factorial(1) 4 factorial(0) - 4 In [78]: 1 def factorial(n): 2 if n == @: 3 return 1 # Base case: factorial of @ is 1 4 else: 5 return n * factorial(n - 1) # Recursive case: n! =n * (n-1)! In [79]: 1 print(factorial(s)) 2. print(factorial(3)) 3. print(factorial(1)) 4 print(factorial(a)) 120 6 1 1 Program 101 Hami \g distance is the number of characters that 1 lustrate: String1: "abcbba" String2: "abcbda” Hamt vs. \g Distance: 1 the only difference. Create a fun nn that computes the hamming distance between two strings. Examples hamming_distance(“abede", "bcdef") + 5 cde") + 0 rung") + 1 localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 63195 11726023, 4:53 AM In [8@, In [81] In [82]: In [83]? out [a3]: In [84] out[84]: Basie Python Program - Jupyter Notebook 1 def hamming_distance(str1, str2): 2 # Check if the strings have the same Length 3 if len(stri) != len(str2): 4 raise ValueError("Input strings must have the same length") 5 6 # Initialize a counter to keep track of differences 7 distance = @ 8 9 # Iterate through the characters of both strings 1@ for i in range(len(str1)): 1 if stra[i] != str2[i]: 2 distance += 1 # Increment the counter for differences 2B 14 return distance 1 print(hamming_distance("abcde", "bcde 2. print(hamming_distance("abcde", 3. print(hamming_distance("strong", ou Program 102 Create a function that takes a list of non-negative integers and strings and return a new list without the strings. Examples filter_list([1, 2, "a", " 311.2) filter_list([1, "a", "b", 0, 15]) — [1, 0, 15] filter r_list({1, 2, "asf", "4", "423", 123]) > [1, 2, 123] def filter_list(Ist): # Initialize an empty List to store non-string elements result = [] 1 2 3 4 5 # Iterate through the elements in the input List 6 for element in 1st: 7 # Check if the element ts a non-negative integer (not a string) 8 if isinstance(element, int) and element >= 9 [Link](element) 6 1 return result 1 filter_list([1, 2, "a", "b"]) (1, 2] 1 filter_list([1, "a", "b", @, 15]) [1, @, 15] localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 64195 112623, 4:53AM In [85] out[s5]: In [86] In [87] out (87): In [88] out [88] In [89]: out [89]: Basic Python Program - Jupyter Notebook 1 filter_list([1, 2, "asf", "1", "123", 123]) [, 2, 123] Program 103 The "Reverser" takes a string as input and returns that string in reverse order, with the opposite case. Examples reverse("Hello World") -* "DLROw OLLEh” reverse("ReVeRSE") + “eSrEvEr" reverse("Radar") + "RADAr™ def reverse(input_str): a 2 # Reverse the string and swap the case of characters 3 reversed_str = input_str[::-1].swapcase() 4 5 return reversed_str 1 reverse("Hello world") *DLROw OLLEh* 1 reverse("ReVeRSE") "eSrEver' 1 reverse("Radan") "RADAR" Program 104 You can assign variables from lists like this: Ist = [1, 2, 3, 4, 5, 6] first = Ist{0) middle = Ist[1: last = Ist[-1] print(first) + outputs 1 print(middle) + outputs [2, 3, 4, 5] print(last) + outputs 6 localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 65195 11128023, 4:53 AM Basic Python Program -Jupytr Notebook With Python 3, you can assign variables from lists in a much more succinct way. Create variables first, middle and last from the given list using destructuring assignment (check the Resources tab for some examples), where: first 4 middle + [2, 3, 4, 5] last +6 t writeyourcodehere into three variables, being In [90] writeyourcodehere = [1, 2, 3, 4, 5, 6] # Unpack the List into variables first, *middle, last = writeyourcodehere In [91]: 1 first out(91]: 4 In [92]: 1 middle out(92]: [2, 3, 4, 5] In [93]: 1 last out[93]: 6 Program 105 Write a function that calculates the factorial of a number recursively. Examples factorial(5) > 120 factorial(3) + 6 factorial(1) +1 factorial(0) + 1 In [94]: 1. def factorial(n): 2 ifn == @: 3 return 1 # Base case: factorial of @ is 1 4 else: 5 return n * factorial(n - 1) # Recursive case: n! = n * (n-1)! In [95]: 1 factorial(5) out[95]: 120 localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 65195 11126023, 4:53AM In [96]: out [96]: In [97] out[97]: In [98] out [98: In [99]: In [100] out [100]: In [101]: out[101] > In [102] out[102]: Basie Python Program -Jupyter Notebook 1 factorial(3) 1 factorial(1) 1 1 factorial(@) Program 106 Write a function that moves all elements of one type to the end of the list. Examples move_to_end({1, 3, 2, 4, 4, 1], 1) + [3, 2,4, 4,1, 4] Move all the 1s to the end of the array. move_to_end({7, 8, 9, 1, 2, 3, 4], 9) + [7, 8, 1,2, 3, 4, 9] move_to_end([" "a") > ["b", "a", "a", "a"] 1 def move_to_end(1st, element): 2 # Initialize a count for the specified element 3 count = Ist. count (element) 4 5 # Remove all occurrences of the element from the List 6 Ast = [x for x in Ist if x != element] 7 8 # Append. the element to the end of the List count times 8 Ist .extend([element] * count) 16 uu return Ist 1 move-to_end({1, 3, 2, 4 4, 1], 1) 13, 2,4) 42, 3] 1 move_to_end([7, 8, 9, 1, 2, 3, 4], 9) (7, 8, 1, 2, 3, 4, 9] 1 move_to_end(["a", a", "b"], a") ['b', ‘a', ‘a’, ‘a"] Program 107 Question1 localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 6795 11726023, 4:53 AM In [103] In [104] out[104): In [105] out [105]: In [106] out[106): In [107]: In [108] out[108} Basic Python Program -Jupyter Notebook Create a function that takes a string and returns a string in which each character is repeated once. Examples double_char("String") — ” double_char("Hello World!") — "HHeelilloo WWoorrlldd!!” double char("1234! ") + "112233441!" def double_char(input_str): doubled_str = 1 2 3 4 for char in input_str: s doubled_str += char * 2 6 7 return doubled_str 1 double_char("string") "ssttrriinngg* 1 double_char("Hello World!") "HHeelllloo WWoorrlidd!!* 1 double_char("1234!_ ") *aaz2azaai!_ Program 108 Create a function that reverses a boolean value and returns the string "boolean expected" if another variable type is given. Examples reverse(True) + False reverse(False) + True reverse(0) "boolean expected” reverse(None) ~ "boolean expected” 1 def reverse(value): 2 if isinstance(value, bool): 3 return not value 4 else: 5 return “boolean expected” 1 reverse(True) False localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 68195 19726723, 4:53 AM In [109]: out[109): In [110] out[116) In [111] out (111 In [112] In [113]: out[113): In [114] out {114}: In [115] out[115]? Basic Python Program - Jupyter Notebook 1 reverse(False) True 1 reverse(@) "boolean expected" 1 reverse(None) "boolean expected’ Program 109 Create a function that returns the thickness (in meters) of a piece of paper after folding it n number of times. The paper starts off with a thickness of 0.5mm. Examples num_layers(1) + "0.001m™ - Paper folded once is 1mm (equal to 0.001m) num_layers(4) 008m" - Paper folded 4 times is 8mm (equal to 0.008m) num_layers(21) + "1048.576m" - Paper folded 21 times is 1048576mm (equal to 1048.576m) 1 def num_layers(n): 2 initial_thickness_mm = @.5 # Initial thickness in millimeters 3 final_thickness_mm = initial_thickness_nm * (2 ** n) 4 final_thickness_m = final_thickness_mm / 1060 # Convert millimeter 5 return "{Final_thickness_m:.3f}m" num_layers(1) *@.001m' 1 num_layers(4) *@.008m' 1 num_layers(21) *1048.576m" Program 110 Create a function that takes a single string as argument and returns an ordered list containing the indices of all capital letters in the string. localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 60195 11726023, 4:53 AM In [116] In [127]: Out [117]: In [118] out[118): In [119] out [119]: In [120]: out[128): In [121] out[121]: In [123]: Basie Python Program -Jupyter Notebook Examples index_of_caps("eDaBiT") ~ [1, 3, 5] index_of_caps("eQuINoX") = [1, 3, 4, 6] index_of_caps("determine") = (1 index_of_caps("STRIKE") — [0, 1, 2, 3, 4, 5] index_of_caps("sUn") [1] def index_of_caps(word): # Use List comprehension to find indices of capital Letters return [i for i, char in enumerate(word) if [Link]()] 1 index_of_caps("eDaBiT") [1,3 5] 1 index_of_caps("eQuINox") [3,4 6] 1 index_of_caps("“determine") o 1 index_of_caps("STRIKE") [2 1, 2, 3, 4, 5] 1 index_of_caps(""sun") f) Program 111 Using list comprehensions, create a function that finds all even numbers from 1 to the given number. Examples. find_even_nums(8) — [2, 4, 6, 8] find_even_nums(4) = [2, 4] find_even_nums(2) — [2] 1. def find_even_nums (num): 2 # Use a List comprehension to generate even numbers from 1 to num 3 return [x for x in range(1, num + 1) if x % 2 == 0] localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 70195 11726023, 4:53 AM In [124] out [124]: In [125] out[125]: In [126] out [126]: In [127] In [128]: out (128): In [129] out[129): In [130]: out [138]: In [131]: out[131}+ Basic Python Program -Jupytr Notebook 1. find_even_nums(8) [2, 4, 6, 8] 1 find_even_nums (4) (2, 4] 1. find_even_nums(2) {21 Program 112 Create a function that takes a list of strings and integers, and filters out the list so that it returns a list of integers only. Examples filter list({1, 2, 3,"a", "b*, 4]) + [1, 2, 3, 4] filter_list(["A", 0, "Edabit", 1729, “Python”, 1729]) — [0, 1729] filter_list({"Nothing” D-0 def filter_list(Ist): 2 # Use a List comprehension to filter out integers 3 return [x for x in Ist if isinstance(x, int)] 1 filter_list([1, 2, 3, "a", » 41) f1, 2, 3, 4] 1 filter list({"A", @, “Edabit", 1729, "Python", 1729}) [8, 1729, 1729] 1 filter_list(["A", @, "Edabit", 1729, "Python", 1729]) [@, 1729, 1729] 1 filter_list(["Nothing o here" ]) Program 113 Given a list of numbers, create a function which returns the list but with each element's index in the list added to itself. This means you add 0 to the number at index 0, add 1 to the number at index 1, etc... Examples localhost 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 71195 11726023, 4:53 AM In [132]: In [133] out[133]: In [134]: out (134): In [135] out[135): In [136]: In [137]? out [137]: In [138] out[138]: Basie Python Program - Jupyter Notebook add_indexes({0, 0, 0, 0, 0}) + [0, 1, 2, 3, 4] add_indexes([1, 2, 3, 4, 5]) — [1, 3, 5,7, 9] add_indexes({5, 4, 3, 2, 11) +15, 5, 5, 5, 5] 1 def add_indexes(1st): 2 # Use List comprehension to add index to each element 3 return [i + val for i, val in enumerate(1st)] 1 add_indexes([@, @, 8, @, @]) [, 1, 2, 3, 4] add_indexes([1, 2, 3, 4, 5]) 13,5, 7, 91 1 add_indexes([5, 4, 3, 2, 1]) IS; 5, 5) 5, 5] Program 114 Create a function that takes the height and radius of a cone as arguments and returns. the volume of the cone rounded to the nearest hundredth. See the resources tab for the formula. Examples cone_volume(3, 2) + 12.57 cone_volume(15, 6) ~ 565.49 cone_volume(18, 0) + 0 1 import math 2 3. def cone_volume(height, radius): 4 if radius == @: 5 return 0 6 volume = (1/3) * [Link] * (radius**2) * height 7 return round(volume, 2) 1 cone_volume(3, 2) 12.57 1 cone_volume(1s, 6) 565.49 localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 72195 112623, 4:53AM In [139] out [139]: In [140]: In [141]: out [141]: In [142] out[142] In [143]: out [143]: Basic Python Program - Jupyter Notebook 1 cone_volume(18, @) ° Program 115 This Triangular Number Sequence is generated from a pattern of dots that form a triangle. The first 5 numbers of the sequence, or dots, ai 1,3, 6, 10, 15 This means that the first triangle has just one dot, the second one has three dots, the third one has 6 dots and so on. Write a function that gives the number of dots wi of the sequence. its corresponding triangle number Examples triangle(1) 1 triangle(6) + 24 triangle(215) + 23220 1 def triangle(n): 2 ifn 65700 get_budgets({ {'name’: ‘John’, ‘ag { ‘name’: ‘Steve’, ‘age’: 32, ‘budget’: 32000 }, { ‘name’: ‘Martin’, ‘age': 16, ‘budget’: 1600 } y) + 62600 localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 75195 11126023, 4:53 AM In [153]: In [154] out[154]: In [155]: out[155)]: In [156] In [157] out (157): In [158]: out [158]: Basie Python Program - Jupyter Notebook def get_budgets(Ist): total_budget = sum(person["budget'] for person in 1st) return total_budget 1 2 3 4 5 # Test cases 6 budgets = [ 7 8 9 e {'name': ‘John’, ‘age’: 21, ‘budget’: 23000}, {'name’: ‘Steve’, ‘age’: 32, ‘budget’: 40000}, {‘name': ‘Martin’, ‘age': 16, ‘budget’: 2760} 1e ] 1 12 budgets2 = [ 2B {‘name': ‘John’, ‘age’: 21, ‘budget’: 29000}, 14 {'name': ‘Steve’, ‘age’: 32, ‘budget’: 32000}, 15 {‘name': ‘Martin’, ‘age’: 16, ‘budget’: 1600} 16 ] 1 get_budgets (budgets1) 65700 1 get_budgets (budgets2) 62600 Program 119 Create a function that takes a string and returns a string with its letters in alphabetical order. Examples alphabs t_soup(“hello”) + “ehilo” alphabet_soup(“edabit") — “abdei alphabet_soup("hacker") + "acehkr” alphabet_soup("geek") + "eeg alphabet_soup("javascript") + "aacijprstv" 1 def alphabet_soup(txt): 2 return '”.join(sorted(txt)) 1 alphabet_soup("hello") *eh1lo* 1 alphabet_soup("edabit") ‘abdeit’ localhost 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 76195 11126023, 4:53AM In [159] out [159]: In [160] out[160} In [161] out (161): In [162]: In [163] out [163]: In [164]: out (164): Basic Python Program -Jupyter Notebook 1 alphabet_soup("hacker") tacehkr’ 1 alphabet_soup("geek") "eegk" 1 alphabet_soup("javascript") *aacijprstv’ Program 120 Suppose that you invest $10,000 for 10 years at an interest rate of 6% compounded monthly. What will be the value of your investment at the end of the 10 year period? Create a function that accepts the principal p, the term in years t, the interest rate r, and the number of compounding periods per year n. The function returns the value at the end of term rounded to the nearest cent. For the example: compound_interest(10000, 10, 0.06, 12) + 18193.97 Note that the interest rate is given as a decimal and n=12 because with monthly ‘compounding there are 12 periods per year. Compounding can also be done annually, quarterly, weekly, or daily. Examples compound_interest(100, 1, 0.05, 1) + 105.0 compound_interest(3500, 15, 0.1, 4) + 15399.26 compound_interest(100000, 20, 0.15, 365) + 2007316.26 1 def compound_interest(p, t, r, n): 2 # Calculate the compound interest using the formula 3 asp*(1+(r/n)) * (n* t) 4 # Round the result to the nearest cent 5 return round(a, 2) 1 compound_interest (10008, 16, 0.06, 12) 18193.97 1 compound_interest(100, 1, @.05, 1) 105.0 localhost: 8888/nolebooks/Piush Kumar Sharma/Basic Python [Link] 77195

You might also like