Тема: Алгоритмическое мышление
0/0
[5, 2, 8, 1, 9]. Найдите второе максимальное число без использования сортировки.
max()remove()numbers = [5, 2, 8, 1, 9] max_num = max(numbers) temp_list = numbers.copy() temp_list.remove(max_num) second_max = max(temp_list) print(second_max) # 8
["Анна", "Борис", "Вера"] и возрасты [25, 30, 28]. Создайте словарь, где ключи - имена, значения - возрасты.
names[0] и ages[0] - первая параdict[names[i]] = ages[i]names = ["Анна", "Борис", "Вера"] ages = [25, 30, 28] people = {} people[names[0]] = ages[0] people[names[1]] = ages[1] people[names[2]] = ages[2] print(people) # {'Анна': 25, 'Борис': 30, 'Вера': 28}
"HELLO world". Подсчитайте количество гласных букв (a, e, i, o, u).
.lower().count() для подсчёта каждой гласной отдельноcount_a + count_e + count_i + count_o + count_utext = "hello world" text_lower = text.lower() count_a = text_lower.count('a') count_e = text_lower.count('e') count_i = text_lower.count('i') count_o = text_lower.count('o') count_u = text_lower.count('u') total_vowels = count_a + count_e + count_i + count_o + count_u print(total_vowels) # 3
[::-1]==word = input("Введите слово: ").lower() reversed_word = word[::-1] is_palindrome = word == reversed_word print(f"Палиндром: {is_palindrome}")
[4, 5, 3, 5, 4]. Вычислите средний балл с использованием встроенной функции.
sum()len()grades = [4, 5, 3, 5, 4] total = sum(grades) count = len(grades) average = total / count print(f"Средний балл: {average}") # 4.2
(2, 3) и (5, 7). Найдите расстояние между ними по формуле (формула: расстояние = √((x2-x1)² + (y2-y1)²)).
x1, y1 = point1dx = x2 - x1, dy = y2 - y1point1 = (2, 3) point2 = (5, 7) x1, y1 = point1 x2, y2 = point2 dx = x2 - x1 dy = y2 - y1 sum_squares = dx**2 + dy**2 distance = sum_squares ** 0.5 print(f"Расстояние: {distance}") # 5.0
max().index()students = [
{'имя': 'Анна', 'оценка': 4},
{'имя': 'Борис', 'оценка': 5},
{'имя': 'Вера', 'оценка': 3}
]
grades = [students[0]['оценка'], students[1]['оценка'], students[2]['оценка']]
max_grade = max(grades)
max_index = grades.index(max_grade)
best_student = students[max_index]
print(f"Лучший студент: {best_student['имя']}") # Борис
.split()len() для каждого словаmax().index()text = "Python это прекрасный язык программирования" words = text.split() lengths = [len(words[0]), len(words[1]), len(words[2]), len(words[3]), len(words[4])] max_length = max(lengths) max_index = lengths.index(max_length) longest_word = words[max_index] print(f"Самое длинное слово: {longest_word}") # программирования
цена > 1000 (даст True=1 или False=0)новая_цена = цена * (0.8 * условие + 1 * (not условие))prices = [500, 1200, 800, 2000, 1500] new_prices = [] new_prices.append(prices[0] * (0.8 * (prices[0] > 1000) + 1 * (not prices[0] > 1000))) new_prices.append(prices[1] * (0.8 * (prices[1] > 1000) + 1 * (not prices[1] > 1000))) new_prices.append(prices[2] * (0.8 * (prices[2] > 1000) + 1 * (not prices[2] > 1000))) new_prices.append(prices[3] * (0.8 * (prices[3] > 1000) + 1 * (not prices[3] > 1000))) new_prices.append(prices[4] * (0.8 * (prices[4] > 1000) + 1 * (not prices[4] > 1000))) print(new_prices) # [500, 960.0, 800, 1600.0, 1200.0]
+sorted()list1 = [1, 3, 5, 7] list2 = [2, 4, 6, 8] merged = list1 + list2 sorted_list = sorted(merged) print(sorted_list) # [1, 2, 3, 4, 5, 6, 7, 8]
set() - автоматически удалятся дубликатыlen()text = "hello world" unique_chars = set(text) count = len(unique_chars) print(f"Уникальные символы: {unique_chars}") print(f"Количество: {count}") # 8
len(password) >= 8in для каждой цифры с orandpassword = input("Введите пароль: ") length_ok = len(password) >= 8 has_digit = ('0' in password or '1' in password or '2' in password or '3' in password or '4' in password or '5' in password or '6' in password or '7' in password or '8' in password or '9' in password) is_valid = length_ok and has_digit print(f"Пароль валидный: {is_valid}")
max()min()numbers = [23, 45, 12, 67, 34, 89, 5] max_num = max(numbers) min_num = min(numbers) difference = max_num - min_num print(f"Разница: {difference}") # 84
prices = {'яблоко': 50, 'банан': 30, 'апельсин': 40}
order = [('яблоко', 3), ('банан', 2), ('апельсин', 1)]
cost1 = prices[order[0][0]] * order[0][1]
cost2 = prices[order[1][0]] * order[1][1]
cost3 = prices[order[2][0]] * order[2][1]
total = cost1 + cost2 + cost3
print(f"Общая стоимость: {total} руб.") # 250
.get() со значением по умолчанию для поискаknowledge = {
'python': 'Высокоуровневый язык программирования',
'список': 'Упорядоченная изменяемая коллекция элементов',
'словарь': 'Коллекция пар ключ-значение'
}
term = input("Введите термин: ").lower()
definition = knowledge.get(term, "Термин не найден в базе знаний")
print(f"{term}: {definition}")
max(), min(), sum(), len()set() для уникальных значений, list() для списков.get() для безопасного доступа к словарям