0% found this document useful (0 votes)
3 views20 pages

Python Code Explanations

The document provides explanations and code solutions for 25 Python programming problems, covering various topics such as counting word lengths, finding duplicates, and filtering dictionary keys. Each problem is accompanied by a breakdown of the code, its functionality, and step-by-step explanations. The document serves as a comprehensive guide for understanding and implementing these coding challenges.

Uploaded by

rithmadaham53
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)
3 views20 pages

Python Code Explanations

The document provides explanations and code solutions for 25 Python programming problems, covering various topics such as counting word lengths, finding duplicates, and filtering dictionary keys. Each problem is accompanied by a breakdown of the code, its functionality, and step-by-step explanations. The document serves as a comprehensive guide for understanding and implementing these coding challenges.

Uploaded by

rithmadaham53
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

■ Python Code

Explanations & Answers


Problems 1 – 25 | Word-by-Word Breakdown

Problem Topic

1 Count word lengths

2 Find duplicate letters

4 Count digit occurrences

5 Find shortest word(s)

6 Count words by length

7 Filter long dictionary keys

8 Count uppercase values

9 Reverse dictionary values

10 Names older than 25

11 Cities ending in "y"

12 Group words by last letter

13 Even/Odd + Positive/Negative/Zero

14 Count consonants (for & while)

15 Reverse string (while loop)

16 Vowel/consonant first letter

17 Names where consonants > vowels

18 Consonant count per word → dict

19 Above average score/height

20 Check all letters unique

21 Vowel AND no repeated letters

22 Label prices low/high

23 Word with most vowels


24 Upper/Lower/Mixed case

25 Palindrome count (for & while)


Problem 1 — Count Word Lengths
items = ["cat", "dog", "tree", "book", "pen"]
result = {}

for item in items:


length = len(item)
if length in result:
result[length] += 1
else:
result[length] = 1
print(result)

What it does:
Counts how many words share each length and stores the count in a dictionary.

Word-by-Word Explanation:

Code Meaning

items = [...] Create a list of words

result = {} Create an empty dictionary to store answers

for item in items Go through each word one by one

length = len(item) Count how many letters are in the word

if length in result Check if that length already exists as a key

result[length] += 1 If yes → add 1 to its count

result[length] = 1 If no → create it and set count to 1

print(result) Show the final answer

Step-by-Step:
"cat" → length 3 → result={3:1}
"dog" → length 3 → result={3:2}
"tree" → length 4 → result={3:2, 4:1}
"book" → length 4 → result={3:2, 4:2}
"pen" → length 3 → result={3:3, 4:2}

Output: {3: 3, 4: 2}

Problem 2 — Find Duplicate Letters


items = "programming"

def count_letters(item):
seen = set()
result = []
for item_1 in item:
if item_1 in seen:
[Link](item_1)
else:
[Link](item_1)
return result
print(count_letters(items))

What it does:
Returns letters that appear more than once in a word.

Word-by-Word Explanation:

Code Meaning

items = "programming" The word we are checking

def count_letters(item) Define a function that takes a word as input

seen = set() Empty set to remember letters already visited

result = [] Empty list to store duplicate letters

for item_1 in item Go through each letter one by one

if item_1 in seen If we already saw this letter before...

[Link](item_1) ...add it to result (it is a duplicate)

else: [Link](item_1) First time seeing it → remember it in seen

return result Send back the list of duplicates

Step-by-Step:
'p' → not seen → seen={'p'}
'r' → not seen → seen={'p','r'}
'o' → not seen → seen adds 'o'
'g' → not seen → seen adds 'g'
'r' → IN seen! → result=['r']
'm' → not seen → seen adds 'm'
'm' → IN seen! → result=['r','m']
'g' → IN seen! → result=['r','m','g']

Output: ['r', 'm', 'g']

Problem 4 — Count Digit Occurrences


mystrings = "a1b22c3"
seen = set()
result = {}

def count_number(mystring):
for mystring_1 in mystring:
if mystring_1.isdigit():
if mystring_1 in seen:
result[mystring_1] += 1
else:
result[mystring_1] = 1
[Link](mystring_1)
return result
print(count_number(mystrings))

What it does:
Counts how many times each digit appears in a mixed string.

Code Meaning

mystrings = "a1b22c3" A mixed string of letters and numbers

seen = set() Remember which digits have been seen

result = {} Empty dictionary to count each digit

for mystring_1 in mystring Go through every character one by one

if mystring_1.isdigit() Check if the character is a number (skip letters)

if mystring_1 in seen If we saw this digit before...

result[mystring_1] += 1 ...add 1 to its count

else: result[...] = 1 First time → start count at 1

[Link](mystring_1) Remember we have now seen this digit

Step-by-Step:
'a' → not a digit → skip
'1' → digit, new → result={'1':1}
'b' → not a digit → skip
'2' → digit, new → result={'1':1,'2':1}
'2' → digit, seen! → result={'1':1,'2':2}
'c' → not a digit → skip
'3' → digit, new → result={'1':1,'2':2,'3':1}
Problem 5 — Find Shortest Word(s)
mystrings = "this is an simple test test"
result = []
mystrings = [Link]()

def shortest_count(mystring):
shortest_len_word = len(mystring[0])
for mystring_1 in mystring:
if shortest_len_word > len(mystring_1):
shortest_len_word = len(mystring_1)
for mystring_1 in mystring:
if shortest_len_word == len(mystring_1):
[Link](mystring_1)
return result
print(shortest_count(mystrings))

What it does:
Finds all words that are the shortest in a sentence. Uses two loops — first to find the length, second to collect
words.

Code Meaning

[Link]() Breaks sentence into a list of words

shortest_len_word = len(mystring[0]) Assume the first word is the shortest

First for loop Find the actual shortest length

if shortest_len_word > len(...) If current word is shorter than assumed shortest...

shortest_len_word = len(...) ...update to this smaller length

Second for loop Collect ALL words matching the shortest length

[Link](mystring_1) Add the matching word to result


Output: ['is', 'an']

Problem 6 — Count Words by Length


mystrings = "hi hello hi cat"
mystrings = [Link]()
result = {}

def count_words(mystring):
for mystring_1 in mystring:
if len(mystring_1) in result:
result[len(mystring_1)] += 1
else:
result[len(mystring_1)] = 1
return result
print(count_words(mystrings))

What it does:
Groups and counts words by their length.

Code Meaning

[Link]() Turns sentence into list of words

for mystring_1 in mystring Go through each word

len(mystring_1) Get the length of the word

if len(...) in result If this length already has a count...

result[len(...)] += 1 ...add 1

else: result[...] = 1 Otherwise start at 1

Step-by-Step:
'hi' → len 2 → result={2:1}
'hello' → len 5 → result={2:1,5:1}
'hi' → len 2 → result={2:2,5:1}
'cat' → len 3 → result={2:2,5:1,3:1}

Problem 7 — Filter Long Dictionary Keys


mydicts = {"apple": 2, "banana": 3, "kiwi": 1, "grapefruit": 4}
result = {}

def dict_count(mydict):
for key, value in [Link]():
if len(key) > 5:
result[key] = value
return result
print(dict_count(mydicts))

What it does:
Keeps only items whose key (word) has more than 5 characters.

Code Meaning

for key, value in [Link]() Loop through every key-value pair

if len(key) > 5 If the key has more than 5 letters...

result[key] = value ...copy it into result


Output: {'banana': 3, 'grapefruit': 4}
Problem 8 — Count Fully Uppercase Values
mydicts = {"a": "HELLO", "b": "World", "c": "TEST"}

def count_upper(mydict):
count = 0
for key, value in [Link]():
if [Link]():
count += 1
return count
print(count_upper(mydicts))

Code Meaning

count = 0 Start counter at zero

for key, value in [Link]() Go through each key-value pair

[Link]() Check if ALL letters in value are uppercase

count += 1 If yes → add 1 to counter

return count Return the final count


"HELLO" → all uppercase → count=1 | "World" → has lowercase → skip | "TEST" → all uppercase → count=2
Output: 2

Problem 9 — Reverse Dictionary Values


mydicts = {"a": "cat", "b": "dog"}
result = {}

def reverse_words(mydict):
for key, value in [Link]():
value = value[::-1]
result[key] = value
return result
print(reverse_words(mydicts))

Code Meaning

for key, value in [Link]() Go through each pair

value[::-1] Reverse the string ([::-1] reads backwards)

result[key] = value Store the reversed word with the same key
"cat" → [::-1] → "tac" | "dog" → [::-1] → "god"
Output: {'a': 'tac', 'b': 'god'}

Problem 10 — Names of People Older Than 25


listofdicts = [{"name": "Ann", "age": 22}, {"name": "Bob", "age": 30}]
def age_count(listofdict):
mylist = []
for listofdict_1 in listofdict:
if listofdict_1.get("age", 0) > 25:
[Link](listofdict_1["name"])
return mylist
print(age_count(listofdicts))

Code Meaning

for listofdict_1 in listofdict Go through each dictionary in the list

.get("age", 0) Safely get the age value; if missing, use 0

> 25 Check if age is above 25

[Link](...["name"]) If yes → collect their name


Ann: 22 > 25? No → skip | Bob: 30 > 25? Yes → result=["Bob"]

Problem 11 — Count Cities Ending in 'y'


listofdicts = [{"name":"A","city":"Kandy"},{"name":"B","city":"Colombo"},{"name":"C","ci
ty":"Hackney"}]

def city_count(listofdict):
count = 0
for listofdict_1 in listofdict:
if listofdict_1.get("city")[-1:] == "y":
count += 1
return count
print(city_count(listofdicts))

Code Meaning

.get("city") Safely get the city value

[-1:] Get the last character of the city name

== "y" Check if it ends with the letter y

count += 1 If yes → add 1 to count


"Kandy" → ends y ✓ | "Colombo" → ends o → skip | "Hackney" → ends y ✓
Output: 2
Problem 12 — Group Words by Last Letter
mylists = ["cat", "bat", "dogs", "dig", "rat"]
result = {}

def group_words(mylist):
for mylist_1 in mylist:
last_letter = mylist_1[-1]
if last_letter not in result:
result[last_letter] = []
result[last_letter].append(mylist_1)
return result
print(group_words(mylists))

Code Meaning

mylist_1[-1] Get the last letter of the word

if last_letter not in result If this letter is not a key yet...

result[last_letter] = [] ...create an empty list for it

result[last_letter].append(...) Add the word under that letter key


Output: {'t': ['cat','bat','rat'], 's': ['dogs'], 'g': ['dig']}

Problem 13 — Even/Odd Split + Positive/Negative/Zero


# Part 1 — Even / Odd
mylists = [1, 2, 3, 4, 5]
result = {"even": [], "odd": []}

def even_odd_count(mylist):
for mylist_1 in mylist:
if mylist_1 % 2 == 0:
result["even"].append(mylist_1)
else:
result["odd"].append(mylist_1)
return result

# Part 2 — Positive / Negative / Zero


mylists = [3, -1, 0, 4, -5, 0, 2]
result = {"positive": [], "negative": [], "zero": []}

def sign_count(mylist):
for mylist_1 in mylist:
if mylist_1 > 0:
result["positive"].append(mylist_1)
elif mylist_1 == 0:
result["zero"].append(mylist_1)
else:
result["negative"].append(mylist_1)
return result

Code Meaning
result = {"even":[],"odd":[]} Dictionary with two empty lists

mylist_1 % 2 == 0 % gives remainder; if 0 → even number

result["even"].append(...) Add to even list

> 0 Greater than zero → positive

== 0 Exactly zero

else Must be negative (less than 0)

Problem 14 — Count Consonants (for & while loop)


# For loop version
def constant_letters(mystring):
vowels = ["a","e","i","o","u"]
count = 0
for mystring_1 in mystring:
if mystring_1 not in vowels:
count += 1
return count

# While loop version


def constant_count(word):
index = 0
constant_count = 0
vowels = ["a","e","i","o","u"]
while index < len(word):
letter = word[index]
if letter not in vowels:
constant_count += 1
index += 1
return constant_count

Code Meaning

vowels = ["a","e","i","o","u"] List of all vowels

if mystring_1 not in vowels If letter is NOT a vowel → it is a consonant

count += 1 Add 1 to consonant count

index = 0 While loop starts at position 0

word[index] Gets letter at current position

index += 1 Move to next letter

while index < len(word) Keep going until end of word


Both versions do the same thing — the while loop manually tracks position using index.
Problem 15 — Reverse String (while loop)
mystrings = "hello"

def reverse_string(mystring):
index = 0
while index < len(mystring):
reverse = mystring[::-1]
index += 1
print(reverse)

reverse_string(mystrings)

Code Meaning

index = 0 Start at position 0

while index < len(mystring) Loop until we pass the last letter

mystring[::-1] Reverse the entire string

index += 1 Move forward (loop eventually stops)

■■ Note: mystring[::-1] runs every loop but only needs to run once. The while loop here is unnecessary — but the
result is still correct.

Output: 'olleh'

Problem 16 — Vowel/Consonant First Letter Count


mylists = ["apple", "banana", "orange", "grape"]
result = {"vowels": 0, "consonant": 0}

def letter_count(mylist):
vowels = ["a","e","i","o","u"]
for mylist_1 in mylist:
if mylist_1[0] in vowels:
result["vowels"] += 1
else:
result["consonant"] += 1
return result
print(letter_count(mylists))

Code Meaning

mylist_1[0] Get only the first letter of the word

if mylist_1[0] in vowels If first letter is a vowel...

result["vowels"] += 1 ...count it as vowel word

else Otherwise first letter is a consonant


"apple" → a → vowel | "banana" → b → consonant | "orange" → o → vowel | "grape" → g → consonant
Output: {'vowels': 2, 'consonant': 2}
Problem 17 — Names Where Consonants > Vowels
mydicts = {"Ann": "idea", "Bob": "strong", "Alice": "washroom"}
result = []

def constant_comparison(mydict):
constant_count = 0
vowel_count = 0
vowel = ["a","e","i","o","u"]
for key, value in [Link]():
for letter in value:
if letter in vowel:
vowel_count += 1
else:
constant_count += 1
if vowel_count < constant_count:
[Link](key)
return result
print(constant_comparison(mydicts))

Code Meaning

for key, value in [Link]() Go through name and their word

for letter in value Check each letter in the word

if letter in vowel If letter is a vowel → add to vowel count

else: constant_count += 1 Otherwise → add to consonant count

if vowel_count < constant_count If consonants beat vowels...

[Link](key) ...collect the name

■■ Bug: vowel_count and constant_count are not reset per word — they accumulate across all words. Reset
them inside the outer loop for correct results.
Problem 18 — Consonant Count Per Word → Dictionary
mystrings = "apple sky banana"
mystrings = [Link]()
result = {}

def dict_count(mystring):
vowels = ["a","e","i","o","u"]
for mystring_1 in mystring:
count = 0
for value in mystring_1:
if value not in vowels:
count += 1
result[mystring_1] = count
return result
print(dict_count(mystrings))

Code Meaning

[Link]() Break sentence into list of words

count = 0 Reset consonant count for each word

for value in mystring_1 Check each letter in the word

if value not in vowels If not a vowel → it is a consonant

count += 1 Add to consonant count

result[mystring_1] = count Store word → consonant count in dictionary

■■ Minor Bug: result[mystring_1] = count is inside the inner loop — it should be outdented one level. The final
answer is still correct because it overwrites each time.

Output: {'apple': 3, 'sky': 2, 'banana': 3}

Problem 19 — Names Above Average Score / Height


dictlists = [{"name":"Ann","score":80},{"name":"Bob","score":60},{"name":"Cara","score":
90}]
result = []

def average_score(dictlist):
total = 0
for dictlist_1 in dictlist:
total += dictlist_1["score"]
count = len(dictlist)
avg = total / count
for dictlist_1 in dictlist:
if avg < dictlist_1["score"]:
[Link](dictlist_1["name"])
return result
print(average_score(dictlists))

Code Meaning
total += dictlist_1["score"] Add each persons score to total

len(dictlist) Count how many people there are

avg = total / count Calculate the average

if avg < dictlist_1["score"] If persons score is above average...

[Link](...["name"]) ...collect their name

Step-by-Step:
Scores: 80, 60, 90
Total = 230, Count = 3, Average = 76.6
80 > 76.6 → Ann ✓
60 > 76.6 → skip
90 > 76.6 → Cara ✓

Output: ['Ann', 'Cara']

Problem 20 — Check All Letters Are Unique


def repeated_letters(user_input):
seen = set()
for userinput_1 in user_input:
if userinput_1 not in seen:
[Link](userinput_1)
else:
return False
return True

user_inputs = input("Enter a word: ")


result = repeated_letters(user_inputs)
print(result)

Code Meaning

seen = set() Empty set to track letters seen

for userinput_1 in user_input Check each letter

if userinput_1 not in seen First time seeing this letter...

[Link](userinput_1) ...remember it

else: return False Seen before → duplicate found → return False

return True No duplicates found → return True


Returns True if all letters are unique, False if any letter repeats.
Problem 21 — Words With a Vowel AND No Repeated Letters
mylists = ["lamp", "sky", "moon", "idea","man","trainee"]
result = []

def question_count(mylist):
vowels = ["a","e","i","o","u"]
for mylist_1 in mylist:
vowel_count = False
repeated_count = False
seen = set()
for mylist_2 in mylist_1:
if mylist_2 in vowels:
vowel_count = True
if mylist_2 in seen:
repeated_count = True
else:
[Link](mylist_2)
if vowel_count == True and repeated_count == False:
[Link](mylist_1)
return result
print(question_count(mylists))

Code Meaning

vowel_count = False Assume no vowel found yet

repeated_count = False Assume no repeated letter yet

seen = set() Fresh set for EACH word

if mylist_2 in vowels Found a vowel → flag it True

if mylist_2 in seen Letter appeared before → flag repeat True

else: [Link](mylist_2) New letter → remember it

Has vowel AND no repeats → keep the word


if vowel_count==True and repeated_count==False

Output: ['lamp', 'idea', 'man'] (moon has repeated 'o', trainee has repeats too)

Problem 22 — Label Prices as Low / High


mydicts = {"pen": 50, "book": 150, "bag": 200}
result = {}

def price_count(mydict):
for key, value in [Link]():
if value < 100:
result[key] = "low"
else:
result[key] = "high"
return result
print(price_count(mydicts))

Code Meaning
for key, value in [Link]() Go through each item and its price

if value < 100 If price is below 100...

result[key] = "low" ...label it "low"

else: result[key] = "high" Otherwise label it "high"


Output: {'pen': 'low', 'book': 'high', 'bag': 'high'}

Problem 23 — Word With Most Vowels


mystrings = "sky education apple idea"
mystrings = [Link]()

def vowel_question(mystring):
vowels = ["a","e","i","o","u"]
best_word = ""
best_count = 0
for mystring_1 in mystring:
vowel_count = 0
for mystring_2 in mystring_1:
if mystring_2 in vowels:
vowel_count += 1
if vowel_count > best_count:
best_count = vowel_count
best_word = mystring_1
return best_word, best_count
print(vowel_question(mystrings))

Code Meaning

best_word = "" Start with no best word

best_count = 0 Start with 0 vowels as best

vowel_count = 0 Reset vowel count per word

for mystring_2 in mystring_1 Check each letter in the word

if mystring_2 in vowels If it is a vowel → add 1

if vowel_count > best_count If this word has MORE vowels than previous best...

best_count = vowel_count ...update best count

best_word = mystring_1 ...update best word

return best_word, best_count Return the winner and its vowel count
Output: ('education', 5)
Problem 24 — Classify Upper / Lower / Mixed Case
mylists = ["HELLO", "world", "PyThOn", "CODE"]
result = {"uppercase": [], "lowercase": [], "mixed": []}

def case_question(mylist):
for mylist_1 in mylist:
if mylist_1.isupper():
result["uppercase"].append(mylist_1)
elif mylist_1.islower():
result["lowercase"].append(mylist_1)
else:
result["mixed"].append(mylist_1)
return result
print(case_question(mylists))

Code Meaning

.isupper() True if ALL letters are uppercase

.islower() True if ALL letters are lowercase

else Neither all-upper nor all-lower → mixed case


"HELLO" → isupper ✓ | "world" → islower ✓ | "PyThOn" → mixed | "CODE" → isupper ✓
Output: {'uppercase': ['HELLO','CODE'], 'lowercase': ['world'], 'mixed': ['PyThOn']}

Problem 25 — Palindrome Count (while & for loop)


# While loop version
mylists = ["madam", "apple", "radar", "tree"]
result = {"palindrome": 0, "non-palindrome": 0}

def palindrome_count(mylist):
count = 0
while count < len(mylist):
word = mylist[count]
if word[::-1] == word:
result["palindrome"] += 1
else:
result["non-palindrome"] += 1
count += 1
return result

# For loop version


mylists = ["level", "test", "deed", "code", "noon"]
result = {"palindrome": 0, "non-palindrome": 0}

def palindrome_count(mylist):
for mylist_1 in mylist:
if mylist_1[::-1] == mylist_1:
result["palindrome"] += 1
else:
result["non-palindrome"] += 1
return result

Code Meaning

count = 0 Start at first word (index 0)

while count < len(mylist) Keep going until past last word

mylist[count] Get word at current position

word[::-1] == word Reverse the word and check if same as original

count += 1 Move to next word

for mylist_1 in mylist Simpler version — directly goes through each word

Palindrome Examples:
"madam" → reversed="madam" ✓ → palindrome
"apple" → reversed="elppa" ✗ → not palindrome
"radar" → reversed="radar" ✓ → palindrome
"level" → reversed="level" ✓ → palindrome
"deed" → reversed="deed" ✓ → palindrome
Key Python Concepts Summary

Concept Simple Meaning

for x in list Do something for each item in the list

while condition Keep doing until the condition becomes false

if / elif / else Make a decision based on a condition

dict[key] += 1 Add 1 to a counter stored in a dictionary

[Link](x) Add an item to the end of a list

[Link](x) Remember an item (sets have no duplicates)

x in set Check if an item exists in a set

[::-1] Reverse a string or list

.split() Break a sentence into a list of words

.isdigit() Check if a character is a number (0-9)

.isupper() / .islower() Check if all letters are uppercase / lowercase

len(x) Count the length of a string or list

% 2 == 0 Check if a number is even (remainder is 0)

.get(key, default) Safely get a value from a dict without error

You might also like