140 PYTHON Programs For Practic
140 PYTHON Programs For Practic
Basic
Python
Programs
This resource can assist
you in preparing for your
interview
Program 1
Hello Python
Program 2
In [2]: 1 # Addition
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(f"sum: {num1} + {num2} = {sum_result}")
In [3]: 1 # Division
num3 = float(input("Enter the dividend for division: "))
3 num4 = float(input("Enter the divisor for division: "))
4 if num4 == 0:
5print("Error: Division by zero is not allowed.")
6 else:
7div_result = num3 / num4
8print(f"Division: {num3} / {num4} = {div_result}")
Program 3
1/95
Program 4
Program 5
Random number: 89
Program 6
Program 7
2/95
In [8]: 1 celsius = float(input("Enter temperature in Celsius: "))
Program 8
Program 9
2+ + =0
where
≠0
The solutions of this quadratic equation is given by:
(− ± ( 2 − 4 )1/2)/(2 )
3/95
In [10]: 1 import math
# Input coefficients
a = float(input("Enter coefficient a: "))
5 b = float(input("Enter coefficient b: "))
6 c = float(input("Enter coefficient c: "))
7
8 # Calculate the discriminant
9 discriminant = b**2 - 4*a*c
Enter coefficient a: 1
Enter coefficient b: 4
Enter coefficient c: 8
Root 1: -2.0 + 2.0i
Root 2: -2.0 - 2.0i
Program 10
In [11]: 1 a = 5
b = 10
3
4 # Swapping without a temporary variable
5 a, b = b, a
6
7
8 print("After swapping:")
9 print("a =", a)
print("b =", b)
After swapping:
a = 10
b = 5
4/95
Program 11
Program 12
if num%2 == 0:
print("This is a even number")
5 else:
6print("This is a odd number")
Enter a number: 3
This is a odd number
Program 13
# if not divided by both 400 (century year) and 4 (not century year)
# year is not leap year
else:
print("{0} is not a leap year".format(year))
5/95
Program 14
Prime Numbers:
A prime 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.
Enter a number: 27
27, is not a prime number
Program 15 ¶
6/95
In [20]: 1 # Python program to display all the prime numbers within an interval
lower = 1
4 upper = 10
5
6 print("Prime numbers between", lower, "and", upper, "are:")
7
8 for num in range(lower, upper + 1):
9# all prime numbers are greater than 1
if num > 1:
for i in range(2, num):
12 if (num % i) == 0:
13 break
else:
15 print(num)
Program 16
Enter a number: 4
The factorial of 4 is 24
Program 17
7/95
In [22]: 1 num = int(input("Display multiplication table of: "))
Program 18
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:
8/95
In [23]: 1 nterms = int(input("How many terms? "))
Program 19
Armstrong Number:
It is 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.
9/95
, we get , which is also
If we calculate 4 + 4 +4 +4 6561 + 256 + 2401 + 256
equal to .
Program 20
10/95
In [26]: 1 # Input the interval from the user
lower = int(input("Enter the lower limit of the interval: "))
3 upper = int(input("Enter the upper limit of the interval: "))
4 5
6 for num in
range(lower, upper + 1): # Iterate through
the numbers i
order = len(str(num)) # Find the number of digits in 'num'
8temp_num = num
9sum = 0
Program 21
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:
= 1,2,3,4,5,6,7,8,...
In [27]: 1 limit = int(input("Enter the limit: "))
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:
|⋅|
LCM( , )= GCD( , )
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.
Program 23
HCF, or Highest Common Factor, is the largest positive integer that divides two or
more numbers without leaving a remainder.
Formula:
12/95
For two numbers a and b, the HCF can be found using the formula:
HCF( , )=GCD( , )
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.
# define a function
def compute_hcf(x, y):
5
6 # choose the smaller number
7if x > y:
8smaller = y
else:
smaller = x
for i in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
13 hcf = i
return hcf
Program 24
Write a Python Program to Convert Decimal to Binary, Octal and Hexadecimal. How
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:
Binary:
Reading the remainders from bottom to top, the binary representation of 27 is 11011.
Octal:
13/95
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.
Hexadecimal:
So, in summary:
Program 25
ASCII value:
Program 26
14/95
In [5]: 1 # This function adds two numbers
def add(x, y):
return x + y
4
5 # This function subtracts two numbers
6 def subtract(x, y):
7return x - y
8
9 # This function multiplies two numbers
def multiply(x, y):
return x * y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:
# take input from the user
choice = input("Enter choice(1/2/3/4): ")
if choice == '1':
38 print(num1, "+", num2, "=", add(num1, num2))
15/95
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
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: 50
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
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, it is defined by
the recurrence relation ( F(n) = F(n-1) + F(n-2) ), with initial conditions ( F(0) = 0 ) and (
F(1) = 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.
16/95
In [9]: 1 # Python program to display the Fibonacci sequence
def recur_fibo(n):
4if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
8
9 nterms = int(input("Enter the number of terms (greater than 0): "))
Program 28
The factorial of a non-negative integer ( n ) is the product of all positive integers less than
or equal to ( n ). It is denoted by ( n! ) and is defined as:
!= ×( −1)×( −2)×…×3×2×1
For example:
is defined to be 1.
17/95
In [11]: 1 # Factorial of a number using recursion
def recur_factorial(n):
4if n == 1:
return n
else:
return n*recur_factorial(n-1)
8
9 num = int(input("Enter the number: "))
Program 29
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.
Weight (kg)
BMI = Height (m)2
Alternatively, in the imperial system:
Weight (lb)
BMI = Height (in)2 × 703
BMI provides a general indication of body fatness but does not directly measure body fat or
distribution. It is widely used in public health and clinical settings as a quick and simple tool
to assess potential health risks associated with weight. Different BMI ranges are
associated with different health categories, but it's important to note that BMI has
limitations and does not account for factors such as muscle mass or distribution of fat.
18/95
In [12]: 1 def bodymassindex(height, weight):
return round((weight / height**2),2)
3
4
5 h = float(input("Enter your height in meters: "))
6 w = float(input("Enter your weight in kg: "))
7 8
bmi = bodymassindex(h, w)
print("Your BMI is: ", bmi)
Program 30
The natural logarithm, often denoted as , is a mathematical function that represents the
logarithm to the base , where is the mathematical constant approximately equal to
. In other words, for a positive number , the natural logarithm of is the exponent
that satisfies the equation .
ln( )
It is commonly used in various branches of mathematics, especially in calculus and
mathematical analysis, as well as in fields such as physics, economics, and engineering.
The natural logarithm has properties that make it particularly useful in situations
involving exponential growth or decay.
19/95
In [13]: 1 import math
Program 31
if n <= 0:
print("Please enter a positive integer.")
else:
result = cube_sum_of_natural_numbers(n)
print(f"The cube sum of the first {n} natural numbers is: {result}"
Program 32
In Python, an array is a data structure used to store a collection of elements, each identified by
an index or a key. Unlike some other programming languages, Python does not have a built-in
array type. Instead, the most commonly used array-like data structure is the list.
A list in Python is a dynamic array, meaning it can change in size during runtime.
Elements in a list can be of different data types, and you can perform various operations
such as adding, removing, or modifying elements. Lists are defined using square brackets
[] and can be indexed and sliced to access specific elements or sublists.
my_list = [1, 2, 3, 4, 5]
20/95
This list can be accessed and manipulated using various built-in functions and methods
in Python.
In [15]: 1 # Finding Sum of Array Using sum()
arr = [1,2,3]
3
4 ans = sum(arr)
5
6 print('Sum of the array is ', ans)
8return total
9
# Example usage:
array = [1, 2, 3]
result = sum_of_array(array)
print("Sum of the array:", result)
Program 33
return largest_element
# Example usage:
my_array = [10, 20, 30, 99]
result = find_largest_element(my_array)
print(f"The largest element in the array is: {result}")
21/95
Program 34
return rotated_arr
# Input array
arr = [1, 2, 3, 4, 5]
Program 35
Write a Python Program to Split the array and add the first part to the end?
22/95
In [20]: 1 def split_and_add(arr, k):
if k <= 0 or k >= len(arr):
return arr
4
5# Split the array into two parts
6first_part = arr[:k]
7second_part = arr[k:]
8
9# Add the first part to the end of the second part
result = second_part + first_part
return result
Program 36
23/95
Program 37
return result
# Input matrices
matrix1 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
matrix2 = [
[9, 8, 7],
[6, 5, 4],
[3, 2, 1]
]
Sum of matrices:
[10, 10, 10]
[10, 10, 10]
[10, 10, 10]
Program 38
24/95
In [2]: 1 # Function to multiply two matrices
def multiply_matrices(mat1, mat2):
# Determine the dimensions of the input matrices
4rows1 = len(mat1)
5cols1 = len(mat1[0])
6rows2 = len(mat2)
7cols2 = len(mat2[0])
8
9# Check if multiplication is possible
if cols1 != rows2:
return "Matrix multiplication is not possible. Number of column
return result
# Example matrices
matrix1 = [[1, 2, 3],
26 [4, 5, 6]]
Program 39
25/95
In [3]: 1 # Function to transpose a matrix
def transpose_matrix(matrix):
rows, cols = len(matrix), len(matrix[0])
# Create an empty matrix to store the transposed data
result = [[0 for _ in range(rows)] for _ in range(cols)]
6
7for i in range(rows):
8for j in range(cols):
9 result[j][i] = matrix[i][j]
return result
# Input matrix
matrix = [
[1, 2, 3],
[4, 5, 6]
]
[1, 4]
[2, 5]
[3, 6]
Program 40
26/95
In [4]: 1 # Program to sort alphabetically the words form a string provided by th
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
Program 42
27/95
In [ ]: 1
In [ ]: 1
Program 43
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
1 2 .
=8+81=89
In [1]: 1 def is_disarium(number):
# Convert the number to a string to iterate over its digits
3num_str = str(number)
4
5# Calculate the sum of digits raised to their respective positions
6 digit_sum = sum(int(i) ** (index + 1) for index, i in enumerate(num 7
Enter a number: 89
89 is a Disarium number.
Program 44
28/95
In [2]: 1 def is_disarium(num):
num_str = str(num)
digit_sum = sum(int(i) ** (index + 1) for index, i in enumerate(num
4return num == digit_sum
5
6 disarium_numbers = [num for num in range(1, 101) if is_disarium(num)]
7
8 print("Disarium numbers between 1 and 100:")
9 for num in disarium_numbers:
print(num, end=" | ")
Program 45
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:
2 + 2
82
2 + 2
68
2 + 2
100
2+ 2+ 2=1
The process reaches 1, so 19 is a Happy Number.
Enter a number: 23
23 is a Happy Number
29/95
Program 46
Write a Python program to print all happy numbers between 1 and 100.
Program 47
A Harshad 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:
30/95
In [5]: 1 def is_harshad_number(num):
# Calculate the sum of the digits of the number
3digit_sum = sum(int(i) for i in str(num))
4
5# Check if the number is divisible by the sum of its digits
6return num % digit_sum == 0
7
8 # Input a number
9 num = int(input("Enter a number: "))
Enter a number: 18
18 is a Harshad Number.
Program 48
Write a Python program to print all pronic numbers between 1 and 100.
∗( +1)
For example, the first few pronic numbers are:
1∗(1+1)=2
2∗(2+1)=6
3∗(3+1)=12
4∗(4+1)=20
Program 49
31/95
Write a Python program to find sum of elements in list
In [7]: 1 # Sample list of numbers
numbers = [10, 20, 30, 40, 50]
3
4 # Initialize a variable to store the sum
5 sum_of_numbers = 0
6
7 # Iterate through the list and accumulate the sum
8 for i in numbers:
9sum_of_numbers += i
Program 50
Program 51
32/95
Program 52
Program 53
Program 54
33/95
In [12]: 1 def find_n_largest_elements(lst, n):
# Sort the list in descending order
sorted_lst = sorted(lst, reverse=True)
4
5# Get the first N elements
6largest_elements = sorted_lst[:n]
7
8return largest_elements
9
# Sample list of numbers
numbers = [30, 10, 45, 5, 20, 50, 15, 3, 345, 54, 67, 87, 98, 100, 34,
N = 3
The 3 largest elements in the list are: [345, 100, 98]
Program 55
Program 56
34/95
Program 57
List after removing empty lists: [[1, 2, 3], [4, 5], [6, 7, 8]]
Program 58
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
Program 59
35/95
In [19]: 1 def count_occurrences(l, element):
count = l.count(element)
3return count
4
5 # Example usage:
6 my_list = [1, 2, 3, 4, 2, 5, 2, 3, 4, 6, 5]
7 element_to_count = 2
8
9 occurrences = count_occurrences(my_list, element_to_count)
print(f"The element {element_to_count} appears {occurrences} times in
Program 60
Write a Python program to find words which are greater than given length k.
return result
# Example usage
word_list = ["apple", "banana", "cherry", "date", "elderberry", "dragon
k = 5
long_words = find_words(word_list, k)
Program 61
36/95
In [21]: 1 def remove_char(input_str, i):
# Check if i is a valid index
if i < 0 or i >= len(input_str):
print(f"Invalid index {i}. The string remains unchanged.")
5return input_str
6
7# Remove the i-th character using slicing
8 result_str = input_str[:i] + input_str[i + 1:] 9
return result_str
# Input string
input_str = "Hello, wWorld!"
i = 7 # Index of the character to remove
Program 62
Program 63
37/95
In [23]: 1 def is_binary_str(input_str):
# Iterate through each character in the input string
3for i in input_str:
4# Check if the i is not '0' or '1'
5if i not in '01':
6 return False # If any character is not '0' or '1', it's no
return True # If all characters are '0' or '1', it's a binary stri
8
9 # Input string to check
input_str = "1001110"
Program 64
return uncommon_words_list
Program 65
38/95
In [25]: 1 def find_duplicates(input_str):
# Create an empty dictionary to store character counts
3char_count = {}
4
5# Initialize a list to store duplicate characters
6duplicates = []
7
8# Iterate through each character in the input string
9for i in input_str:
# If the character is already in the dictionary, increment its
if i in char_count:
12 char_count[i] += 1
else:
14 char_count[i] = 1
15
# Iterate through the dictionary and add characters with count > 1
for i, count in char_count.items():
if count > 1:
19 duplicates.append(i)
20
return duplicates
# Input a string
input_string = "piyush sharma"
Program 66
39/95
In [26]: 1 import re
def check_special_char(in_str):
# Define a regular expression pattern to match special characters
5 pattern = r'[!@#$%^&*()_+{}\[\]:;<>,.?~\\\/\'"\-=]' 6
# Input a string
input_string = str(input("Enter a string: "))
Program 67
40/95
Program 68
# Iterate through the values of the dictionary and add them to the tota
for i in my_dict.values():
total_sum += i
Program 69
41/95
Program 70
In [31]: 1 key_values_list = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
Program 71
# Create an OrderedDict
ordered_dict = OrderedDict([('b', 2), ('c', 3), ('d', 4)])
5
6 # Item to insert at the beginning
7 new_item = ('a', 1)
8
9 # Create a new OrderedDict with the new item as the first element
new_ordered_dict = OrderedDict([new_item])
Updated OrderedDict: OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
Program 72
42/95
In [33]: 1 from collections import OrderedDict
# Input strings
input_string = "hello world"
reference_string = "helo wrd"
The order of characters in the input string matches the reference string.
Program 73
Sorted by keys:
apple: 3
banana: 1
cherry: 2
date: 4
43/95
In [35]: 1 # Sort by values
Sorted by values:
banana: 1
cherry: 2
apple: 3
date: 4
Program 74
Write a program that calculates and prints the value according to the given formula:
2
= Square root of
Following are the fixed values of C and H:
C is 50. H is 30.
Example
100,150,180
18,22,24
44/95
In [36]: 1 import math
# Fixed values
4 C=50
5 H=30
6
7 # Function to calculate Q
8 def calculate_Q(D):
9return int(math.sqrt((2 * C * D) / H))
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*j.
Example
3,5
45/95
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.
without,hello,bag,world
bag,hello,without,world
Program 77
Write a program that accepts a sequence of whitespace separated words as
input and prints the words after removing all duplicate words and sorting them
alphanumerically.
hello world and practice makes perfect and hello world again
46/95
In [39]: 1 # Accept input from the user
input_sequence = input("Enter a sequence of whitespace-separated words:
3
4 # Split the input into words and convert it into a set to remove duplic
5 words = set(input_sequence.split())
6
7 # Sort the unique words alphanumerically
8 sorted_words = sorted(words)
9
# Join the sorted words into a string with whitespace separation
result = ' '.join(sorted_words)
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:
LETTERS 10
DIGITS 3
47/95
Program 80
A website 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:
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
ABd1234@1,a F1#,2w3E*,2We3345
ABd1234@1
48/95
In [41]: 1 import re
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.
49/95
In [43]: 1 n = int(input("Enter your desired range: "))
divisible_by_seven_generator = DivisibleBySeven(n).generate_divisible_b
4
5 for num in divisible_by_seven_generator:
6print(num)
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:
2:2
3.:1
3?:1
New:1
Python:5
Read:1
and:1
between:1
choosing:1
or:2
to:1
50/95
In [44]: 1 input_sentence = input("Enter a sentence: ")
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.
51/95
In [45]: 1 class Person:
def getGender(self):
3return "Unknown"
4
5 class Male(Person):
6def getGender(self):
7return "Male"
8
9 class Female(Person):
def getGender(self):
return "Female"
Unknown
Male
Female
Program 84
Please write a program to generate all sentences where subject is in ["I", "You"]
and verb is in ["Play", "Love"] and the object is in ["Hockey","Football"].
I Play Hockey.
I Play Football.
I Love Hockey.
I Love Football.
You Play Hockey.
You Play Football.
You Love Hockey.
You Love Football.
52/95
Program 85
Please write a program to compress and decompress the 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.
53/95
In [49]: 1 def binary_search(arr, target):
left, right = 0, len(arr) - 1
3
4while left <= right:
5mid = (left + right) // 2
6
7if arr[mid] == target:
8 return mid # Element found, return its index
elif arr[mid] < target:
10 left = mid + 1 # Target is in the right half
else:
12 right = mid - 1 # Target is in the left half
# Example usage:
sorted_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
target_element = 4
if result != -1:
print(f"Element {target_element} found at index {result}")
else:
print(f"Element {target_element} not found in the list")
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:
100
0,35,70
In [51]: 1 try:
n = int(input("Enter a value for n: "))
3result = divisible_by_5_and_7(n)
4print(','.join(map(str, result)))
5 except ValueError:
6print("Invalid input. Please enter a valid integer for n.")
54/95
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:
10
0,2,4,6,8,10
In [53]: 1 try:
n = int(input("Enter a value for n: "))
3result = even_numbers(n)
4print(','.join(map(str, result)))
5 except ValueError:
6print("Invalid input. Please enter a valid integer for n.")
Program 89
The Fibonacci Sequence is computed based on the following formula:
f(n)=0 if n=0
f(n)=1 if n=1
f(n)=f(n-1)+f(n-2) if n>1
Please write a program using list comprehension to print the Fibonacci Sequence
in comma separated form with a given n input by console.
Example:
0,1,1,2,3,5,8,13
55/95
In [55]: 1 def fibonacci(n):
sequence = [0, 1] # Initializing the sequence with the first two F
3[sequence.append(sequence[-1] + sequence[-2]) for _ in range(2, n)]
4return sequence
In [56]: 1 try:
n = int(input("Enter a value for n: "))
3result = fibonacci(n)
4print(','.join(map(str, result)))
5 except ValueError:
6print("Invalid input. Please enter a valid integer for n.")
Program 90
Assuming that we have some email addresses in the
"username@companyname.com (mailto:username@companyname.com)"
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:
john@google.com (mailto:john@google.com)
john
In [58]: 1 try:
email = input("Enter an email address: ")
3username = extract_username(email)
print(username)
5 except ValueError:
6print("Invalid input. Please enter a valid email address.")
56/95
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.
9 class Square(Shape):
def __init__(self, length):
super().__init__() # Call the constructor of the parent class
self.length = length
def area(self):
return self.length ** 2 # Calculate the area of the square
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
Hint :- Assume all input is in lower case and at least two characters long.
57/95
In [61]: 1 def stutter(word):
if len(word) < 2:
return "Word must be at least two characters long."
4
5stuttered_word = f"{word[:2]}... {word[:2]}... {word}?"
6return stuttered_word
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
def radians_to_degrees(radians):
degrees = radians * (180 / math.pi)
5return round(degrees, 1)
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.
Given a non-negative integer num, implement a function that returns True if num is
a Curzon number, or False otherwise.
Examples
58/95
is_curzon(5) ➞ True
2**5+1=33
2*5+1=11
33 is a multiple of 11
is_curzon(10) ➞ False
2**10+1=1025
2*10+1=21
is_curzon(14) ➞ True
2**14+1=16385
2*14+1=29
16385 is a multiple of 29
Curzon Number:
For example:
Curzon numbers are a specific subset of integers with this unique mathematical property.
True
False
True
59/95
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
def area_of_hexagon(x):
area = (3 * math.sqrt(3) * x**2) / 2
5return round(area, 1)
2.6
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"
#1*1=1
binary(5) ➞ "101"
#1*1+1*4=5
binary(10) ➞ 1010
#1*2+1*8=10
60/95
In [69]: 1 def binary(decimal):
binary_str = ""
while decimal > 0:
remainder = decimal % 2
binary_str = str(remainder) + binary_str
6decimal = decimal // 2
7return binary_str if binary_str else "0"
In [70]: 1 print(binary(1))
print(binary(5))
3 print(binary(10))
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, 2) ➞ 30
#2+4+6+8+10=30
evenly_divisible(1, 10, 3) ➞ 18
#3+6+9=18
0
30
18
Program 98
Create a function that returns True if a given inequality expression is correct
and False otherwise.
61/95
Examples
True
False
True
Program 99
Create a function that replaces all the vowels in a string with a specified character.
Examples
th# ##rdv#rk
m?nn?? m??s?
sh*k*sp**r*
Program 100
Write a function that calculates the factorial of a number recursively.
Examples
factorial(5) ➞ 120
62/95
factorial(3) ➞ 6
factorial(1) ➞ 1
factorial(0) ➞ 1
In [79]: 1 print(factorial(5))
print(factorial(3))
3 print(factorial(1))
4 print(factorial(0))
120
6
1
1
Program 101
Hamming distance is the number of characters that differ between two strings.
To illustrate:
String1: "abcbba"
String2: "abcbda"
Create a function that computes the hamming distance between two strings.
Examples
hamming_distance("abcde", "bcdef") ➞ 5
hamming_distance("abcde", "abcde") ➞ 0
hamming_distance("strong", "strung") ➞ 1
63/95
In [80]: 1 def hamming_distance(str1, str2):
# Check if the strings have the same length
3if len(str1) != len(str2):
4 raise ValueError("Input strings must have the same length") 5
return distance
5
0
1
Program 102
Create a function that takes a list of non-negative integers and strings and return
a new list without the strings.
Examples
Out[83]: [1, 2]
64/95
In [85]: 1 filter_list([1, 2, "aasf", "1", "123", 123])
Program 103
The "Reverser" takes a string as input and returns that string in reverse order,
with the opposite case.
Examples
reverse("ReVeRsE") ➞ "eSrEvEr"
reverse("Radar") ➞ "RADAr"
5return reversed_str
In [88]: 1 reverse("ReVeRsE")
Out[88]: 'eSrEvEr'
In [89]: 1 reverse("Radar")
Out[89]: 'RADAr'
Program 104
You can assign variables from lists like this:
lst = [1, 2, 3, 4, 5, 6]
first = lst[0]
middle = lst[1:-1]
last = lst[-1]
print(first) ➞ outputs 1
print(last) ➞ outputs 6
65/95
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 ➞ 1
middle ➞ [2, 3, 4, 5]
last ➞ 6
Your task is to unpack the list writeyourcodehere into three variables, being
fi t iddl d l
t ith iddl
bi thi i
bt th fi t
d
In [90]: 1 writeyourcodehere = [1, 2, 3, 4, 5, 6]
In [91]: 1 first
Out[91]: 1
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 [95]: 1 factorial(5)
Out[95]: 120
66/95
In [96]: 1 factorial(3)
Out[96]: 6
In [97]: 1 factorial(1)
Out[97]: 1
In [98]: 1 factorial(0)
Out[98]: 1
Program 106
Write a function that moves all elements of one type to the end of the list.
Examples
Out[100]: [3, 2, 4, 4, 1, 1]
Out[101]: [7, 8, 1, 2, 3, 4, 9]
Program 107
Question1
67/95
Create a function that takes a string and returns a string in which each character
is repeated once.
Examples
double_char("String") ➞ "SSttrriinngg"
In [104]: 1 double_char("String")
Out[104]: 'SSttrriinngg'
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
In [108]: 1 reverse(True)
Out[108]: False
68/95
In [109]: 1 reverse(False)
Out[109]: True
In [110]: 1 reverse(0)
In [111]: 1 reverse(None)
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"
num_layers(4) ➞ "0.008m"
num_layers(21) ➞ "1048.576m"
In [113]: 1 num_layers(1)
Out[113]: '0.001m'
In [114]: 1 num_layers(4)
Out[114]: '0.008m'
In [115]: 1 num_layers(21)
Out[115]: '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.
69/95
Examples
index_of_caps("eDaBiT") ➞ [1, 3, 5]
index_of_caps("eQuINoX") ➞ [1, 3, 4, 6]
index_of_caps("determine") ➞ []
index_of_caps("STRIKE") ➞ [0, 1, 2, 3, 4, 5]
index_of_caps("sUn") ➞ [1]
In [117]: 1 index_of_caps("eDaBiT")
Out[117]: [1, 3, 5]
In [118]: 1 index_of_caps("eQuINoX")
Out[118]: [1, 3, 4, 6]
In [119]: 1 index_of_caps("determine")
Out[119]: []
In [120]: 1 index_of_caps("STRIKE")
Out[120]: [0, 1, 2, 3, 4, 5]
In [121]: 1 index_of_caps("sUn")
Out[121]: [1]
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]
70/95
In [124]: 1 find_even_nums(8)
Out[124]: [2, 4, 6, 8]
In [125]: 1 find_even_nums(4)
Out[125]: [2, 4]
In [126]: 1 find_even_nums(2)
Out[126]: [2]
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(["Nothing", "here"]) ➞ []
Out[128]: [1, 2, 3, 4]
Out[131]: []
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
71/95
add_indexes([0, 0, 0, 0, 0]) ➞ [0, 1, 2, 3, 4]
Out[133]: [0, 1, 2, 3, 4]
Out[134]: [1, 3, 5, 7, 9]
Out[135]: [5, 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
In [137]: 1 cone_volume(3, 2)
Out[137]: 12.57
In [138]: 1 cone_volume(15, 6)
Out[138]: 565.49
72/95
In [139]: 1 cone_volume(18, 0)
Out[139]: 0
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, are:
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 with its corresponding triangle
number of the sequence.
Examples
triangle(1) ➞ 1
triangle(6) ➞ 21
triangle(215) ➞ 23220
In [141]: 1 triangle(1)
Out[141]: 1
In [142]: 1 triangle(6)
Out[142]: 21
In [143]: 1 triangle(215)
Out[143]: 23220
73/95
Program 116
Create a function that takes a list of numbers between 1 and 10 (excluding
one number) and returns the missing number.
Examples
missing_num([1, 2, 3, 4, 6, 7, 8, 9, 10]) ➞ 5
missing_num([7, 2, 3, 6, 5, 9, 1, 4, 8]) ➞ 10
missing_num([10, 5, 1, 2, 4, 6, 8, 3, 9]) ➞ 7
Out[145]: 5
Out[146]: 10
Out[147]: 7
Program 117
Write a function that takes a list and a number as arguments. Add the number to
the end of the list, then remove the first element of the list. The function should
then return the updated list.
Examples
74/95
In [148]: 1 def next_in_line(lst, num):
if lst:
lst.pop(0) # Remove the first element
lst.append(num) # Add the number to the end
return lst
else:
7 return "No list has been selected"
Out[149]: [6, 7, 8, 9, 1]
In [152]: 1 next_in_line([], 6)
Program 118
Create the function that takes a list of dictionaries and returns the sum of people's
budgets.
Examples
get_budgets([
]) ➞ 65700
get_budgets([
]) ➞ 62600
75/95
In [153]: 1 def get_budgets(lst):
total_budget = sum(person['budget'] for person in lst)
3return total_budget
4
5 # Test cases
6 budgets1 = [
7{'name': 'John', 'age': 21, 'budget': 23000},
8{'name': 'Steve', 'age': 32, 'budget': 40000},
9{'name': 'Martin', 'age': 16, 'budget': 2700}
]
budgets2 = [
{'name': 'John', 'age': 21, 'budget': 29000},
{'name': 'Steve', 'age': 32, 'budget': 32000},
{'name': 'Martin', 'age': 16, 'budget': 1600}
]
In [154]: 1 get_budgets(budgets1)
Out[154]: 65700
In [155]: 1 get_budgets(budgets2)
Out[155]: 62600
Program 119
Create a function that takes a string and returns a string with its letters
in alphabetical order.
Examples
alphabet_soup("hello") ➞ "ehllo"
alphabet_soup("edabit") ➞ "abdeit"
alphabet_soup("hacker") ➞ "acehkr"
alphabet_soup("geek") ➞ "eegk"
alphabet_soup("javascript") ➞ "aacijprstv"
In [157]: 1 alphabet_soup("hello")
Out[157]: 'ehllo'
In [158]: 1 alphabet_soup("edabit")
Out[158]: 'abdeit'
76/95
In [159]: 1 alphabet_soup("hacker")
Out[159]: 'acehkr'
In [160]: 1 alphabet_soup("geek")
Out[160]: 'eegk'
n [161]: 1 alphabet_soup("javascript")
Out[161]: '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.
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
Out[163]: 18193.97
Out[164]: 105.0
77/95
In [165]: 1 compound_interest(3500, 15, 0.1, 4)
Out[165]: 15399.26
Out[166]: 2007316.26
Program 121
Write a function that takes a list of elements and returns only the integers.
Examples
Out[171]: [1]
Program 122
Create a function that takes three parameters where:
Return an ordered list with numbers in the range that are divisible by the
third parameter n.
78/95
Return an empty list if there are no numbers that are divisible by n.
Examples
list_operation(7, 9, 2) ➞ [8]
list_operation(15, 20, 7) ➞ []
Out[173]: [3, 6, 9]
In [174]: 1 list_operation(7, 9, 2)
Out[174]: [8]
Out[175]: []
Program 123
Create a function that takes in two lists and returns True if the second list follows the
first list by one element, and False otherwise. In other words, determine if the
second list is the first list shifted to the right by 1.
Examples
Notes:
Both input lists will be of the same length, and will have a minimum length of 2.
The values of the 0-indexed element in the second list and the n-1th indexed
element in the first list do not matter.
79/95
In [177]: 1 simon_says([1, 2], [5, 1])
Out[177]: True
Out[178]: False
Out[179]: True
Out[180]: False
Program 124
A group of friends have decided to start a secret society. The name will be the first
letter of each of their names, sorted in alphabetical order. Create a function that
takes in a list of names and returns the name of the secret society.
Examples
Out[182]: 'AMS'
Out[183]: 'CHLN'
Out[184]: 'CJMPRR'
Program 125
An isogram is a word that has no duplicate letters. Create a function that takes a string
and returns either True or False depending on whether or not it's an "isogram".
Examples
80/95
is_isogram("Algorism") ➞ True
is_isogram("PasSword") ➞ False
is_isogram("Consecutive") ➞ False
Notes
In [186]: 1 is_isogram("Algorism")
Out[186]: True
In [187]: 1 is_isogram("PasSword")
Out[187]: False
In [188]: 1 is_isogram("Consecutive")
Out[188]: False
Program 126
Create a function that takes a string and returns True or False, depending on
whether the characters are in order or not.
Examples
is_in_order("abc") ➞ True
is_in_order("edabit") ➞ False
is_in_order("123") ➞ True
is_in_order("xyzz") ➞ True
81/95
Notes
In [190]: 1 is_in_order("abc")
Out[190]: True
In [191]: 1 is_in_order("edabit")
Out[191]: False
In [192]: 1 is_in_order("123")
Out[192]: True
In [193]: 1 is_in_order("xyzz")
Out[193]: True
Program 127
Create a function that takes a number as an argument and returns True or False
depending on whether the number is symmetrical or not. A number is
symmetrical when it is the same as its reverse.
Examples
is_symmetrical(7227) ➞ True
is_symmetrical(12567) ➞ False
is_symmetrical(44444444) ➞ True
is_symmetrical(9939) ➞ False
is_symmetrical(1112111) ➞ True
In [195]: 1 is_symmetrical(7227)
Out[195]: True
82/95
In [196]: 1 is_symmetrical(12567)
Out[196]: False
In [197]: 1 is_symmetrical(44444444)
Out[197]: True
In [199]: 1 is_symmetrical(44444444)
Out[199]: True
In [200]: 1 is_symmetrical(1112111)
Out[200]: True
Program 128
Given a string of numbers separated by a comma and space, return the product
of the numbers.
Examples
multiply_nums("2, 3") ➞ 6
multiply_nums("1, 2, 3, 4") ➞ 24
return result
Out[202]: 6
Out[203]: 24
83/95
In [204]: 1 multiply_nums("54, 75, 453, 0")
Out[204]: 0
Out[205]: -20
Program 129
Create a function that squares every digit of a number.
Examples
square_digits(9119) ➞ 811181
square_digits(2483) ➞ 416649
square_digits(3212) ➞ 9414
Notes
In [207]: 1 square_digits(9119)
Out[207]: 811181
In [208]: 1 square_digits(2483)
Out[208]: 416649
In [209]: 1 square_digits(3212)
Out[209]: 9414
84/95
Program 130
Create a function that sorts a list and removes all duplicate items from it.
Examples
unique_set = set(sorted(lst))
4
5# Convert the set back to a list and return it
6return list(unique_set)
Out[211]: [1, 3, 5]
Out[212]: [4]
Out[214]: [1, 2, 3]
85/95
Program 131
Create a function that returns the mean of all digits.
Examples
mean(42) ➞ 3
mean(12345) ➞ 3
mean(666) ➞ 6
Notes
The mean of all digits is the sum of digits / how many digits there are (e.g.
mean of digits in 512 is (5+1+2)/3(number of digits) = 8/3=2). The mean will
always be an integer.
return int(digit_mean)
In [216]: 1 mean(42)
Out[216]: 3
In [217]: 1 mean(12345)
Out[217]: 3
In [218]: 1 mean(666)
Out[218]: 6
Program 132
Create a function that takes an integer and returns a list from 1 to the given
number, where:
Examples
86/95
amplify(4) ➞ [1, 2, 3, 40]
amplify(3) ➞ [1, 2, 3]
amplify(25) ➞ [1, 2, 3, 40, 5, 6, 7, 80, 9, 10, 11, 120, 13, 14, 15, 160, 17, 18, 19, 200,
Notes
In [220]: 1 amplify(4)
In [221]: 1 amplify(3)
Out[221]: [1, 2, 3]
In [222]: 1 amplify(25)
Out[222]: [1,
2,
3,
40,
5,
6,
7,
80,
9,
10,
11,
120,
13,
14,
15,
160,
17,
18,
19,
200,
21,
22,
23,
240,
25]
Program 133
Create a function that takes a list of numbers and return the number that's unique.
87/95
Examples
unique([3, 3, 3, 7, 3, 3]) ➞ 7
unique([0, 1, 1, 1, 1, 1, 1, 1]) ➞ 0
Notes
Test cases will always have exactly one unique number while all others are the same.
Out[224]: 7
Out[225]: 0.77
Out[226]: 0
Program 134
Your task is to create a Circle constructor that creates a circle with a radius
provided by an argument. The circles constructed must have two getters getArea()
(PIr^2) and getPerimeter() (2PI*r) which give both respective areas and perimeter
(circumference).
For help with this class, I have provided you with a Rectangle constructor which you
can use as a base example.
Examples
circy = Circle(11)
circy.getArea()
88/95
Should return 380.132711084365
circy = Circle(4.44)
circy.getPerimeter()
Notes
class Circle:
def __init__(self, radius):
5self.radius = radius
6
7def getArea(self):
8# Calculate and return the area of the circle
9return round(math.pi * self.radius**2)
10
def getPerimeter(self):
# Calculate and return the perimeter (circumference) of the cir
return round(2 * math.pi * self.radius)
380
69
62
28
Program 135
Create a function that takes a list of strings and return a list, sorted from shortest
to longest.
Examples
Notes
89/95
All test cases contain lists with strings of different lengths, so you won't have to deal
ih li l i f h l h
In [230]: 1 def sort_by_length(lst):
2
3 return sorted(lst, key=len) # Using sorted() function with a cu
Program 136
Create a function that validates whether three given integers form a Pythagorean
triplet. The sum of the squares of the two smallest integers must equal the square
of the largest number to be validated.
Examples
is_triplet(3, 4, 5) ➞ True
3²+4²=25
5²=25
5² + 12² = 169
13² = 169
is_triplet(1, 2, 3) ➞ False
1²+2²=5
3²=9
Notes
In [235]: 1 is_triplet(3, 4, 5)
Out[235]: True
90/95
In [236]: 1 is_triplet(13, 5, 12)
Out[236]: True
In [237]: 1 is_triplet(1, 2, 3)
Out[237]: False
Program 137
Create a function that takes three integer arguments (a, b, c) and returns the
amount of integers which are of equal value.
Examples
equal(3, 4, 3) ➞ 2
equal(1, 1, 1) ➞ 3
equal(3, 4, 1) ➞ 0
Notes
In [239]: 1 equal(3, 4, 3)
Out[239]: 2
In [240]: 1 equal(1, 1, 1)
Out[240]: 3
In [241]: 1 equal(3, 4, 1)
Out[241]: 0
Program 138
Write a function that converts a dictionary into a list of keys-values tuples.
Examples
dict_to_list({
"D": 1,
91/95
"B": 2
"C": 3
dict_to_list({
"likes": 2,
"dislikes": 3,
"followers": 10
Notes
8return result
In [243]: 1 dict_to_list({
"D": 1,
3"B": 2,
"C": 3
5 })
In [244]: dict_to_list({
2
3 "likes": 2,
4
5 "dislikes": 3,
6
7 "followers": 10
8
9 })
Program 139
Write a function that creates a dictionary with each (key, value) pair being the
(lower case, upper case) versions of a letter, respectively.
Examples
92/95
mapping(["a", "b", "c"]) ➞ { "a": "A", "b": "B", "c": "C" }
mapping(["a", "v", "y", "z"]) ➞ { "a": "A", "v": "V", "y": "Y", "z": "Z" }
Notes
Program 140
Write a function, that replaces all vowels in a string with a specified vowel.
Examples
Notes
93/95
In [250]: 1 vow_replace("apples and bananas", "u")
Program 141
Create a function that takes a string as input and capitalizes a letter if its ASCII
code is even and returns its lower case version if its ASCII code is odd.
Examples
BeauTiFuL moRNiNg."
94/95
95/95