Python · Синтаксис · Початковий рівень
Функції рівень 2
Розширена практика функцій у Python: обробка строк та чисел, логічні перевірки, списки, фільтрація, підрахунки, пошук значень та написання невеликих функцій, що перевикористовуються.
Короткий вступ до теми та пояснення перед вправами (вправи нижче):
Патерни цього рівня
#Довідник: методи рядка, зрізи та патерни функцій
#Вправи:
Even або Odd.
#def even_or_odd(n):
pass
Рішення
def even_or_odd(n):
if n % 2 == 0:
return "Even"
else:
return "Odd"
# або так можна: спочатку отримати остачу
def even_or_odd(n):
rest = n % 2
if rest == 0:
return "Even"
return "Odd"
Перевертання рядка функцією.
#def reverse_text(text):
pass
Рішення
def reverse_text(text):
return text[::-1]
# або так можна через цикл
def reverse_text(text):
result = ""
for char in text:
result = char + result
return result
Середнє арифметичне.
#def average(a, b):
pass
Рішення
def average(a, b):
return (a + b) / 2
Підрахунок голосних.
#def count_vowels(text):
pass
Рішення
def count_vowels(text):
vowels = "aeiouy"
count = 0
for ch in text.lower():
if ch in vowels:
count += 1
return count
Подільність на 3 і 5.
#def divisible_by_3_and_5(n):
pass
Рішення
def divisible_by_3_and_5(n):
return n % 3 == 0 and n % 5 == 0
Рядок без пробілів.
#def remove_spaces(text):
pass
Рішення
def remove_spaces(text):
result = ""
for ch in text:
if ch != " ":
result += ch
return result
# або так:
def remove_spaces(text):
return text.replace(" ", "")
Сума додатних елементів.
#def sum_positive(numbers):
pass
Рішення
def sum_positive(numbers):
total = 0
for n in numbers:
if n > 0:
total += n
return total
Перевірка паліндрома.
#def is_palindrome(text):
pass
Рішення
def is_palindrome(text):
return text == text[::-1]
# або так можна: підготувати перевернутий рядок окремо
def is_palindrome(text):
reversed_text = text[::-1]
return text == reversed_text
Positive, Negative або Zero.
#def describe_number(n):
pass
Рішення
def describe_number(n):
if n > 0:
return "Positive"
elif n < 0:
return "Negative"
else:
return "Zero"
Кількість слів у рядку.
#def count_words(text):
pass
Рішення
def count_words(text):
if text == "":
return 0
return len(text.split())
Кратність десяти.
#def is_multiple_of_ten(n):
pass
Рішення
def is_multiple_of_ten(n):
return n % 10 == 0
Перший і останній символ функцією.
#def first_and_last(text):
pass
Рішення
def first_and_last(text):
if text == "":
return ""
return text[0] + text[-1]
Yes, якщо більше 100.
#def more_than_hundred(n):
pass
Рішення
def more_than_hundred(n):
if n > 100:
return "Yes"
return "No"
# Або так через тернарний оператор:
def more_than_hundred(n):
return "Yes" if n > 100 else "No"
Підрахунок букви a.
#def count_a(text):
pass
Рішення
def count_a(text):
count = 0
for ch in text.lower():
if ch == "a":
count += 1
return count
# або
def count_a(text):
return text.lower().count("a")
Різниця за модулем.
#def abs_diff(a, b):
pass
Рішення
def abs_diff(a, b):
diff = a - b
if diff < 0:
diff = -diff
return diff
# або так можна через abs
def difference(a, b):
return abs(a - b)
Парна довжина рядка.
#def is_even_length(text):
pass
Рішення
def is_even_length(text):
return len(text) % 2 == 0
Остання цифра числа.
#def last_digit(n):
pass
Рішення
def last_digit(n):
if n < 0:
n = -n
return n % 10
# або так можна через рядок
def last_digit(n):
return int(str(abs(n))[-1])
Без першої та останньої літери.
#def trim_edges(text):
pass
Рішення
def trim_edges(text):
if len(text) <= 2:
return ""
return text[1:-1]
Small, Medium або Large.
#def size_label(n):
pass
Рішення
def size_label(n):
if n < 10:
return "Small"
elif n <= 100:
return "Medium"
else:
return "Large"
Видалення знаків оклику.
#def remove_exclamations(text):
pass
Рішення
def remove_exclamations(text):
result = ""
for ch in text:
if ch != "!":
result += ch
return result
# або так можна через replace
def remove_exclamation(text):
return text.replace("!", "")