0% found this document useful (0 votes)
21 views12 pages

Chapter 8 Advanced Python Programs

The document provides multiple Python programs that demonstrate various functionalities, including removing duplicates from a list, finding the longest word in a list, removing the ith occurrence of a word, filtering tuples based on a range, and manipulating strings. Each program includes a problem description, solution steps, source code, and runtime test cases. The examples cover a range of topics suitable for learning Python programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views12 pages

Chapter 8 Advanced Python Programs

The document provides multiple Python programs that demonstrate various functionalities, including removing duplicates from a list, finding the longest word in a list, removing the ith occurrence of a word, filtering tuples based on a range, and manipulating strings. Each program includes a problem description, solution steps, source code, and runtime test cases. The examples cover a range of topics suitable for learning Python programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Leela Soft 1000 MCQ Programs Madhu

Enter the number of elements in list:3


Enter element1:56
Enter element2:34
Enter element3:78
New list is:
[78, 34, 56]

Python Program to Remove the Duplicate Items from a List


Problem Description
The program takes a lists and removes the duplicate items from the list.

Problem Solution
1. Take the number of elements in the list and store it in a variable.
2. Accept the values into the list using a for loop and insert them into the list.
3. Use a for loop to traverse through the elements of the list.
4. Use an if statement to check if the element is already there in the list and if it is not there,
append it to another list.
5. Print the non-duplicate items of the list.
6. Exit.

Program/Source Code
Here is source code of the Python Program to remove the duplicate items from a list. The program
output is also shown below.

a=[]
n= int(input("Enter the number of elements in list:"))
for x in range(0,n):
element=int(input("Enter element" + str(x+1) + ":"))
a.append(element)
b = set()
unique = []
for x in a:
if x not in b:
unique.append(x)
b.add(x)
print("Non-duplicate items:")
print(unique)

Program Explanation
1. User must enter the number of elements in the list and store it in a variable.
2. User must enter the values of elements into the list.

www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft 1000 MCQ Programs Madhu

3. The append function obtains each element from the user and adds the same to the end
of the list as many times as the number of elements taken.
4. The for loop basically traverses through the elements of the list and the if statement
checks if the element is a duplicate or not.
5. If the element isn’t a duplicate, it is added into another list.
6. The list containing non-duplicate items is then displayed.

Runtime Test Cases

Case 1:
Enter the number of elements in list:5
Enter element1:10
Enter element2:10
Enter element3:20
Enter element4:20
Enter element5:20
Non-duplicate items:
[10, 20]

Case 2:
Enter the number of elements in list:7
Enter element1:10
Enter element2:20
Enter element3:20
Enter element4:30
Enter element5:40
Enter element6:40
Enter element7:50
Non-duplicate items:
[10, 20, 30, 40, 50]

Python Program to Read a List of Words and Return the Length of the Longest One
Problem Description
The program takes a list of words and returns the word with the longest length.

Problem Solution
1. Take the number of elements in the list and store it in a variable.
2. Accept the values into the list using a for loop and insert them into the list.
3. First assume that the first element is the word with the longest length.
4. Then using a for loop and if statement, compare the lengths of the words in the list with
the first element.

www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft 1000 MCQ Programs Madhu

5. Store the name of the word with the longest length in a temporary variable.
6. Display the word with the longest length
7. Exit.

Program/Source Code
Here is source code of the Python Program to read a list of words and return the length of the
longest one. The program output is also shown below.

a=[]
n= int(input("Enter the number of elements in list:"))
for x in range(0,n):
element=input("Enter element" + str(x+1) + ":")
a.append(element)
max1=len(a[0])
temp=a[0]
for i in a:
if(len(i)>max1):
max1=len(i)
temp=i
print("The word with the longest length is:")
print(temp)
Program Explanation
1. User must enter the number of elements in the list and store it in a variable.
2. User must enter the values of elements into the list.
3. The append function obtains each element from the user and adds the same to the end
of the list as many times as the number of elements taken.
4. Assuming that the first element in the list has the longest length, its length is stored in a
variable to be compared with other lengths later in the program.
5. Based on the above assumption, the first element is also copied to a temporary variable.
6. The for loop is used to traverse through the elements in the list.
7. The if statement then compares the lengths of other elements with the length of the first
element in the list.
8. If the length of a particular word is the largest, that word is copied to the temporary
variable.
9. The word with the longest length is printed.

Runtime Test Cases

Case 1:
Enter the number of elements in list:4
Enter element1:"Apple"

www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft 1000 MCQ Programs Madhu

Enter element2:"Ball"
Enter element3:"Cat"
Enter element4:"Dinosaur"
The word with the longest length is:
Dinosaur

Case 2:
Enter the number of elements in list:3
Enter element1:"Bangalore"
Enter element2:"Mumbai"
Enter element3:"Delhi"
The word with the longest length is:
Bangalore

Python Program to Remove the ith Occurrence of the Given Word in a List where Words can
Repeat
Problem Description
The program takes a list and removes the ith occurrence of the given word in the list where words
can repeat.

Problem Solution
1. Take the number of elements in the list and store it in a variable.
2. Accept the values into the list using a for loop and insert them into the list.
3. Use a for loop to traverse through the elements in the list.
4. Then use an if statement to check if the word to be removed matches the element and
the occurrence number and otherwise it appends the element to another list.
5. The number of repetitions along with the updated list and distinct elements is printed.
6. Exit.

Program/Source Code
Here is source code of the Python Program to remove the ith occurrence of the given word in list
where words can repeat. The program output is also shown below.

a=[]
n= int(input("Enter the number of elements in list:"))
for x in range(0,n):
element=input("Enter element" + str(x+1) + ":")
a.append(element)
print(a)
c=[]
count=0

www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft 1000 MCQ Programs Madhu

b=input("Enter word to remove: ")


n=int(input("Enter the occurrence to remove: "))
for i in a:
if(i==b):
count=count+1
if(count!=n):
c.append(i)
else:
c.append(i)
if(count==0):
print("Item not found ")
else:
print("The number of repetitions is: ",count)
print("Updated list is: ",c)
print("The distinct elements are: ",set(a))

Program Explanation
1. User must enter the number of elements in the list and store it in a variable.
2. User must enter the values of elements into the list.
3. The append function obtains each element from the user and adds the same to the end
of the list as many times as the number of elements taken.
4. User must enter the word and the occurrence of the word to remove.
5. A for loop is used to traverse across the elements in the list.
6. An if statement then checks whether the element matches equal to the word that must
be removed and whether the occurrence of the element matches the occurrence to be removed.
7. If both aren’t true, the element is appended to another list.
8. If only the word matches, the count value is incremented.
9. Finally the number of repetitions along with the updated list and the distinct elements is
printed.

Runtime Test Cases

Case 1:
Enter the number of elements in list:5
Enter element1:"apple"
Enter element2:"apple"
Enter element3:"ball"
Enter element4:"ball"
Enter element5:"cat"
['apple', 'apple', 'ball', 'ball', 'cat']
Enter word to remove: "ball"

www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft 1000 MCQ Programs Madhu

Enter the occurence to remove: 2


('The number of repitions is: ', 2)
('Updated list is: ', ['apple', 'apple', 'ball', 'cat'])
('The distinct elements are: ', set(['ball', 'apple', 'cat']))

Case 2:
Enter the number of elements in list:6
Enter element1:"A"
Enter element2:"B"
Enter element3:"A"
Enter element4:"A"
Enter element5:"C"
Enter element6:"A"
['A', 'B', 'A', 'A', 'C', 'A']
Enter word to remove: "A"
Enter the occurence to remove: 3
('The number of repitions is: ', 4)
('Updated list is: ', ['A', 'B', 'A', 'C', 'A'])
('The distinct elements are: ', set(['A', 'C', 'B']))

Python Program to Remove All Tuples in a List of Tuples with the USN Outside the Given Range
Problem Description
The program removes all tuples in a list of tuples with the USN outside the given range.

Problem Solution
1. Take in the lower and upper roll number from the user.
2. Then append the prefixes of the USN’s to the roll numbers.
3. Using list comprehension, find out which USN’s lie in the given range.
4. Print the list containing the tuples.
5. Exit.

Program/Source Code
Here is source code of the Python Program to remove all tuples in a list of tuples with the USN
outside the given range. The program output is also shown below.

y=[('a','12CS039'),('b','12CS320'),('c','12CS055'),('d','12CS100')]
low=int(input("Enter lower roll number (starting with 12CS):"))
up=int(input("Enter upper roll number (starting with 12CS):"))
l='12CS0'+str(low)
u='12CS'+str(up)
p=[x for x in y if x[1]>l and x[1]<u]

www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft 1000 MCQ Programs Madhu

print(p)

Program Explanation
1. User must enter the upper and lower roll number.
2. The prefixes are then appended to the roll numbers using the ‘+’ operator to form the
USN.
3. List comprehension is then used to find the USN’s within the upper and lower range.
4. The list containing USN’s in the given range is then printed.

Runtime Test Cases

Case 1:
Enter lower roll number (starting with 12CS):50
Enter upper roll number (starting with 12CS):150
[('c', '12CS055'), ('d', '12CS100')]

4. Python Programming Examples on Strings


Python Program to Replace all Occurrences of ‘a’ with $ in a String
Problem Description
The program takes a string and replaces all occurrences of ‘a’ with ‘$’.

Problem Solution
1. Take a string and store it in a variable.
2. Using the replace function, replace all occurrences of ‘a’ and ‘A’ with ‘$’ and store it back
in the variable.
3. Print the modified string.
4. Exit.

string=input("Enter string:")
string=string.replace('a','$')
string=string.replace('A','$')
print("Modified string:")
print(string)

Runtime Test Cases


Case 1:

www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft 1000 MCQ Programs Madhu

Enter string:Apple
Modified string:
$pple

Case 2:
Enter string:Asia
Modified string:
$si$

Python Program to Remove the nth Index Character from a Non-Empty String
Problem Description
The program takes a string and removes the nth index character from the non-empty string.

Problem Solution
1. Take a string from the user and store it in a variable.
2. Take the index of the character to remove.
3. Pass the string and the index as arguments to a function named remove.
4. In the function, the string should then be split into two halves before the index character
and after the index character.
5. These two halves should then be merged together.
6. Print the modified string.
7. Exit.

def remove(string, n):


first = string[:n]
last = string[n+1:]
return first + last
string=input("Enter the sring:")
n=int(input("Enter the index of the character to remove:"))
print("Modified string:")
print(remove(string, n))

Runtime Test Cases


Case 1:
Enter the sring:Hello
Enter the index of the character to remove:3
Modified string:
Helo

www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft 1000 MCQ Programs Madhu

Case 2:
Enter the sring:Checking
Enter the index of the character to remove:4
Modified string:
Checing

Python Program to Detect if Two Strings are Anagrams


Problem Description
The program takes two strings and checks if the two strings are anagrams.

Anagrams:
A word, phrase, or name formed by rearranging the letters of another, such as cinema, formed
from iceman.

Problem Solution
1. Take two strings from the user and store them in separate variables.
2. Then use sorted() to sort both the strings into lists.
3. Compare the sorted lists and check if they are equal.
4. Print the final result.
5. Exit.

s1=input("Enter first string:")


s2=input("Enter second string:")
if(sorted(s1)==sorted(s2)):
print("The strings are anagrams.")
else:
print("The strings aren't anagrams.")

Program Explanation
1. User must enter both the strings and store them in separate variables.
2. The characters of both the strings are sorted into separate lists.
3. They are then checked whether they are equal or not using an if statement.
4. If they are equal, they are anagrams as the characters are simply jumbled in anagrams.
5. If they aren’t equal, the strings aren’t anagrams.
6. The final result is printed.

Runtime Test Cases


Case 1:
Enter first string:anagram

www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft 1000 MCQ Programs Madhu

Enter second string:nagaram


The strings are anagrams.

Case 2:
Enter first string:hello
Enter second string:world
The strings aren't anagrams.

Python Program to Form a New String where the First Character and the Last Character have
been Exchanged
Problem Description
The program takes a string and swaps the first character and the last character of the string.

Problem Solution
1. Take a string from the user and store it in a variable.
2. Pass the string as an argument to a function.
3. In the function, split the string.
4. Then add the last character to the middle part of the string which is in turn added to the
first character.
5. Print the modified string.
6. Exit.

def change(string):
return string[-1:] + string[1:-1] + string[:1]
string=input("Enter string:")
print("Modified string:")
print(change(string))

Program Explanation
1. User must enter a string and store it in a variable.
2. This string is passed as an argument to a function.
3. In the function, using string slicing, the string is first split into three parts which is the last
character, middle part and the first character of the string.
4. These three parts are then concatenated using the ‘+’ operator.
5. The modified string is then printed.

Runtime Test Cases


Case 1:
Enter string:abcd

www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft 1000 MCQ Programs Madhu

Modified string:
dbca

Case 2:
Enter string:hello world
Modified string:
dello worlh

Python Program to Count the Number of Vowels in a String


Problem Description
The program takes a string and counts the number of vowels in a string.

Problem Solution
1. Take a string from the user and store it in a variable.
2. Initialize a count variable to 0.
3. Use a for loop to traverse through the characters in the string.
4. Use an if statement to check if the character is a vowel or not and increment the count
variable if it is a vowel.
5. Print the total number of vowels in the string.
6. Exit.

string=input("Enter string:")
vowels=0
for i in string:
if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E' or i=='I' or i=='O' or i=='U'):
vowels=vowels+1
print("Number of vowels are:")
print(vowels)

Program Explanation
1. User must enter a string and store it in a variable.
2. The count variable is initialized to zero.
3. The for loop is used to traverse through the characters in the string.
4. An if statement checks if the character is a vowel or not.
5. The count is incremented each time a vowel is encountered.
6. The total count of vowels in the string is printed.

Runtime Test Cases

www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft 1000 MCQ Programs Madhu

Case 1:
Enter string:Hello world
Number of vowels are:
3

Case 2:
Enter string:WELCOME
Number of vowels are:
3

Python Program to Take in a String and Replace Every Blank Space with Hyphen
Problem Description
The program takes a string and replaces every blank space with a hyphen.

Problem Solution
1. Take a string and store it in a variable.
2. Using the replace function, replace all occurrences of ‘ ‘ with ‘-‘ and store it back in the
variable.
3. Print the modified string.
4. Exit.

string=input("Enter string:")
string=string.replace(' ','-')
print("Modified string:")
print(string)

Program Explanation
1. User must enter the string and store it in a variable.
2. The replace function replaces all occurrences of ‘ ‘ with ‘-‘ and store it back in the same
variable.
3. The modified string is printed.

Runtime Test Cases

Case 1:
Enter string:hello world
Modified string:
hello-world

www.leelasoft.com Cell: 78 42 66 47 66

You might also like