48 set programs: creating sets, adding and removing items, union, intersection, difference, subsets and frozensets. Sets of strings have no fixed order, so these solutions print sorted(...) whenever the order would otherwise change from run to run.
Before you start
Read the Sets lesson first if the topic is new to you.
Write a Python program to sort the lines of a file by their length.
Output
x
short
medium line
a much longer line here
Approach
sorted(lines, key=len).
Solution
Python
withopen("story.txt","w")asf:f.write("medium line\nx\na much longer line here\nshort\n")withopen("story.txt")asf:lines=f.read().splitlines()forlineinsorted(lines,key=len):print(line)
Output
x
short
medium line
a much longer line here
Learn the concept
New to this topic? Read the lesson, then come back.
withopen("story.txt","w")asf:f.write("Python is a very good tool for test automation\n")withopen("story.txt")asf:print([wforwinf.read().split()iflen(w)<5])
Write a Python program to count the consonants in a file.
Output
16
Approach
Letters that are not vowels.
Solution
Python
withopen("story.txt","w")asf:f.write("Python file handling is easy\n")withopen("story.txt")asf:text=f.read().lower()print(sum(ch.isalpha()andchnotin"aeiou"forchintext))
Output
16
Learn the concept
New to this topic? Read the lesson, then come back.