Практика для программиста

God

Уже не совсем ламер.
Пользователь
Апр 11, 2020
91
14
8
hackerrank.com
Большое количество бесплатных заданий (не уверен в наличии платных) с автоматическими проверками.
Из недостатков только язык сайта.

Вот пример задачи:
Gary is an avid hiker. He tracks his hikes meticulously, paying close attention to small details like topography. During his last hike he took exactly steps. For every step he took, he noted if it was an uphill, , or a downhill, step. Gary's hikes start and end at sea level and each step up or down represents a unit change in altitude. We define the following terms:
  • A mountain is a sequence of consecutive steps above sea level, starting with a step up from sea level and ending with a step down to sea level.
  • A valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level.
Given Gary's sequence of up and down steps during his last hike, find and print the number of valleys he walked through.
For example, if Gary's path is , he first enters a valley units deep. Then he climbs out an up onto a mountain units high. Finally, he returns to sea level and ends his hike.
Function Description
Complete the countingValleys function in the editor below. It must return an integer that denotes the number of valleys Gary traversed.
countingValleys has the following parameter(s):
  • n: the number of steps Gary takes
  • s: a string describing his path
Input Format
The first line contains an integer , the number of steps in Gary's hike.
The second line contains a single string , of characters that describe his path.

Output Format
Print a single integer that denotes the number of valleys Gary walked through during his hike.
Sample Input
8
UDDDUDUU

Sample Output
1

Explanation
If we represent _ as sea level, a step up as /, and a step down as \, Gary's hike can be drawn as:
Код:
_/\      _
   \    /
    \/\/


He enters and leaves one valley.

Если по русски:

Гэри заядлый путешественник. Он путешествует только по холмам и всегда записывает последовательность спусков и подъёмов: подъём он обозначает как U (up), а спуск как D (down). Иногда он спускается ниже уровня моря, и когда поднимается обратно на уровень моря понимает, что прошёл долину.

Задача:
Создать функцию, принимающую первым аргументом количество спусков и подъёмов, а вторым - строку, содержащую последовательность из U и D, и высчитывающую, сколько долин прошёл Гэри.

Пример ввода:
8
UDDDUDUU

Пример вывода:
1

Объяснение:
Обозначим уровень моря как _, спуск как \, а подъём - /.
Код:
_/\      _
   \    /
    \/\/
Он опустился ниже уровня моря 1 раз и поднялся на уровень моря 1 раз. Он прошёл 1 долину.

У вас не будет проблем с отладкой получения ввода, код для его осуществления уже внесён в поле для ввода кода для решения задачи. Всё что нужно сделать - функцию(примечание переводчика).
 
  • Мне нравится
Реакции: Евгения

God

Уже не совсем ламер.
Пользователь
Апр 11, 2020
91
14
8
Теперь приведу своё решение задачи:
Я решил записать уровень Гэри в переменную score, а количество долин в переменную valleys:
Python:
def countingValleys(n, s):
    score = 0
    valleys = 0
Теперь прогоним переменную s (строка с путём Гэри) через for:
Python:
def countingValleys(n, s):
    score = 0
    valleys = 0
    for letter in s:
        if letter == 'U':
            score += 1
        elif letter == 'D':
            score -= 1
если Гэри поднялся (U) - прибавляем к его уровню 1. Если опустился (D) - отнимаем.

Ну и проверка долин:
Python:
def countingValleys(n, s):
    score = 0
    valleys = 0
    for letter in s:
        if letter == 'U':
            score += 1
        elif letter == 'D':
            score -= 1
        if score == 0 and letter == 'U':
            valleys += 1
Условиями для пополнения списка долин станут уровень моря (score = 0), и то, что Гэри только что поднялся (U).
Вот и всё.
Для проверки правильности решения добавьте в функцию return valleys.
 
  • Мне нравится
Реакции: Евгения

Форум IT Специалистов