|
|
1) Write a program that takes a list with duplicate elements and creates a new list with only unique elements.
original_list = [1, 2, 2, 3, 4, 4, 5, 1]
unique_list = []
for x in original_list:
if(x not in unique_list):
unique_list.append(x)
print(unique_list)
Output
[1, 2, 3, 4, 5]
2) Write program to count the number of occurrences of each word in a sentence
str=input("Please enter a sentence:")
def CountofEachWordInASentence(str):
lstWords=str.split(" ")
DictWords={}
for x in lstWords:
if(x not in DictWords):
DictWords[x]=1
else:
DictWords[x]=DictWords[x] + 1
return DictWords
print(CountofEachWordInASentence(str))
3) Write a program that takes a list and "rotates" it to the right by k steps. Example: [1, 2, 3, 4, 5] rotated by 2 becomes [4, 5, 1, 2, 3].
my_list = [1, 2, 3, 4, 5]
rotated_list=my_list.copy()
print(f"Original: {my_list}")
k=2
def getRotatedIndex(counter, k, listLen):
newRotatedInd=counter+k
maxIndex=listLen-1
if(newRotatedInd > maxIndex):
newRotatedInd= newRotatedInd-maxIndex-1
return newRotatedInd
listlen=len(my_list)
counter=0
for x in my_list:
ind=getRotatedIndex(counter,k,listlen)
rotated_list[ind]=x
counter=counter+1
print(f"Rotated List: {rotated_list}")
output
Original: [1, 2, 3, 4, 5]
Rotated List=[4, 5, 1, 2, 3]
2) Write program to decrement items in a List
myList=[54,78,79,45,69,80,81]
def DecrementItemsInAList(myList):
for x in range(0,len(myList),1):
myList[x]=myList[x]-1
return myList
print(DecrementItemsInAList(myList))
4) Write a program to find the lowest number in a List
myList=[54,78,79,45,69,80,81] def LowestNumberInTheList(myList): lowestNumber=min(myList) return lowestNumber print(LowestNumberInTheList(myList))
5) Write a program to find the greatest number in a List.
myList=[54,78,79,45,99,69,80,81] def GreatestNumberInTheList(myList): GreatestNumber=max(myList) return GreatestNumber print(GreatestNumberInTheList(myList))
6) Write a program to find the 3rd largest number in a List.
myList=[54,78,79,45,99,69,80,81] def ThirdLargestNumberInTheList(myList): #Get the largest number GreatestNumber=max(myList) myList.remove(GreatestNumber) #Get the 2nd Largest number SecondGreatestNumber=max(myList) myList.remove(SecondGreatestNumber) #Get the 3rd largest number ThirdGreatestNumber=max(myList) return ThirdGreatestNumber print(ThirdLargestNumberInTheList(myList))
7) Write a program to check if a number is even or odd.
strNum=input("Please enter a number:")
intNum=int(strNum)
def IsANumberIsEvenOrOdd(intNum):
if(intNum%2 ==0):
return "It is an even number"
else:
return "It is an odd number"
print(IsANumberIsEvenOrOdd(intNum))
8) Write a program to find factorial of a number
strNum=input("Please enter a number:")
intNum=int(strNum)
def FindFactorialOfAnumber(intNum):
num=1
for x in range(1,intNum+1,1):
num=num * x
return num
print(FindFactorialOfAnumber(intNum))
9) Write a program to check if a number is a Prime Number or not
strNum=input("Please enter a number:")
intNum=int(strNum)
def CheckIfANumberIsPrimeNumber(intNum):
lst=[2,3,5]
if(intNum <=1):
return "Please enter number greater than 1."
else:
for x in lst:
if(intNum==x):
continue;
if(intNum%x==0):
return "It is not a prime Number"
return "It is a Prime Number"
print(CheckIfANumberIsPrimeNumber(intNum))
10) Write a program to reverse a string
str=input("Enter a string: ")
def ReverseAString1(str):
reverseStr=""
for x in range(len(str)-1, -1,-1):
reverseStr=reverseStr + str[x]
reverseStr=reverseStr.strip()
return reverseStr
def ReverseAString2(str):
return str[::-1]
#Function call ReverseAString1
print("From Function ReverseAString1: " + ReverseAString1(str))
#Function call ReverseAString2
print("From Function ReverseAString2: " + ReverseAString2(str))
11) Write a program to produce the following output
**********
*********
********
*******
******
*****
****
***
**
*
count=10
while count > 0:
for x in range(0,count,1):
print("*",end='')
print("")
count=count-1
12) Write a program to produce the following output
*
**
***
****
*****
******
*******
********
*********
**********
count=1
while count < 10:
for x in range(0,count,1):
print("*",end='')
print("")
count=count+1
13) Write a program to check if the first character of a string is a vowel.
str=input("Enter a string:")
def CheckIfStringStartWithAVowel(str):
retValue="No"
ch=str[0]
strVowels="AEIOU"
if(ch.upper() in strVowels):
retValue="Yes"
return retValue
retStr=CheckIfStringStartWithAVowel(str)
print(f"Does string start with a vowel? {retStr}")
14) Check if the first and last number of a list is same or not. Take a pre-defined list in the code itself.
myList=[20,25,27,78,20]
firtNum=myList[0]
lastNum=myList[-1]
if(firtNum==lastNum):
print("Yes, the first and last numbers in a list are same.")
else:
print("No, the first and last numbers in a list are not same.")
15) Write a program to calculate the Grade of a student through 5 subjects. Take marks as input from the user.
maths = int(input("Please enter number for maths: "))
physics = int(input("Enter number for physics: "))
chemistry = int(input("Enter number for chemistry: "))
biology = int(input("Enter number for biology: "))
english = int(input("Enter number for english: "))
sub_marks = m + p + c + b + e
percentage_marks = (sub_marks/500)*100
if percentage_marks>90:
print("You have got A+ Grade")
elif percentage_marks<=90 and perc>80:
print("You have got A Grade")
elif percentage_marks<=80 and perc>70:
print("You have got B+ Grade")
elif percentage_marks<=70 and perc>60:
print("You have got B Grade")
elif percentage_marks<=60 and perc>50:
print("You have got C+ Grade")
elif percentage_marks<=50 and perc>40:
print("You have got C Grade")
elif percentage_marks<=40 and perc>33:
print("You have got D Grade")
else:
print("Sorry! You Failed!")
16) Write a program to check if the 3rd last character of a string is a vowel or not.
str=input("Enter a string:")
thirdChar=str[-3]
strVowels="AEIOU"
if(thirdChar.upper() in strVowels):
print("Yes, the 3rd last character in a string is a Vowel.")
else:
print("No, the 3rd last character in a string is not a Vowel.")
17) Write a program to check if a given number is a Palindrome. for ex, 545. Keep prompting for input until a numeric value is entered.
strNum=""
while True:
num=input("Enter a number:")
strNum=str(num)
if(strNum.isdigit()):
break;
#reverse it
strReverse= strNum[::-1]
print(strReverse)
if(strReverse==strNum):
print("The number entered is a Pallindrome.")
else:
print("The number entered is not a Pallindrome.")
18) Write a program to print the multiplication table of 5.
for x in range(1,11,1):
y=5*x;
print(f"5 * {x} = {y}")
output
-------
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
19) Write a program in Python that accepts a string and prints "It is a perfect string" if it only has single quotes, alphabet, and '-'. Otherwise, it should print "It is not a perfect string"
str=input("Enter a String: ")
strResult="It is a perfect string."
for x in str:
#check if x is not an alphabet
if(x.isalpha()==False):
if ( x!='-' and x!="'"):
strResult="It is not a perfect string."
break;
print(strResult)
output
-------
Enter a String: Hello $ hhh%
It is not a perfect string.
20) Python program that converts a dictionary of student marks into a new dictionary containing each student's minimum, maximum, and average marks stored as a list.
# 1. Define the initial dictionary containing student names and 5 subject marks
student_marks = {
"Alice": [85, 92, 78, 89, 95],
"Bob": [70, 65, 82, 74, 69],
"Charlie": [98, 91, 94, 88, 92],
"Diana": [60, 55, 58, 62, 61]
}
# 2. Initialize an empty dictionary to hold the final processed statistics
processed_data = {}
# 3. Iterate through the original dictionary to compute metrics for each student
for name, marks in student_marks.items():
# Calculate the required statistics using built-in Python functions
min_marks = min(marks)
max_marks = max(marks)
average_marks = sum(marks) / len(marks) # Dynamically divides sum by count (5)
# Store the results as a list mapped to the student's name
processed_data[name] = [min_marks, max_marks, average_marks]
# 4. Display the newly structured output dictionary
print("Processed Student Data (Format: [Min, Max, Average]):")
print(processed_data)
output
Processed Student Data (Format: [Min, Max, Average]):
{'Alice': [78, 95, 87.8], 'Bob': [65, 82, 72.0], 'Charlie': [88, 98, 92.6], 'Diana': [55, 62, 59.2]}
21) Check if Two Strings are Anagram - For example
string1="listen" string2= "silent"
Output: Yes
string1=input("Enter string 1")
string2=input("Enter string 2")
print("Yes" if sorted(string1) == sorted(string2) else "No")
output
Enter string 1:listen
Enter string 2:netils
Yes
22) Write a program to sort a string in Python
string1=input("Enter string 1:")
lst=sorted(string1)
st="".join(lst)
print(st)
output
Enter string 1:AHDLFDFKDBBZZ
ABBDDDFFHKLZZ
23) Write a program to count how many times each word appears in a sentence.
string1=input("Enter string 1:")
lst=string1.split(" ")
dict={}
for x in lst:
dict[x]=lst.count(x)
print(dict)
output
Enter string 1:AA CC AA BB CC
{'AA': 2, 'CC': 2, 'BB': 1}