Python 100 problems and solutions for Data science learner
Naresh Maddela
Data science & ML ll Top Data Science Voice ll 1M+ impressions on LinkedIn || Top 1% on @TopMate
i am Naresh maddela #Datascience learner
I’m excited to share that I’ve put together a comprehensive collection of 100 problems and solutions
focused on for and while loops in Python. Whether you're just starting your coding journey or looking to sharpen your skills, these problems are designed to help you practice and master looping constructs
For Loop Problems
While Loop Problems
In?[?]:
1. Print numbers from 1 to 10.
In?[5]:
for i in range (1,11):
print(i)
1
2
3
4
5
6
7
8
9
10
2.Print the first 10 multiples of 5.
In?[6]:
for i in range (1,11):
print(i*5)
5
10
15
20
25
30
35
40
45
50
3.Print the elements of a list.
In?[18]:
my_list = [1,2,3,4,5, "data science"]
for elements in my_list:
print(elements)
1
2
3
4
5
data science
In?[17]:
hello = ["python", "is","good","for","Data science"]
for i in hello:
print(i)
python
is
good
for
Data science
4.Print the elements of a list in reverse order.
In?[21]:
hello = ["python", "is","good","for","Data science"]
for i in reversed(hello):
print(i)
Data science
for
good
is
python
5.Calculate the sum of all numbers in a list.
In?[31]:
my_list = [1,4,5,8,9]
hello = 0
for i in my_list:
hello += i
print(hello)
27
In?[33]:
my_list = [1,4,5,8,9]
total = sum(my_list)
print(total)
27
6.Calculate the average of all numbers in a list.
In?[40]:
my_list = [1,4,5,8,9]
hello = 0
for i in my_list:
hello += i
average = hello/ len(my_list)
print(average)
5.4
In?[41]:
my_list = [1,4,5,8,9]
total = sum(my_list)/len(my_list)
print(total)
5.4
7.Print all even numbers from 1 to 20.
In?[46]:
for i in range (1,21):
if i % 2 == 0:
print(i)
2
4
6
8
10
12
14
16
18
20
8.Print all odd numbers from 1 to 20.
In?[47]:
for i in range (1,21):
if i % 2 == 1:
print(i)
1
3
5
7
9
11
13
15
17
19
9.Print all prime numbers between 1 and 50.
In?[12]:
def is_prime(n):
if n<=1:
return False
for i in range(2,int(n**0.5)+1):
if n % i == 0 :
return False
return True
for i in range(1,51):
if is_prime(i):
print(i)
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
In?[14]:
def prime(n):
if n<=1:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True
for i in range(1,51):
if prime(i):
print(i)
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
In?[5]:
def prime(n):
if n<=1:
return False
for i in range(2,int(n**0.5)+1):
if n % i == 0:
return False
return True
for i in range(1,25):
if prime(i):
print(i)
2
3
5
7
11
13
17
19
23
10.Print the factorial of a number.
In?[18]:
n = 5
factr = 1
for i in range(1,n+1):
factr *=i
print(factr)
120
In?[24]:
n = 10
factorial = 1
for i in range(1,n+1):
factorial *=i
print("factorial :",factorial)
factorial : 3628800
In?[13]:
n = 150
factorial = 1
for i in range(1,n+1):
factorial *=i
print("fatcorial is",factorial)
fatcorial is 57133839564458545904789328652610540031895535786011264182548375833179829124845398393126574488675311145377107878746854204162666250198684504466355949195922066574942592095735778929325357290444962472405416790722118445437122269675520000000000000000000000000000000000000
11.Print the Fibonacci sequence up to the 10th term.
In?[4]:
a,b = 0,1
for _ in range(10):
print(a)
a,b = b,a+b
0
1
1
2
3
5
8
13
21
34
In?[6]:
a,b = 0,1
for _ in range(20):
print(a)
a,b = b,a+b
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
12.Count the number of vowels in a string.
In?[14]:
string = "hello world"
vowels = "aeiou"
count = 0
for char in (string):
if char in vowels:
count += 1
print(count)
3
In?[17]:
string = "data scientist"
vowels = "aeiou"
count = 0
for char in string:
if char in vowels:
count +=1
print("vowels are",count)
vowels are 5
13.Count the number of words in a string.
In?[19]:
string = "i want to be a data scientist"
count = string.split()
print(len(count))
7
In?[22]:
string = " data scientist is a tough job as per records"
count = string.split()
print("total words in string is", len(count))
total words in string is 9
14.Reverse a string.
In?[33]:
#type 1
string = "i want be a data scientist"
reverse = string[::-1]
print(reverse)
tsitneics atad a eb tnaw i
In?[32]:
#type 2
string = "i want be a data scientist"
reverse = ""
for char in string:
reverse = char + reverse
print(reverse)
tsitneics atad a eb tnaw i
15.Print the squares of numbers from 1 to 10
In?[34]:
for i in range(1,11):
print(i**2)
1
4
9
16
25
36
49
64
81
100
16.Print the cube of numbers from 1 to 10.
In?[35]:
for i in range(1,11):
print(i**3)
1
8
27
64
125
216
343
512
729
1000
17.Find the maximum element in a list
In?[1]:
#type 1
list = [1.5,55,8855,595,5522,5,45,15,25,15]
high = max(list)
print(high)
8855
In?[10]:
#type 2
list = [1.5,55,8855,595,5522,5,45,15,25,15]
high =list[0]
for elem in list:
if elem > high:
high = elem
print(high)
8855
In?[13]:
#type 3
list = [1.5,55,8855,595,5522,5,45,15,25,15]
hello = [0]
high =hello[0]
for elem in list:
if elem > high:
high = elem
print(high)
8855
18.Find the minimum element in a list.
In?[14]:
#type 1
list = [1.5,55,8855,595,5522,5,45,15,25,15]
minimum = min(list)
print(minimum)
1.5
In?[16]:
#type 2
list = [1.5,55,8855,595,5522,5,45,15,25,15]
minimum = list[0]
for elem in list:
if elem < minimum:
minimum = elem
print(minimum)
1.5
In?[25]:
#type 3
list = [1.5,55,8855,595,5522,5,45,15,25,15]
hello = [2]
minimum = hello[0]
for elem in list:
if elem < minimum:
minimum = elem
print(minimum)
1.5
19.Find the second largest element in a list.
In?[2]:
#type 1
my_list = [1.5,55,8855,595,5522,5,45,15,25,15]
second = list(set(my_list))
second.sort()
second_largest =second[-2]
print(second_largest)
5522
In?[8]:
#type 2
list = [1.5,55,8855,595,5522,5,45,15,25,15]
first,second = float('-inf'),float('-inf')
for elem in list:
if elem > first:
second = first
first = elem
elif elem > second and elem != first:
second = elem
print(second)
5522
In?[13]:
#type 2
list = [1.5,55,8855,595,6000,5522,5,45,15,25,15]
first, second = float('-inf'), float('-inf')
for elem in list:
if elem > first:
second = first
first = elem
elif elem > second and elem != first:
second = elem
print(second)
6000
20.Find the second smallest element in a list.
In?[2]:
#type 1
list = [1.5,55,8855,595,5522,5,45,15,25,15]
first, second = float('inf'), float('inf')
for elem in list:
if elem < first:
second = first
first = elem
elif elem < second and elem != first:
second = elem
print(second)
5
In?[1]:
#type 2
my_list = [1.5,55,8855,595,5522,5,45,15,25,15]
second = list(set(my_list))
second.sort()
second_smallest =second[1]
print(second_smallest)
5
21.Remove duplicates from a list.
In?[3]:
#type 1
my_list = [1,1,1,1,2,2,2,2,255,5,588,8,8,55,522,25,5]
second = list(set(my_list))
second.sort()
print(second)
[1, 2, 5, 8, 25, 55, 255, 522, 588]
In?[4]:
#type 2
my_list = [1,1,1,1,2,2,2,2,255,5,588,8,8,55,522,25,5]
unique_list = []
for elem in my_list:
if elem not in unique_list:
unique_list.append(elem)
unique_list.sort()
print("unique items", unique_list )
unique items [1, 2, 5, 8, 25, 55, 255, 522, 588]
22.Check if a number is a palindrome.
In?[8]:
#type 1 short method
num = 121
if str (num) == str(num)[::-1] :
print(" this is a palindrome")
else:
print("this is not a palindrome")
this is a palindrome
In?[18]:
#type 2 long method
num = 1331
original = num
reverse = 0
while num > 0:
digit = num % 10
reverse = reverse *10 + digit
num//=10
if original == reverse:
print("this is a palindrome")
else:
print("this is not a palindrome")
this is a palindrome
23.Check if a string is a palindrome.
In?[19]:
string = "madam"
if string == string[::-1]:
print("string is a palindrome")
else:
print("string is not a palindrome")
string is a palindrome
In?[20]:
string = "hello"
if string == string[::-1]:
print("string is a palindrome")
else:
print("string is not a palindrome")
string is not a palindrome
24.Print a pattern of stars in the shape of a triangle.
In?[21]:
row = 5
for i in range(1,row+1):
print("*"*i)
*
**
***
****
*****
25.Print a pattern of numbers in the shape of a triangle.
In?[9]:
row = 10
for i in range(1,row+1):
for j in range(1,i+1):
print(j,end=' ')
print()
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10
26.Print a pattern of stars in the shape of a pyramid.
In?[28]:
row = 5
for i in range(5):
print(' '*(rows-i-1)+ '*'*(2*i+1))
*
***
*****
*******
*********
27.Print a pattern of numbers in the shape of a pyramid.
In?[6]:
row = 5
for i in range(1,row+1):
print(' ' *(row-i),end='')
for j in range(1,i+1):
print(j,end=' ')
print()
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
In?[8]:
rows = 10
for i in range(1, rows + 1):
print(' ' * (rows - i), end='')
for j in range(1, i + 1):
print(j, end=' ')
print()
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10
28.Print a pattern of stars in the shape of a diamond.
In?[13]:
rows = 5
for i in range(rows):
print(' ' * (rows - i - 1) + '*' * (2 * i + 1))
for i in range(rows - 2, -1, -1):
print(' ' * (rows - i - 1) + '*' * (2 * i + 1))
*
***
*****
*******
*********
*******
*****
***
*
29.Print a pattern of numbers in the shape of a diamond.
In?[12]:
row = 5
for i in range(1, row+1):
print(' '*(row-i),end='')
for j in range(1,i+1):
print(j,end=' ')
print()
for i in range(row -1,0,-1):
print(' '*(row-i),end='')
for j in range(1,i+1):
print(j,end=' ')
print()
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
30.Print the transpose of a matrix.
In?[19]:
matrix = [[1,2,3],[4,5,6],[7,8,9]]
transpose = []
for i in range(len(matrix[0])):
row=[]
for j in range(len(matrix)):
row.append(matrix[j][i])
transpose.append(row)
for row in transpose:
print(row)
[1, 4, 7]
[2, 5, 8]
[3, 6, 9]
In?[34]:
def transpose(matrix):
transposed_matrix = list(zip(*matrix))
for row in transposed_matrix:
print(row)
# Example usage
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
transpose((matrix))
(1, 4, 7)
(2, 5, 8)
(3, 6, 9)
In?[32]:
def transpose(matrix):
transposed_matrix = list(zip(*matrix))
for row in transposed_matrix:
print(list(row))
# Example usage
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
transpose(matrix)
[1, 4, 7]
[2, 5, 8]
[3, 6, 9]
31.Multiply two matrices
In?[9]:
A = [[1,2],[3,4]]
B = [[5,6],[7,8]]
results = [[0,0],[0,0]]
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
results[i][j] += A[i][k] * B[k][j]
for row in results:
print(row)
[19, 22]
[43, 50]
32.Print the diagonal elements of a matrix
In?[11]:
matrix = [[1,2,3],[4,5,6],[7,8,9]]
for i in range(len(matrix)):
print(matrix[i][i])
1
5
9
33.Print the anti-diagonal elements of a matrix
In?[14]:
matrix = [[1,2,3],[4,5,6],[7,8,9]]
for i in range(len(matrix)):
print(matrix[i] [len(matrix) -i -1])
3
5
7
34.Calculate the sum of the diagonal elements of a matrix
In?[19]:
matrix = [[1,2,3],[4,5,6],[7,8,9]]
total = 0
for i in range(len(matrix)):
total += matrix[i][i]
print("sum of total is ",total)
sum of total is 15
35. Calculate the sum of the anti-diagonal elements of a matrix
In?[21]:
matrix = [[1,2,5],[4,5,6],[7,8,9]]
total = 0
for i in range(len(matrix)):
total += matrix[i][len(matrix) -i -1]
print("sum of total is ",total)
sum of total is 17
36.Print the boundary elements of a matrix
In?[22]:
matrix = [[1,2,5],[4,5,6],[7,8,9]]
rows, cols = len(matrix), len(matrix[0])
for i in range(cols):
print(matrix[0][i], end=' ')
for i in range(1, rows):
print(matrix[i][cols -1], end=' ')
for i in range(cols -2, -1, -1):
print(matrix[rows -1][i], end=' ')
for i in range(rows -2,0,-1):
print(matrix[i][0], end=' ')
1 2 5 6 9 8 7 4
37.Print the spiral order of a matrix
In?[26]:
matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
rows, cols = len(matrix), len(matrix[0])
spiral = []
top, bottom, left, right = 0, rows - 1, 0, cols - 1
while top <= bottom and left <= right:
for i in range(left, right + 1):
spiral.append(matrix[top][i])
top += 1
for i in range(top, bottom + 1):
spiral.append(matrix[i][right])
right -= 1
if top <= bottom:
for i in range(right, left - 1, -1):
spiral.append(matrix[bottom][i])
bottom -= 1
if left <= right:
for i in range(bottom, top - 1, -1):
spiral.append(matrix[i][left])
left += 1
print("Spiral order:", spiral)
Spiral order: [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
38.Print the elements of an array in sorted order
In?[30]:
my_list = [1,5,6,8,7,9,1,3,2]
for elem in sorted(my_list):
print(elem)
1
1
2
3
5
6
7
8
9
39.Sort an array in ascending order
In?[29]:
my_list = [1,5,6,8,7,9,1,3,]
my_list.sort()
print(my_list)
[1, 1, 3, 5, 6, 7, 8, 9]
40.Sort an array in descending order
In?[34]:
my_list = [1,5,6,8,7,9,1,3]
my_list.sort(reverse=True)
print(my_list)
[9, 8, 7, 6, 5, 3, 1, 1]
In?[35]:
my_list = [2,5,6,1,879,46,13,565]
my_list.sort(reverse=True)
print(my_list)
[879, 565, 46, 13, 6, 5, 2, 1]
41.Check if a list is sorted in ascending order
In?[3]:
my_list = [1,2,3,4,5]
is_sorted = all(my_list[i] <= my_list[i +1] for i in range(len(my_list)-1))
print("it list sorted in ascending order",is_sorted)
it list sorted in ascending order True
42.check if a list sorted in decending order
In?[6]:
my_list = [5,4,3,2,1]
is_sorted = all(my_list[i] >= my_list[i +1] for i in range(len(my_list)-1))
print("it list sorted in decending order",is_sorted)
it list sorted in decending order True
43.find th intersection of two lists
In?[9]:
list1 = [1,2,3,4]
list2 = [3,4,5,6]
intersection = [elem for elem in list1 if elem in list2]
print("intersection:",intersection)
intersection: [3, 4]
44.find the union of two lists
In?[10]:
list1 = [1,2,3,4]
list2 = [3,4,5,6]
union = list(set(list1 + list2))
print("union:", union)
union: [1, 2, 3, 4, 5, 6]
45.find the difference between two lists
In?[12]:
list1 = [1,2,3,4]
list2 = [3,4,5,6]
difference = [elem for elem in list1 if elem not in list2 ]
print("differencce:", difference)
differencce: [1, 2]
46.Find the symmetric difference between two lists
In?[18]:
list1 = [1,2,3,4]
list2 = [3,4,5,6]
symmetric_difference = list(set(list1).symmetric_difference(set(list2)))
print("symmetric difference:", symmetric_difference)
symmetric difference: [1, 2, 5, 6]
47. Print the frequency of each element in a list
In?[21]:
my_list = [1,2,2,2,3,4,5,6,5,2,5,7]
frequency = {}
for elem in my_list:
if elem in frequency:
frequency[elem] += 1
else:
frequency[elem] = 1
for key, value in frequency.items():
print(f"{key}: {value}")
1: 1
2: 4
3: 1
4: 1
5: 3
6: 1
7: 1
48.Find the most frequent element in a list
In?[30]:
my_list = [1,2,3,4,56,5,5,5,5,5,55,566,55,5,5,6,6,6,6,]
frequency = {}
for elem in my_list:
if elem in frequency:
frequency[elem] += 1
else:
frequency[elem] = 1
most_frequency = max(frequency, key=frequency.get)
print("Most frequent element:", most_frequency)
Most frequent element: 5
49.Find the least frequent element in a list
In?[32]:
my_list = [1,2,2,3,5,6,4,2,5,2]
frequency ={}
for elem in my_list:
if elem in frequency:
frequency[elem] += 1
else:
frequency[elem] = 1
least_frequent = min(frequency, key=frequency.get)
print("Least frequent element:", least_frequent)
Least frequent element: 1
50.Check if two strings are anagrams
In?[33]:
string1 = "listen"
string2 = "slient"
if sorted(string1) == sorted(string2):
print("strings are anagrams")
else:
print("strings are not anagrams")
strings are anagrams
51.Find the common elements in three lists
In?[4]:
list1 = [1,2,3]
list2 = [2,3,4]
list3 = [3,4,5]
common = list(set(list1) & set(list2) & set(list3))
print("common elements:", common)
common elements: [3]
52.Find the unique elements in three lists
In?[6]:
list1 = [1, 2, 3]
list2 = [2, 3, 4]
list3 = [3, 4, 5]
unique = list(set(list1).symmetric_difference(set(list2)).symmetric_difference(set(list3)))
print("Unique elements:", unique)
Unique elements: [1, 3, 5]
53.Merge two sorted lists
In?[2]:
list1 = [1,3,5]
list2 = [2,4,6]
merged_list = sorted(list1 + list2)
print("merged list",merged_list)
merged list [1, 2, 3, 4, 5, 6]
54.Find the longest word in a list
In?[3]:
words = ["indian cricket","apple","cherry"]
longest_word = max(words, key=len)
print("longest word:",longest_word)
longest word: indian cricket
55.Find the shortest word in a list
In?[4]:
words = ["indian cricket","apple","cherry"]
shortest_word = min(words, key=len)
print("shortest word:",shortest_word)
shortest word: apple
56.Find the length of the longest word in a list
In?[6]:
words = ["indian cricket","apple","cherry"]
longest_word = max(len(word) for word in words)
print("length of longest word:",longest_word)
length of longest word: 14
57.Find the length of the shortest word in a list
In?[5]:
words = ["indian cricket","apple","cherry"]
shortest_word = min(len(word) for word in words)
print("length of shortest word:",shortest_word)
length of shortest word: 5
In?[?]:
57
58.Count the occurrence of each character in a string
In?[7]:
string = "india"
frequency = {}
for char in string:
if char in frequency:
frequency[char] += 1
else:
frequency[char] = 1
for key, value in frequency.items():
print(f"{key}: {value}")
i: 2
n: 1
d: 1
a: 1
59.Find the most frequent character in a string
In?[8]:
string = "hello"
frequency = {}
for char in string:
if char in frequency:
frequency[char] += 1
else:
frequency[char] = 1
most_frequent = max(frequency, key=frequency.get)
print("Most frequent character:", most_frequent)
Most frequent character: l
60.Find the least frequent character in a string
In?[9]:
string = "hello"
frequency = {}
for char in string:
if char in frequency:
frequency[char] += 1
else:
frequency[char] = 1
least_frequent = min(frequency, key=frequency.get)
print("Least frequent character:", least_frequent)
Least frequent character: h
61.Count the number of digits in a number
In?[1]:
num = 12345
count = 0
while num > 0:
num//=10
count += 1
print("number of digits:",count)
number of digits: 5
62.Find the sum of digits of a number
In?[6]:
num = 12345
total = 0
while num > 0:
total += num % 10
num//=10
print("sum of digits:",total)
sum of digits: 15
63.Find the product of digits of a number
In?[7]:
num = 12345
product = 1
while num > 0:
product *= num % 10
num //= 10
print("product of digits:",product)
product of digits: 120
64.Reverse the digits of a number
In?[8]:
num = 12345
reversed_num = 0
while num >0:
reversed_num = reversed_num *10 + num % 10
num //= 10
print("reversed number:", reversed_num)
reversed number: 54321
65.Find the sum of the first n natural numbers
In?[10]:
n = 10
total = sum(range(1, n+1))
print("sum of first n natural numbers:",total)
sum of first n natural numbers: 55
66.Find the sum of the squares of the first n natural numbers
In?[12]:
n = 10
total = sum(i**2 for i in range(1,n+1))
print("sum of squares of first n natural numbers:",total)
sum of squares of first n natural numbers: 385
67.Find the sum of the cubes of the first n natural numbers
In?[13]:
n = 10
total = sum(i**3 for i in range(1, n + 1))
print("Sum of cubes of first n natural numbers:", total)
Sum of cubes of first n natural numbers: 3025
68.Find the product of the first n natural numbers
In?[14]:
n = 5
product = 1
for i in range(1, n+1):
product *= i
print("product of first n natural numbers:",product)
product of first n natural numbers: 120
69.Find the GCD (greatest common divisor) of two numbers
In?[15]:
import math
num1, num2 = 48, 18
gcd = math.gcd(num1,num2)
print("GCD:", gcd)
GCD: 6
70.Find the LCM (least common multiple) of two numbers
In?[16]:
import math
num1, num2 =12,15
lcm = abs(num1 * num2) // math.gcd(num1, num2)
print("LCM:",lcm)
LCM: 60
71.Print the prime factors of a number
In?[2]:
num = 56
prime_factor = []
divisor = 2
while num > 1:
while num % divisor == 0:
prime_factor.append(divisor)
num//= divisor
divisor += 1
print("prime factors:", prime_factor)
prime factors: [2, 2, 2, 7]
72.Check if a number is an Armstrong number
In?[5]:
num = 153
sum_of_cubes = sum(int(digit)**3 for digit in str(num))
if sum_of_cubes ==num:
print("number is an Armstrong number")
else:
print("number is not an Armstrong number")
number is an Armstrong number
73.Find the sum of the first n even numbers
In?[6]:
n = 10
total = sum(i for i in range(2 * n) if i % 2 == 0)
print("sum of first n even number:",total)
sum of first n even number: 90
74.Find the sum of the first n odd numbers
In?[9]:
n = 10
total = sum( i for i in range(2 * n) if i % 2 != 0)
print("sum of first n odd number:", total)
sum of first n odd number: 100
75.Find the sum of a geometric series
In?[10]:
a = 1 #first term
r = 2 #common ratio
n = 10 #number of terms
total = a * (1 - r**n) // (1 - r)
print("sum of geometric series:", total)
sum of geometric series: 1023
76.Find the sum of an arithmetic series
In?[11]:
a = 1 #first term
d = 1 #common differnce
n = 10 #number of terms
total = n *(2*a + (n-1)*d)// 2
print("sum of arthmetic series:", total)
sum of arthmetic series: 55
77.Find the roots of a quadratic equation
In?[13]:
import cmath
a, b, c = 1, -3,2
d = cmath.sqrt(b**2 - 4*a*c)
root1 = (-b + d) / (2 * a)
root2 = (-b -d) / (2 * a)
print("roots:", root1,root2)
roots: (2+0j) (1+0j)
78.Check if a year is a leap year
In?[17]:
year = 2024
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print("leap year")
else:
print("not a leap year")
leap year
79. Print the first n Fibonacci numbers
In?[18]:
n = 10
a, b = 0, 1
for _ in range(n):
print(a)
a, b = b, a+b
0
1
1
2
3
5
8
13
21
34
80.Check if a string is a pangram
In?[25]:
import string
sentence = "The quick brown fox jumps over the lazy dog"
alphabet = set(string.ascii_lowercase)
if set(sentence.lower()) >= alphabet:
print("Pangram")
else:
print("Not a pangram")
Pangram
In?[24]:
import string
sentence = "Hello"
alphabet = set(string.ascii_lowercase)
if set(sentence.lower()) >= alphabet :
print("pangram")
else:
print("not a pangram")
not a pangram
81.Check if a string is a heterogram
In?[2]:
sentence = "The quick brown fox jumps"
if len(set(sentence)) == len(sentence.replace(" ","")):
print("Heterogram")
else:
print("Not a hetogram")
Not a hetogram
82.Find the longest common prefix among a list of strings
In?[7]:
strings = ["flower","flow","flight"]
if not strings:
print("No common prefix")
else:
prefix = strings[0]
for s in strings[1:]:
while s[:len(prefix)] != prefix and prefix:
prefix = prefix[:-1]
print("Longest common prefix:", prefix)
Longest common prefix: fl
83.Find the longest common suffix among a list of strings
In?[12]:
strigs = ["abstraction","distraction","reaction"]
if not strings:
print("No common suffix")
else:
suffix = strings[0]
for s in strings[1:]:
while s[- len(suffix):] != suffix and suffix:
suffix = suffix[1:]
print("Longest common suffix:", suffix)
Longest common suffix: action
84.Find the longest substring without repeating characters
In?[13]:
s = "abcabcbb"
longest_substring =""
for i in range(len(s)):
seen = set()
current_substring = ""
for j in range (i, len(s)):
if s[j] in seen:
break
seen.add(s[j])
current_substring += s[j]
if len(current_substring) > len(longest_substring):
longest_substring = current_substring
print("Longest substring without repeating characters:", longest_substring)
Longest substring without repeating characters: abc
85.Find the length of the longest substring without repeating characters
In?[19]:
s = "abcabcbb"
longest_length = 0
for i in range(len(s)):
seen = set()
current_length = 0
for j in range(i,len(s)):
if s[j] in seen:
break
seen.add(s[j])
current_length += 1
if current_length > longest_length:
longest_length = current_length
print("length of longest substring without repeating characters:",longest_length)
length of longest substring without repeating characters: 3
In?[18]:
Length of longest substring without repeating characters: 0
In?[20]:
s = "hellohleloj"
longest_length = 0
for i in range(len(s)):
seen = set()
current_length = 0
for j in range(i, len(s)):
if s[j] in seen:
break
seen.add(s[j])
current_length += 1
if current_length > longest_length:
longest_length = current_length
print("Length of longest substring without repeating characters:", longest_length)
Length of longest substring without repeating characters: 4
86.Find the first non-repeating character in a string
In?[21]:
s = "swisszz"
frequency = {}
for char in s:
frequency[char] = frequency.get(char,0) + 1
for char in s :
if frequency[char] == 1:
print("first non-repeating character:", char)
break
first non-repeating character: w
87. check if a string has all unique characters
In?[27]:
s = "abcdefg"
if len(s) == len(set(s)):
print("all character are unique")
else:
print("character are not unique")
all character are unique
In?[28]:
s = "abcdefffg"
if len(s) == len(set(s)):
print("all character are unique")
else:
print("character are not unique")
character are not unique
88.Remove duplicates from a list
In?[33]:
my_list = [1,1,11,1,1,122,2,2,2,22,55,5,3,3,5,55,22,2,2,2]
my_list = list(set(my_list))
my_list.sort()
print("list without duplicate:", my_list)
list without duplicate: [1, 2, 3, 5, 11, 22, 55, 122]
89.Convert a string to uppercase.
In?[40]:
string = "datascience"
converted_string = string.upper()
print(converted_string)
DATASCIENCE
90.Capitalize the first letter of each word in a string.
In?[41]:
# Define the string
input_string = "datascience"
# Capitalize the first letter of each word
capitalized_string = input_string.title()
# Print the result
print(capitalized_string)
Datascience
91.Reverse the words in a string.
In?[44]:
string = "Datascience"
reverse = string[::-1]
print(reverse)
ecneicsataD
92.Remove vowels from a string.
In?[45]:
def remove_vowels(input_string):
vowels = "aeiouAEIOU"
return input_string.translate(str.maketrans('', '', vowels))
# Define the string
input_string = "Remove vowels from a string."
# Remove vowels
no_vowels_string = remove_vowels(input_string)
# Print the result
print(no_vowels_string)
Rmv vwls frm strng.
93.Replace vowels in a string with a specified character.
In?[47]:
def replace_vowels(input_string, replacement_char):
vowels = "aeiouAEIOU"
result = ''
for char in input_string:
if char in vowels:
result += replacement_char
else:
result += char
return result
# Define the string and the replacement character
input_string = "Replace vowels in a string."
replacement_char = '@'
# Replace vowels
replaced_string = replace_vowels(input_string, replacement_char)
# Print the result
print(replaced_string)
R@pl@c@ v@w@ls @n @ str@ng.
94.Remove consonants from a string.
In?[48]:
def remove_consonants(input_string):
vowels = "aeiouAEIOU"
return ''.join([char for char in input_string if char in vowels or not char.isalpha()])
# Define the string
input_string = "Remove consonants from a string."
# Remove consonants
no_consonants_string = remove_consonants(input_string)
# Print the result
print(no_consonants_string)
eoe ooa o a i.
95.Replace consonants in a string with a specified character.
In?[50]:
def replace_consonants(input_string, replacement_char):
vowels = "aeiouAEIOU"
return ''.join([replacement_char if char.isalpha() and char not in vowels else char for char in input_string])
# Define the string and the replacement character
input_string = "Replace consonants in a string."
replacement_char = '*'
# Replace consonants
replaced_string = replace_consonants(input_string, replacement_char)
# Print the result
print(replaced_string)
*e**a*e *o**o*a*** i* a ***i**.
96.Print the ASCII value of each character in a string.
In?[51]:
def print_ascii_values(input_string):
for char in input_string:
print(f"Character: {char} - ASCII Value: {ord(char)}")
# Define the string
input_string = "Hello, World!"
# Print ASCII values
print_ascii_values(input_string)
Character: H - ASCII Value: 72
Character: e - ASCII Value: 101
Character: l - ASCII Value: 108
Character: l - ASCII Value: 108
Character: o - ASCII Value: 111
Character: , - ASCII Value: 44
Character: - ASCII Value: 32
Character: W - ASCII Value: 87
Character: o - ASCII Value: 111
Character: r - ASCII Value: 114
Character: l - ASCII Value: 108
Character: d - ASCII Value: 100
Character: ! - ASCII Value: 33
97.Print the character corresponding to each ASCII value in a list.
In?[52]:
def print_characters_from_ascii(ascii_values):
for value in ascii_values:
print(f"ASCII Value: {value} - Character: {chr(value)}")
# Define the list of ASCII values
ascii_values = [72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33]
# Print characters corresponding to ASCII values
print_characters_from_ascii(ascii_values)
ASCII Value: 72 - Character: H
ASCII Value: 101 - Character: e
ASCII Value: 108 - Character: l
ASCII Value: 108 - Character: l
ASCII Value: 111 - Character: o
ASCII Value: 44 - Character: ,
ASCII Value: 32 - Character:
ASCII Value: 87 - Character: W
ASCII Value: 111 - Character: o
ASCII Value: 114 - Character: r
ASCII Value: 108 - Character: l
ASCII Value: 100 - Character: d
ASCII Value: 33 - Character: !
98.Print the elements of a list of lists.
In?[54]:
def print_list_of_lists(list_of_lists):
for sublist in list_of_lists:
for element in sublist:
print(element, end=' ')
print() # Move to the next line after each sublist
# Define the list of lists
list_of_lists = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Print elements of the list of lists
print_list_of_lists(list_of_lists)
1 2 3
4 5 6
7 8 9
99.Flatten a list of lists.
In?[55]:
#Using List Comprehension
def flatten_list_of_lists(list_of_lists):
return [element for sublist in list_of_lists for element in sublist]
# Define the list of lists
list_of_lists = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Flatten the list of lists
flattened_list = flatten_list_of_lists(list_of_lists)
# Print the result
print(flattened_list)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
100.Print the transpose of a list of lists.
In?[56]:
def transpose_list_of_lists(list_of_lists):
# Use zip and unpacking to transpose the list of lists
transposed = list(map(list, zip(*list_of_lists)))
return transposed
def print_transposed_list(list_of_lists):
transposed = transpose_list_of_lists(list_of_lists)
for row in transposed:
print(row)
# Define the list of lists
list_of_lists = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Print the transpose of the list of lists
print_transposed_list(list_of_lists)
[1, 4, 7]
[2, 5, 8]
[3, 6, 9]