Python · Syntax · Beginner
OOP, dictionaries, algorithmic thinking
Python exercises on OOP, dictionaries, and algorithmic thinking: classes for data analysis, counting words and characters, working with ratings, passwords, statistics, and dictionary transformations.
Quick topic start and explanations before exercises (exercises below):
Registry, counter, and aggregator patterns
#Dicts, sets, and class patterns quick reference
#Exercises:
WordCounter for text.
#class WordCounter:
pass
Solution
class WordCounter:
def __init__(self, text):
self.text = text
def count(self):
result = {}
words = self.text.split()
for w in words:
if w in result:
result[w] += 1
else:
result[w] = 1
return result
GradeBook grade journal.
#class GradeBook:
pass
Solution
class GradeBook:
def __init__(self):
self.data = {}
def add(self, name, grade):
if name not in self.data:
self.data[name] = []
self.data[name].append(grade)
def average(self, name):
grades = self.data.get(name, [])
if not grades:
return 0
return sum(grades) / len(grades)
Counting each letter.
#def letter_stats(text):
pass
Solution
def letter_stats(text):
result = {}
for ch in text:
if ch.isalpha():
ch = ch.lower()
if ch in result:
result[ch] += 1
else:
result[ch] = 1
return result
Checking password strength.
#class PasswordChecker:
pass
Solution
class PasswordChecker:
def check(self, password):
if len(password) < 8:
return False
has_digit = False
for ch in password:
if ch.isdigit():
has_digit = True
break
return has_digit
Product inventory.
#class Inventory:
pass
Solution
class Inventory:
def __init__(self):
self.items = {}
def add_item(self, name, count):
if name in self.items:
self.items[name] += count
else:
self.items[name] = count
def total_items(self):
total = 0
for c in self.items.values():
total += c
return total
Grouping words by length.
#def length_groups(words):
pass
Solution
def length_groups(words):
result = {}
for w in words:
l = len(w)
if l in result:
result[l] += 1
else:
result[l] = 1
return result
BankAccount without going negative.
#class BankAccount:
pass
Solution
class BankAccount:
def __init__(self, balance=0):
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount <= self.balance:
self.balance -= amount
return True
return False
Vowels and consonants.
#def vowels_and_consonants(text):
pass
Solution
def vowels_and_consonants(text):
vowels = "aeiouy"
result = {"vowels": 0, "consonants": 0}
for ch in text.lower():
if ch.isalpha():
if ch in vowels:
result["vowels"] += 1
else:
result["consonants"] += 1
return result
User registration.
#USERS = []
class UserRegistry:
pass
Solution
USERS = []
class UserRegistry:
def register(self, username):
if username in USERS:
return False
USERS.append(username)
return True
Classification of numbers.
#def number_summary(nums):
pass
Solution
def number_summary(nums):
result = {"positive": 0, "negative": 0, "zero": 0}
for n in nums:
if n > 0:
result["positive"] += 1
elif n < 0:
result["negative"] += 1
else:
result["zero"] += 1
return result
Shopping cart.
#class ShoppingCart:
pass
Solution
class ShoppingCart:
def __init__(self):
self.items = {}
def add(self, product, price):
self.items[product] = price
def total(self):
total = 0
for p in self.items.values():
total += p
return total
Position of the first appearance of a character.
#def first_positions(text):
pass
Solution
def first_positions(text):
result = {}
for i in range(len(text)):
if text[i] not in result:
result[text[i]] = i
return result
Player score table.
#class ScoreTable:
pass
Solution
class ScoreTable:
def __init__(self):
self.scores = {}
def add(self, name, points):
if name in self.scores:
self.scores[name] += points
else:
self.scores[name] = points
def top_player(self):
if not self.scores:
return None
top = None
max_score = -1
for name, score in self.scores.items():
if score > max_score:
max_score = score
top = name
return top
Swapping keys and values.
#def swap_dict(d):
pass
Solution
def swap_dict(d):
result = {}
for k, v in d.items():
result[v] = k
return result
Text analyzer.
#class TextAnalyzer:
pass
Solution
class TextAnalyzer:
def __init__(self, text):
self.text = text
def analyze(self):
chars = len(self.text)
lines = self.text.count("\n") + 1 if self.text else 0
words = len(self.text.split())
return {
"chars": chars,
"words": words,
"lines": lines
}