Docsity

Python Programming Exercises: Data Structures, Functions, and Object-Oriented Programming, Exercises of Programming Languages

Toggle sidebar
bg1
MARKS BY GPT -4 : 7/10
Marks by gemini :8/10
MARKS By perplexity : 7/10
. **Q1:** Write a Python program that: - Takes a string input from the user
and checks if it is a palindrome. - If it is, store the string in a list and print all
stored palindromes. - If it isn't, replace every vowel in the string with a
corresponding number (a=1, e=2, etc.) and print the modified string. -
Ensure all strings are stored in a tuple and print the tuple at the end
name=input("Enter : ")
length=len(name)
name2=(name[0:length+1])[::-1]
Status= Trueif name==name2 else False
l=[]
if Status==True:
  l.append(name)
  print(l)
  t1=(l)
  print(t1)
else:
  name1 = ((((name.replace("a", "1")).replace("e", "2")).replace("i",
"3")).replace("o", "4")).replace("u", "5")
  print(name1)
  t=(name1)
  print(t)
. 2. **Q2:** Write a Python script that: - Reads a file containing a list of
numbers, one per line. - For each number, check if it is even or odd using a
conditional expression. - Store the results in a dictionary, where the number
is the key and the value is "Even" or "Odd". - Sort the dictionary by keys and
write the sorted results to a new file.
numberDetails={}
with open("log.txt","r") as f:
  num=f.readline()
  while num!="":
    number=int(num)
    if number%2==0:
pf3
pf4
pf5
pf8
pf9

Partial preview of the text

Download Python Programming Exercises: Data Structures, Functions, and Object-Oriented Programming and more Exercises Programming Languages in PDF only on Docsity!

MARKS BY GPT -4 : 7/

Marks by gemini :8/

MARKS By perplexity : 7/

. Q1: Write a Python program that: - Takes a string input from the user

and checks if it is a palindrome. - If it is, store the string in a list and print all

stored palindromes. - If it isn't, replace every vowel in the string with a

corresponding number (a=1, e=2, etc.) and print the modified string. -

Ensure all strings are stored in a tuple and print the tuple at the end

name=input("Enter : ") length=len(name) name2=(name[ 0 :length+ 1 ])[::- 1 ] Status= True if name==name2 else False l=[] if Status==True: l.append(name) print(l) t1=(l) print(t1) else: name1 = ((((name.replace("a", "1")).replace("e", "2")).replace("i", "3")).replace("o", "4")).replace("u", "5") print(name1) t=(name1) print(t)

. 2. Q2: Write a Python script that: - Reads a file containing a list of

numbers, one per line. - For each number, check if it is even or odd using a

conditional expression. - Store the results in a dictionary, where the number

is the key and the value is "Even" or "Odd". - Sort the dictionary by keys and

write the sorted results to a new file.

numberDetails={} with open("log.txt","r") as f: num=f.readline() while num!="": number=int(num) if number% 2 == 0 :

numberDetails.update({number:"Even"}) else: numberDetails.update({number:"odd"}) num=f.readline() print(f"Hello its My dictionary {numberDetails}") sorted_numberDetails=dict(sorted(numberDetails.items())) print(sorted_numberDetails.items()) with open("log1.txt","w") as f: for key,value in sorted_numberDetails.items(): f.write(f"{key} : {value}\n")

# Original dictionary

my_dict = {'banana': 3, 'apple': 1, 'pear': 2}

# Convert dictionary to a list of tuples (key-value pairs)

items = my_dict.items()

# Sort the list of tuples by key

sorted_items = sorted(items)

# Convert the sorted list of tuples back to a dictionary

sorted_dict = dict(sorted_items)

print("Sorted by keys:", sorted_dict)

3. Q3: Create a Python program that: - Prompts the user for the name,

age, and marks of multiple students (marks should be stored as a list). -

Store this information in a dictionary where the keys are the student names

and the values are tuples containing the age and marks. - Calculate the

average marks for each student using a loop and store students with

averages above 75 in a set. - Write the names of these high-scoring students

to a file and display the file content on the console.

names=[] ages=[]

for item in odd: file.write(str(item)) file.write("\n") for item in even: file.write(str(item)) file.write("\n") def evensum(even): if not(even): return 0 return even.pop()+evensum(even) sum=evensum(even.copy()) print(f"Sum is {sum} ")

5. Q5: Write a Python program where: - You define a function that takes a

list of words and returns a dictionary where the keys are the words and the

values are the length of each word. - Prompt the user for a sentence, split it

into words, and pass the list of words to the function. - Save the dictionary to

a file, and then read it back and print the contents in alphabetical order of

the words.

def listTOdictionary(wordlist): dict={} for word in wordlist : wordlength=len(word) dict[word]=wordlength return dict Sentence=input(" Enter Sentence \n") wordlist=Sentence.split(" ") mydict=listTOdictionary(wordlist) with open("data.txt","w") as fileofdata: for key in mydict: fileofdata.write(f"{key} {mydict[key]}\n") newdict={} with open("data.txt","r") as fileofdata: read=fileofdata.readline() while read!="": wordwithlen=read.split(" ") value=int(wordwithlen[ 1 ]) newdict[wordwithlen[ 0 ]]=value read=fileofdata.readline() print(newdict) sortdictionary=dict(sorted(newdict.items()))

print(sortdictionary) for keys in sortdictionary: print(F"{keys} : {sortdictionary[keys]}")

6. Q6: Create a class Person with attributes name, age, and address.

Then: - Create a subclass Employee that inherits from Person and adds an

attribute salary. - Create an object for Employee and store these objects in a

list. - Loop through the list and print the details of each employee who has a

salary greater than 50,000. - Save the list of such employees to a text file.

from random import randint class Person: def init(self,name,age,address): self.name=name self.age=age self.address=address def showdetails(self): print(f"name :{self.name}\n age : {self.age} \n address : {self.address}") class Empolyee(Person): def init(self, name, age, address,salary): super().init(name, age, address) self.salary=salary def showdetails(self): super().showdetails(self) print(f"salary :{self.salary}") def str(self): return f"name :{self.name}\n age : {self.age} \n address : {self.address} \n salary {self.salary}\n " listofEmpolyees=[] listofEmpolyees.append(Empolyee("Umar", 22 ," Ali town lahore",randint( 0 , 100000 ))) listofEmpolyees.append(Empolyee("Nimr", 21 ,"Town ship lahore",randint( 0 , 100000 ))) listofEmpolyees.append(Empolyee("Hifza", 19 ,"model town lahore",randint( 0 , 100000 ))) for empolyee in listofEmpolyees: if empolyee.salary> 50000 : print(empolyee) with open("data.txt","+a") as file: file.write(f"name :{empolyee.name}\n age : {empolyee.age} \n address : {empolyee.address} \n salary {empolyee.salary}")

appeared in the original string. - Write the dictionary to a file and print the

unique characters in reverse order.

characters=input("Enter : ") uniqueCharacter=set() uniqueCharacter=set(characters) uniqueCharacterlist=[] uniqueCharacterlist=list(uniqueCharacter) uniqueCharacterlist.sort() characterFruequency={} for element in uniqueCharacterlist: frequency=characters.count(element) characterFruequency[element]=frequency print(characterFruequency) with open("data.txt","w") as file: for key,value in characterFruequency.items(): file.write(f"{key} {value}\n") print(uniqueCharacterlist[::- 1 ])

9. Q9: Implement a Python script where: - You define a function that

takes a dictionary of student names and their scores. - The function should

return a list of students who have scores above the class average. - Store

this list of high scorers in a tuple, then write the tuple to a file. - After writing,

read the file and display the high scorers in alphabetical order

from random import randint def student_Scores(results): add=0. length=len(results) for key in results: add+=results[key] average=add/length top_achievers=[] for student in results: if results[student] > average : top_achievers.append(student) return top_achievers studentdata={} for i in range( 0 , 4 ): name=input("Enter : ") studentdata[name]=randint( 0 , 100 ) toppers=tuple(student_Scores(studentdata)) print(studentdata)

with open("data.txt","w") as studentrecord: for item in toppers: studentrecord.write(f"{item}\n") names=[] with open("data.txt") as studentrecord: names=studentrecord.readlines() alphabeticsortednames=[] for item in names: alphabeticsortednames.append(item.strip("\n")) alphabeticsortednames.sort() print(alphabeticsortednames)

. 10. Q10: Create a Python program that: - Prompts the user to enter

multiple sentences. - Split the sentences into words and store the words in a

list. - Find and print the longest word and the word with the highest

frequency using a loop and conditional expressions. - Write the longest word

and most frequent word to a file along with their respective lengths and

frequencies

Sentences=[] for i in range( 0 , 3 ): Sentences.append(input(" ENTER : ")) words=[[],[],[]] words[ 0 ]=Sentences[ 0 ].split(" ") words[ 1 ]=Sentences[ 1 ].split(" ") words[ 2 ]=Sentences[ 2 ].split(" ") longestlength= 0 print(words) for wordlist in words: for word in wordlist: if longestlength<len(word): longestlength=len(word) longestword=word maximumFrequency= 0 maximumFrequencyword=None for wordlist in words: for word in wordlist: frequency= 0 for i in range( 0 ,len(words)): for oneword in words[i]: if word==oneword: frequency+= 1 if frequency>maximumFrequency: