PARIKSHIT TASK 1
DHRUV SARAOGI
Python Basics
EASY
1. Calculate the Area of a Circle
Write a Python program that calculates the area of a circle given its radius.
o Input:
5
o Output:
78.54
(Hint: Use the formula: πr²)
import math
pi=[Link]
a=int(input("Enter the radius of the circle: "))
area=pi*a**2
print("The area of the circle is: %.2f" %area)
2. Convert Celsius to Fahrenheit
Write a Python program that converts a temperature from Celsius to Fahrenheit.
o Input:
0
o Output:
32
(Hint: Use the formula: (C × 9/5) + 32)
celsius_temp = float(input("Enter temperature in Celsius: "))
fahrenheit_temp = (celsius_temp * 9/5) + 32
print(f"{celsius_temp} degrees Celsius is equal to {fahrenheit_temp}
degrees Fahrenheit.")
MEDIUM
3. Remove Duplicates from a List
Write a Python program that removes duplicate elements from a list of integers.
o Input:
[1, 2, 2, 3, 4, 4, 5]
o Output:
[1, 2, 3, 4, 5]
n=int(input("Enter the number of elements in the list: "))
list1=[]
for i in range(0,n):
x=int(input("Enter the element: "))
[Link](x)
set1=set(list1)
list1=list(set1)
print("The list after removing duplicates is: ",list1)
4. Count Vowels in a String
Write a Python program to count the number of vowels (a, e, i, o, u) in a given string,
ignoring case.
o Input:
"Python Programming"
o Output:
4
n="aeiouAEIOU"
s=input("Enter a string:")
count=0
for i in s:
if i in n:
count+=1
print("Number of vowels in the string is:",count)
5. Find the Second Largest Number in a List
Write a Python program to find the second largest number in a list of integers.
o Input:
[12, 45, 67, 23, 89, 90]
o Output:
89
#find second largest number in a list
n=int(input("enter the number of elements in the list:"))
L=[]
for i in range(n):
[Link](int(input("enter the element:")))
[Link]()
print("second largest number in the list is:",L[-2])
6. Capitalize First Letter of Each Word
Write a Python program to capitalize the first letter of every word in a given sentence.
o Input:
"hello world from python"
o Output:
"Hello World From Python"
n=input("Enter a string: ")
print([Link]())
7. Reverse a String
Write a Python program to reverse a given string.
o Input:
"Innovation"
o Output:
"noitavonnI"
n=input("Enter a string: ")
print(n[::-1])
HARD
8. Palindrome Check
Write a Python program to check if a given string is a palindrome (reads the same forward
and backward).
o Input:
"madam"
o Output:
True
n=input("Enter a string: ")
print(n[::-1]==n)
9. Find All Prime Numbers Below a Given Number
Write a Python program that returns all prime numbers less than a given number n.
o Input:
20
o Output:
[2, 3, 5, 7, 11, 13, 17, 19]
n=int(input("Enter a number: "))
prime=[]
count=0
for i in range(2,n):
for j in range(1,i+1):
if i%j==0:
count+=1
if count==2:
[Link](i)
count=0
print(prime)
10. Generate Fibonacci Sequence
Write a Python program to generate the first n numbers of the Fibonacci sequence.
Input:
7
Output:
[0, 1, 1, 2, 3, 5, 8]
n=int(input("Enter a number: "))
fibonacci=[]
num1 = 0
num2 = 1
next_number = num2
count = 1
while count <= n:
[Link](num1)
count += 1
num1, num2 = num2, next_number
next_number = num1 + num2
print(fibonacci)
11. Binary Search Algorithm
Write a Python program to implement the binary search algorithm for a sorted list of
integers.
Input:
List: [1, 3, 5, 7, 9, 11, 13]
Target: 9
Output:
Found at index 4
def binary_search(arr, target):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
n=int(input("Enter the number of elements in the list: "))
arr=[]
for i in range(n):
[Link](int(input()))
t=int(input("Enter the element to be searched: "))
result = binary_search(arr, t)
if result != -1:
print("Element found at index",result)
else:
print("Element not found")
12. Calculate Factorial Using Recursion
Write a Python program to calculate the factorial of a given number using recursion.
Input:
5
Output:
120
def factorial(n):
if n==0:
return 1
else:
return n*factorial(n-1)
n=int(input("Enter a number: "))
print("Factorial of",n,"is",factorial(n))
13. Matrix Transposition
Write a Python program to find the transpose of a matrix (rows become columns and vice
versa).
Input:
[[1, 2, 3], [4, 5, 6]]
Output:
[[1, 4], [2, 5], [3, 6]]
import numpy as np
n=int(input("Enter the size of the matrix(rows)"))
m=int(input("Enter the size of the matrix(columns)"))
matrix=[Link]((n,m),dtype='int64')
mt=[Link]((m,n),dtype='int64')
for i in range(0,n):
for j in range(0,m):
matrix[i][j]=int(input())
print(matrix)
for i in range(m):
for j in range(n):
mt[i][j]=matrix[j][i]
print(mt)
14. Longest Word in a Sentence
Write a Python program to find the longest word in a given sentence.
Input:
"Exploration of Python programming"
Output:
"Exploration"
n=input("enter a string")
s=[Link](" ")
max=0
word=""
for i in s:
if len(i)>max:
max=len(i)
word=i
print(word)
15. Check for Balanced Parentheses
Write a Python program to check if a given string containing parentheses is balanced or not.
Input:
"(())"
Output:
True
Input:
"(()"
Output:
False
n=input("enter a string")
count =0
for chr in n:
if chr=="(":
count+=1
elif chr==")":
count-=1
if count == 0:
print(True)
else:
print(False)
Pandas and Numpy
EASY
1. Create a NumPy Array
Write a Python program to create a NumPy array with values ranging from 1 to 10.
o Input: None
o Output:
o array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
import numpy as np
a=[Link](1,11)
print(a)
2. Select a Column from a DataFrame
Given the DataFrame below, write a Pandas program to select the Name column.
o Input:
Python
df = [Link]({
'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25,
30, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
})
o Output:
o 0 Alice
o 1 Bob
o Name: Name, dtype: object
import pandas as pd
df = [Link]({'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30,
35],
'City': ['New York', 'Los Angeles', 'Chicago']})
print(df['Name'])
3. Create a DataFrame from a Dictionary
Write a Python program to create a Pandas DataFrame from the dictionary below.
o Input:
Python
data = {'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}
o Output:
o ABC
o 0147
o 1258
o 2369
data = {'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}
df = [Link] (data)
print(df)
MEDIUM
4. Find the Mean of a NumPy Array
Write a Python program to find the mean of a given NumPy array.
o Input:
o array([10, 20, 30, 40, 50])
o Output:
o 30.0
import numpy as np
a=[Link]([10,20,30,40,50])
print([Link]()/len(a))
5. Filter Rows by Condition in Pandas
Given the DataFrame below, write a Pandas program to filter rows where the Age is greater than 30.
o Input:
Python
df = [Link]({
'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25,
30, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
})
o Output:
o Name Age City
2 Charlie 35 Chicago
o
import pandas as pd
df = [Link]({
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
})
print(df[df['Age']>30])
6. Generate a Random NumPy Array
Write a Python program to generate a 3x3 matrix of random values between 0 and 1 using NumPy.
o Input: None
o Output: (Values may vary)
o array([[0.329, 0.957, 0.604],
o [0.158, 0.940, 0.136],
o [0.410, 0.234, 0.732]])
import numpy as np
a=[Link]((3,3))
print(a)
7. Calculate the Sum of Each Column in a DataFrame
Given the DataFrame below, write a Pandas program to calculate the sum of each column.
o Input:
Python
df = [Link]({ 'A': [1,
2, 3],
'B': [4, 5, 6],
'C': [7, 8, 9]
})
o Output:
o A 6
o B 15
o C 24
o dtype: int64
data = {'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}
df = [Link] (data)
[Link]()
8. Replace Missing Values in a DataFrame
Write a Pandas program to replace missing values (NaN) in the DataFrame with the mean of the
respective column.
o Input:
Python
df = [Link]({ 'A': [1,
[Link], 3],
'B': [4, 5, [Link]],
'C': [7, 8, 9]
})
o Output:
o A BC
o 0 1.0 4.0 7
o 1 2.0 5.0 8
o 2 3.0 4.5 9
import pandas as pd
import numpy as np
df = [Link]({
'A': [1, [Link], 3],
'B': [4, 5, [Link]],
'C': [7, 8, 9]
})
df ['A'].fillna (df['A'].mean(), )
df ['B'].fillna (df['B'].mean(), )
df ['C'].fillna (df['C'].mean(), )
df
HARD
9. Find the Dot Product of Two NumPy Arrays
Write a Python program to calculate the dot product of two NumPy arrays.
o Input:
Python
array_1 = [Link]([1, 2, 3])
array_2 = [Link]([4, 5, 6])
o Output:
o 32
import numpy as np
array_1 = [Link]([1, 2, 3])
array_2 = [Link]([4, 5, 6])
a=[Link](array_1,array_2)
print(a)
10. Group By and Aggregate in Pandas
Given the DataFrame below, write a Pandas program to group by the City column and calculate the
mean Age for each city.
Input:
Python
df = [Link]({
'Name': ['Alice', 'Bob', 'Charlie', 'David'], 'Age': [25, 30,
35, 40],
'City': ['New York', 'Los Angeles', 'Chicago', 'New York']
})
Output:
Age
City
Chicago 35.0
Los Angeles 30.0
New York 32.5
import pandas as pd
df = [Link]({
'Name': ['Alice', 'Bob', 'Charlie', 'David'],
'Age': [25, 30, 35, 40],
'City': ['New York', 'Los Angeles', 'Chicago', 'New York']
})
result = [Link]('City')['Age'].mean()
print(result)
11. Apply a Function to a DataFrame Column
Write a Python program to apply a custom function to the Age column of the DataFrame below to
convert the ages from years to months.
Input:
Python
df = [Link]({
'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25,
30, 35]
})
def years_to_months(age):
return age * 12
Output:
Name Age
0 Alice 300
1 Bob 360
2 Charlie 420
import pandas as pd
df = [Link]({
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35]
})
def years_to_months(age):
return age * 12
df['Age'] = df['Age'].apply(years_to_months)
print(df)
12. Concatenate DataFrames
Write a Pandas program to concatenate the two DataFrames below.
Input:
Python
df1 = [Link]({'A': [1, 2], 'B': [3, 4]})
df2 = [Link]({'A': [5, 6], 'B': [7, 8]})
Output:
AB
013
124
057
168
import pandas as pd
df1 = [Link]({'A': [1, 2], 'B': [3, 4]})
df2 = [Link]({'A': [5, 6], 'B': [7, 8]})
df3 = [Link]([df1, df2])
print(df3)
13. Find the Eigenvalues and Eigenvectors
Write a Python program to find the eigenvalues and eigenvectors of a 2x2 matrix using NumPy.
Input:
Python
matrix = [Link]([[4, 2], [1, 3]])
Output:
Eigenvalues: [5.236, 1.764]
Eigenvectors:
[[ 0.894, -0.707],
[ 0.447, 0.707]]
import numpy as np
matrix = [Link]([[4, 2], [1, 3]])
u,v=[Link](matrix)
print("Eigenvalues of the said matrix",u)
print("Eigenvectors of the said matrix",v)
14. Reshape a NumPy Array
Write a Python program to reshape a 1D NumPy array into a 3x3 matrix.
Input:
Python
array = [Link]([1, 2, 3, 4, 5, 6, 7, 8, 9])
Output:
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
import numpy as np
array = [Link]([1, 2, 3, 4, 5, 6, 7, 8, 9])
a = [Link](3, 3)
print(a)
15. Pivot a DataFrame
Given the DataFrame below, write a Pandas program to pivot the DataFrame so that the Name column
becomes the index, and the Subject column values become columns with the corresponding Score.
Input:
Python
df = [Link]({
'Name': ['Alice', 'Bob', 'Alice', 'Bob'],
'Subject': ['Math', 'Math', 'Science', 'Science'], 'Score':
[85, 78, 92, 81]
})
Output:
Math Science
Name
Alice 85 92
Bob 78 81
import pandas as pd
df = [Link]({
'Name': ['Alice', 'Bob', 'Alice', 'Bob'],
'Subject': ['Math', 'Math', 'Science', 'Science'], 'Score': [85, 78,
92, 81]
})
pivot_df = [Link](index='Name', columns='Subject', values='Score')
print(pivot_df)