Добро пожаловать на новую статью по решению алгоритмических задач, в которой я собрал для вас список новых задач из разных источников разных сложностей, чтобы каждый смог попробовать в себя в этом увлекательном деле!
Цель статьи заключается в тренировке практик по применению различных алгоритмов, в поддержании навыка "Писать код" в тонусе ну и само собой немного поразвлечься!
Что было раньше:
В предыдущей части (нажмите на строку) мы решили:
- Frog's Dinner (Ужин лягушки) (Нажмите на строку)
- Negation of a Value (Отрицание значения) (Нажмите на строку)
- Colored Hexes! (Цветные HEX-значения) (Нажмите на строку)
- Showing X to Y of Z Products (Отображение от X до Y Z продуктов.) (Нажмите на строку)
- Simple Fun #360: Calculate 1 to n Using The Fewest Numbers (Простая забава #360: Вычислите от 1 до n, используя наименьшее количество чисел) (Нажмите на строку)
В этой части вас ждут еще более интересные алгоритмические задачи. Давайте приступим!
Решение новых задач:
Задача 1
Платформа: CodeWars
Название задачи: Return the day (Верни день)
Ссылка на задачу: https://www.codewars.com/kata/59dd3ccdded72fc78b000b25 (Нажмите на строку)
Сложность: 8 (8 / 8)
Уже решили (На момент написания статьи): 9,332 из 25,741
Тэги: Фундаментальные
Оригинальное описание задачи:
Complete the function which returns the weekday according to the input number:
1
returns "Sunday"
2
returns "Monday"
3
returns "Tuesday"
4
returns "Wednesday"
5
returns "Thursday"
6
returns "Friday"
7
returns "Saturday"
- Otherwise returns
"Wrong, please enter a number between 1 and 7"
Пояснение задачи:
Суть задачи заключается в том чтобы написать функцию, которая возвращает день недели согласно введённому числу.
Например:
1 соответствует "Воскресенье",
2 – "Понедельник",
3 – "Вторник",
4 – "Среда",
5 – "Четверг",
6 – "Пятница",
7 – "Суббота".
Если число не входит в диапазон от 1 до 7, функция должна вернуть сообщение "Ошибка, пожалуйста, введите число между 1 и 7".
Задача 2
Платформа: CodeWars
Название задачи: Say Me Please Operations (Назови мне, пожалуйста, операции)
Ссылка на задачу: https://www.codewars.com/kata/5b5e0c0d83d64866bc00001d (Нажмите на строку)
Сложность: 7 (7 / 8)
Уже решили (На момент написания статьи): 560 из 1,246
Тэги: Алгоритмы, Логика, Строки, Списки
Оригинальное описание задачи:
You have a string of numbers; starting with the third number each number is the result of an operation performed using the previous two numbers.
Complete the function which returns a string of the operations in order and separated by a comma and a space, e.g. "subtraction, subtraction, addition"
The available operations are (in this order of preference):
1) addition
2) subtraction
3) multiplication
4) division
Notes:
- All input data is valid
- The number of numbers in the input string >= 3
- For a case like
"2 2 4"
- when multiple variants are possible - choose the first possible operation from the list (in this case "addition"
)
- Integer division should be used
Example
"9 4 5 20 25" --> "subtraction, multiplication, addition"
Because:
9 - 4 = 5 --> subtraction
4 * 5 = 20 --> multiplication
5 + 20 = 25 --> addition
Пояснение задачи:
Задача заключается в том, чтобы по строке чисел восстановить последовательность операций, которые привели к получению этих чисел. Каждая операция выполняется над двумя предыдущими числами. Операции выбираются в следующем порядке приоритетов: сложение, вычитание, умножение, деление. Функция должна возвращать строку с перечислением выполненных операций через запятую и пробел, например: "вычитание, вычитание, сложение".
Замечания:
Все входные данные корректны.
Количество чисел во входной строке всегда больше или равно трём.
Если возможно несколько вариантов операции, следует выбирать первую подходящую операцию из списка.
Деление производится целочисленно.
Например:
"9 4 5 20 25" → "вычитание, умножение, сложение"
Потому что: 9 - 4 = 5 → вычитание 4 * 5 = 20 → умножение 5 + 20 = 25 → сложение
Задача 3
Платформа: CodeWars
Название задачи: Reversing a Process (Обращение процесса)
Ссылка на задачу: https://www.codewars.com/kata/5dad6e5264e25a001918a1fc (Нажмите на строку)
Сложность: 6 (6 / 8)
Уже решили (На момент написания статьи): 1,086 из 2,817
Тэги: Фундаментальные
Оригинальное описание задачи:
Suppose we know the process by which a string s
was encoded to a string r
(see explanation below). The aim of the kata is to decode this string r
to get back the original string s
.
Explanation of the encoding process:
- input: a string
s
composed of lowercase letters from "a" to "z", and a positive integer num
- we know there is a correspondence between
abcde...uvwxyz
and 0, 1, 2 ..., 23, 24, 25
: 0 <-> a, 1 <-> b ...
- if
c
is a character of s
whose corresponding number is x
, apply to x
the function f: x-> f(x) = num * x % 26
, then find ch
the corresponding character of f(x)
- Accumulate all these
ch
in a string r
- concatenate
num
and r
and return the result
For example:
encode("mer", 6015) --> "6015ekx"
m --> 12, 12 * 6015 % 26 = 4, 4 --> e
e --> 4, 4 * 6015 % 26 = 10, 10 --> k
r --> 17, 17 * 6015 % 26 = 23, 23 --> x
So we get "ekx", hence the output is "6015ekx"
Task
A string s
was encoded to string r
by the above process. complete the function to get back s
whenever it is possible.
Indeed it can happen that the decoding is impossible for strings composed of whatever letters from "a" to "z" when positive integer num has not been correctly chosen. In that case return "Impossible to decode"
.
Examples
decode "6015ekx" -> "mer"
decode "5057aan" -> "Impossible to decode"
Пояснение задачи:
Предположим, мы знаем процесс кодирования строки s в строку r.
Задача состоит в том, чтобы раскодировать эту строку r, чтобы получить исходную строку s.
Объяснение процесса кодирования:
Входные данные: строка s, состоящая из строчных букв от 'a' до 'z', и положительное целое число num.
Между символами abcde...uvwxyz и числами 0, 1, 2 ..., 23, 24, 25 существует соответствие: 0 <-> a, 1 <-> b ...
Если c — символ строки s, соответствующий числу x, то применяется функция f: x -> f(x) = num * x % 26, после чего находится символ ch, соответствующий результату функции f(x).
Все такие символы ch собираются в строку r.
Затем число num объединяется со строкой r, и возвращается результат.
Пример:
encode("mer", 6015) --> "6015ekx"
m --> 12, 12 * 6015 % 26 = 4, 4 --> e
e --> 4, 4 * 6015 % 26 = 10, 10 --> k
r --> 17, 17 * 6015 % 26 = 23, 23 --> x
Задача 4
Платформа: CodeWars
Название задачи: Roman numerals, Zeroes and Fractions (Римские цифры, нули и дроби)
Ссылка на задачу: https://www.codewars.com/kata/55832eda1430b01275000059 (Нажмите на строку)
Сложность: 5 (5 / 8)
Уже решили (На момент написания статьи): 250 из 308
Тэги: Алгоритмы
Оригинальное описание задачи:
We all know about Roman Numerals, and if not, here's a nice introduction kata. And if you were anything like me, you 'knew' that the numerals were not used for zeroes or fractions; but not so!
I learned something new today: the Romans did use fractions and there was even a glyph used to indicate zero.
So in this kata, we will be implementing Roman numerals and fractions.
Although the Romans used base 10 for their counting of units, they used base 12 for their fractions. The system used dots to represent twelfths, and an S
to represent a half like so:
- 1/12 =
.
- 2/12 =
:
- 3/12 =
:.
- 4/12 =
::
- 5/12 =
:.:
- 6/12 =
S
- 7/12 =
S.
- 8/12 =
S:
- 9/12 =
S:.
- 10/12 =
S::
- 11/12 =
S:.:
- 12/12 =
I
(as usual)
Further, zero was represented by N
Kata
Complete the method that takes two parameters: an integer component in the range 0 to 5000 inclusive, and an optional fractional component in the range 0 to 11 inclusive.
You must return a string with the encoded value. Any input values outside the ranges given above should return "NaR"
(i.e. "Not a Roman" :-)
Examples
roman_fractions(-12) #=> "NaR"
roman_fractions(0, -1) #=> "NaR"
roman_fractions(0, 12) #=> "NaR"
roman_fractions(0) #=> "N"
roman_fractions(0, 3) #=> ":."
roman_fractions(1) #=> "I"
roman_fractions(1, 0) #=> "I"
roman_fractions(1, 5) #=> "I:.:"
roman_fractions(1, 9) #=> "IS:."
roman_fractions(1632, 2) #=> "MDCXXXII:"
roman_fractions(5000) #=> "MMMMM"
roman_fractions(5001) #=> "NaR"
Пояснение задачи:
Римские цифры обычно ассоциируются только с целыми числами, но римляне использовали их и для дробей.
В этой задаче нам предстоит реализовать систему римских цифр, включая дроби.
Для целых чисел используется стандартная система римских цифр, а вот дроби записываются следующим образом:
Римская цифра для 1/12 обозначается как .
Для 2/12 — :
Для 3/12 — :.
И так далее, где каждый дополнительный знак : добавляет ещё 1/12.
При достижении половины (6/12), используется символ S.
Число 12/12 снова становится единицей (I), а ноль обозначается символом N.
Необходимо создать функцию, который принимает два параметра: целое число в диапазоне от 0 до 5000 включительно и необязательную дробь в диапазоне от 0 до 11 включительно.
Метод должен возвращать строку с представлением числа в римской системе счисления.
Если значения выходят за указанные диапазоны, метод должен вернуть "NaR" ("Не римское").
Например:
roman_fractions(-12) #=> "NaR"
roman_fractions(0, -1) #=> "NaR"
roman_fractions(0, 12) #=> "NaR"
roman_fractions(0) #=> "N"
roman_fractions(0, 3) #=> ":."
roman_fractions(1) #=> "I"
roman_fractions(1, 0) #=> "I"
roman_fractions(1, 5) #=> "I:.:"
roman_fractions(1, 9) #=> "IS:."
roman_fractions(1632, 2) #=> "MDCXXXII:"
roman_fractions(5000) #=> "MMMMM"
roman_fractions(5001) #=> "NaR"
Задача 5
Платформа: CodeWars
Название задачи: Permutation Square Roots (Квадратные корни, перестановки)
Ссылка на задачу: https://www.codewars.com/kata/67952bc999934d6e6e818000 (Нажмите на строку)
Сложность: 4 (4 / 8)
Уже решили (На момент написания статьи): 14 из 14
Тэги: Математика, Перестановки, Массивы
Оригинальное описание задачи:
Overview
Given a permutation (a list representing an arrangement of [0,1,...,n−1][0, 1, ..., n - 1][0,1,...,n−1] for some nnn), find a square root of that permutation (a new arrangement that, when applied to itself, gives the original permutation.)
Explanation
In this kata, a permutation of length nnn is a list containing each non-negative integer less than nnn exactly once, in some order. For instance, [1,7,6,3,2,4,5,0][1, 7, 6, 3, 2, 4, 5, 0][1,7,6,3,2,4,5,0] is a permutation of length 888. 1
Each permutation can be thought of as a rearrangement of the list [0,1,...,n−1][0, 1, ..., n - 1][0,1,...,n−1]. It may also be thought of as a function, where the the inputs are the indices and the outputs are the values at those indices:
k 0 1 2 3 4 5 6 7
f(k) 1 7 6 3 2 4 5 0
Like any function, f(k)f(k)f(k) may be composed with another function, or with itself. The function f(f(k))f(f(k))f(f(k)) will also represent a permutation of the same length:
k 0 1 2 3 4 5 6 7
f(k) 1 7 6 3 2 4 5 0
f(f(k)) 7 0 5 3 6 2 4 1
We may call [7,0,5,3,6,2,4,1][7, 0, 5, 3, 6, 2, 4, 1][7,0,5,3,6,2,4,1] the square of [1,7,6,3,2,4,5,0][1, 7, 6, 3, 2, 4, 5, 0][1,7,6,3,2,4,5,0]. It makes sense, then, to call [1,7,6,3,2,4,5,0][1, 7, 6, 3, 2, 4, 5, 0][1,7,6,3,2,4,5,0] a square root of [7,0,5,3,6,2,4,1][7, 0, 5, 3, 6, 2, 4, 1][7,0,5,3,6,2,4,1].
Like real numbers, permutations may have multiple square roots, or no square roots. The only other square root of [7,0,5,3,6,2,4,1][7, 0, 5, 3, 6, 2, 4, 1][7,0,5,3,6,2,4,1] is [1,7,4,3,5,6,2,0][1, 7, 4, 3, 5, 6, 2, 0][1,7,4,3,5,6,2,0], though some permutations may have many more square roots. On the other hand, the permutation [1,0][1, 0][1,0] has none. (To see this, note that the only permutations of length 222 are [0,1][0, 1][0,1] and [1,0][1, 0][1,0], both of which square to [0,1][0, 1][0,1].)
Objective
Write a function get_square_root
that accepts a permutation as a list of integers for its input. If that permutation has one or more square roots as defined above, return any one of those permutations also in list form. Otherwise, return None
.
Example 1
has_square_root([7, 0, 5, 3, 6, 2, 4, 1])
# should return [1, 7, 6, 3, 2, 4, 5, 0] or [1, 7, 4, 3, 5, 6, 2, 0]
Example 2
has_square_root([1, 0])
# should return None
All inputs will be lists of length nnn, where 1≤n≤50001 \leq n \leq 50001≤n≤5000. Inputs will always be valid permutations, containing exclusively non-negative integers less than nnn, and never containing duplicates.
- It is more standard in mathematics for permutations be rearrangements of [1,2,...,n][1, 2, ..., n][1,2,...,n], but zero-indexed permutations are easier to work with here. The actual objects being arranged do not fundamentally matter. There is a more useful notation for permutations called cycle notation, but this is not used in this kata.
Пояснение задачи:
Перестановка — это список, содержащий каждое неотрицательное целое число меньше nn ровно один раз, в некотором порядке.
Например, [1, 7, 6, 3, 2, 4, 5, 0] — это перестановка длины 8.
Каждая перестановка может рассматриваться как функция, где индексы являются входными данными, а значения на этих индексах — выходными данными.
Цель данной задачи — найти квадратный корень заданной перестановки, т.е. такую перестановку, при применении которой дважды получится исходная перестановка.
Если такой корень существует, вернуть его в виде списка.
Если нет, вернуть None.
Новое в конфигурации Algo1C:

https://github.com/SalavatovNabiulla/Algo1C
- 0.5 : Добавлена возможность выбирать контекст исполнения кода, например: НаСервере или НаКлиенте
- 0.4 : Исправлена ошибка при выводе содержимого исключения
- 0.3 : Добавлена возможность сохранять и загружать задачи; Внесены небольшие изменения в интерфейс
- 0.2 : Исправлена ошибка при выводе результата (Отдельная благодарность SAShikutkin)
Заключение:
Платформа: CodeWars
Название задачи: Return the day (Верни день)
Ссылка на задачу: https://www.codewars.com/kata/59dd3ccdded72fc78b000b25 (Нажмите на строку)
Сложность: 8 (8 / 8)
Уже решили (На момент написания статьи): 9,332 из 25,741
Тэги: Фундаментальные
Оригинальное описание задачи:
Complete the function which returns the weekday according to the input number:
1
returns"Sunday"
2
returns"Monday"
3
returns"Tuesday"
4
returns"Wednesday"
5
returns"Thursday"
6
returns"Friday"
7
returns"Saturday"
- Otherwise returns
"Wrong, please enter a number between 1 and 7"
Пояснение задачи:
Суть задачи заключается в том чтобы написать функцию, которая возвращает день недели согласно введённому числу.
Например:
1 соответствует "Воскресенье",
2 – "Понедельник",
3 – "Вторник",
4 – "Среда",
5 – "Четверг",
6 – "Пятница",
7 – "Суббота".
Если число не входит в диапазон от 1 до 7, функция должна вернуть сообщение "Ошибка, пожалуйста, введите число между 1 и 7".
Платформа: CodeWars
Название задачи: Say Me Please Operations (Назови мне, пожалуйста, операции)
Ссылка на задачу: https://www.codewars.com/kata/5b5e0c0d83d64866bc00001d (Нажмите на строку)
Сложность: 7 (7 / 8)
Уже решили (На момент написания статьи): 560 из 1,246
Тэги: Алгоритмы, Логика, Строки, Списки
Оригинальное описание задачи:
You have a string of numbers; starting with the third number each number is the result of an operation performed using the previous two numbers.
Complete the function which returns a string of the operations in order and separated by a comma and a space, e.g.
"subtraction, subtraction, addition"
The available operations are (in this order of preference):
1) addition 2) subtraction 3) multiplication 4) division
Notes:
- All input data is valid
- The number of numbers in the input string >= 3
- For a case like
"2 2 4"
- when multiple variants are possible - choose the first possible operation from the list (in this case"addition"
)- Integer division should be used
Example
"9 4 5 20 25" --> "subtraction, multiplication, addition"
Because:
9 - 4 = 5 --> subtraction 4 * 5 = 20 --> multiplication 5 + 20 = 25 --> addition
Пояснение задачи:
Задача заключается в том, чтобы по строке чисел восстановить последовательность операций, которые привели к получению этих чисел. Каждая операция выполняется над двумя предыдущими числами. Операции выбираются в следующем порядке приоритетов: сложение, вычитание, умножение, деление. Функция должна возвращать строку с перечислением выполненных операций через запятую и пробел, например: "вычитание, вычитание, сложение".
Замечания:
Все входные данные корректны.
Количество чисел во входной строке всегда больше или равно трём.
Если возможно несколько вариантов операции, следует выбирать первую подходящую операцию из списка.
Деление производится целочисленно.
Например:
"9 4 5 20 25" → "вычитание, умножение, сложение"
Потому что: 9 - 4 = 5 → вычитание 4 * 5 = 20 → умножение 5 + 20 = 25 → сложение
Платформа: CodeWars
Название задачи: Reversing a Process (Обращение процесса)
Ссылка на задачу: https://www.codewars.com/kata/5dad6e5264e25a001918a1fc (Нажмите на строку)
Сложность: 6 (6 / 8)
Уже решили (На момент написания статьи): 1,086 из 2,817
Тэги: Фундаментальные
Оригинальное описание задачи:
Suppose we know the process by which a string
s
was encoded to a stringr
(see explanation below). The aim of the kata is to decode this stringr
to get back the original strings
.Explanation of the encoding process:
- input: a string
s
composed of lowercase letters from "a" to "z", and a positive integernum
- we know there is a correspondence between
abcde...uvwxyz
and0, 1, 2 ..., 23, 24, 25
:0 <-> a, 1 <-> b ...
- if
c
is a character ofs
whose corresponding number isx
, apply tox
the functionf: x-> f(x) = num * x % 26
, then findch
the corresponding character off(x)
- Accumulate all these
ch
in a stringr
- concatenate
num
andr
and return the resultFor example:
encode("mer", 6015) --> "6015ekx" m --> 12, 12 * 6015 % 26 = 4, 4 --> e e --> 4, 4 * 6015 % 26 = 10, 10 --> k r --> 17, 17 * 6015 % 26 = 23, 23 --> x So we get "ekx", hence the output is "6015ekx"
Task
A string
s
was encoded to stringr
by the above process. complete the function to get backs
whenever it is possible.Indeed it can happen that the decoding is impossible for strings composed of whatever letters from "a" to "z" when positive integer num has not been correctly chosen. In that case return
"Impossible to decode"
.Examples
decode "6015ekx" -> "mer" decode "5057aan" -> "Impossible to decode"
Пояснение задачи:
Предположим, мы знаем процесс кодирования строки s в строку r.
Задача состоит в том, чтобы раскодировать эту строку r, чтобы получить исходную строку s.
Объяснение процесса кодирования:
Входные данные: строка s, состоящая из строчных букв от 'a' до 'z', и положительное целое число num.
Между символами abcde...uvwxyz и числами 0, 1, 2 ..., 23, 24, 25 существует соответствие: 0 <-> a, 1 <-> b ...
Если c — символ строки s, соответствующий числу x, то применяется функция f: x -> f(x) = num * x % 26, после чего находится символ ch, соответствующий результату функции f(x).
Все такие символы ch собираются в строку r.
Затем число num объединяется со строкой r, и возвращается результат.
Пример:encode("mer", 6015) --> "6015ekx" m --> 12, 12 * 6015 % 26 = 4, 4 --> e e --> 4, 4 * 6015 % 26 = 10, 10 --> k r --> 17, 17 * 6015 % 26 = 23, 23 --> x
Платформа: CodeWars
Название задачи: Roman numerals, Zeroes and Fractions (Римские цифры, нули и дроби)
Ссылка на задачу: https://www.codewars.com/kata/55832eda1430b01275000059 (Нажмите на строку)
Сложность: 5 (5 / 8)
Уже решили (На момент написания статьи): 250 из 308
Тэги: Алгоритмы
Оригинальное описание задачи:
We all know about Roman Numerals, and if not, here's a nice introduction kata. And if you were anything like me, you 'knew' that the numerals were not used for zeroes or fractions; but not so!
I learned something new today: the Romans did use fractions and there was even a glyph used to indicate zero.
So in this kata, we will be implementing Roman numerals and fractions.
Although the Romans used base 10 for their counting of units, they used base 12 for their fractions. The system used dots to represent twelfths, and an
S
to represent a half like so:
- 1/12 =
.
- 2/12 =
:
- 3/12 =
:.
- 4/12 =
::
- 5/12 =
:.:
- 6/12 =
S
- 7/12 =
S.
- 8/12 =
S:
- 9/12 =
S:.
- 10/12 =
S::
- 11/12 =
S:.:
- 12/12 =
I
(as usual)Further, zero was represented by
N
Kata
Complete the method that takes two parameters: an integer component in the range 0 to 5000 inclusive, and an optional fractional component in the range 0 to 11 inclusive.
You must return a string with the encoded value. Any input values outside the ranges given above should return
"NaR"
(i.e. "Not a Roman" :-)Examples
roman_fractions(-12) #=> "NaR" roman_fractions(0, -1) #=> "NaR" roman_fractions(0, 12) #=> "NaR" roman_fractions(0) #=> "N" roman_fractions(0, 3) #=> ":." roman_fractions(1) #=> "I" roman_fractions(1, 0) #=> "I" roman_fractions(1, 5) #=> "I:.:" roman_fractions(1, 9) #=> "IS:." roman_fractions(1632, 2) #=> "MDCXXXII:" roman_fractions(5000) #=> "MMMMM" roman_fractions(5001) #=> "NaR"
Пояснение задачи:
Римские цифры обычно ассоциируются только с целыми числами, но римляне использовали их и для дробей.
В этой задаче нам предстоит реализовать систему римских цифр, включая дроби.
Для целых чисел используется стандартная система римских цифр, а вот дроби записываются следующим образом:
Римская цифра для 1/12 обозначается как .
Для 2/12 — :
Для 3/12 — :.
И так далее, где каждый дополнительный знак : добавляет ещё 1/12.
При достижении половины (6/12), используется символ S.
Число 12/12 снова становится единицей (I), а ноль обозначается символом N.
Необходимо создать функцию, который принимает два параметра: целое число в диапазоне от 0 до 5000 включительно и необязательную дробь в диапазоне от 0 до 11 включительно.
Метод должен возвращать строку с представлением числа в римской системе счисления.
Если значения выходят за указанные диапазоны, метод должен вернуть "NaR" ("Не римское").
Например:
roman_fractions(-12) #=> "NaR"
roman_fractions(0, -1) #=> "NaR"
roman_fractions(0, 12) #=> "NaR"
roman_fractions(0) #=> "N"
roman_fractions(0, 3) #=> ":."
roman_fractions(1) #=> "I"
roman_fractions(1, 0) #=> "I"
roman_fractions(1, 5) #=> "I:.:"
roman_fractions(1, 9) #=> "IS:."
roman_fractions(1632, 2) #=> "MDCXXXII:"
roman_fractions(5000) #=> "MMMMM"
roman_fractions(5001) #=> "NaR"
Платформа: CodeWars
Название задачи: Permutation Square Roots (Квадратные корни, перестановки)
Ссылка на задачу: https://www.codewars.com/kata/67952bc999934d6e6e818000 (Нажмите на строку)
Сложность: 4 (4 / 8)
Уже решили (На момент написания статьи): 14 из 14
Тэги: Математика, Перестановки, Массивы
Оригинальное описание задачи:
Overview
Given a permutation (a list representing an arrangement of [0,1,...,n−1][0, 1, ..., n - 1][0,1,...,n−1] for some nnn), find a square root of that permutation (a new arrangement that, when applied to itself, gives the original permutation.)
Explanation
In this kata, a permutation of length nnn is a list containing each non-negative integer less than nnn exactly once, in some order. For instance, [1,7,6,3,2,4,5,0][1, 7, 6, 3, 2, 4, 5, 0][1,7,6,3,2,4,5,0] is a permutation of length 888. 1
Each permutation can be thought of as a rearrangement of the list [0,1,...,n−1][0, 1, ..., n - 1][0,1,...,n−1]. It may also be thought of as a function, where the the inputs are the indices and the outputs are the values at those indices:
k 0 1 2 3 4 5 6 7 f(k) 1 7 6 3 2 4 5 0
Like any function, f(k)f(k)f(k) may be composed with another function, or with itself. The function f(f(k))f(f(k))f(f(k)) will also represent a permutation of the same length:
k 0 1 2 3 4 5 6 7 f(k) 1 7 6 3 2 4 5 0 f(f(k)) 7 0 5 3 6 2 4 1
We may call [7,0,5,3,6,2,4,1][7, 0, 5, 3, 6, 2, 4, 1][7,0,5,3,6,2,4,1] the square of [1,7,6,3,2,4,5,0][1, 7, 6, 3, 2, 4, 5, 0][1,7,6,3,2,4,5,0]. It makes sense, then, to call [1,7,6,3,2,4,5,0][1, 7, 6, 3, 2, 4, 5, 0][1,7,6,3,2,4,5,0] a square root of [7,0,5,3,6,2,4,1][7, 0, 5, 3, 6, 2, 4, 1][7,0,5,3,6,2,4,1].
Like real numbers, permutations may have multiple square roots, or no square roots. The only other square root of [7,0,5,3,6,2,4,1][7, 0, 5, 3, 6, 2, 4, 1][7,0,5,3,6,2,4,1] is [1,7,4,3,5,6,2,0][1, 7, 4, 3, 5, 6, 2, 0][1,7,4,3,5,6,2,0], though some permutations may have many more square roots. On the other hand, the permutation [1,0][1, 0][1,0] has none. (To see this, note that the only permutations of length 222 are [0,1][0, 1][0,1] and [1,0][1, 0][1,0], both of which square to [0,1][0, 1][0,1].)
Objective
Write a function
get_square_root
that accepts a permutation as a list of integers for its input. If that permutation has one or more square roots as defined above, return any one of those permutations also in list form. Otherwise, returnNone
.Example 1
has_square_root([7, 0, 5, 3, 6, 2, 4, 1]) # should return [1, 7, 6, 3, 2, 4, 5, 0] or [1, 7, 4, 3, 5, 6, 2, 0]
Example 2
has_square_root([1, 0]) # should return None
All inputs will be lists of length nnn, where 1≤n≤50001 \leq n \leq 50001≤n≤5000. Inputs will always be valid permutations, containing exclusively non-negative integers less than nnn, and never containing duplicates.
- It is more standard in mathematics for permutations be rearrangements of [1,2,...,n][1, 2, ..., n][1,2,...,n], but zero-indexed permutations are easier to work with here. The actual objects being arranged do not fundamentally matter. There is a more useful notation for permutations called cycle notation, but this is not used in this kata.
Пояснение задачи:
Перестановка — это список, содержащий каждое неотрицательное целое число меньше nn ровно один раз, в некотором порядке.
Например, [1, 7, 6, 3, 2, 4, 5, 0] — это перестановка длины 8.
Каждая перестановка может рассматриваться как функция, где индексы являются входными данными, а значения на этих индексах — выходными данными.
Цель данной задачи — найти квадратный корень заданной перестановки, т.е. такую перестановку, при применении которой дважды получится исходная перестановка.
Если такой корень существует, вернуть его в виде списка.
Если нет, вернуть None.
https://github.com/SalavatovNabiulla/Algo1C
- 0.5 : Добавлена возможность выбирать контекст исполнения кода, например: НаСервере или НаКлиенте
- 0.4 : Исправлена ошибка при выводе содержимого исключения
- 0.3 : Добавлена возможность сохранять и загружать задачи; Внесены небольшие изменения в интерфейс
- 0.2 : Исправлена ошибка при выводе результата (Отдельная благодарность SAShikutkin)
Ну что ж, пока на этом всё, надеюсь, статья была увлекательной для вас, благодарю за внимание.
Подключайтесь к решению алгоритмических задач вместе со мной, делитесь вашим мнением и решениями в комментариях, сохраняя при этом позитивный настрой!
Увидимся в новой статье!