Sly32, you changed the signature, if we change the signature in the problem (and the types of arguments in the function must be the same, no tuples), I can drive your function and benchmark tests.
Do you make the same decision as that tommy-gung, but it can be improved, if you think about how.
tommy-gung, решение рабочее, но можно оптимизировать) первая реализация у меня тоже так работала, это первое что приходит в голову.
tommy-gung, a working solution, but it is possible to optimize) the first implementation I have also worked well, this is the first that comes to mind.
hakuna matata, Go tour.
Есть ещё одна очень легенькая задачка, но по которой можно определить как человек умеет оптимизировать код:
Есть список чисел, например [3, 2, 4], а также целевое число 6. Необходимо вернуть индексы из массива, сумма значений которых будет равна целевому числу. Если в результате есть несколько комбинаций, нужно вернуть первую.
Например, [3, 2, 4] и целевое число 6.
2 + 4 = 6, у 2 индекс 1, а у 4 индекс 2, возвращаем массив с индексами [1, 2].
Например, [1, -4, 6, 9, 4, 3, 8], и целевое число 5.
5 = -4 + 9, у -4 индекс 1, а у 9 индекс 3, возвращаем [1, 3]
Сигнатура функции принимает массив чисел, и целевое число, возвращает массив чисел (длина массива два элемента):
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]:
class Solution { /** * @param Integer[] $nums * @param Integer $target * @return Integer[] */ function twoSum($nums, $target) { }}
Решения кидайте прямо сюда, желательно ссылками на pastebin, чтобы не палить спойлеры с решениями.
У меня получилось две реализации, первую написал "в тупую", вторую - оптимизировал.
There is another very legenky task, but which can be defined as the person is able to optimize the code:
There is a list of numbers, for example [3, 2, 4], and the target number 6. It is necessary to return the indices of the array, the sum of which is equal to the target number. If as a result there are some combinations should be returned first.
For example, [3, 2, 4] and the target number of 6.
2 + 4 = 6, y 2 Index 1 and Index 2 y 4, return the array indices [1, 2].
For example, [1, -4, 6, 9, 4, 3, 8], and the target number 5.
5 = -4 + 9, y -4 index 1 and index 3 in 9, return [1, 3]
The signature function takes an array of numbers, and the target number, it returns an array of numbers (two elements of the array length):
class Solution: def twoSum (self, nums: List [int], target: int) -> List [int]:
class Solution { / ** * @Param Integer [] $ nums * @Param Integer $ target * @Return Integer [] * / function twoSum ($ nums, $ target) { } }
Solutions throw right here, it is desirable to link to pastebin, so as not to scorch spoilers with solutions.
I got two implementations, the first written "in a dull", the second - optimized.
hakuna matata, на Go такое пишется изи, у меня было и 100к грин-тредов, шлющих куда-то данные.
hakuna matata, the Go Easy is written, I had 100k and green of threads shlyuschih somewhere data.
Сложно, на самом деле re2 подключить не так просто, нужно скомпилить как либу, потом слинковать в бинарник. Потому что на Go никто не портировал re2. Как будет свободное время - поковыряюсь.
Go без компиляции: 0.005807088 секунд Go с компиляцией: 0.000459663 секунд (x12 speedup) PHP: 0.000177860 секунд (x2.5 speedup, х32 speedup)
А так? Понятное дело, что большинство приложений делают что-то ещё, кроме выполнения регулярок. На самом деле есть ещё несколько мест, где PHP быстрее Go (там где задача плохо бьется на потоки и где вызов функции описан в сишном модуле). Например, всякие TLS реализации могут быть быстрее в пыхе, только их там особо и негде применить.
It is difficult to really connect re2 not so easy, you need to be compiled as an libu, then linked into the binary. Because the Go no ported re2. It will be free time -'ll dig.
Go without compilation: 0.005807088 seconds Go to compilation: 0.000459663 seconds (x12 speedup) PHP: 0.000177860 seconds (x2.5 speedup, speedup x32)
And so? It is clear that most of the applications are doing something else besides performing regex. In fact, there are still a few places where PHP faster Go (where the problem is bad beats on flows and where the function call is described in sishnom module). For example, any TLS implementations can be faster in pyhe only them there by themselves, and no place to apply.
Там без разницы, хоть большая, хоть маленькая строка. И да, тест действительно синтетический, но это просто пример того, что быстрый язык в одних задачах не всегда быстр в других.
Либы под много что есть, было бы глупо создать тему, где каждый бы подключал либу и делал вызов одной функции. Суть темы прокачать скилл и пообщаться на тему кода и разработки (что мы и делаем, в принципе).