Python · Синтаксис · Начальный уровень
ООП, словари, алгоритмическое мышление
Упражнения по Python на ООП, словари и алгоритмическое мышление: классы для анализа данных, подсчёт слов и символов, работа с оценками, паролями, статистикой и преобразованием словарей.
Краткое введение в тему и пояснения перед упражнениями (упражнения ниже):
Паттерны реестра, счётчика и агрегатора
#Быстрый справочник: словари, множества и паттерны классов
#Упражнения:
WordCounter для текста.
#class WordCounter:
pass
Решение
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.
#class GradeBook:
pass
Решение
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)
Подсчёт каждой буквы.
#def letter_stats(text):
pass
Решение
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
Проверка надёжности пароля.
#class PasswordChecker:
pass
Решение
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
Инвентарь товаров.
#class Inventory:
pass
Решение
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
Группировка слов по длине.
#def length_groups(words):
pass
Решение
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 без минуса.
#class BankAccount:
pass
Решение
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
Гласные и согласные.
#def vowels_and_consonants(text):
pass
Решение
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
Регистрация пользователей.
#USERS = []
class UserRegistry:
pass
Решение
USERS = []
class UserRegistry:
def register(self, username):
if username in USERS:
return False
USERS.append(username)
return True
Классификация чисел.
#def number_summary(nums):
pass
Решение
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
Корзина покупок.
#class ShoppingCart:
pass
Решение
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
Позиция первого появления символа.
#def first_positions(text):
pass
Решение
def first_positions(text):
result = {}
for i in range(len(text)):
if text[i] not in result:
result[text[i]] = i
return result
Таблица очков игроков.
#class ScoreTable:
pass
Решение
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
Обмен ключей и значений.
#def swap_dict(d):
pass
Решение
def swap_dict(d):
result = {}
for k, v in d.items():
result[v] = k
return result
Анализатор текста.
#class TextAnalyzer:
pass
Решение
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
}