• 1
    Input and Output Data
    • Tasks
  • 2
    Conditions
    • Tasks
  • 3
    For Loop
    • Tasks
  • 4
    Strings
    • Tasks
  • 5
    While Loop
    • Tasks
  • 6
    Lists
    • Tasks
  • 7
    Two-Dimensional Arrays
    • Tasks
  • 8
    Dictionaries
    • Tasks
  • 9
    Sets
    • Tasks
  • 10
    Functions and Recursion
    • Tasks
  • к

Занятие 4. Lines

Difficulty level:

Task«Contest»

you participate in a prestigious literary competition. The jury appreciates not only the depth of thought, but also the wealth of the language. To impress, you decided to analyze your essay and find the longest and shortest word in it. This will help you understand how diverse your vocabulary is.

rn

task:
Write a program that accepts one line of text (your essay) and finds the longest and shortest word in it.

rn

restrictions:

rn
    rn
  1. word & nbsp; & mdash; This is any sequence of characters separated by spaces.
  2. rn
  3. punctuation: & nbsp; punctuation marks at the beginning or at the end of the word (.,! Symbols.
  4. RN
  5. register: & nbsp; comparison of words should be register-dependent. the same.
  6. rn
  7. resolution of the draw: rn
  8. If a few words have the same minimum length, the shortest one is considered to be the first to alphabetical. Style = "Font-Size: 14pt;"> empty input: if there is no words in the text (the line is empty or consists only of spaces and punctuation marks), the program should display the message ".".
  9. rn

    & nbsp;

    Input format

    One line of text (string), which may contain words, gaps and punctuation marks.

    Output format

    The longest word from the text (String). On the next line & mdash; The shortest word from the text (string).

    Example

    Input

    Hello, peace! This is a very, very long word and another word.

    Output

    Very, very
    and

    Hint

    There will be no clue here, decide for yourself!

main.py
Test 1
Test 2
Test 3
Test 4
Test 5
Test 6
Test 7
Test 8
Test 9
Test 10
Developer’s solution
# Заранее определяем строку со знаками препинания, которые нужно удалить
punctuation = '.,!?:;-"()\''

# Получаем строку текста от пользователя
text = input()

# Преобразуем весь текст в нижний регистр для регистронезависимого сравнения
# и разбиваем его на отдельные слова по пробелам
raw_words = text.lower().split()

# Создаем пустой список для хранения очищенных слов
cleaned_words = []

# Используем цикл for для перебора каждого "сырого" слова
for raw_word in raw_words:
    # Удаляем знаки препинания с начала и конца каждого слова
    word = raw_word.strip(punctuation)
    # Если после очистки слово не стало пустым, добавляем его в наш список
    if word:
        cleaned_words.append(word)

# Проверяем, нашлись ли в тексте какие-либо слова
if not cleaned_words:
    # Если список пуст, выводим соответствующее сообщение
    print("Слова не найдены.")
else:
    # Инициализируем самое длинное и самое короткое слово первым словом из списка
    longest_word = cleaned_words[0]
    shortest_word = cleaned_words[0]

    # Начинаем цикл со второго элемента, так как первый уже взят за основу
    for word in cleaned_words[1:]:
        # Условие для поиска самого длинного слова
        # Оно становится новым самым длинным, если его длина больше
        # ИЛИ если длины равны, но оно по алфавиту идет раньше
        if len(word) > len(longest_word) or (len(word) == len(longest_word) and word < longest_word):
            longest_word = word
        
        # Условие для поиска самого короткого слова
        # Оно становится новым самым коротким, если его длина меньше
        # ИЛИ если длины равны, но оно по алфавиту идет раньше
        if len(word) < len(shortest_word) or (len(word) == len(shortest_word) and word < shortest_word):
            shortest_word = word

    # Выводим найденное самое длинное слово
    print(longest_word)
    # Выводим найденное самое короткое слово на новой строке
    print(shortest_word)

🎉 Congratulations! 🎉

You did an excellent job with the task! It was a challenging problem, but you found the correct solution. You are one step closer to mastering programming! Keep up the good work, because every stage you pass makes you even stronger.

AD

Advertisement

red-snake blue-snake green-snake

Running your code...

Помощник ИИ

Привет! Я твой помощник по программированию. Задавай любые вопросы по Python, я могу рассказать о функциях, методах, обьяснить то, что тебе не понятно, а так же о текущей задаче!