description
stringlengths
38
154k
category
stringclasses
5 values
solutions
stringlengths
13
289k
name
stringlengths
3
179
id
stringlengths
24
24
tags
listlengths
0
13
url
stringlengths
54
54
rank_name
stringclasses
8 values
For this kata you will have to forget how to add two numbers. It can be best explained using the following meme: [![Dayane Rivas adding up a sum while competing in the Guatemalan television show "Combate" in May 2016](https://i.ibb.co/Y01rMJR/caf.png)](https://knowyourmeme.com/memes/girl-at-whiteboard-adding) In simple terms, our method does not like the principle of carrying over numbers and just writes down every number it calculates :-) You may assume both integers are positive integers. ## Examples ```math \large \begin{array}{lll} & 1 & 6 \\ + & 1 & 8 \\ \hline & 2 & 1 4 \\ \end{array} \qquad \large \begin{array}{lll} & 2 & 6 \\ + & 3 & 9 \\ \hline & 5 & 15 \\ \end{array} \qquad ```   ```math \large \begin{array}{lll} & 1 & 2 & 2 \\ + & & 8 & 1 \\ \hline & 1 & 10 & 3 \\ \end{array} \qquad \large \begin{array}{lll} & 7 & 2 \\ + & & 9 \\ \hline & 7 & 11 \\ \end{array} ``` ~~~if:java You may assume both integers are positive integers and the result will not be bigger than `Integer.MAX_VALUE` ~~~
algorithms
def add(a, b): s = "" while a + b: a, p = divmod(a, 10) b, q = divmod(b, 10) s = str(p + q) + s return int(s or '0')
16+18=214
5effa412233ac3002a9e471d
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/5effa412233ac3002a9e471d
7 kyu
In cryptanalysis, words patterns can be a useful tool in cracking simple ciphers. A word pattern is a description of the patterns of letters occurring in a word, where each letter is given an integer code in order of appearance. So the first letter is given the code 0, and second is then assigned 1 if it is different to the first letter or 0 otherwise, and so on. As an example, the word "hello" would become "0.1.2.2.3". For this task case-sensitivity is ignored, so "hello", "helLo" and "heLlo" will all return the same word pattern. Your task is to return the word pattern for a given word. All words provided will be non-empty strings of alphabetic characters only, i.e. matching the regex "[a-zA-Z]+".
reference
def word_pattern(word): ret, box, i = [], {}, 0 for e in word . lower(): if e not in box: box[e] = str(i) i += 1 ret . append(box[e]) return '.' . join(ret)
Cryptanalysis Word Patterns
5f3142b3a28d9b002ef58f5e
[ "Fundamentals" ]
https://www.codewars.com/kata/5f3142b3a28d9b002ef58f5e
7 kyu
You probably know that some characters written on a piece of paper, after turning this sheet 180 degrees, can be read, although sometimes in a different way. So, uppercase letters "H", "I", "N", "O", "S", "X", "Z" after rotation are not changed, the letter "M" becomes a "W", and Vice versa, the letter "W" becomes a "M". We will call a word "shifter" if it consists only of letters "H", "I", "N", "O", "S", "X", "Z", "M" and "W". After turning the sheet, this word can also be read, although in a different way. So, the word "WOW "turns into the word "MOM". On the other hand, the word "HOME" is not a shifter. Find the number of **unique** shifter words in the input string (without duplicates). All shifters to be counted, even if they are paired (like "MOM" and "WOW"). String contains only uppercase letters. #### Examples ```javascript shifter("SOS IN THE HOME") === 2 // shifter words are "SOS" and "IN" shifter("WHO IS SHIFTER AND WHO IS NO") === 3 // shifter words are "WHO", "IS", "NO" shifter("TASK") === 0 // no shifter words shifter("") === 0 // no shifter words in empty string ``` ```python shifter("SOS IN THE HOME") == 2 # shifter words are "SOS" and "IN" shifter("WHO IS SHIFTER AND WHO IS NO") == 3 # shifter words are "WHO", "IS", "NO" shifter("TASK") == 0 # no shifter words shifter("") == 0 # no shifter words in empty string ``` ```java Shifter.count("SOS IN THE HOME") == 2 // shifter words are "SOS" and "IN" Shifter.count("WHO IS SHIFTER AND WHO IS NO") == 3 // shifter words are "WHO", "IS", "NO" Shifter.count("TASK") == 0 // no shifter words Shifter.count("") == 0 // no shifter words in empty string ``` ```rust shifter("SOS IN THE HOME") == 2 // shifter words are "SOS" and "IN" shifter("WHO IS SHIFTER AND WHO IS NO") == 3 // shifter words are "WHO", "IS", "NO" shifter("TASK") == 0 // no shifter words shifter("") == 0 // no shifter words in empty string ```
reference
def shifter(st): return sum(all(elem in "HIMNOSWXZ" for elem in x) for x in set(st . split()))
Shifter words
603b2bb1c7646d000f900083
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/603b2bb1c7646d000f900083
7 kyu
[FRACTRAN](https://esolangs.org/wiki/Fractran) is a Turing-complete esoteric programming language invented by John Conway. In Fractran, a program consists of a finite list of positive fractions. The input to a program is a positive integer `$n$`. The program is run by updating the integer `$n$` as follows: * For the first fraction `$f$` in the list for which `$n \cdot f$` is an integer, replace `$n$` by `$n \cdot f$` * Start from the beginning and repeat this rule until no fraction in the list produces an integer when multiplied by `$n$`, then halt. ## Example: This Fractran program: `$ \left( \dfrac{455}{33}, \dfrac{11}{13}, \dfrac{1}{11}, \dfrac{3}{7}, \dfrac{11}{2}, \dfrac{1}{3} \right)\quad $` given any integer of format `$2^a3^b$` outputs `$5^{a\times b}$`, hence it can be said that the program "multiplies" the integers `$a$` and `$b$`. Here is a simple instance: Input: `$12 = 2^2 3^1 ,\:$`here `$\: a=2,\: b=1$` Computation: `$2^23 \xrightarrow{11/2} 2\cdot3\cdot11 \xrightarrow{455/33} 2\cdot5\cdot7\cdot13 \xrightarrow{11/13} 2\cdot5\cdot7\cdot11 \xrightarrow{1/11} 2\cdot5\cdot7 \xrightarrow{3/7}2\cdot3\cdot5 \xrightarrow{11/2} 3\cdot5\cdot11 \xrightarrow{455/33} 5^2\cdot7\cdot13\xrightarrow{11/13}5^2\cdot7\cdot11\xrightarrow{1/11}5^2\cdot7\xrightarrow{3/7}3\cdot5^2\xrightarrow{1/3}5^2$` Output: `$5^2=5^{2\times 1} \:$`, in essence it multiplied `$2$` and `$1$`. ## Task: Your task is to write a function `fractran(code, n)` that runs the FRACTRAN program `code` with initial value `n` and returns the final `n` value after halting. * `code` is a string, formatted like this: `'455/33 11/13 1/11 3/7 11/2 1/3'` * `n` is an integer with `n >= 1` * every program consists of at least one fraction * if the program does not halt after `1000` cycles, return the `n` value after that many cycles **Note**: If this is too easy you could try writing a [Fractran interpreter in Fractran](https://stackoverflow.com/questions/1749905/code-golf-fractran) :D
algorithms
from fractions import Fraction as F def fractran(code, n): fs = [F(f) for f in code . split()] for _ in range(1000): try: n = next(f * n for f in fs if (f * n). denominator == 1) except StopIteration: break return n
Fractran Interpreter
5ebae674014091001729a9d7
[ "Interpreters", "Esoteric Languages" ]
https://www.codewars.com/kata/5ebae674014091001729a9d7
7 kyu
There are some stones on Bob's table in a row, and each of them can be red, green or blue, indicated by the characters `R`, `G`, and `B`. Help Bob find the minimum number of stones he needs to remove from the table so that the stones in each pair of adjacent stones have different colors. Examples: ``` "RGBRGBRGGB" => 1 "RGGRGBBRGRR" => 3 "RRRRGGGGBBBB" => 9 ```
reference
def solution(s): st = [1 for i in range(1, len(s)) if s[i - 1] == s[i]] return sum(st)
Stones on the Table
5f70e4cce10f9e0001c8995a
[ "Fundamentals" ]
https://www.codewars.com/kata/5f70e4cce10f9e0001c8995a
7 kyu
Given a string as input, return a new string with each letter pushed to the right by its respective index in the alphabet. We all know that `A` is a slow and `Z` is a fast letter. This means that `Z` gets shifted to the right by 25 spaces, `A` doesn't get shifted at all, and `B` gets shifted by 1 space. You can assume the following things about your input: - It will only contain uppercase letters from `A` to `Z`, no whitespaces or punctuation; - Input strings will not exceed 100 characters (although your output string might!) Note that if 2 or more letters fall onto the same space after shifting, the latest character will be used. For example: `"BA" -> " A"` ## Examples ``` "AZ" --> "A Z" "ABC" --> "A B C" "ACE" --> "A C E" "CBA" --> "  A" "HELLOWORLD" --> "  E H DLL OLO R W" ```
algorithms
def speedify(s): lst = [' '] * (len(s) + 26) for i, c in enumerate(s): lst[i + ord(c) - 65] = c return '' . join(lst). rstrip()
The Speed of Letters
5fc7caa854783c002196f2cb
[ "Algorithms" ]
https://www.codewars.com/kata/5fc7caa854783c002196f2cb
7 kyu
We will call a natural number a "doubleton number" if it contains exactly two distinct digits. For example, `23, 35, 100, 12121` are doubleton numbers, and `123` and `9980` are not. For a given natural number `n` (from `1` to `1 000 000`), you need to find the next doubleton number. If `n` itself is a doubleton, return the next bigger than `n`. #### Examples: ```coffeescript doubleton(120) == 121 doubleton(1234) == 1311 doubleton(10) == 12 ``` ```crystal doubleton(120) == 121 doubleton(1234) == 1311 doubleton(10) == 12 ``` ```javascript doubleton(120) === 121 doubleton(1234) === 1311 doubleton(10) === 12 ``` ```python doubleton(120) == 121 doubleton(1234) == 1311 doubleton(10) == 12 ``` ```ruby doubleton(120) == 121 doubleton(1234) == 1311 doubleton(10) == 12 ``` ```haskell doubleton 10 == 12 doubleton 120 == 121 doubleton 1234 == 1311 ``` ```prolog doubleton(10, 12). doubleton(120, 121). doubleton(1234, 1311). ``` ```swift doubleton(120) == 121 doubleton(1234) == 1311 doubleton(10) == 12 ``` ```rust doubleton(10) == 12 doubleton(120) == 121 doubleton(1234) == 1311 ``` ```csharp Doubleton(120) == 121 Doubleton(1234) == 1311 Doubleton(10) == 12 ``` ```julia doubleton(120) # returns 121 doubleton(1234) # returns 1311 doubleton(10) # returns 12 ``` ```vb Doubleton(120) 'returns 121 Doubleton(1234) 'returns 1311 Doubleton(10) 'returns 12 ```
reference
def doubleton(num): n = num + 1 while len(set(str(n))) != 2: n += 1 return n
Doubleton number
604287495a72ae00131685c7
[ "Sets", "Fundamentals" ]
https://www.codewars.com/kata/604287495a72ae00131685c7
7 kyu
Given a list of integers, find the positive difference between each consecutive pair of numbers, and put this into a new list of differences. Then, find the differences between consecutive pairs in this new list, and repeat until the list has a length of `1`. Then, return the single value. The list will only contain integers, and will not be empty. For example: ```python differences([1, 2, 3]) => [1, 1] => [0] => 0 differences([1, 5, 2, 7, 8, 9, 0]) => [4, 3, 5, 1, 1, 9] => [1, 2, 4, 0, 8] => ... => 1 differences([2, 3, 1]) => [1, 2] => 1 ``` ```haskell differences [1, 2, 3] -> [1, 1] -> [0] -> 0 differences [1, 5, 2, 7, 8, 9, 0] -> [4, 3, 5, 1, 1, 9] -> [1, 2, 4, 0, 8] -> .. -> 1 differences [2, 3, 1] -> [1, 2] -> [1] -> 1 ``` ```javascript differences([1, 2, 3]) => [1, 1] => [0] -> 0 differences([1, 5, 2, 7, 8, 9, 0]) => [4, 3, 5, 1, 1, 9] => [1, 2, 4, 0, 8] => .. => 1 differences([2, 3, 1]) => [1, 2] => [1] => 1 ```
algorithms
def differences(lst): if len(lst) < 2: return lst[0] if lst else 0 return differences([abs(b - a) for a, b in zip(lst, lst[1:])])
Consecutive Differences
5ff22b6e833a9300180bb953
[ "Algorithms" ]
https://www.codewars.com/kata/5ff22b6e833a9300180bb953
7 kyu
Red Knight is chasing two pawns. Which pawn will be caught, and where? #### Input / Output Input will be two integers: - `N` / `n` (Ruby) vertical position of Red Knight (`0` or `1`). - `P` / `p` (Ruby) horizontal position of two pawns (between `2` and `1000000`). Output has to be a _tuple_ (python, haskell, Rust, prolog, C#), an _array_ (javascript, ruby), an _object_ (java), or a _structure_ (C) with: - `"Black"` or `"White"` - which pawn was caught - Where it was caught (horizontal position) #### Example ```python Input = 0, 4 Output = ("White", 8) ``` ```haskell Input = 0, 4 Output = ("White", 8) ``` ```javascript Input = 0, 4 Output = ["White", 8] ``` ```ruby Input = 0, 4 Output = ["White", 8] ``` ```c typedef struct Pawn_Distance { char pawn; unsigned distance; } pd; pd red_knight(unsigned N, unsigned P); // Note: C code uses a char in place of a string // use 'B' for "Black" and 'W' for "White" Input = 0U, 4U Output = pd{'W', 8U}; ``` ```rust Input = 0, 4 Output = ("White", 8) ``` ```java // This class is preloaded class PawnDistance { private String color; private long distance; public PawnDistance(String s, long d) { color = s; distance = d; } } Input = 0, 4; Output = new PawnDistance("White", 8); ``` ```prolog red_knight(0, 4, ("White", 8)). ``` ```csharp Input = 0, 4 Output = ("White", 8) ``` <svg width="450" height="142" xmlns="http://www.w3.org/2000/svg"> <g> <title>background</title> </g> <g> <title>Layer 1</title> <rect stroke="#fff" id="svg_1" height="50" width="50" x="77" stroke-width="0" fill="#769656" y="9.28571"/> <rect stroke="#fff" id="svg_2" height="50" width="50" y="9.28571" x="27" stroke-width="0" fill="#eeeed2"/> <rect stroke="#fff" id="svg_4" height="50" width="50" y="9.28571" x="127" stroke-width="0" fill="#eeeed2"/> <rect stroke="#fff" id="svg_3" height="50" width="50" x="277" stroke-width="0" fill="#769656" y="9.28571"/> <rect stroke="#fff" id="svg_6" height="50" width="50" y="9.28571" x="227" stroke-width="0" fill="#eeeed2"/> <rect stroke="#fff" id="svg_7" height="50" width="50" y="9.28571" x="327" stroke-width="0" fill="#eeeed2"/> <rect stroke="#fff" id="svg_8" height="50" width="50" y="9.28571" x="177" stroke-width="0" fill="#769656"/> <rect stroke="#fff" id="svg_9" height="50" width="50" x="127" stroke-width="0" fill="#769656" y="59.28572"/> <rect stroke="#fff" id="svg_10" height="50" width="50" y="59.28572" x="77" stroke-width="0" fill="#eeeed2"/> <rect stroke="#fff" id="svg_11" height="50" width="50" y="59.28572" x="177" stroke-width="0" fill="#eeeed2"/> <rect stroke="#fff" id="svg_12" height="50" width="50" y="59.28572" x="27" stroke-width="0" fill="#769656"/> <rect stroke="#fff" id="svg_13" height="50" width="50" x="327.00001" stroke-width="0" fill="#769656" y="59.28572"/> <rect stroke="#fff" id="svg_14" height="50" width="50" y="59.28572" x="277.00001" stroke-width="0" fill="#eeeed2"/> <rect stroke="#fff" id="svg_15" height="50" width="50" y="59.28572" x="377.00001" stroke-width="0" fill="#eeeed2"/> <rect stroke="#fff" id="svg_16" height="50" width="50" y="59.28572" x="227.00001" stroke-width="0" fill="#769656"/> <rect stroke="#fff" id="svg_17" height="50" width="50" y="9.28571" x="377" stroke-width="0" fill="#769656"/> <path stroke="#544545" id="svg_5" d="m58.63751,53.70918c1.38529,0.04365 3.41278,-0.61956 1.99635,-2.09899c-1.5421,-0.56322 0.27408,-2.43002 -1.27137,-3.30938c-1.24049,-1.63665 -2.92636,-3.13124 -3.43512,-5.12989c0.07901,-1.35549 1.82523,-2.15768 0.99213,-3.65801c0.81734,-2.4009 0.62845,-5.16434 -0.86355,-7.32255c-1.26691,-2.00454 -2.80508,-4.12849 -2.64286,-6.55426c1.58894,0.61479 3.27086,1.15345 5.01957,0.87424c1.64404,-0.14147 3.1185,1.09202 4.79548,0.42132c1.69992,-0.32724 2.71106,-2.43327 1.44359,-3.66438c-1.3851,-1.09624 -3.42017,-1.13153 -4.74114,-2.35496c-1.74288,-1.33774 -3.35495,-3.14709 -5.75706,-3.38359c-1.06168,-0.22522 -1.51705,-1.21372 -2.10474,-1.95451c-0.48838,1.17491 -1.33781,2.21385 -2.61625,2.73471c-2.59972,1.39527 -3.24686,4.34504 -4.20557,6.7699c-0.70885,1.89907 -1.29942,3.88184 -2.48643,5.57723c-0.01262,0.81368 1.31978,1.1576 0.41984,2.11149c-0.46804,2.58709 -0.48819,5.23629 -0.44669,7.85361c0.78938,1.28084 1.5084,2.71045 0.4554,4.18038c-0.70338,1.79667 -2.45513,2.97504 -3.31697,4.67046c-0.48718,0.87789 0.94977,2.15243 -0.84056,1.93164c-1.63499,0.80149 -0.31478,2.75789 1.31134,2.18873c6.09395,0.14358 12.20133,0.28696 18.29462,0.11678l0,0l-0.00001,0.00003z" stroke-width="NaN" fill="#c43131"/> <text xml:space="preserve" text-anchor="start" font-family="Helvetica, Arial, sans-serif" font-size="24" id="svg_21" y="131.50108" x="92.41379" stroke-width="NaN" stroke="#6b5656" fill="#ff7f00">1</text> <text xml:space="preserve" text-anchor="start" font-family="Helvetica, Arial, sans-serif" font-size="24" id="svg_22" y="132.53556" x="143.44827" stroke-width="NaN" stroke="#6b5656" fill="#ff7f00">2</text> <text xml:space="preserve" text-anchor="start" font-family="Helvetica, Arial, sans-serif" font-size="24" id="svg_23" y="132.19073" x="193.7931" stroke-width="NaN" stroke="#6b5656" fill="#ff7f00">3</text> <text xml:space="preserve" text-anchor="start" font-family="Helvetica, Arial, sans-serif" font-size="24" id="svg_24" y="130.4666" x="42.06896" stroke-width="NaN" stroke="#6b5656" fill="#ff7f00">0</text> <text xml:space="preserve" text-anchor="start" font-family="Helvetica, Arial, sans-serif" font-size="24" id="svg_25" y="132.19073" x="244.13794" stroke-width="NaN" stroke="#6b5656" fill="#ff7f00">4</text> <text xml:space="preserve" text-anchor="start" font-family="Helvetica, Arial, sans-serif" font-size="24" id="svg_26" y="132.53556" x="296.89656" stroke-width="NaN" stroke="#6b5656" fill="#ff7f00">5</text> <text xml:space="preserve" text-anchor="start" font-family="Helvetica, Arial, sans-serif" font-size="24" id="svg_27" y="131.50108" x="345.17241" stroke-width="NaN" stroke="#6b5656" fill="#ff7f00">6</text> <text xml:space="preserve" text-anchor="start" font-family="Helvetica, Arial, sans-serif" font-size="24" id="svg_28" y="131.15625" x="397.58621" stroke-width="NaN" stroke="#6b5656" fill="#ff7f00">7</text> <text xml:space="preserve" text-anchor="start" font-family="Helvetica, Arial, sans-serif" font-size="24" id="svg_29" y="38.0528" x="5.17241" stroke-width="NaN" stroke="#6b5656" fill="#ff7f00">0</text> <text xml:space="preserve" text-anchor="start" font-family="Helvetica, Arial, sans-serif" font-size="24" id="svg_30" y="89.43211" x="4.82758" stroke-width="NaN" stroke="#6b5656" fill="#ff7f00">1</text> <path stroke="#544545" id="svg_31" d="m91.71362,39.19855l50.78449,0l0,24.65518l-7.78448,0l15.56896,12.32759l15.56897,-12.32759l-7.78449,0l0,-36.98277l-66.35345,0l0,12.32759z" stroke-width="NaN" fill="none"/> <path id="svg_32" d="m281.52305,42.45613l4.48309,-4.21317l-8.66784,0l-8.66782,0l0,-2.60815l0,-2.60815l8.56838,0c4.7126,0 8.56838,-0.13219 8.56838,-0.29376c0,-0.16157 -1.87607,-2.05749 -4.16905,-4.21317l-4.16906,-3.91941l3.85348,0l3.85347,0l5.88512,5.52253l5.88512,5.52252l-5.89641,5.51196l-5.89641,5.51196l-4.05678,0l-4.05679,0l4.4831,-4.21317l0,0l0.00002,0.00001z" stroke-opacity="null" stroke-width="NaN" stroke="#544545" fill="none"/> <path id="svg_33" d="m281.52305,90.04234l4.48309,-4.21317l-8.66784,0l-8.66782,0l0,-2.60815l0,-2.60815l8.56838,0c4.71261,0 8.56838,-0.13219 8.56838,-0.29377c0,-0.16156 -1.87607,-2.05749 -4.16905,-4.21316l-4.16906,-3.91941l3.85349,0l3.85347,0l5.88512,5.52253l5.88512,5.52253l-5.89641,5.51195l-5.8964,5.51196l-4.05679,0l-4.05679,0l4.48311,-4.21316l0,0z" stroke-opacity="null" stroke-width="NaN" stroke="#544545" fill="none"/> </g> <g> <title>background</title> </g> <g> <title>background</title> <rect fill="none" id="canvas_background" height="144" width="452" y="-1" x="-1"/> <path id="svg_18" d="m243.23375,47.58404c-1.01358,0.15423 -2.4698,-0.80853 -1.18661,-1.68349c1.0859,-0.56899 0.04388,-2.05065 1.19219,-2.77034c1.16763,-1.59407 2.41073,-3.22356 2.99261,-5.13613c-0.08119,-0.91627 -1.89601,-2.433 -0.05741,-2.73018c1.51604,0.17624 0.96156,-2.0935 1.48554,-3.07695c0.31508,-1.49274 0.54411,-3.01038 0.48757,-4.5393c-1.05579,-0.02948 -2.1332,0.09344 -3.16827,-0.15758c-0.66024,-0.86664 1.49169,-1.29814 1.84678,-2.08039c0.74504,-1.12431 -1.09067,-2.36654 -0.30486,-3.69561c0.50193,-2.01193 2.82394,-3.31633 4.7887,-2.57933c2.03456,0.52762 3.53852,2.93101 2.5715,4.93018c-0.0772,0.38569 -0.68143,0.88577 -0.47963,1.19291c0.88097,0.61138 1.901,1.14419 2.45915,2.08822c-0.79027,0.573 -2.1126,0.13662 -3.09861,0.40882c-0.89704,0.79568 -0.01095,2.42257 0.03499,3.51422c0.27984,1.24728 0.52689,2.50556 0.84758,3.74147c0.67416,0.26297 2.05885,0.56747 1.29927,1.65988c-1.08286,0.87908 -0.5528,2.2793 0.05812,3.26578c0.76036,1.52343 2.0656,2.6872 2.86521,4.17544c0.29694,0.68709 -0.76459,1.90396 0.55841,1.6194c1.43428,0.30467 0.576,2.29341 -0.71284,1.82354c-4.74882,0.16721 -9.50739,0.23509 -14.25632,0.05013l-0.22308,-0.0207l0,0l0,0z" stroke="#000" fill="#fff"/> <path id="svg_20" d="m242.89477,100.80436c-1.01358,0.15423 -2.4698,-0.80853 -1.18661,-1.68349c1.0859,-0.56899 0.04388,-2.05064 1.19219,-2.77033c1.16763,-1.59407 2.41073,-3.22356 2.99261,-5.13613c-0.08119,-0.91627 -1.89602,-2.433 -0.05742,-2.73018c1.51605,0.17624 0.96156,-2.0935 1.48554,-3.07696c0.31508,-1.49274 0.54411,-3.01037 0.48758,-4.53929c-1.0558,-0.02948 -2.1332,0.09344 -3.16827,-0.15758c-0.66024,-0.86664 1.49169,-1.29814 1.84678,-2.08039c0.74504,-1.12431 -1.09067,-2.36654 -0.30486,-3.69561c0.50192,-2.01193 2.82394,-3.31633 4.7887,-2.57933c2.03456,0.52761 3.53852,2.931 2.5715,4.93017c-0.0772,0.38569 -0.68143,0.88577 -0.47963,1.19292c0.88097,0.61138 1.901,1.14419 2.45915,2.08821c-0.79026,0.57301 -2.11259,0.13663 -3.0986,0.40882c-0.89705,0.79568 -0.01096,2.42257 0.03499,3.51422c0.27984,1.24728 0.52689,2.50556 0.84758,3.74147c0.67415,0.26297 2.05885,0.56747 1.29927,1.65989c-1.08286,0.87908 -0.5528,2.27929 0.05812,3.26577c0.76036,1.52343 2.06559,2.6872 2.86521,4.17544c0.29695,0.68709 -0.76459,1.90396 0.55841,1.6194c1.43428,0.30468 0.57601,2.29342 -0.71284,1.82354c-4.74882,0.16721 -9.50739,0.23509 -14.25632,0.05013l-0.22308,-0.02069l0,0l0,0z" stroke-width="1.5" fill="#000000"/> </g> </svg> #### Notes - Red Knight will always start at horizontal position `0`. - The black pawn will always be at the bottom (vertical position `1`). - The white pawn will always be at the top (vertical position `0`). - The pawns move first, and they move simultaneously. - Red Knight moves `2` squares forward and `1` up or down. - Pawns always move `1` square forward. - Both pawns will start at the same horizontal position.
reference
def red_knight(N, P): return ('White' if P % 2 == N else 'Black', P * 2)
Red Knight
5fc4349ddb878a0017838d0f
[ "Puzzles", "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/5fc4349ddb878a0017838d0f
7 kyu
A laboratory is testing how atoms react in ionic state during nuclear fusion. They introduce different elements with Hydrogen in high temperature and pressurized chamber. Due to unknown reason the chamber lost its power and the elements in it started precipitating</br> Given the number of atoms of Carbon [C],Hydrogen[H] and Oxygen[O] in the chamber. Calculate how many molecules of Water [H<sub>2</sub>O], Carbon Dioxide [CO<sub>2</sub>] and Methane [CH<sub>4</sub>] will be produced following the order of reaction affinity below</br> <pre = lang="python"> <code>1. Hydrogen reacts with Oxygen = H<sub>2</sub>O 2. Carbon reacts with Oxygen = CO<sub>2</sub> 3. Carbon reacts with Hydrogen = CH<sub>4</sub> </code></pre> <img src="https://i.imgur.com/wDYZ9zg.jpg"/> <b>FOR EXAMPLE:</b><br/> (C,H,O) = (45,11,100)<br/> return no. of water, carbon dioxide and methane molecules<br/> <u>Output should be like:</u><br/> (5,45,0)<br/>
reference
# Make sure you follow the order of reaction # output should be H2O,CO2,CH4 def burner(c, h, o): water = co2 = methane = 0 while h > 1 and o > 0: water += 1 h -= 2 o -= 1 while c > 0 and o > 1: co2 += 1 c -= 1 o -= 2 while c > 0 and h > 3: methane += 1 c -= 1 h -= 4 return water, co2, methane
⚠️Fusion Chamber Shutdown⚠️
5fde1ea66ba4060008ea5bd9
[ "Fundamentals" ]
https://www.codewars.com/kata/5fde1ea66ba4060008ea5bd9
7 kyu
# Right in the Center _This is inspired by one of Nick Parlante's exercises on the [CodingBat](https://codingbat.com/java) online code practice tool._ Given a sequence of characters, does `"abc"` appear in the CENTER of the sequence? The sequence of characters could contain more than one `"abc"`. To define CENTER, the number of characters in the sequence to the left and right of the "abc" (which is in the middle) must differ by at most one. If it is in the CENTER, return `True`. Otherwise, return `False`. Write a function as the solution for this problem. This kata looks simple, but it might not be easy. ## Example is_in_middle("AAabcBB") -> True is_in_middle("AabcBB") -> True is_in_middle("AabcBBB") -> False
reference
def is_in_middle(s): while len(s) > 4: s = s[1: - 1] return 'abc' in s
Right in the Centre
5f5da7a415fbdc0001ae3c69
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5f5da7a415fbdc0001ae3c69
7 kyu
Your friend has recently started using Codewars to learn more advanced coding. They have just created their first kata, and they want to write a proper description for it, using codeblocks, images and hyperlinks. However, they are struggling to understand how to use Markdown formatting properly, so they decide to ask for your help, by having you write a program that will generate some of the syntaxes for you. ## Markdown syntaxes * links: `[displayed text](url address)` * images: `![replacement message](url address)` * codeblocks: we'll use multiline codeblocks like the following ```` ```language code ``` ```` ## Task Your task is to create a function called `generate_markdowns` or `generateMarkdowns`. It will take three parameters: - `markdown` - The type of markdown to return. It can be ``"link"``, ``"img"`` or ``"code"``. - `text` - The text,message or code to display - `url_or_language` or `urlOrLanguage` - gives either the url address to use or the name of the language for the codeblock. ### Examples --- ```python generate_markdowns('link','Github Codewars','https://github.com/codewars') # returns: "[Github Codewars](https://github.com/codewars)" ``` When used in the description: [Github Codewars](https://github.com/codewars) --- ```python generate_markdowns('img','this should be a picture','https://github.com/codewars/gna.jpg') # returns: "![this should be a picture](https://github.com/codewars/gna.jpg)" ``` When used in the description (no image, sorry... ;o ): ![this should be a picture](https://github.com/codewars/gna.jpg) --- ```python code = '''\ def generate_markdowns(markdown, text, url_or_language): # Your code here! pass''' generate_markdowns('code', code, 'python') # returns: "```python\ndef generate_markdowns(markdown, text, url_or_language):\n # Your code here!\n pass\n```" ``` When used in the description: ```python def generate_markdowns(markdown, text, url_or_language): # Your code here! pass ```
reference
MODELS = { 'link': '[{txt}]({uL})', 'img': '![{txt}]({uL})', 'code': "```{uL}\n{txt}\n```", } def generate_markdowns(mkd, txt, url_or_language): return MODELS[mkd]. format(txt=txt, uL=url_or_language)
Generating Markdowns
5f656199132bf60027275739
[ "Fundamentals" ]
https://www.codewars.com/kata/5f656199132bf60027275739
7 kyu
If you've completed this kata already and want a bigger challenge, here's the [3D version](https://www.codewars.com/kata/5f849ab530b05d00145b9495/) Bob is bored during his physics lessons so he's built himself a toy box to help pass the time. The box is special because it has the ability to change gravity. There are some columns of toy cubes in the box arranged in a line. The `i`-th column contains `a_i` cubes. At first, the gravity in the box is pulling the cubes downwards. When Bob switches the gravity, it begins to pull all the cubes to a certain side of the box, `d`, which can be either `'L'` or `'R'` (left or right). Below is an example of what a box of cubes might look like before and after switching gravity. ``` +---+ +---+ | | | | +---+ +---+ +---++---+ +---+ +---++---++---+ | || | | | --> | || || | +---++---+ +---+ +---++---++---+ +---++---++---++---+ +---++---++---++---+ | || || || | | || || || | +---++---++---++---+ +---++---++---++---+ ``` Given the initial configuration of the cubes in the box, find out how many cubes are in each of the `n` columns after Bob switches the gravity. ### Examples (input -> output: ``` * 'R', [3, 2, 1, 2] -> [1, 2, 2, 3] * 'L', [1, 4, 5, 3, 5 ] -> [5, 5, 4, 3, 1] ```
games
def flip(d, a): return sorted(a, reverse=d == 'L')
Gravity Flip
5f70c883e10f9e0001c89673
[ "Puzzles", "Arrays" ]
https://www.codewars.com/kata/5f70c883e10f9e0001c89673
8 kyu
## Introduction `float`s have limited precision and are unable to exactly represent some values. Rounding errors accumulate with repeated computation, and numbers expected to be equal often differ slightly. As a result, it is common advice to not use an exact equality comparison (`==`) with floats. ```python >>> a, b, c = 1e-9, 1e-9, 3.33e7 >>> (a + b) + c == a + (b + c) False >>> 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 == 1.0 False ``` ```cpp a, b, c = 1e-9, 1e-9, 3.33e7; (a + b) + c == a + (b + c); --> false 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 == 1.0; --> false ``` The solution is to check if a computed value is close to an expected value, without requiring them to be exactly equal. It seems very easy, but many katas test float results the wrong way. ## Task You have: - a float value that comes from a computation and may have accumulated errors up to ±0.001 - a reference value ```if:python - a function `approx_equals` that compare the two values taking into account loss of precision; the function should return `True` if and only if the two values are close to each other, the maximum allowed difference is `0.001` ``` ```if:cpp - a function `approx_equals` that compare the two values taking into account loss of precision; the function should return `true` if and only if the two values are close to each other, the maximum allowed difference is `0.001` ``` The function is bugged and sometimes returns wrong results. Your task is to correct the bug. ## Note This kata uses fixed tolerance for simplicity reasons, but usually relative tolerance is better. Fixed tolerance is useful for comparisons near zero or when the magnitude of the values is known.
bug_fixes
def approx_equals(a, b): return abs(a - b) < 0.001
Floating point comparison
5f9f43328a6bff002fa29eb8
[ "Fundamentals", "Mathematics", "Debugging" ]
https://www.codewars.com/kata/5f9f43328a6bff002fa29eb8
8 kyu
Bob has a ladder. He wants to climb this ladder, but being a precocious child, he wonders in exactly how many ways he could climb this `n` size ladder using jumps of up to distance `k`. Consider this example... n = 5 k = 3 Here, Bob has a ladder of length `5`, and with each jump, he can ascend up to `3` steps ( he can climb either `1`, `2`, or `3` steps at a time, each time ). This gives the following possibilities: 1 1 1 1 1 1 1 1 2 1 1 2 1 1 2 1 1 2 1 1 1 1 2 2 2 2 1 2 1 2 1 1 3 1 3 1 3 1 1 2 3 3 2 Your task is to calculate for Bob the number of ways to climb a ladder of length `n` in steps up to `k` ( `13` in above case ). Constraints: ```javascript 1 <= n <= 50 1 <= k <= 15 ```
reference
from collections import deque def count_ways(n, k): s, d = 1, deque([0] * k) for i in range(n): d . append(s) s = 2 * s - d . popleft() return s - d . pop()
Bob's Jump
5eea52f43ed68e00016701f3
[ "Performance", "Fundamentals" ]
https://www.codewars.com/kata/5eea52f43ed68e00016701f3
null
## Your Task Complete the function to convert an integer into a string of the Turkish name. * input will always be an integer 0-99; * output should always be lower case. ## Background Forming the Turkish names for the numbers 0-99 is very straightforward: * units (0-9) and tens (10, 20, 30, etc.) each have their own unique name; * all other numbers are simply _[tens] + [unit]_, like _twenty one_ in English. Unlike English, Turkish does not have "teen"-suffixed numbers; e.g. 13 would be directly translated as "ten three" rather than "thirteen" in English. Turkish names of units and tens are as follows: ``` 0 = sıfır 1 = bir 2 = iki 3 = üç 4 = dört 5 = beş 6 = altı 7 = yedi 8 = sekiz 9 = dokuz 10 = on 20 = yirmi 30 = otuz 40 = kırk 50 = elli 60 = altmış 70 = yetmiş 80 = seksen 90 = doksan ``` ## Examples ``` 1 --> "bir" 13 --> "on üç" 27 --> "yirmi yedi" 38 --> "otuz sekiz" 77 --> "yetmiş yedi" 94 --> "doksan dört" ``` Good luck, or _iyi şanslar_ :)
reference
UNITS = ' bir iki üç dört beş altı yedi sekiz dokuz' . split(' ') TENS = ' on yirmi otuz kırk elli altmış yetmiş seksen doksan' . split(' ') def get_turkish_number(n): return f' { TENS [ n / / 10 ] } { UNITS [ n % 10 ] } ' . strip() or 'sıfır'
Turkish Numbers, 0-99
5ebd53ea50d0680031190b96
[ "Fundamentals" ]
https://www.codewars.com/kata/5ebd53ea50d0680031190b96
7 kyu
## Task Create a function that given a sequence of strings, groups the elements that can be obtained by rotating others, ignoring upper or lower cases. In the event that an element appears more than once in the input sequence, only one of them will be taken into account for the result, discarding the rest. ## Input Sequence of strings. Valid characters for those strings are uppercase and lowercase characters from the alphabet and whitespaces. ## Output Sequence of elements. Each element is the group of inputs that can be obtained by rotating the strings. Sort the elements of each group alphabetically. Sort the groups descendingly by size and in the case of a tie, by the first element of the group alphabetically. ## Examples ```python ['Tokyo', 'London', 'Rome', 'Donlon', 'Kyoto', 'Paris', 'Okyot'] --> [['Kyoto', 'Okyot', 'Tokyo'], ['Donlon', 'London'], ['Paris'], ['Rome']] ['Rome', 'Rome', 'Rome', 'Donlon', 'London'] --> [['Donlon', 'London'], ['Rome']] [] --> [] ```
games
def group_cities(seq): result = [] sort_result = [] seq = list(dict . fromkeys(seq)) # removing duplicates for e, i in enumerate(seq): sort_result = [j for j in seq if len(j) == len( i) and j . lower() in 2 * (i . lower())] if not sorted(sort_result) in result: result . append(sorted(sort_result)) return (sorted(sorted(result), key=len, reverse=True))
rotate the letters of each element
5e98712b7de14f0026ef1cc1
[ "Lists", "Strings", "Sorting" ]
https://www.codewars.com/kata/5e98712b7de14f0026ef1cc1
6 kyu
Let us take a string composed of decimal digits: `"10111213"`. We want to code this string as a string of `0` and `1` and after that be able to decode it. To code we decompose the given string in its decimal digits (in the above example: `1 0 1 1 1 2 1 3`) and we will code each digit. #### Coding process to code a number n expressed in base 10: For each digit `d` of `n` - a) Let `k` be the number of bits of `d` - b) Write `k-1` times the digit `0` followed by the digit `1` - c) Write digit `d` as a binary string, with the rightmost bit being the least significant - d) Concat the result of b) and c) to get the coding of `d` At last concatenate all the results got for the digits of `n`. #### An example So we code `0` as `10`, `1` as `11`, `2` as `0110`, `3` as `0111` ... etc... With the given process, the initial string `"10111213"` becomes: `"11101111110110110111"` resulting of concatenation of `11 10 11 11 11 0110 11 0111`. #### Task: - Given `strng` a string of digits representing a decimal number the function `code(strng)` should return the coding of `strng` as explained above. - Given a string `strng` resulting from the previous coding, decode it to get the corresponding decimal string. #### Examples: ``` code("77338855") --> "001111001111011101110001100000011000001101001101" code("77338") --> "0011110011110111011100011000" code("0011121314") --> "1010111111011011011111001100" decode("001111001111011101110001100000011000001101001101") -> "77338855" decode("0011110011110111011100011000") -> "77338" decode("1010111111011011011111001100") -> "0011121314" ``` #### Notes - SHELL: The only tested function is `decode`. - Please could you ask before translating.
reference
def code(s): return '' . join(f' { "0" * ( d . bit_length () - 1 )} 1 { d : b } ' for d in map(int, s)) def decode(s): it, n, out = iter(s), 1, [] for c in it: if c == '0': n += 1 else: out . append(int('' . join(next(it) for _ in range(n)), 2)) n = 1 return '' . join(map(str, out))
Binaries
5d98b6b38b0f6c001a461198
[ "Fundamentals" ]
https://www.codewars.com/kata/5d98b6b38b0f6c001a461198
6 kyu
A floating-point number can be represented as `mantissa * radix ^ exponent` (^ is raising radix to power exponent). In this kata we will be given a positive floating-point number `aNumber` and we want to decompose it into a positive integer `mantissa` composed of a given number of digits (called `digitsNumber`) and of an `exponent`. #### Example: `aNumber = 0.06` If the number of digits asked for the `mantissa` is `digitsNumber = 10` one can write ``` aNumber : 6000000000 * 10 ^ -11 ``` the exponent in this example est `-11`. #### Task The function `mantExp(aNumber, digitsNumber)` will return `aNumber` in the form of a string: "mantissaPexponent" (concatenation of "mantissa", "P", "exponent"). So: ### Examples: ``` mantExp(0.06, 10) returns "6000000000P-11". mantExp(72.0, 12) returns "720000000000P-10" mantExp(1.0, 5) returns "10000P-4" mantExp(123456.0, 4) returns "1234P2" ``` #### Notes: - In some languages `aNumber` could be given in the form of a string: ``` mantExp("0.06", 10) returns "6000000000P-11". ``` - 1 <= digitsNumber <= 15 - 0 < aNumber < 5.0 ^ 128 - Please ask before translating
reference
def mant_exp(a_number, digits_number): exp = 0 m = a_number num = 10 * * digits_number if m < num: # negative exponent while m * 10 < num: m *= 10 exp -= 1 else: while m >= num: m /= 10 exp += 1 return str(int(m)) + 'P' + str(exp)
A floating-point system
5df754981f177f0032259090
[ "Fundamentals" ]
https://www.codewars.com/kata/5df754981f177f0032259090
6 kyu
### Description Find the sum of all numbers with the same digits (permutations) as the input number, **including duplicates**. However, due to the fact that this is a performance edition kata, the input can go up to `10**10000`. That's a number with 10001 digits (at most)! Be sure to use efficient algorithms and good luck! All numbers tested for will be positive. ### Examples ``` 98 --> 187 ; 89 + 98 = 187 123 --> 1332 ; 123 + 132 + 213 + 231 + 312 + 321 = 1332 1185 --> 99990 ; 1185 + 1158 + 1815 + 1851 + 1518 + 1581 + 1185 + 1158 + 1815 + + 1851 + 1518 + 1581 + 8115 + 8151 + 8115 + 8151 + 8511 + 8511 + + 5118 + 5181 + 5118 + 5181 + 5811 + 5811 = 99990 ```
reference
from math import factorial as fact def sum_arrangements(n): s = str(n) perms = fact(len(s) - 1) coefAll = int('1' * len(s)) return coefAll * perms * sum(map(int, s))
Sum of all numbers with the same digits (performance edition)
5eb9a92898f59000184c8e34
[ "Performance", "Permutations", "Fundamentals" ]
https://www.codewars.com/kata/5eb9a92898f59000184c8e34
6 kyu
In this kata your task is to differentiate a mathematical expression given as a string in prefix notation. The result should be the derivative of the expression returned in prefix notation. To simplify things we will use a simple list format made up of parentesis and spaces. - The expression format is (func arg1) or (op arg1 arg2) where op means operator, func means function and arg1, arg2 are aguments to the operator or function. For example (+ x 1) or (cos x) - The expressions will always have balanced parentesis and with spaces between list items. - Expression operators, functions and arguments will all be lowercase. - Expressions are single variable expressions using ```x``` as the variable. - Expressions can have nested arguments at any depth for example ```(+ (* 1 x) (* 2 (+ x 1)))``` Examples of prefix notation in this format: ``` (+ x 2) // prefix notation version of x+2 (* (+ x 3) 5) // same as 5 * (x + 3) (cos (+ x 1)) // same as cos(x+1) (^ x 2) // same as x^2 meaning x raised to power of 2 ``` The operators and functions you are required to implement are ```+ - * / ^ cos sin tan exp ln``` where ```^``` means raised to power of. ```exp``` is the exponential function (same as `e^x`) and ```ln``` is the natural logarithm (base e). Example of input values and their derivatives: ``` (* 1 x) => 1 (^ x 3) => (* 3 (^ x 2)) (cos x) => (* -1 (sin x)) ``` In addition to returning the derivative your solution must also do *some* simplifications of the result but only what is specified below. - The returned expression should not have unecessary 0 or 1 factors. For example it should not return ```(* 1 (+ x 1))``` but simply the term ```(+ x 1)``` similarly it should not return ```(* 0 (+ x 1))``` instead it should return just 0 - Results with two constant values such as for example ```(+ 2 2)``` should be evaluated and returned as a single value 4 - Any argument raised to the zero power should return 1 and if raised to 1 should return the same value or variable. For example (^ x 0) should return 1 and (^ x 1) should return x - No simplifications are expected for functions like cos, sin, exp, ln... (but their arguments might require a simplification). Think recursively and build your answer according to the [rules of derivation](http://www.rapidtables.com/math/calculus/derivative.htm) and sample test cases. If you need to diff any test expressions you can use [Wolfram Alpha](http://www.wolframalpha.com/) however remember we use prefix format in this kata. Best of luck !
algorithms
def parse_expr(s): s = s[1: - 1] if s[0] == '(' else s if s . isdigit(): return ('num', int(s)) elif ' ' not in s: return ('var', s) depth = 0 first_space = s . index(' ') op = s[: first_space] for i, c in enumerate(s[first_space + 1:]): if c == '(': depth += 1 elif c == ')': depth -= 1 if depth == 0 and c == ' ': second_space = first_space + i + 1 return op, parse_expr(s[first_space + 1: second_space]), parse_expr(s[second_space + 1::]) return op, parse_expr(s[first_space + 1:]) def deriv(expr): op, a, b = expr + ((None,) if len(expr) < 3 else ()) return { 'num': lambda: ('num', 0), 'var': lambda: ('num', 1), '+': lambda: ('+', deriv(a), deriv(b)), '-': lambda: ('-', deriv(a), deriv(b)), '*': lambda: ('+', ('*', deriv(a), b), ('*', a, deriv(b))), '/': lambda: ('/', ('-', ('*', deriv(a), b), ('*', a, deriv(b))), ('^', b, ('num', 2))), 'exp': lambda: ('*', deriv(a), ('exp', a)), 'tan': lambda: ('*', deriv(a), ('+', ('num', 1), ('^', ('tan', a), 2))), 'sin': lambda: ('*', deriv(a), ('cos', a)), 'cos': lambda: ('*', deriv(a), ('*', ('num', - 1), ('sin', a))), 'ln': lambda: ('/', deriv(a), a), '^': lambda: ('*', ('*', ('num', b[1]), ('^', a, ('num', b[1] - 1))), deriv(a)) if b[0] == 'num' else ('*', expr, deriv(('*', b, ('ln', a)))) }. get(op)() def simplify(expr): op, a, b = expr + ((None,) if len(expr) < 3 else ()) if type(a) == type(()): a = simplify(a) if type(b) == type(()): b = simplify(b) if op in ('num', 'var'): return a elif op == '*' and 0 in (a, b): return 0 elif op == '^' and b == 1: return a elif op == '^' and b == 0: return 1 elif op == '*' and 1 in (a, b): return a * b elif op == '+' and 0 in (a, b): return a if a else b elif op == '-' and b == 0: return a elif type(a) == type(b) == int: return calc(op, a, b) else: return (op, a) + ((b,) if b else ()) def calc(op, a, b): return {'+': a + b, '-': a - b, '*': a * b, '/': a / b, '^': a * * b}. get(op) def to_str(expr): return str(expr). replace(',', ''). replace('\'', '') def diff(expr): return to_str(simplify(deriv(parse_expr(expr))))
Symbolic differentiation of prefix expressions
584daf7215ac503d5a0001ae
[ "Algorithms" ]
https://www.codewars.com/kata/584daf7215ac503d5a0001ae
2 kyu
You will be given an array of strings. The words in the array should mesh together where one or more letters at the end of one word will have the same letters (in the same order) as the next word in the array. But, there are times when all the words won't mesh. **Examples of meshed words:** "apply" and "plywood" "apple" and "each" "behemoth" and "mother" **Examples of words that do not mesh:** "apply" and "playground" "apple" and "peggy" "behemoth" and "mathematics" If all the words in the given array mesh together, then your code should return the meshed letters in a string. You should return the longest common substring. You won't know how many letters the meshed words have in common, but it will be at least one. ```if-not:rust If any pair of consecutive words fails to mesh, your code should return "failed to mesh". Input: An array of strings. There will always be at least two words in the input array. Output: Either a string of letters that mesh the words together or the string `"failed to mesh"`. ``` ```if:rust If all the words don't mesh together, then your code should return `None`. * **Input:** A slice of `&str`. There will always be at least two words in the input slice. * **Output:** An `Option`, being either a `String` of letters that mesh the words together or `None` otherwise. ``` ## Examples #1: ``` ["allow", "lowering", "ringmaster", "terror"] --> "lowringter" ``` because: * the letters `"low"` in the first two words mesh together * the letters `"ring"` in the second and third word mesh together * the letters `"ter"` in the third and fourth words mesh together. #2: ``` ["kingdom", "dominator", "notorious", "usual", "allegory"] --> "failed to mesh" ``` Although the words `"dominator"` and `"notorious"` share letters in the same order, the last letters of the first word don't mesh with the first letters of the second word.
reference
import re def word_mesh(arr): common = re . findall(r'(.+) (?=\1)', ' ' . join(arr)) return '' . join(common) if len(common) + 1 == len(arr) else 'failed to mesh'
Word Mesh
5c1ae703ba76f438530000a2
[ "Regular Expressions", "Arrays", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5c1ae703ba76f438530000a2
6 kyu
Given an array of integers and an integer `m`, return the sum of the product of its subsequences of length `m`. Ex1: ```python a = [1, 2, 3] m = 2 ``` ```javascript a = [1, 2, 3] m = 2 ``` ```haskell xs = [1, 2, 3] m = 2 ``` ```cobol xs = [1, 2, 3] m = 2 ``` ```go a := []int{1, 2, 3} m := 2 ``` the subsequences (of length 2) are `(1,2) (1,3) (2,3)`, you should multiply the numbers of each subsequence and take their sum ```python product_sum = (1*2) + (1*3) + (2*3) #=> 11 ``` ```javascript productSum = (1*2) + (1*3) + (2*3) //=> 11 ``` ```haskell productSum = (1*2) + (1*3) + (2*3) -- > 11 ``` ```go ProductSum = (1*2) + (1*3) + (2*3) //=> 11 ``` ```cobol product-sum = (1 * 2) + (1 * 3) + (2 * 3) = 11 ``` Ex2: ```python a = [2,3,4,5] m = 3 ``` ```javascript a = [2,3,4,5] m = 3 ``` ```haskell xs = [2,3,4,5] m = 3 ``` ```go a := []int{2,3,4,5} m := 3 ``` ```cobol a = [2,3,4,5] m = 3 ``` the subsequences (of length 3) are `(2,3,4) (2,4,5) (2,3,5) (3,4,5)` ```python product_sum = (2*3*4) + (2*3*5) + (2*4*5) + (3*4*5) #=> 154 ``` ```javascript productSum = (2*3*4) + (2*3*5) + (2*4*5) + (3*4*5) //=> 154 ``` ```haskell productSum = (2*3*4) + (2*3*5) + (2*4*5) + (3*4*5) -- > 154 ``` ```go ProductSum = (2*3*4) + (2*3*5) + (2*4*5) + (3*4*5) //=> 154 ``` ```cobol product-sum = (2 * 3 * 4) + (2 * 3 * 5) + (2 * 4 * 5) + (3 * 4 * 5) = 154 ``` ## Task: ~~~if:python Write a function `product_sum(a, m)`` that does as described above ~~~ ~~~if:javascript Write a function `productSum(a, m)`` that does as described above ~~~ ~~~if:haskell Write a function `productSum :: [Int] -> Int -> Int` that does as described above ~~~ ~~~if:go Write a function `productSum(a, m)`` that does as described above ~~~ ~~~if:cobol Write a function `product-sum(a, m)`` that does as described above ~~~ The sum can be really large, so return the result in modulo **10<sup>9</sup>+7** ## Constraints **0 <= A[i] < 1000000** ~~~if:python ``` 1 <= m <= 20 49 random tests |A| <= 10^4 1 big test |A| = 10^5 ``` ~~~ ~~~if:javascript ``` 1 <= m <= 20 89 random tests |A| = 10^4 1 big test |A| = 10^6 ``` ~~~ ~~~if:haskell ``` 1 <= m <= 20 49 random tests |A| = 10^4 1 big test |A| = 10^5 ``` ~~~ ~~~if:go ``` 1 <= m <= 50 99 random tests |A| = 10^5 1 big test |A| = 10^6 ``` ~~~ ~~~if:cobol ``` 1 <= m <= 20 20 random tests |A| <= 10^4 1 big test |A| = 10^5 ``` ~~~ **m < |A|**
reference
def product_sum(xs, m): ss = [1] + [0] * m for x in xs: for i in range(m, 0, - 1): ss[i] += ss[i - 1] * x return ss[m] % (10 * * 9 + 7)
Subsequence Product Sum
5d653190d94b3b0021ec8f2b
[ "Combinatorics", "Performance", "Dynamic Programming", "Fundamentals" ]
https://www.codewars.com/kata/5d653190d94b3b0021ec8f2b
5 kyu
# Autoformat code level 2 You have received a code file, it looks like that it has been written by different people with different code editors. There is an unwanted mix of spaces `" "` and tabs `"\t"` where there should only be spaces. ## Task: The function must correct errors in the indentation of each line of text. Adjust the spaces at the beginning to the closest level of intentation. In the event of a tie, opt for the larger. One tab `"\t"` is equivalent to as many spaces `" "` as it takes to reach the next tabstop. Indentation levels must have a multiple of 4 spaces. ## Example: In the examples spaces are represented with `"·"`, tabs with `\t` ``` ·\t# comment var·int·=·2; if·(true){ ···console.log(int); ··} ·console.log('end'); ``` Should be: ``` ····# comment var·int·=·2; if·(true){ ····console.log(int); ····} console.log('end'); ```
reference
import re def autoformat(s): return re . sub(r'^[ \t]+', indenter, s, flags=re . M) def indenter(m, s=0): for c in m[0]: s += c == ' ' or 4 - s % 4 n, r = divmod(s, 4) return ' ' * (n + (r > 1)) * 4
Computer problem series #7: Indentation mix
5db017dd3affec001f3775b1
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/5db017dd3affec001f3775b1
6 kyu
You're in the casino, playing Roulette, going for the "1-18" bets only and desperate to beat the house and so you want to test how effective the [Martingale strategy](https://en.wikipedia.org/wiki/Martingale_(betting_system)) is. You will be given a starting cash balance and an array of binary digits to represent a win (`1`) or a loss (`0`). Return your balance after playing all rounds. *The Martingale strategy* You start with a stake of `100` dollars. If you lose a round, you lose the stake placed on that round and you double the stake for your next bet. When you win, you win 100% of the stake and revert back to staking 100 dollars on your next bet. ## Example ``` martingale(1000, [1, 1, 0, 0, 1]) === 1300 ``` Explanation: * you win your 1st round: gain $100, balance = 1100 * you win the 2nd round: gain $100, balance = 1200 * you lose the 3rd round: lose $100 dollars, balance = 1100 * double stake for 4th round and lose: staked $200, lose $200, balance = 900 * double stake for 5th round and win: staked $400, won $400, balance = 1300 **Note: Your balance is allowed to go below 0.**
games
def martingale(bank, outcomes): stake = 100 for i in outcomes: if i == 0: bank -= stake stake *= 2 else: bank += stake stake = 100 return bank
Mr Martingale
5eb34624fec7d10016de426e
[ "Games", "Puzzles" ]
https://www.codewars.com/kata/5eb34624fec7d10016de426e
7 kyu
Adding tip to a restaurant bill in a graceful way can be tricky, thats why you need make a function for it. The function will receive the restaurant bill (always a positive number) as an argument. You need to 1) **add at least 15%** in tip, 2) round that number up to an *elegant* value and 3) return it. What is an *elegant* number? It depends on the magnitude of the number to be rounded. Numbers below 10 should simply be rounded to whole numbers. Numbers 10 and above should be rounded like this: 10 - 99.99... ---> Round to number divisible by 5 100 - 999.99... ---> Round to number divisible by 50 1000 - 9999.99... ---> Round to number divisible by 500 And so on... Good luck! ## Examples ``` 1 --> 2 7 --> 9 12 --> 15 86 --> 100 ```
reference
from math import ceil, log10 def graceful_tipping(bill): bill *= 1.15 if bill < 10: return ceil(bill) e = int(log10(bill)) unit = (10 * * e) / 2 return ceil(bill / unit) * unit
Graceful Tipping
5eb27d81077a7400171c6820
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5eb27d81077a7400171c6820
7 kyu
This kata provides you with a list of parent-child pairs `family_list`, and from this family description you'll need to find the relationship between two members(what is the relation of latter with former) which is given as `target_pair`. For example, the family list may be given as: ```python [('Enid', 'Susan'), ('Susan', 'Deborah'), ('Enid', 'Dianne')] ``` ```javascript [['Enid', 'Susan'], ['Susan', 'Deborah'], ['Enid', 'Dianne']] ``` This describes the family: Enid | |---------| Susan Dianne | Deborah The relationship pair `('Deborah', 'Enid')` should return 'Grandmother' as Enid is Deborah's Grandmother. This family tree can cover up to 3 generations, with varying numbers of children for each parent. We only focus on the females in the family, and so children will have only one parent. The possible responses are Mother, Daughter, Grandmother, Granddaughter, Sister, Cousin, Aunt, Niece (each matching their 'real life' equivalents). There will always be a valid answer. Enjoy, and be nice to your Mother!
algorithms
def relations(family_list, target_pair): parents = {} for parent, child in family_list: parents[child] = parent a, b = target_pair ap = parents . get(a) app = parents . get(ap) bp = parents . get(b) bpp = parents . get(bp) if b == ap: return 'Mother' if b == app: return 'Grandmother' if a == bp: return 'Daughter' if a == bpp: return 'Granddaughter' if ap == bp: return 'Sister' if app == bpp: return 'Cousin' if app == bp: return 'Aunt' if ap == bpp: return 'Niece'
Family Relations
5eaf798e739e39001218a2f4
[ "Trees", "Algorithms", "Data Structures" ]
https://www.codewars.com/kata/5eaf798e739e39001218a2f4
7 kyu
## **Task** Four mirrors are placed in a way that they form a rectangle with corners at coordinates `(0, 0)`, `(max_x, 0)`, `(0, max_y)`, and `(max_x, max_y)`. A light ray enters this rectangle through a hole at the position `(0, 0)` and moves at an angle of 45 degrees relative to the axes. Each time it hits one of the mirrors, it gets reflected. In the end, the light ray hits one of the rectangle's corners, and flies out. Your function must determine whether the exit point is either `(0, 0)` or `(max_x, max_y)`. If it is either `(0, 0)` or `(max_x, max_y)`, return `True` and `False` otherwise. **Example** For `max_x = 10` and `max_y = 20`, the ray goes through the following lattice points: `(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10), (9, 11), (8, 12), (7, 13), (6, 14), (5, 15), (4, 16), (3, 17), (2, 18), (1, 19), (0, 20)`. The ray left the rectangle at position `(0, 20)`, so the result is `False`. Here is an image of the light being reflected. ![d](https://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Arithmetic-billiard-40-10.jpg/450px-Arithmetic-billiard-40-10.jpg) Also, once completing this kata, please do not rate it based off of the difficulty level(kyu) and instead on whether you think it is a good kata.
algorithms
def reflections(n, m): x = y = 0 dx = dy = 1 while 1: x += dx y += dy if x == y == 0 or x == n and y == m: return 1 if 0 in (x, y) and (x == n or y == m): return 0 if x in (0, n): dx *= - 1 if y in (0, m): dy *= - 1
Reflecting Light
5eaf88f92b679f001423cc66
[ "Geometry", "Algorithms" ]
https://www.codewars.com/kata/5eaf88f92b679f001423cc66
7 kyu
This is the subsequent Kata of [this one](https://www.codewars.com/kata/597ccf7613d879c4cb00000f). In this Kata you should convert the representation of "type"s, from Kotlin to Java, and **you don't have to know Kotlin or Java in advance** :D ```if:haskell If you successfully parsed the input, return `Right result`, otherwise give me `Left "Hugh?"`. ``` ```if:javascript If you successfully parsed the input, return the result, otherwise give me `null`. ``` ```if:java If you successfully parsed the input, return the result, otherwise give me `null`. ``` ```if:python If you successfully parsed the input, return the result, otherwise give me `None`. ``` In Kotlin and Java, C-style identifiers are valid `simple type`s. Like, `_A`, `ice1000`, `Voile`. We can have generic parameters, which are valid in both Kotlin\&Java: `List<String>`, or more than one parameters: `F<A,B>`. We can specify the complete package name of the types, like `java.util.List<String>`. We can also have types of nested classes: `List<Long>.Iterator<Long>`. We have covariance: `Option<out T>` in Kotlin and `Option<? extends T>` in Java (be careful about the spaces, there are spaces between `?` and `extends`, `extends` and `T`). Contravariance as well: `Maker<in T>` in Kotlin and `Maker<? super T>` in Java (again, spaces). In Kotlin, there's something called "star projection" like `List<*>`, and you should translate it into `List<?>`. Also, you should rename `Int`(`kotlin.Int`) into `Integer`(`java.lang.Integer`), and `Unit` into `Void`. Finally, the most complex part of this Kata -- the types of lambda expressions. `(A) -> B` in Kotlin, should be transpiled into `Function1<A,B>` in Java (be careful, here we don't have spaces in Java). `() -> B` -> `Function0<B>` `(A, B) -> C` -> `Function2<A,B,C>` So let's see the strict bnf definition: ### Kotlin ```bnf name ::= <valid java identifier> typeParam ::= "*" | "in " type | "out " type | type typeParams ::= typeParam [ "," typeParams ] simpleUserType ::= name [ "<" typeParams ">" ] userType ::= simpleUserType [ "." userType ] parameters ::= type [ "," parameters ] functionType ::= "(" [ parameters ] ")" "->" type type ::= functionType | name | userType ``` ### Java ```bnf name ::= <valid java identifier> typeParam ::= type | "?" | "? super " type | "? extends " type typeParams ::= typeParam [ "," typeParams ] simpleUserType ::= name [ "<" params ">" ] userType ::= simpleUserType [ "." userType ] parameters ::= type [ "," parameters ] functionType ::= "Function" ++ (number of parameters) "<" [ parameters "," ] type ">" type ::= functionType | name | userType ``` (`++` in bnf means there shouldn't be spaces there) for more information please see the example tests. Enjoy!
reference
import re NAME = r'[_a-zA-Z]\w*' TOKENIZER = re . compile(fr'->|(?:in |out )(?= * { NAME } )| { NAME } |.') CONVERTER = {'*': '?', 'in ': '? super ', 'out ': '? extends ', 'Int': 'Integer', 'Unit': 'Void'} class InvalidExpr (Exception): pass def FATAL (msg): raise InvalidExpr (msg) def transpile(s): def walk(step=0): nonlocal i i += step while i < len (tokens) and tokens [i] == ' ': i += 1 def eat (what=None): nonlocal i ret = taste(what) if what and not ret: FATAL(f'Expected { what } but got { ret } (i= { i } )') walk(1) return CONVERTER . get(ret, ret) def taste(what=None): return i < len (tokens) and (what is None or re . match (what , tokens [i ])) and tokens [i ] # ----------------------------------------------------- def _type(): if taste(r'\('): return _functionType() elif not taste(NAME): FATAL(f"Expected a name but got { taste ()} ") name = eat() if taste('[<.]'): return _userType(name) else: return name def _functionType(): eat() params = [] if not taste(r'\)'): while 1: params . append(_type()) if taste(r'\)'): break eat(',') eat(r'\)') eat("->") params . append(_type()) return f'Function { len ( params ) - 1 } < { "," . join ( params ) } >' def _userType(name): userT = name if taste('<'): userT += _typeParams() if taste(r'\.'): userT += eat (r'\.') + _userType (eat (NAME )) return userT def _typeParams(): lst = [] eat('<') while 1: lst . append(_typeParam()) if not taste(','): break eat() eat('>') return f"< { ',' . join ( lst ) } >" def _typeParam(): if taste(r'\*|in |out '): x = eat() if x != '?': x += eat(NAME) return x else: return _type() # ----------------------------------------------------- i, tokens = 0, TOKENIZER . findall(s) try: walk() ans = _type() if i == len(tokens): return ans except InvalidExpr as e: pass
Type Transpiler
59a6949d398b5d6aec000007
[ "Algorithms", "Strings" ]
https://www.codewars.com/kata/59a6949d398b5d6aec000007
3 kyu
Stacey is a big [AD&D](https://en.wikipedia.org/wiki/Dungeons_%26_Dragons) games nerd. Moreover, she's a munchkin. Not a [cat breed](https://en.wikipedia.org/wiki/Munchkin_cat), but a person who likes to get maximum efficiency of their character. As you might know, many aspects of such games are modelled by rolling dice and checking it against a threshold value determined by various aspects. Stacey wants to always control the situation and know whether she can beat the foe with certain special ability or not. Unfortunately she doesn't know probabilty theory well enough. Help Stacey by providing a calculating utility for her. P.S.: Stacey says that she has tried to implement a calculator by Monte-Carlo modelling: calling rand() in a loop, but she hasn't been satisfied with precision of this method. ### Examples `P(1d6 >= 4)` means the chance of getting 4 points or higher on a regular cubic die. Obviously the chance is `3/6` cause there're 6 possibilities in total (1, 2, 3, 4, 5, 6) and only three of them are >= 4: (4, 5, 6) `P(2d6 >= 3)` gives us `35/36`, cause the only possibility to get < 3 is rolling exactly 1+1. Exactly 2 as sum of two dice appears only if both have 1. While total amount of different outcomes is 6\*6 = 36. Hence resulting probability is 1-1/36, which is 35/36 ### Your task is to write a function, which will calculate the probability of that a die with `N` sides rolled `M` times (`MdN` in AD&D notation) will get at least `T` points. We don't add modifiers cause they are already incorporated into the threshold. Input arguments will be valid integers with the following limits: - `rolls` 1..20 - `sides` 2..100 - `threshold` 1..2000
algorithms
from math import factorial as fac def comb(n, k): return fac(n) / (fac(k) * fac(n - k)) def roll_dice(n, m, x): return 1 - sum((- 1) * * k * comb(n, k) * comb(x - 1 - k * m, x - n - 1 - k * m) / m * * n for k in range(n + 1) if x - n - 1 >= m * k)
Dice rolls threshold
55d18ceefdc5aba4290000e5
[ "Probability", "Combinatorics", "Algorithms" ]
https://www.codewars.com/kata/55d18ceefdc5aba4290000e5
4 kyu
# The folly of Mr Pong While Mrs Pong is away visiting her sister, **Mr Pong** has foolishly set up a ping pong table in his lounge room, and invites his neighbour **Mr Ping** over for a friendly ping pong session. When Mr Ping hits the ping pong ball, the ping pong ball goes `ping`. When Mr Pong hits the ping pong ball, the ping pong ball goes `pong`. Unfortunately, not every hit goes where it was meant to... Sometimes the ping pong ball hits the net, or bounces off a wall, or it ricochets off Mrs Pong's rather expensive porcelain collection, a light fitting, or various pieces of lounge furniture, before finally coming to rest on the floor. When that happens there are all kinds of bad noises. ## Example A typical rally may sound like this: `ping`-`pong`-`ping`-`pong`-`ping`-`pong`-`ping`-`pong`-`dong`-`tang`-`bing`-`tink`-`donk`-`donk`-`donk` * Mr Ping served * There were several good returns * Mr Pong hits a bad shot which broke the handle off his wife's 2nd favourite teacup. Oops. # Kata Task Who scored the most points? ## Input The sounds of one or more rallies. ## Output The name of the winning player: `ping` or `pong` # Notes * To score a point the same player must both serve and win the rally. * Whoever picks the ball off the floor will serve next. It's random. * A bad noise is anything other than `ping` or `pong`. * A bad noise means whoever hit the ball last hit a bad shot. * For some unknown reason all noises are 4 lowercase characters, and delimited by `-` * If scores are even, then the winner is the player who did NOT hit the final bad shot. * There are no double hits. * The final rally always ends with the ball on the floor. * All input is valid.
algorithms
def ping_pong(sounds: str) - > str: p, c, f = dict . fromkeys(('ping', 'pong'), 0), None, None for x in sounds . split('-'): if c and x not in p: f = c if c and x in p: p[c] += 1 c = [None, x][x in p] if len(set(p . values())) == 1: p . pop(f) return max(p . items(), key=lambda x: x[1])[0]
Ping Pong
5ea39ab1d8425e0029fcd035
[ "Algorithms" ]
https://www.codewars.com/kata/5ea39ab1d8425e0029fcd035
6 kyu
In lambda calculus, the only primitive are lambdas. No numbers, no strings, and of course no booleans. Everything is reduced to anonymous functions. Booleans are defined thusly ( this definition is `Preloaded` for you ) : ```lambdacalc True = \ true _false . true False = \ _true false . false ``` ```haskell type Boolean = forall a. a -> a -> a -- this requires RankNTypes false,true :: Boolean false = \ t f -> f true = \ t f -> t ``` ```javascript const False = t => f => f ; const True = t => f => t ; ``` ```python false = lambda t: lambda f: f true = lambda t: lambda f: t ``` Your task will be to implement basic operators on booleans (using only lambdas and function application) : `not`, `and`, `or`. ## <span style="color:magenta">However!</span> Your combinators will <span style="color:magenta">not</span> be applied in <span style="color:magenta">prefix</span> position: `not` will be applied <span style="color:magenta">postfix</span>, and `and` and `or` will be applied <span style="color:magenta">infix</span>.<br> To make this at all possible, they will consist of single letters, like this: ```lambdacalc True n o t -> False True a n d False -> False False o r True -> True ``` ```haskell true n o t `shouldBe` false true a n d false `shouldBe` false false o r true `shouldBe` true ``` ```javascript True (n)(o)(t) == False True (a)(n)(d) (False) == False False (o)(r) (True) == True ``` ```python true (n)(o)(t) == false true (a)(n)(d) (false) == false false (o)(r) (true) == true ``` Actual testing will be extensional; the resulting function should behave correctly as `false` or `true`, but need not actually _be_ `false` or `true`.<br> Getting the types right is part of the puzzle; there are multiple solutions anyway.<br> Yes, you can only define <span style="color:magenta">one</span> `n` and <span style="color:magenta">one</span> `o`. ## <span style="color:green">For Bonus Points and Bragging Rights</span> `xor` is missing! If you can make `xor` work, please publish a fork with the additional testing and earn Eternal Bragging Rights ( or at least until Christmas ). ```if:haskell Haskell's strong static typing is not very conducive to permanently including that testing. ```
algorithms
n = false(false) o = true(true) t = false a = false d = true(false) r = false(true) x = None
Church Booleans - Prefix is Overrated
5ea91813b4702500282042c3
[ "Puzzles", "Algorithms" ]
https://www.codewars.com/kata/5ea91813b4702500282042c3
6 kyu
# One is the loneliest number ## Task The range of vision of a digit is its own value. `1` can see one digit to the left and one digit to the right,` 2` can see two digits, and so on. Thus, the loneliness of a digit `N` is the sum of the digits which it can see. Given a non-negative integer, your funtion must determine if there's at least one digit `1` in this integer such that its loneliness value is minimal. ## Example ``` number = 34315 ``` digit | can see on the left | can see on the right | loneliness --- | --- | --- | --- 3 | - | 431 | 4 + 3 + 1 = <span style="color:red">8</span> 4 | 3 | 315 | 3 + 3 + 1 + 5 = 12 3 | 34 | 15 | 3 + 4 + 1 + 5 = 13 1 | 3 | 5 | 3 + 5 = <span style="color:red">8</span> 5 | 3431 | - | 3 + 4 + 3 + 1 = 11 Is there a `1` for which the loneliness is minimal? Yes.
games
def loneliest(n): a = list(map(int, str(n))) b = [(sum(a[max(0, i - x): i + x + 1]) - x, x) for i, x in enumerate(a)] return (min(b)[0], 1) in b
One is the loneliest number
5dfa33aacec189000f25e9a9
[ "Lists", "Puzzles" ]
https://www.codewars.com/kata/5dfa33aacec189000f25e9a9
6 kyu
In this kata your task is to create a hamiltonian cycle on a grid: a closed path which visits every single square in the grid exactly once. Finding hamiltonian cycles is in general a NP-complete problem; however, in the case of a grid, the problem is <strong>not</strong>, and you can find a much simpler solution! Interestingly, the game Snake can be solved through a hamiltonian cycle or, when it doesn't exist, a slightly modified version of it; but you are required to find out by yourself when the modification is needed, so I can't say more on the topic ;). ## Task Given the size of the grid as two arguments `a` and `b`: * If no hamiltonian cycle exists, return `None` * Otherwise, return a list of tuples representing the path: for a grid `a * b` the solution consists of tuples `(x,y)` such that `0 <= x < a` and `0 <= y < b`. Note that you can only move horizontally or vertically to adjacent squares. * **Any** valid hamiltonian cycle can be used to solve the kata. * The start/end point must be present at both ends of the output. * The case `1 x 1` is not considered a hamiltonian cycle here, so return `None`. ## Examples - A possible solution for a `2 x 2` grid is: [(0,0),(0,1),(1,1),(1,0),(0,0)] - The image below shows a possible hamiltonian path for a `6 x 6` grid: <img src="https://i.postimg.cc/vZgBnR1h/new-grid.jpg" width="200px" height="auto" /></a>
games
def find_cycle(a, b): if (a % 2 and b % 2) or 1 in {a, b}: return None else: r, c = (a, b) if a % 2 == 0 else (b, a) res = [(0, y) for y in range(c)] res . extend([(x, c - 1) for x in range(1, r)]) for k, x in enumerate(range(r - 1, 0, - 1)): res . extend([(x, y if k % 2 else c - 2 - y) for y in range(c - 1)]) res . append((0, 0)) return res if r == a else [(y, x) for x, y in res]
Hamiltonian cycle: create one !
5ea6f5d99fe5a2001e14ba13
[ "Puzzles", "Graph Theory" ]
https://www.codewars.com/kata/5ea6f5d99fe5a2001e14ba13
6 kyu
# Max From Common DataFrames ## Input parameters Two `pandas.DataFrame` objects ## Task Your function must return a new `pandas.DataFrame` with the same data and columns from the first parameter. For common columns in both inputs you must return the greater value of each cell for that column. You must not modify the original inputs. Input DataFrame will never be empty. The number rows of both inputs will be the same. ## Examples ### Inputs ``` A B C 0 2.5 2.0 2.0 1 2.0 2.0 2.0 ``` ``` C B D E 0 1.0 6.0 7.0 1.0 1 8.5 1.0 9.0 1.0 ``` ### Output ``` A B C 0 2.5 6.0 2.0 1 2.0 2.0 8.5 ``` Hint: Use pandas methods
reference
import pandas as pd def max_common(df_a, df_b): return pd . concat([df_a, df_b]). filter(items=df_a . columns). groupby(level=0). max()
Pandas Series 102: Max From Common DataFrames
5ea2a798f9632c0032659a75
[ "Data Frames", "Fundamentals", "Data Science" ]
https://www.codewars.com/kata/5ea2a798f9632c0032659a75
6 kyu
# Rename Columns ## Input parameters 1. `pandas.DataFrame` object 2. sequence ## Task Your function must return a new `pandas.DataFrame` object with same data than the original input but now its column names are the elements of the sequence. You must not modify the original input. The number of columns of the input will always be equal to the size of the sequence. ## Examples ``` 0 1 2 0 1 2 3 1 4 5 6 names = ['A', 'B', 'C'] ``` ``` A B C 0 1 2 3 1 4 5 6 ```
reference
import pandas as pd def rename_columns(df, names): return pd . DataFrame(data=df . values, columns=names)
Pandas Series 101: Rename Columns
5e60cdcd01712200335bd676
[ "Strings", "Data Frames", "Fundamentals", "Data Science" ]
https://www.codewars.com/kata/5e60cdcd01712200335bd676
7 kyu
## Task: Given a circle and an external point, you have to find the tangents from point to the circle. ------ ## Background: One of the easiest methods in Analytic Geometry for finding the tangent lines from an external point is using the polar line. In the image we have below, we may see the method: ![Imgur](https://i.imgur.com/69dtG2L.png) We have - Circle `$C$`, the coordinates of its center `$O$` are `$(\alpha, \beta)$`, and has a radius `$r$`. - An external point `$P$` with coordinates `$(x_P, y_P)$` - A polar line `$p$` which intersect with circle C at points `$T_1$` and `$T_2$`. - Point `$P$` is joined by `$T_1$` and `$T_2$` by the tangents `$t_1$` and `$t_2$` respectively. For obtaining the polar line, we may apply a formula based on the equation of the circle, as it follows. Equation for the circle: `$x^2 + y^2-2\alpha x - 2\beta y+\alpha^2+\beta^2-r^2=0$` Equation of polar line: `$(x-\alpha)(x_p - \alpha) + (y - \beta)(y_p - \beta) -r^2=0 $` Equation of tangents are considered to be the form of: Tangent 1: `$y = m_1x+c_1$` Tangent 2: `$y = m_2x+c_2$` ----- ## Input/Output: You have to create a function `tang_from_point()` which will receive arguments `[[α, β], r]` and `[x_p, y_p]` the function should return an array with the parameters of both tangent lines, in other words: ```python tang_from_point([[α, β], r], [x_p, y_p]) should return [[m1, c1], [m2, c2]] (sorted list by the value of m). The values of m1, c1 and m2, c2 will be expressed up to four decimals (rounded result) ``` #### Note: The gradient of the tangent is always a real number (cases of tangents perpendicular to x axis will not be present in the tests) ---- ## Examples: ```python tang_from_point([[6, 6], 4], [14, 2]) ---> [[-1.3333, 20.6667], [-0.0, 2.0]] # It means that the equation of the tangent lines are: y = -1.3333 x + 20.6667 (t1) y = 2.0 (t2) ``` ```python tang_from_point([[-2, 6], 4], [12, 8]) ---> [[-0.1459, 7.7925], [0.457, 2.5161]] ``` Even though there are many methods to solve the problem, we select the method of the polar line due to its easier calculations(comparing with other methods)
reference
import math def dist(x, y): return (x * * 2 + y * * 2) * * .5 def tang_from_point(circle, point): ((cx, cy), r), (px, py) = circle, point a, b = math . asin(r / dist(py - cy, px - cx) ), math . atan2(py - cy, px - cx) return [[round(m, 4), round(py - m * px, 4)] for m in sorted((math . tan(b + a), math . tan(b - a)))]
Tangent Lines to a Circle from an External Point
5602c713f75452a7c500005c
[ "Fundamentals", "Mathematics", "Geometry" ]
https://www.codewars.com/kata/5602c713f75452a7c500005c
6 kyu
We have a certain number of lattice points of coordinates (x, y), (both integer values). A random laser beam crosses the lattice points field. We are interested in finding the maximum number of lattice points that may be encountered by a single laser beam, and the number of different laser beams that cross that maximum of lattice points. ## Input * A list/array (depending on your language) of lattice points * All lattice points are unique * All coordinates are integer * Maximum number of points: 40 ## Output An tuple/array (depending on your language) of two elements, first being the maximum number of lattice points crossed by one laser beam, and the number of laser beams crossing that maximum number of points. ### Example 1 ``` Case 1 points = [(3, 7), (6, 4), (11, 7), (9, 4), (3, 10), (7, 6), (7, 1), (13, 1), (16, -1), (14, -1), (11, 2)] ``` <a href="http://imgur.com/AjMN86f"><img src="http://i.imgur.com/AjMN86f.png?1" title="source: imgur.com" /></a> For this set of lattice points, there is a single laser beam that encounters 5 points, so the output is `5,1`. ### Example 2 ``` Case 2 points = [(2, 3), (5, 1), (4, 3), (2, -2), (8, 4), (11, -3), (11, 1)] ``` <a href="http://imgur.com/yjAV0qb"><img src="http://i.imgur.com/yjAV0qb.png?1" title="source: imgur.com" /></a> For this set of lattice points, there are two laser beams that encounter 3 lattice points each one, so the output is `3,2`.
reference
from fractions import Fraction from collections import defaultdict from itertools import combinations from math import inf def max_encount_points(lst): d = defaultdict(int) for (i, j), (x, y) in combinations(lst, 2): slope = Fraction(y - j, (x - i)) if x - i else inf ord0 = j - slope * i if x - i else x d[(slope, ord0)] += 1 m = max(d . values()) n = [* d . values()]. count(m) return (1 + (1 + 8 * m) * * .5) / 2, n
Maximum Possible Amount of Lattice Points That May Be Encountered By a Single Laser Beam.
56ccc33b29aab18ca4001c64
[ "Fundamentals", "Data Structures", "Algorithms", "Mathematics", "Logic", "Geometry" ]
https://www.codewars.com/kata/56ccc33b29aab18ca4001c64
6 kyu
You are given: - an array of integers, ```arr ```, all of them positive. - an integer ```k, 2 <= k <= 4 ```, (amount of digits) - an integer ```s, 6 <= s <= 24 ```, sum value of k contiguous digits. You have to search the maximum or minimum number obtained as a result of concatenating the numbers of the array in all possible orders but discarding the numbers having an amount of ```k``` contiguous digits which sum is higher than ```s```. Let's see an example: ```python arr = [18, 35, 76] k = 2 s = 9 concat_max_min(arr, k, s) == [18, 3518] # the concatened numbers that fulfill the constraint that the sum of its every 2 contiguous digits is not higher than 9 are: 18, 35, 3518 (concatened numbers) arr = [18, 35, 76] k = 2 s = 14 concat_max_min(arr, k, s) == [18, 763518] # Because the concatened numbers that fulfill the constrains are: 18, 35, 76, 1835, 3518, 3576, 7618, 7635, 183576, 357618, 761835, 763518 ``` The function will discard the numbers that their amount of digits is less than ```k```. ```python arr = [18, 35, 76] k = 3 s = 18 concat_max_min(arr, k, s) == [1835, 763518] # all the numbers that have less than 3 digits will be discarded, now the numbers are: 1835, 3518, 3576, 7618, 7635, 183576, 357618, 761835, 763518 ``` If ```s``` decreases, will decrease the selected concatened numbers: ```python arr = [18, 35, 76] k = 3 s = 15 concat_max_min(arr, k, s) == [3518, 7618] # the selected concatened numbers are only: 3518 and 7618 ``` If there is only one number the function should output it: ```python arr = [18, 35, 76] k = 2 s = 8 concat_max_min(arr, k, s) == [35, 35] ``` If there is no a single number that fulfills the conditions, the function will return an empty list: ```python arr = [18, 35, 76] k = 2 s = 7 concat_max_min(arr, k, s) == [] ``` Enjoy it!!
reference
from itertools import permutations def concat_max_min(arr, k, s): num = [] for i in range(1, len(arr) + 1): for x in permutations(arr, i): m = '' . join(map(str, x)) if len(m) >= k and all(sum(map(int, m[j: j + k])) <= s for j in range(len(m) - k + 1)): num . append(int(m)) return [min(num), max(num)] if num else []
Max & Min Numbers Concatenation with Constraints
57180ffc1c27346abd0011ee
[ "Fundamentals", "Data Structures", "Algorithms", "Mathematics", "Logic", "Strings" ]
https://www.codewars.com/kata/57180ffc1c27346abd0011ee
5 kyu
A proper fraction: `n/d` has the property that `gcd(n,d)` equals to `1`, being gcd(n,d) **the greatest common divisor** of `n` and `d`. These kind of fractions receive also the name of **Irreducible Fractions**. If we generate all the proper fractions, with values less than one and positive, higher than zero, in decending order of value, having a maximum denominator, `d_max`, equals to `9`, we will have the following table: ``` Fraction Value Position '1/1' 1.0 0 '8/9' 0.8888888888888888 1 '7/8' 0.875 2 '6/7' 0.8571428571428571 3 '5/6' 0.8333333333333334 4 '4/5' 0.8 5 '7/9' 0.7777777777777778 6 '3/4' 0.75 7 '5/7' 0.7142857142857143 8 '2/3' 0.6666666666666666 9 '5/8' 0.625 10 '3/5' 0.6 11 '4/7' 0.5714285714285714 12 '5/9' 0.5555555555555556 13 '1/2' 0.5 14 '4/9' 0.4444444444444444 15 '3/7' 0.42857142857142855 16 '2/5' 0.4 17 '3/8' 0.375 18 '1/3' 0.3333333333333333 19 '2/7' 0.2857142857142857 20 '1/4' 0.25 21 '2/9' 0.2222222222222222 22 '1/5' 0.2 23 '1/6' 0.16666666666666666 24 '1/7' 0.14285714285714285 25 '1/8' 0.125 26 '1/9' 0.1111111111111111 27 ``` We have a total of 28 irreducible fractions. Just for an example, the fraction '2/7' is placed at the `20-th` position in a 0-based list. Prepare a code that may receive the maximum value of the denominator, `d_max` and a position, `pos` and ouputs the corresponding irreducible fraction. Thus, naming the function, `f`, will receive the two arguments in this order: `f(d_max, pos)`, and will output the corresponding proper fraction for the given maximum denominator and position in a string format like:`"n/d"`, (`n` and `d`, numerator and denominator of the result). For the example given above: ``` f(9, 20) === "2/7" ``` If the position is a higher number than the total amount of possible proper fractions that can be generated for a certain denominator, the function will output "-1". ``` f(9, 30) === "-1" ``` More examples will be given in the example tests box. Features of the random Tests: ``` Number of Basic Tests: 10 Number of Random Tests: 185 Ranges of arguments for the Random Tests: 100 <= d_max <= 100,000 ``` Have a good time!
reference
def f(d_max, n): """Calculate the nth element of d_max-th Farey sequence in descending order.""" a, b, c, d = 1, 1, d_max - 1, d_max for _ in range(n): if a == 0: break k = (d_max + b) / / d a, b, c, d = c, d, (k * c - a), (k * d - b) return f" { a } / { b } " if a else "-1"
Give me the Corresponding Proper Fraction!
5cb758d83e6dce00149bb5cd
[ "Performance", "Algorithms", "Mathematics", "Data Structures", "Strings", "Recursion" ]
https://www.codewars.com/kata/5cb758d83e6dce00149bb5cd
5 kyu
Write a class decorator `@remember` which makes the class remember its own objects, storing them in a dictionary with the creating arguments as keys. Also, you have to avoid creating a new member of the class with the same initial arguments as a previously remembered member. Additionally, if the (decorated) class is `A`, you will have to reach that dictionary of remembered objects *directly on* `A`, i.e. by `A[args]` and by the loop `for x in A` over the keys. <h2>Example</h2> A sample usage: @remember class A(object): def __init__(self, x,y=0,z=0): pass a = A(1) b = A(2,3) c = A(4,5,6) d = A(1) >>> A[1] is a is d True >>> A[2,3] is b True >>> A[4,5,6] is c True >>> for x in A: print x, (2,3) (4,5,6) 1 **Notes.** 1. Other dict methods like `items()`, `keys()`, etc. are nice to have but *not required* to be implemented on the decorated class itself for this kata. 2. You don't have to deal with named arguments at creating an instance of your class (such as `z` in `A(1,z=5)`). 3. If the constructor is called with a single argument, the argument itself will be the key and not its 1-tuple.
reference
class MetaDict (type): def __getitem__(cls, item): return cls . members[item] def __iter__(cls): return (key for key in cls . members) def remember(cls): class Recall (cls): __metaclass__ = MetaDict members = {} def __new__(c, * args): key = args[0] if len(args) == 1 else args if key in c . members: return c . members[key] self = cls . __new__(c, * args) c . members[key] = self return self Recall . __name__ = cls . __name__ return Recall
Remember members decorator
571957959906af00f90012f3
[ "Decorator", "Singleton" ]
https://www.codewars.com/kata/571957959906af00f90012f3
4 kyu
Imagine if there were no order of operations. Instead, you would do the problem from left to right. For example, the equation `$a +b *c /d$` would become `$(((a+b)*c)//d)$` (`Math.floor(((a+b)*c)/d)` in JS). Return `None`/`null` (depending on your language) if the equation is `""`. ### Task: Given an equation with a random amount of spaces greater than or equal to zero between each number and operation, return the result without order of operations. Note that if two numbers are spaces apart, act as if they were one number: `1 3` = `13`. However, if given something `% 0` or something `/ 0`, return `None/null`. More about order of operations: [here](https://en.wikipedia.org/wiki/Order_of_operations#:~:text=In%20the%20United%20States%2C%20the,Excuse%20My%20Dear%20Aunt%20Sally%22.) ### Key: - `^` represents `**` ```if:python - `/` represents `//` or `math.floor` because the result will always be an integer ``` ```if:javascript - `/` should always be rounded down(`Math.floor`) because the result will always be an integer ``` ### Operations allowed: `+, -, * , /, ^, %` ### Example: `no_order(2 + 3 - 4 * 1 ^ 3) returns 1` because: ``` 2 + 3 - 4 * 1 ^ 3 = 2 + 3 - 4 * 1 ^ 3 = 5 - 4 * 1 ^ 3 = 1 * 1 ^ 3 = 1 ^ 3 = 1 ```
algorithms
def no_order(equation): equation = equation . replace(' ', '') equation = equation . replace('+', ')+') equation = equation . replace('-', ')-') equation = equation . replace('*', ')*') equation = equation . replace('/', ')//') equation = equation . replace('%', ')%') equation = equation . replace('^', ')**') equation = '(' * equation . count(')') + equation try: return eval(equation) except: pass
No Order of Operations
5e9df3a0a758c80033cefca1
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5e9df3a0a758c80033cefca1
6 kyu
We want to create an object with methods for various HTML elements: `div`, `p`, `span` and `h1` for the sake of this Kata. These methods will wrap the passed-in string in the tag associated with each. ```javascript Format.div("foo"); // returns "<div>foo</div>" Format.p("bar"); // returns "<p>bar</p>" Format.span("fiz"); // returns "<span>fiz</span>" Format.h1("buz"); // returns "<h1>buz</h1>" ``` ```python format.div("foo") # returns "<div>foo</div>" format.p("bar") # returns "<p>bar</p>" format.span("fiz") # returns "<span>fiz</span>" format.h1("buz") # returns "<h1>buz</h1>" ``` We also want to be able to add additional formatting by chaining our methods together. ```javascript Format.div.h1("FooBar"); // "<div><h1>FooBar</h1><div>" Format.div.p.span("FizBuz"); // "<div><p><span>FizBuz</span></p></div>" ``` ```python format.div.h1("FooBar") # "<div><h1>FooBar</h1><div>" format.div.p.span("FizBuz") # "<div><p><span>FizBuz</span></p></div>" ``` and so on, as deep as we care to use. Multiple arguments should be concatenated and wrapped in the correct HTML formatting. ```javascript Format.div.h1("Foo", "Bar"); // "<div><h1>FooBar</h1></div>" ``` ```python format.div.h1("Foo", "Bar") # "<div><h1>FooBar</h1></div>" ``` We should be able to store the created methods and reuse them. ```javascript var wrapInDiv = Format.div; wrapInDiv("Foo"); // "<div>Foo</div>" wrapInDiv.p("Bar"); // "<div><p>Bar</p></div>" var wrapInDivH1 = Format.div.h1; wrapInDivH1("Far"); // "<div><h1>Far</h1></div>" wrapInDivH1.span("Bar"); // "<div><h1><span>Bar</span></h1></div>" ``` ```python wrap_in_div = format.div wrap_in_div("Foo") # "<div>Foo</div>" wrap_in_div.p("Bar") # "<div><p>Bar</p></div>" wrap_in_div_h1 = format.div.h1 wrap_in_div_h1("Far") # "<div><h1>Far</h1></div>" wrap_in_div_h1.span("Bar") # "<div><h1><span>Bar</span></h1></div>" ``` And finally, we should be able to nest calls. ```javascript Format.div( Format.h1("Title"), Format.p(`Paragraph with a ${ Format.span('span') }.`) ) // returns "<div><h1>Title</h1><p>Paragraph with a <span>span</span>.</p></div>" ``` ```python format.div( format.h1("Title"), format.p(f"Paragraph with a {format.span('span')}.") ) # returns "<div><h1>Title</h1><p>Paragraph with a <span>span</span>.</p></div>" ```
games
id_ = lambda * cnts: '' . join(cnts) class Tag: def __init__(self, f=id_): self . func = f def __call__(self, * contents): return self . func(* contents) def __getattr__(self, tag): return Tag( lambda * cnts: self(f'< { tag } > { "" . join ( cnts ) } </ { tag } >')) Format = Tag()
field chained HTML formatting
5e98a87ce8255200011ea60f
[ "Puzzles" ]
https://www.codewars.com/kata/5e98a87ce8255200011ea60f
5 kyu
### Background In classical cryptography, the Hill cipher is a polygraphic substitution cipher based on linear algebra. It was invented by Lester S. Hill in 1929. ### Task This cipher involves a text key which has to be turned into a matrix and text which needs to be encoded. The text key can be of any perfect square length but for the sake of this kata we will focus on keys of length 4 forming a 2x2 matrix. To encrypt a message using the hill cipher, first of all you need to convert the text key into a key matrix. To do that you will convert the key row wise into a 2x2 matrix. Then you will substitute the letters with their respective positions on the alphabet: A=0, B=1,C=2 and so on till Z=25. So for example if we get the key text as ```cats```, the key matrix will be: [[ 2 0] [19 18]] Now the next step is to break the text into pairs of two and convert those pairs into 2x1 matrices. If your text has an odd number of letters then just add a Z next to your last letter. Now again convert those letters into their respective position in the alphabet as above. So for example the text ```Hi``` would be converted into: [[7] [8]] Now we need to [multiply](https://www.mathsisfun.com/algebra/matrix-multiplying.html) the key matrix by the text matrix to get our encrypted matrix and then find out the encrypted matrix [modulo](https://en.wikipedia.org/wiki/Modulo_operation) 26: [[ 2 0] * [[7] = [[14] = [[14] mod 26 [19 18]] [8]] [277]] [17]] For the final step we just find out the letters at the alphabet position of 14 and 17 which are ```O``` and ```R```. So ```OR``` is our encrypted message for the message ```Hi``` In this kata you will be given a function named ```encrypt``` with the parameters ```text``` and ```key``` and you have to return the encrypted message in all uppercase letters ``` python encrypt('','azyb') → '' encrypt('Hi','cats') → 'OR' encrypt('This is a good day','bbaa') → 'AAAAAAGACAGAYA' ``` Note: - The text to encrypt will contain characters other than the alphabets, its your job to clean them before converting text to matrices. Spaces also need to be removed - The text may contain both uppercase and lowercase alphabets. Its your job to standardize them, the encrypted text however should be returned in uppercase letters. - The key will always contain 4 lowercase alphabet.
reference
import numpy as np def encrypt(text, key): # Declare string variable to store the answer ans = '' # Covert all the alphabets to upper case and clean everything else clean_text = '' . join([i . upper() for i in text if i . isalpha()]) # Add Z to the cleaned text if the length of it is odd clean_text += 'Z' * (len(clean_text) % 2) # Return empty string if the cleaned text is empty if len(clean_text) == 0: return '' # Find the key matrix km = np . matrix([[ord(key[0]) - 97, ord(key[1]) - 97], [ord(key[2]) - 97, ord(key[3]) - 97]]) # Create a text matrix tm = np . matrix([[ord(clean_text[i]) - 65, ord(clean_text[i + 1]) - 65] for i in range(0, len(clean_text), 2)]). T # Multiply the key matrix by the text matrix and apply modulo 26 am = (km * tm) % 26 # Convert the numbers back to letters and append them to the ans variable for i in np . array(am . T): ans += chr(i[0] + 65) ans += chr(i[1] + 65) # Return the answer variable return ans
Hill Cipher: Encryption
5e958a9bbb01ec000f3c75d8
[ "Cryptography", "Matrix", "Security", "Fundamentals" ]
https://www.codewars.com/kata/5e958a9bbb01ec000f3c75d8
6 kyu
As you may know, once some people pass their teens, they jokingly only celebrate their 20th or 21st birthday, forever. With some maths skills, that's totally possible - you only need to select the correct number base! For example, if they turn 32, that's exactly 20 - in base 16... Already 39? That's just 21, in base 19! Your task is to translate the given age to the much desired 20 (or 21) years, and indicate the number base, in the format specified below. **Note:** input will be always > 21 ### Examples: ``` 32 --> "32? That's just 20, in base 16!" 39 --> "39? That's just 21, in base 19!" ``` *Hint: if you don't know (enough) about [numeral systems](https://en.wikipedia.org/wiki/Numeral_system) and [radix](https://en.wikipedia.org/wiki/Radix), just observe the pattern!* --- ### My other katas If you enjoyed this kata then please try [my other katas](https://www.codewars.com/users/anter69/authored)! :-) #### *Translations are welcome!*
reference
def womens_age(n): return f" { n } ? That's just { 20 + n % 2 } , in base { n / / 2 } !"
Happy Birthday, Darling!
5e96332d18ac870032eb735f
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5e96332d18ac870032eb735f
7 kyu
Rotate a 2D infinite array by 1 / 8<sup>th</sup> of a full turn, clockwise ### Example ```haskell rotate :: [[a]] -> [[a]] rotate [ "1234.." , "abc.." , "AB.." , "0.." , .. ] -> [ "1" , "a2" , "Ab3" , "0Bc4" , .. ] ``` ```python # Generators represented with list notation rotate([[1,2,3,4,...], ['a','b','c',...], ['A','B',...], ['0',...], ...]) == [[1], ['a',2], ['A','b',3], ['0','B','c',4], ...] ``` ### Notes * Input will be infinite in both dimensions * Result elements need no leading or trailing padding ~~~if:python #### Python: - Inputs/Output will be generators of generators ~~~
algorithms
def rotate(seq): s = [] while True: s . append(next(seq)) yield iter([* map(next, s)][:: - 1])
Rotate 1 / 8th ( Infinity version )
5e921a2550beae0025322e79
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/5e921a2550beae0025322e79
6 kyu
You are given a table, in which every key is a stringified number, and each corresponding value is an array of characters, e.g. ```javascript { "1": ["A", "B", "C"], "2": ["A", "B", "D", "A"], } ``` Create a function that returns a table with the same keys, but each character should appear only once among the value-arrays, e.g. ```javascript { "1": ["C"], "2": ["A", "B", "D"], } ``` ## Rules * Whenever two keys share the same character, they should be compared **numerically**, and the larger key will keep that character. That's why in the example above the array under the key `"2"` contains `"A"` and `"B"`, as `2 > 1`. * If duplicate characters are found in the same array, the first occurance should be kept. ___ ## Example 1 ```javascript input = { "1": ["C", "F", "G"], "2": ["A", "B", "C"], "3": ["A", "B", "D"], } output = { "1": ["F", "G"], "2": ["C"], "3": ["A", "B", "D"], } ``` ___ ## Example 2 ```javascript input = { "1": ["A"], "2": ["A"], "3": ["A"], } output = { "1": [], "2": [], "3": ["A"], } ``` ___ ## Example 3 ```javascript input = { "432": ["A", "A", "B", "D"], "53": ["L", "G", "B", "C"], "236": ["L", "A", "X", "G", "H", "X"], "11": ["P", "R", "S", "D"], } output = { "11": ["P", "R", "S"], "53": ["C"], "236": ["L", "X", "G", "H"], "432": ["A", "B", "D"], } ```
reference
def remove_duplicate_ids(obj): out, seen = {}, {} for i in sorted(obj . keys(), key=int, reverse=True): uniques = [] for v in obj[i]: if v not in seen: uniques . append(v) seen[v] = 1 out[i] = uniques return out
Duplicates. Duplicates Everywhere.
5e8dd197c122f6001a8637ca
[ "Arrays", "Sets", "Sorting", "Fundamentals" ]
https://www.codewars.com/kata/5e8dd197c122f6001a8637ca
6 kyu
<center><h1>DefaultList</h1></center> The collections module has defaultdict, which gives you a default value for trying to get the value of a key which does not exist in the dictionary instead of raising an error. Why not do this for a list? Your job is to create a class (or a function which returns an object) called <code>DefaultList</code>. The class will have two parameters to be given: a list, and a default value. The list will obviously be the list that corresponds to that object. The default value will be returned any time an index of the list is called in the code that would normally raise an error (i.e. i > len(list) - 1 or i < -len(list)). This class must also support the regular list functions extend, append, insert, remove, and pop. Because slicing a list never raises an error (slicing a list between two indexes that are not a part of the list returns [], slicing will not be tested for. <h3>Example</h3> <code class="language-python"> lst = DefaultList([<span class="cm-string">'hello'</span>, <span class="cm-string">'abcd'</span>, <span class="cm-string">'123'</span>, <span class="cm-number">123</span>, <span class="cm-keyword">True</span>, <span class="cm-keyword">False</span>], <span class="cm-string">'default_value'</span>)<br> lst[<span class="cm-number">4</span>] = <span class="cm-keyword">True</span><br> lst[<span class="cm-number">80</span>] = <span class="cm-string">'default_value'</span><br>lst.<span class="cm-property">extend</span>([<span class="cm-number">104</span>, <span class="cm-number">1044</span>, <span class="cm-number">4066</span>, <span class="cm-number">-2</span>])<br> lst[<span class="cm-number">9</span>] = <span class="cm-number">-2</span> </code>
reference
class DefaultList (list): def __init__(self, it, default): super(). __init__(it) self . default = default def __getitem__(self, i): try: return super(). __getitem__(i) except IndexError: return self . default
DefaultList
5e882048999e6c0023412908
[ "Fundamentals" ]
https://www.codewars.com/kata/5e882048999e6c0023412908
6 kyu
# Task: Your function should return a valid regular expression. This is a pattern which is normally used to match parts of a string. In this case will be used to check if all the characters given in the input appear in a string. ## Input Non empty string of unique alphabet characters upper and lower case. ## Output Regular expression pattern string. ## Examples Your function should return a string. ```python # Function example def regex_contains_all(st): return r"abc" ``` ```javascript function regexContainsAll(str) { return "abc"; } ``` ```ruby def regex_contains_all(s) "abc" end ``` ```java public static String regexContainsAll(str) { return "abc"; } ``` That regex pattern will be tested like this. ```python # Test abc = 'abc' pattern = regex_contains_all(abc) st = 'zzzaaacccbbbzzz' bool(re.match(pattern, st), f"Testing if {st} contains all characters in {abc} with your pattern {pattern}") -> True ``` ```javascript const abc = "abc"; const pattern = regexContainsAll(abc); const str = "zzzaaacccbbbzzz"; new RegExp(pattern).test(str); // -> true ``` ```ruby abc = "abc" pattern = regex_contains_all(abc) str = "zzzaaacccbbbzzz" /#{pattern}/ === str # -> true ``` ```java String abc = "abc"; String pattern = regexContainsAll(abc); String str = "zzzaaacccbbbzzz"; Pattern.compile(pattern).matcher(str).find(); // -> true ```
reference
def regex_contains_all(st): return '' . join(f'(?=.* { x } )' for x in set(st))
regex pattern to check if string has all characters
5e4eb72bb95d28002dbbecde
[ "Regular Expressions", "Fundamentals", "Strings" ]
https://www.codewars.com/kata/5e4eb72bb95d28002dbbecde
6 kyu
## **Task** You are given a positive integer (`n`), and your task is to find the largest number **less than** `n`, which can be written in the form `a**b`, where `a` can be any non-negative integer and `b` is an integer greater than or equal to `2`. Try not to make the code time out :) The input range is from `1` to `1,000,000`. ## **Return** Return your answer in the form `(x, y)` or (`[x, y]`, depending on the language ), where `x` is the value of `a**b`, and `y` is the number of occurrences of `a**b`. By the way ** means ^ or power, so 2 ** 4 = 16. If you are given a number less than or equal to `4`, that is not `1`, return `(1, -1)`, because there is an infinite number of values for it: `1**2, 1**3, 1**4, ...`. If you are given `1`, return `(0, -1)`. ## **Examples** ``` 3 --> (1, -1) # because it's less than 4 6 --> (4, 1) # because the largest such number below 6 is 4, # and there is only one way to write it: 2**2 65 --> (64, 3) # because there are three occurrences of 64: 2**6, 4**3, 8**2 90 --> (81, 2) # because the largest such number below 90 is 81, # and there are two ways of getting it: 3**4, 9**2 ``` By the way, after finishing this kata, please try some of my other katas: [here.](https://www.codewars.com/collections/tonylicodings-authored-katas)
algorithms
def largest_power(n): print(n) if n <= 4: if n == 1: return (0, - 1) return (1, - 1) # num_of_occurances freq = 0 x = [] largest = 0 j = 0 while 2 * * largest < n: largest += 1 largest -= 1 for i in range(2, largest + 1): while j * * i < n: j += 1 j -= 1 x . append(j * * i) j = 0 return (max(x), x . count(max(x)))
Largest Value of a Power Less Than a Number
5e860c16c7826f002dc60ebb
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5e860c16c7826f002dc60ebb
6 kyu
**DESCRIPTION:** Your strict math teacher is teaching you about right triangles, and the Pythagorean Theorem: `$a^2 + b^2 = c^2$` whereas `$a$` and `$b$` are the legs of the right triangle and `$c$` is the hypotenuse of the right triangle. On the test however, the question asks: **What are the possible integer lengths for the other side of the triangle given two sides `$a$` and `$b$`**, but since you never learned anything about that in class, you realize she meant **What are the possible integer lengths for the other side of the right triangle given two sides `$a$` and `$b$`**. Because you want to address the fact that she asked the wrong question and the fact that you're smart at math, you've decided to answer all the possible values for the third side **EXCLUDING** the possibilities for a right triangle in increasing order. **EXAMPLES:** ``` side_len(1, 1) --> [1] side_len(3, 4) --> [2, 3, 4, 6] side_len(4, 6) --> [3, 4, 5, 6, 7, 8, 9] ``` **RETURN:** Return your answer as a list of all the possible third side lengths of the triangle without the right triangles in increasing order. By the way, after finishing this kata, please try some of my other katas: [Here](https://www.codewars.com/collections/tonylicodings-authored-katas) NOTE: When given side_len(x, y), y will always be greater than or equal to x. Also, if a right triangle's legs are passed in, exclude the hypotenuse. If a right triangle's leg and hypotenuse are passed in, exclude the other leg.
reference
def side_len(x, y): return [z for z in range(abs(x - y) + 1, x + y) if z * z not in (abs(x * x - y * y), x * x + y * y)]
Possible side lengths of a triangle excluding right triangles.
5e81303e7bf0410025e01031
[ "Fundamentals" ]
https://www.codewars.com/kata/5e81303e7bf0410025e01031
7 kyu
<style> .header { padding: 5px 5%; border-left: 5px solid #e9ed28; color: #ffcc66 !important; background-image: linear-gradient(to right, #222, rgb(0,0,0,0)); } </style> <h2 class="header">Overview</h2> <p>The task is simple - given a 2D array (list), generate an HTML table representing the data from this array.</p> <p>You need to write a function called <code>to_table</code>/<code>toTable</code>, that takes three arguments:</p> <ul> <li><code>data</code> - a 2D array (list),</li> <li><code>headers</code> - an optional boolean value. If <code>True</code>, the first row of the array is considered a header (see below). Defaults to <code>False</code>,</li> <li><code>index</code> - an optional boolean value. If <code>True</code>, the first column in the table should contain 1-based indices of the corresponding row. If <code>headers</code> arguments is <code>True</code>, this column should have an empty header. Defaults to <code>False</code>.</li> </ul> and returns a string containing HTML tags representing the table. <h2 class="header">Details</h2> HTML table is structured like this: ```xml <table> <thead> <!-- an optional table header --> <tr> <!-- a header row --> <th>header1</th> <!-- a single header cell --> <th>header2</th> </tr> </thead> <tbody> <!-- a table's body --> <tr> <!-- a table's row --> <td>row1, col1</td> <!-- a row's cell --> <td>row1, col2</td> </tr> <tr> <td>row2, col1</td> <td>row2, col2</td> </tr> </tbody> </table> ``` The table header is optional. If `header` argument is `False` then the table starts with `<tbody>` tag, ommiting `<thead>`. So, for example: ```python to_table([["lorem", "ipsum"], ["dolor", "sit amet"]], True, True) ``` ```javascript toTable([["lorem", "ipsum"], ["dolor", "sit amet"]], true, true) ``` returns ```python "<table><thead><tr><th></th><th>lorem</th><th>ipsum</th></tr></thead><tbody><tr><td>1</td><td>dolor</td><td>sit amet</td></tr></tbody></table>" ``` As you can see, no linebreaks or whitespaces (except for the ones present in the array values) are included, so the HTML code is minified. <b><u>IMPORTANT NOTE:</u></b> if the value in the array happens to be `None`, the value of the according cell in the table should be en ampty string (`""`)! Otherwise, just use a string representation of the given value, so, dependent on the language, the output can be slightly different. No additional parsing is needed on the data. <h2 class="header">Additional info</h2> For your convenience, there is a preloaded function `esc_html`/`escHtml` that takes a string with HTML tags and escape them; it is necessary if you want to use `print`/`console.log` on your resulting strings, elsewise Codewars processes HTML tags, so they appear invisible in the stdout. Test cases will always provide valid data, that is - up to three arguments, first a NxM array (list) with N and M > 0, second and third a boolean. The values in the array will always be either `string`, `number`, `bool` or `None`/`null`. For more examples, see test cases. P.S.: I understand, that with larger inputs checking for mismatches in the expected and actual output can be cumbersome, but as of now I can hardly come up with something that would make this easier. Any ideas would be helpful!
reference
def to_table(data, header=False, withIdx=False): head = f'<thead> { getLine ( data [ 0 ], withIdx , "th" ) } </thead>' * header body = f'<tbody> { "" . join ( getLine ( d , withIdx , n = i ) for i , d in enumerate ( data [ header :], 1 )) } </tbody>' return f'<table> { head }{ body } </table>' def getLine(row, withIdx, tag='td', n=''): line = withIdx * [f'< { tag } > { n } </ { tag } >'] + \ [f'< { tag } > { "" if d is None else d } </ { tag } >' for d in row] return f'<tr> { "" . join ( line ) } </tr>'
Array to HTML table
5e7e4b7cd889f7001728fd4a
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5e7e4b7cd889f7001728fd4a
6 kyu
In Scala, an underscore may be used to create a partially applied version of an infix operator using placeholder syntax. For example, `(_ * 3)` is a function that multiplies its input by 3. With a bit of manipulation, this idea can be extended to work on any arbitrary expression. Create an value/object named `x` that acts as a placeholder in an arithmetic expression. The placeholder should support the four basic integer arithmetic operations: addition, subtraction, multiplication, and integral (floor) division. When the expression with placeholders is called, it should fill the placeholders in the expression from left to right (regardless of operator precedence) with the values it is given. Here are a few examples: ``` calling (x + 3) with [1] gives 1 + 3 = 4 calling (10 - x) with [4] gives 10 - 4 = 6 calling (x + 2 * x) with [1 3] gives 1 + 2 * 3 = 1 + 6 = 7 calling ((x + 2) * x) with [1 3] gives (1 + 2) * 3 = 3 * 3 = 9 calling (4 * (x / 2)) with [5] gives 4 * (5 / 2) = 4 * 2 = 8 ``` All inputs and outputs to/from the expression will be integer types. All expressions tested in this kata will be valid, i.e. there will be no division by zero and the number of values passed in will always be the same as the number of placeholders. Note: `eval` and `exec` are disabled
algorithms
# -*- coding: utf-8 -*- import operator class Placeholder: def __init__(self, op=None, left=None, right=None): self . op = op self . left = left self . right = right def calc(self, args): if self . op: x, args = self . left . calc(args) if isinstance( self . left, Placeholder) else (self . left, args) y, args = self . right . calc(args) if isinstance( self . right, Placeholder) else (self . right, args) return self . op(x, y), args return args[0], args[1:] def __call__(self, * args): return self . calc(args)[0] def __add__(self, other): return Placeholder(op=operator . add, left=self, right=other) def __sub__(self, other): return Placeholder(op=operator . sub, left=self, right=other) def __mul__(self, other): return Placeholder(op=operator . mul, left=self, right=other) def __floordiv__(self, other): return Placeholder(op=operator . floordiv, left=self, right=other) def __radd__(self, other): return Placeholder(op=operator . add, left=other, right=self) def __rsub__(self, other): return Placeholder(op=operator . sub, left=other, right=self) def __rmul__(self, other): return Placeholder(op=operator . mul, left=other, right=self) def __rfloordiv__(self, other): return Placeholder(op=operator . floordiv, left=other, right=self) x = Placeholder()
Arithmetic Expression Placeholders
5e7bc286a758770033b56a5a
[ "Algorithms" ]
https://www.codewars.com/kata/5e7bc286a758770033b56a5a
5 kyu
<center><h1 style="font-size: 30px;">HTML Element Generator</h1></center> <p>In this kata, you will be creating a python function that will take arguments and turn them into an HTML element.</p> <h3>An HTML tag has three parts:</h3> <ol> <li>The opening tag, which consists of a tag name and potentially attributes, all in between angle brackets.</li> <li>The element content, which is the data that is shown on the webpage. This is in between the opening and closing tags.</li> <li>And the closing tag, which is an opening angle bracket, a forward slash, the name of the tag, and a closing angle bracket</li> </ol> <center><img style="width: 500px;" src="https://learn-the-web.algonquindesign.ca/topics/html-semantics/html-tag-parts.png"></center> <p>If you were to have multiple attributes, they would each appear with a single space separating them</p> <img style="height: 200px; float: right;" src="https://camo.githubusercontent.com/eef23486a6ddd309ece42e7405b183c67d5901e8/687474703a2f2f692e696d6775722e636f6d2f676c547465325a2e706e67"> <p>Some tags do <b>not</b> require a closing tag. These are called self-closing tags. For this kata, any tag passed into the function without 'element content' (keyword arguments) will be treated in this way: after the tag name (and any attributes), there will be a space and then a forward slash. See the picture to the right.</p> <br> <p>Data will be passed into the <code>html</code> function as such: </p> <ul style="list-style-type:square;"> <li>The first argument will be the tag name</li> <li>Any other non-keyword arguments will be element content. If no element content is given, the return value will be expected to be a self-closing tag. If more than one argument is given as element content, you will return multiple of the same element, just with different element content, separated by one or more newline characters.<br> Ex: <br> <code> &lt;p class="paragraph-text" id="example"&gt;Hello World!&lt;/p&gt;\n&lt;p class="paragraph-text" id="example"&gt;This is HTML code!&lt;/p&gt; </code></li> <li style="color:#f88;"><b>IMPORTANT: </b> Because class is a python keyword, and class is a very important HTML attribute, you will also have to implement a keyword argument named <b style="color:red;">cls</b>, as opposed to class. This attribute will appear as <i style="color: red;"><b>class</b></i>="variable" in the return value of your function</li> <li>Any other keyword arguments of the function will be treated as attributes of the element. The keyword is the attribute name (left of the equals sign), and the keyword's value is the attribute's value (right of the equals sign).</li> <li>Element attributes will appear in the return value of your function in the order that they appear in the function's arguments when it is called. If cls is an argument of the function, it will always appear first (before any other keyword arguments).</li> <br><p style="text-align: center; border:1px solid gray">Several Examples are provided</p>
reference
def html(tag, * contents, * * attr): openTag = tag + \ '' . join( f' { "class" if k == "cls" else k } =" { v } "' for k, v in attr . items()) return '\n' . join(f'< { openTag } > { c } </ { tag } >' for c in contents) or f'< { openTag } />'
HTML Element Generator
5e7837d0262211001ecf04d7
[ "Fundamentals" ]
https://www.codewars.com/kata/5e7837d0262211001ecf04d7
6 kyu
You have a path of `n` tiles in your garden that you'd like to paint, and four different colors to do so. 'Thing is... You don't want any two adjacent tiles to be of the same color and you'd like that it'd cost you the minimum possible amount of money. 'Second thing is... due to differences in the texture and matter of each tile, the quantity of paint needed to cover each tile may differe a lot. So, you are given `n x 4` array, that represents the costs of painting each tile of the path with the four available colors and you need to find a way to get the minimal total cost of painting the whole path, without two consecutive tiles being of the same color. <b>Example</b> For 6 tiles: ``` # color: 1 2 3 4 costs = [[ 1, 3, 4, 5], # tile 1 ^ [ 2, 3, 2, 3], # 2 ^ [ 3, 1, 4, 1], # 3 ^ [ 2, 3, 1, 3], # 4 ^ [ 5, 4, 2, 4], # 5 ^ [ 6, 1, 6, 6]] # 6 ^ ``` Optimal painting: tile 1 with color 1, tile 2 with color 3, tile 3 with color 2, tile 4 with color 1, tile 5 with color 3, tile 6 with color 2. Total cost is `costs[0][0] + costs[1][2] + costs[2][1] + costs[3][0] + costs[4][2] + costs[5][1] == 1+2+1+2+2+1 == 9`. <b>Note:</b> You need to find an efficient algorithm because number of solution can be as high as 3000. <b>Note:</b> Multiple solution may exists. Your task is to return the minimum cost, not to find all possible solutions.
algorithms
def paint_tiles(costs): t = [0] * 4 for cs in costs: t = [c + min(t[j] for j in range(4) if j != i) for i, c in enumerate(cs)] return min(t)
Paint Tiles
5e297e9f63f1db003317cbac
[ "Dynamic Programming", "Algorithms" ]
https://www.codewars.com/kata/5e297e9f63f1db003317cbac
6 kyu
You get a list of nodes. Return the sorted list of nodes without any duplicates. See example test cases for expected inputs and outputs. ( Node data structure is inspired by `Cytoscape.js JSON`) ## Restriction ``` Your code length should not be longer than 85 characters. ```
reference
def remove_duplicate(A): return [* map(eval, sorted(set(map(str, A))))]
[ Code Golf ] Remove duplicated nodes
5c237d7c1ea8b34b32000244
[ "Restricted", "Fundamentals" ]
https://www.codewars.com/kata/5c237d7c1ea8b34b32000244
6 kyu
You are given 2 numbers is `n` and `k`. You need to find the number of integers between 1 and n (inclusive) that contains exactly `k` non-zero digit. Example1 ` almost_everywhere_zero(100, 1) return 19` by following condition we have 19 numbers that have k = 1 digits( not count zero ) ` [1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100]` Example2 ` almost_everywhere_zero(11, 2) return 1` we have only `11` that has 2 digits(ten not count because zero is not count) ` 11` constrains `1≤n<pow(10,100)` `1≤k≤100`
algorithms
from scipy . special import comb def almost_everywhere_zero(n, k): if k == 0: return 1 first, * rest = str(n) l = len(rest) return 9 * * k * comb(l, k, exact=True) + \ (int(first) - 1) * 9 * * (k - 1) * comb(l, k - 1, exact=True) + \ almost_everywhere_zero(int("" . join(rest) or 0), k - 1)
Almost Everywhere Zero
5e64cc85f45989000f61526c
[ "Algorithms", "Logic", "Mathematics" ]
https://www.codewars.com/kata/5e64cc85f45989000f61526c
4 kyu
In my school, a grand musical is performed every 4 years. This means that every student who comes to this school will get to see a musical performed exactly once in their 4-year stay. This is not always the case in other schools though. For a given duration of time, an interval after which a musical is performed, and the duration of class enrolment, can you determine how many class-years did not get to have a musical performed in their school? A musical is always performed for the start_class. `Example:` ```python no_musical(start_class = 2000, end_class = 2010, musical_performed_every = 5, duration_of_enrolment_in_school = 3) = 4 ``` `Explanation:` Only the class of 2000 gets to see the musical performed in 2000. The next musical will be in 2005 so only the class of 2003 in their last year, 2004 in their second year, and 2005 in their first year, get to see it. The next musical will be in 2010 so only the class of 2008, 2009 and 2010 get to see it. This leaves us with the class of 2001, 2002, 2006 and 2007 who never get to see a musical, a total of 4 classes :( TO NOTE: 1. In this kata, if duration of enrolment in school is, say, 4 years, members of a class that starts in 2000 will graduate in 2003, not 2004. Their years of enrolment in the school would be 2000, 2001, 2002 and 2003. (In the standard way that we are used to the term 'class of', they would be the class of 1999 as they would graduate in 2003, but we do not do that here) 1. As seen in the example, the range is end-inclusive. The last class should also be accounted for. 1. Very minor note, we assume all the students in the school will actually go to watch the musical - not that it matters for this kata anyway. That said, I am not really a musical person :-( 5 sample tests, 50 randomized tests. Good luck.
reference
def no_musical(classS, classE, showFreq, classT): nYears, deltaY = classE - classS, showFreq - classT if not showFreq: return nYears + 1 if deltaY < 1: return 0 n, r = divmod(nYears, showFreq) return deltaY * n + min(r, deltaY)
No musical :(
5e65916b4696e500134987e1
[ "Mathematics", "Logic", "Fundamentals" ]
https://www.codewars.com/kata/5e65916b4696e500134987e1
7 kyu
<style> table, th, td { border: 1px solid black; } </style> <h2>Introduction (skippable)</h2> Let's suppose you got a cake... : <strike>I eat it and the kata ends.</strike> <br> <br> Consider it to weigh `3 hg`, with the <b>smallest possible</b> slice to weigh `1 hg`.<br> In <b>how many ways</b> can you serve the <b>whole</b> cake? <br> You can either <font color = red>avoid</font> or <font color = cyan>use</font> the knife:<br> <font color = red>3</font><br> <font color = cyan>2 + 1</font><br> <font color = cyan>1 + 2</font><br> <font color = cyan>1 + 1 + 1</font><br> It can be served in <font color = yellow><b>4</b></font> different ways, assuming that _order matters_. <br><br> The number `3` has been expressed as the sum of <a href="https://en.wikipedia.org/wiki/Natural_number">natural</a> numbers.<br> This is called a <a href="https://en.wikipedia.org/wiki/Composition_(combinatorics)"><b>composition</b></a> : our cake has <font color = yellow><b>4 compositions</b></font>.<br><br>Notice that if _order didn't matter_ it would be called a <a href="https://en.wikipedia.org/wiki/Partition_(number_theory)"><b>partition</b></a>.<br>Thus there would have been <font color = orange>3 partitions</font>, being 2+1 and 1+2 considered the same. <h2>Description</h2> Partitions sound like constrained Compositions.<br>What if another aspect of Compositions, instead of order, gets restricted ?<br> Let's call these <b>odd-even compositions</b> and call the number to decompose "N". <br> N = 4 <br> <i>To reach <b>4</b> we can...</i> <br> <table style="width:40%"> <tr> <th>Compositions</th> <th>Odd-Even Compositions</th> </tr> <tr> <td>4</td> <td><font color = gray>4</font></td> </tr> <tr> <td>3 + 1</td> <td><strike><font color = red>3</font> + <font color = gray>1</font></strike></td> </tr> <tr> <td>2 + 2</td> <td><font color = green>2</font> + <font color = gray>2</font></td> </tr> <tr> <td>2 + 1 + 1</td> <td><font color = green>2</font> + <font color = gray>1</font> + <font color = gray>1</font></td> </tr> <tr> <td>1 + 3</td> <td><font color = gray>1</font> + <font color = gray>3</font></td> </tr> <tr> <td>1 + 2 + 1</td> <td><strike><font color = gray>1</font> + <font color = red>2</font> + <font color = gray>1</font></strike></td> </tr> <tr> <td>1 + 1 + 2</td> <td><font color = gray>1</font> + <font color = gray>1</font> + <font color = gray>2</font></td> </tr> <tr> <td>1 + 1 + 1 + 1</td> <td><font color = gray>1</font> + <font color = gray>1</font> + <font color = gray>1</font> + <font color = gray>1</font></td> </tr> <tr> <td>Total : 8</td> <td>Total : 6</td> </tr> </table> <br> And back to the example of the cake (notice the similarity with the previous example): N = 3 <br> <i>To reach <b>3</b> we can...</i> <br> <table style="width:40%"> <tr> <th>Compositions</th> <th>Odd-Even Compositions</th> </tr> <tr> <td>3</td> <td><font color = gray>3</font></td> </tr> <tr> <td>2 + 1</td> <td><strike><font color = red>2</font> + <font color = gray>1</font></strike></td> </tr> <tr> <td>1 + 2</td> <td><font color = gray>1</font> + <font color = gray>2</font></td> </tr> <tr> <td>1 + 1 + 1</td> <td><font color = gray>1</font> + <font color = gray>1</font> + <font color = gray>1</font></td> </tr> <tr> <td>Total : 4</td> <td>Total : 3</td> </tr> </table> Notice how numbers are highlighted: <ul style="list-style-type:square;"> <li><font color = "gray">Gray numbers</font> are always valid.<br>i.e. 1 and the <b>number itself</b> (which is N).</li> <li><font color = "green">Green numbers</font> are valid because they share parity/disparity with N<br>with N=4, <b>2</b> is valid because both are even.</li> <li><font color = "red">Red numbers</font> are not valid because they don't share parity/disparity with N<br>back to the first example, <b>3</b> is not valid because it is odd, while <b>4</b> is even.</li> </ul> <br> Thus about the first example (N=4): <ul style="list-style-type:square;"> <li> "3+1" is <font color=red>invalid</font> : <ul> <li> 3 is <font color=red>red</font> because 3 is odd while 4 (N) is even. </li> </ul> </li> <li> "1+2+1" is <font color=red>invalid</font> : <ul> <li> 1 is <font color=gray>gray</font> and N becomes N=N-1 --> N=3 </li> <li> 2 is <font color=red>red</font> because 2 is even while 3 (N) is odd. </li> </ul> </li> <li> "1+3" is <font color=green>valid</font> : <ul> <li> 1 is <font color=gray>gray</font> and N becomes N=N-1 --> N=3 </li> <li> 3 is <font color=gray>gray</font> because 3 is the number itself (N=3) </li> </ul> </li> <li> "2+2" is <font color=green>valid</font> : <ul> <li> 2 is <font color=green>green</font> because 2 and 4(N) are even, so N=N-2 --> N=2 </li> <li> 2 is <font color=gray>gray</font> because 2 is the number itself (N=2) </li> </ul> </li> </ul> <h2>Task</h2> Return the number of <b>odd-even compositions*</b> by which the given number can be expressed.<br> * didn't know how else to call them D: ... i've just "invented" the name <h2>Warning</h2> The given numbers will range <b>from 0 to 10^3 inclusive</b>, then time-out may occur if your solution isn't fast enough. <br> <b>If input is 0 return 1.</b> <h2>Other Examples</h2> ```python odd_even_compositions(0) # returns 1 odd_even_compositions(7) # returns 27 odd_even_compositions(28) # returns 3188646 ``` <h3>Hints</h3> <ul style="list-style-type:square;"> <li>If additions feel weird, try to express the concept using subtractions.</li> <li>I asked you to calculate <b>odd-even compositions</b>.<br>What if i asked to calculate <b>compositions</b>?</li> </ul>
algorithms
def odd_even_compositions(Q): return not Q or (2 - (1 & Q)) * 3 * * (~ - Q >> 1)
Odd-Even Compositions
5e614d3ffa2602002922a5ad
[ "Algorithms", "Performance", "Mathematics" ]
https://www.codewars.com/kata/5e614d3ffa2602002922a5ad
5 kyu
A *Vampire number* is a positive integer `z` with a factorization `x * y = z` such that - `x` and `y` have the same number of digits and - the multiset of digits of `z` is equal to the multiset of digits of `x` and `y`. - Additionally, to avoid trivialities, `x` and `y` may not both end with `0`. In this case, `x` and `y` are called *fangs* of `z`. (The fangs of a Vampire number may not be unique, but this shouldn't bother us.) The first three Vampire numbers are ``` 1260 = 21*60 1395 = 15*93 1435 = 35*41 ``` Write an algorithm that on input `k` returns the `k`th Vampire number. To avoid time-outs, the Python version will test with `1 <= k <= 155`. PS: In the OEIS, the Vampire numbers are sequence [A014575](https://oeis.org/A014575). PPS: So called *Pseudo-Vampire Numbers* are treated in [this kata](http://www.codewars.com/kata/vampire-numbers-1).
games
def is_vampire(x, y): return sorted(f" { x }{ y } ") == sorted( f" { x * y } ") and x % 10 + y % 10 > 0 vampires = sorted({x * y for p in (1, 2) for x in range(10 * * p, 10 * * (p + 1)) for y in range(x, 10 * * (p + 1)) if is_vampire(x, y)}) def VampireNumber(k): return vampires[k - 1]
Vampire numbers less than 1 000 000
558d5c71c68d1e86b000010f
[ "Puzzles" ]
https://www.codewars.com/kata/558d5c71c68d1e86b000010f
7 kyu
Consider the following equation of a surface `S`: `z*z*z = x*x * y*y`. Take a cross section of `S` by a plane `P: z = k` where `k` is a positive integer `(k > 0)`. Call this cross section `C(k)`. #### Task Find the *number* of points of `C(k)` whose coordinates are positive integers. #### Examples If we call `c(k)` the function which returns this number we have ``` c(1) -> 1 c(4) -> 4 c(4096576) -> 160 c(2019) -> 0 which means that no point of C(2019) has integer coordinates. ``` #### Notes - k can go up to about 10,000,000,000 - Prolog: the function `c`is called `section`. - COBOL: the function `c`is called `sections`. - Please could you ask before translating : some translations are already written.
reference
def c(k): from math import sqrt root = int(sqrt(k)) if (root * root != k): return 0 i = 2 num = k * root result = 1 while (num > 1): div_num_nb = 0 while (num % i == 0): num / /= i div_num_nb += 1 result *= div_num_nb + 1 i += 1 return result
Sections
5da1df6d8b0f6c0026e6d58d
[ "Fundamentals" ]
https://www.codewars.com/kata/5da1df6d8b0f6c0026e6d58d
5 kyu
# An introduction to propositional logic Logic and proof theory are fields that study the formalization of logical statements and the structure of valid proofs. One of the most common ways to represent logical reasonings is with **propositional logic**. A propositional formula is no more than what you normally use in your *if statements*, but without functions or predicates. The basic unit for these formulas are **literals**. Let's see some examples: ``` f = p ∧ q ``` Here ```p``` and ```q``` would be the literals. This formula means that *f* evaluates to ```True``` only when both ```p``` **and** ```q``` are True too. The ```∧``` operator is formally called **conjunction** and is often called **and**. ``` f = p ∨ q ``` This formula means that *f* evaluates to ```True``` only when any of ```p``` **or** ```q``` are True. This includes the case when both are True. The ```∨``` operator is formally called **disjunction** and is often called **or**. ``` f = ¬p ``` The ```¬``` operator is analogous to the **not** operation. it evaluates to True only when its argument evaluates to False. Normally, there are also two other operators called **implication** and **biconditional**, but we will ignore them for this kata (they can be expressed in terms of the other three anyways). Once we know this, can construct what is called an **interpretation** in order to evaluate a propositional formula. This is a fancy name for any structure that tells us which literals are False and which ones are True. Normally, interpretations are given as a set: ```python p = Literal('p') q = Literal('q') r = Literal('r') f = p ∨ q ∨ ¬r i_1 = {p, q} # p and q are True, r is False i_2 = {r} # r is True, p and q are False i_3 = {} # p, q and r are False # Note: the 'evaluate' function is not given evaluate(f, i_1) == True evaluate(f, i_2) == False evaluate(f, i_3) == True ``` As you can see, if the literal is in the set, we say it evaluates to True, else it is False. As a final note, an interpretation that makes a formula True is called a **model** when all the literals in the set appear in the formula. # The SAT problem This is a famous NP problem that is stated as follows: > Given a propositional formula *F*, does it exist an interpretation such that it evaluates to True? (i.e. is *F* **satisfiable**?) Numerous algorithms exist for this purpose, and your task is to program one of them. Right now, you are not supposed to program an efficient algorithm, but I may create a performance version if this kata gets good reception :) # Specification Program a ```sat(f: Formula)``` function that returns the following: - ```False``` if ```f``` is not satisfiable. - An interpretation that makes ```f``` evaluate to True in the case that it is satisfiable. # Preloaded code You are given a class ```Formula``` that has the following members: - ```args```: arguments of the operation if the formula is not a literal (children nodes of the formula's tree). They are given as a list of Formula objects that has one element in the case of the negation operator and two or more elements in the case of the conjunction and disjunction operators. - ```is_literal()```: True if the formula is a literal (i.e. not an operation). - ```is_and()```: True if the formula is a **conjunction**. - ```is_or()```: True if the formula is a **disjunction**. - ```is_not()```: True if the formula is a **negation**. You are also given a class ```Literal``` that extends from ```Formula``` and has the following members: - ```name```: string that represents the literal. Two literals with the same name **are the same literal**. *Note: the rest of members are not guaranteed in the case of a literal* The ```&``` operator is overloaded as the conjunction, ```|``` as the disjunction and ```~``` as the negation. Also, a ```__repr__``` function is given for debugging purposes. # Extra examples ``` f = ¬(p ∨ q) # Satisfiable with {} ``` ``` f = ¬(p ∧ q) # Satisfiable with {p}, {q} and {} ``` ``` f = p ∧ (q ∨ r) # Satisfiable with {p, q}, {p, r} and {p, q, r} ``` ``` f = ¬p ∨ ¬q # Satisfiable with {p}, {q} and {} (See De Morgan's Laws) ``` ``` f = p ∧ ¬p # Not satisfiable ```
algorithms
from itertools import compress, product, chain from functools import partial def check(f, s): if f . is_literal(): return f in s elif f . is_and(): return all(check(e, s) for e in f . args) elif f . is_or(): return any(check(e, s) for e in f . args) elif f . is_not(): return not check(f . args[0], s) def get_name(f): if f . is_literal(): yield f else: yield from chain . from_iterable(map(get_name, f . args)) def sat(f): s = set(get_name(f)) return next(filter(partial(check, f), map(set, map(partial(compress, s), product((0, 1), repeat=len(s))))), False)
Propositional SAT Problem
5e5fbcc5fa2602003316f7b5
[ "Logic", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5e5fbcc5fa2602003316f7b5
5 kyu
<style> .cod {background:rgba(250, 250, 250, 0.05); padding: 10px; border-radius:20px;} .cod:hover {background: rgba(250, 250, 250, 0.067); transition: all 1.0s} </style> <h1>The n-Bonacci Ratio</h1> <div class="cod">The Fibonacci sequence is the sequence that starts with 0, 1 that increases by the previous two terms added together each time.<br> In mathematical terms: <table><tr><td>F(0) = 0</td> <td>F(1) = 1</td> <td>F(x) = F(x-1) + F(x-2)</td></tr></table> As the number of terms approaches infinity, the ratio between the last term and the term before that approaches a constant. This is known as the golden ratio. It is approximately equal to 1.61803.</div><hr> <div class="cod">There is another sequence called the Pell Sequence (or the two-bonacci sequence), which is very similar to the Fibonacci sequence: <table><tr><td>P(0) = 0</td> <td>P(1) = 1</td> <td>P(x) = 2 * P(x-1) + P(x-2)</td></tr></table> The ratio between the last two numbers as the length of the sequence approaches infinity also approaches a constant: approximately 2.4142. This is known as the silver ratio.</div><hr> <div id="challenge" class="cod lod"> <strong style="color: rgb(255, 65, 65);"> Your job is to find the n-bonacci ratio as the number of terms approaches infinity, where the n-bonacci sequence is defined as: <table><tr><td>n-bonacci(0) = 0</td> <td>n-bonacci(1) = 1</td> <td>n-bonacci(x) = n * n-bonacci(x-1) + n-bonacci(x-2)</td></tr></table> <i>This value must be precise to at least 8 decimal places.</i></strong></div>
reference
from math import sqrt def n_bonacci_ratio(n): return (n + sqrt(n * * 2 + 4)) / 2
n-Bonacci Ratio
5e60cc55d8e2eb000fe57a1c
[ "Mathematics", "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/5e60cc55d8e2eb000fe57a1c
7 kyu
**The Rub** You need to make a function that takes an object as an argument, and returns a very similar object but with a special property. The returned object should allow a user to access values by providing only the beginning of the key for the value they want. For example if the given object has a key `idNumber`, you should be able to access its value on the returned object by using a key `idNum` or even simply `id`. `Num` and `Number` shouldn't work because we are only looking for matches at the beginning of a key. Be aware that you _could_ simply add all these partial keys one by one to the object. However, for the sake of avoiding clutter, we don't want to have a JSON with a bunch of nonsensical keys. Thus, in the random tests there will be a test to check that you did not add or remove any keys from the object passed in or the object returned. Also, if a key is tested that appears as the beginning of more than one key in the original object (e.g. if the original object had a key `idNumber` and `idString` and we wanted to test the key `id`) then return the value corresponding with whichever key comes first **alphabetically**. (In this case it would be `idNumber`s value because it comes first alphabetically.) **Example** ```javascript let o = partialKeys({ abcd: 1 }) o.abcd === 1 // true o.abc === 1 // true o.ab === 1 // true o.a === 1 // true o.b === 1 // false! Object.keys(o) // ['abcd'] ``` ```python o = partial_keys({"abcd": 1}) o['abcd'] == 1 # true o['abc'] == 1 # true o['ab'] == 1 # true o['a'] == 1 # true o['b'] == 1 # false! o['b'] == None # true list(o.keys()) # ['abcd'] ``` ```ruby o = partial_keys({"abcd" => 1}) o['abcd'] == 1 # true o['abc'] == 1 # true o['ab'] == 1 # true o['a'] == 1 # true o['b'] == 1 # false! o['b'].nil? # true o.keys # ['abcd'] ```
games
def partial_keys(d): class Dct (dict): def __getitem__(self, pk): k = min((k for k in self if k . startswith(pk)), default=None) return k if k is None else super(). __getitem__(k) return Dct(d)
Partial Keys
5e602796017122002e5bc2ed
[ "Regular Expressions" ]
https://www.codewars.com/kata/5e602796017122002e5bc2ed
6 kyu
Oh no! Someone left the server at your local car dealership too close to a blender and now all of their data is scrambled. It is your job to unscramble the data and put it into an easy to read dictionary. Unscramble the list you are given and return the values in a dictionary such as the following: ``` dictionary = {'make': make, 'model': model, 'year': year, 'new': new} ``` You will be given a list containing a string (the make of the car), a tuple containing two strings (the model and sub-model), an integer (the year the car was manufactured) and a boolean (whether the car is new or used 'True' or 'False'), but you will not know the order of the list. Return the dictionary where 'make' is a String, 'model' is a String, 'year' is an integer, and 'new' is a boolean of whether it is new (True) or used (False) **P.S Model should be converted to a string, separating the values by one Space**
reference
def id_(k): return lambda v: (k, v) CONFIG = { bool: id_('new'), int: id_('year'), tuple: lambda t: ('model', ' ' . join(t)), str: id_('make'), } def make_model_year(lst): return dict(CONFIG[type(data)](data) for data in lst)
Data Type Scramble
5e5acfe31b1c240012717a78
[ "Parsing", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5e5acfe31b1c240012717a78
7 kyu
The conveyor can move parts in four directions: right(r), left(l), up(u) and down(d), wrapping around the border of the grid. There is also one element that is the output of the conveyor(f). The conveyor is represented by a rectangular list of strings, as shown below: ```python ["rdfrd", "uluul"] ``` During the step, the part moves along the conveyor to an adjacent cell according to the specified direction. For each conveyor cell, it is necessary to calculate the number of steps for which the element will reach the output tile `f` (-1 if this is not possible). The result is returned as a 2D array of integers. Example: ```python ["rfl"] => [[1, 0, 1]] ["rdfrd", => [[-1, -1, 0, -1, -1], "uluul"] [-1, -1, 1, -1, -1]] ["lfl"] => [[2, 0, 1]] ```
reference
def path_counter(con): out = [[- 1] * len(con[0]) for i in range(len(con))] f = 0, 0 for y in range(len(con)): for x in range(len(con[0])): if con[y][x] == 'f': f = y, x break out[f[0]][f[1]] = 0 dirs = {(0, 1): 'l', (0, - 1): 'r', (1, 0): 'u', (- 1, 0): 'd'} stack = [f] while stack: y, x = stack . pop() for dy, dx in dirs . keys(): ny, nx = (y + dy) % len(con), (x + dx) % len(con[0]) if con[ny][nx] == dirs[(dy, dx)]: out[ny][nx] = out[y][x] + 1 stack . append((ny, nx)) return out
Elementary conveyor
5e417587e35dfb0036bd5d02
[ "Performance", "Fundamentals" ]
https://www.codewars.com/kata/5e417587e35dfb0036bd5d02
4 kyu
You are given a line from a movie subtitle file as a string.\ The line consists of time interval when the text is shown: ```start(hh:mm:ss,ms) --> stop(hh:mm:ss,ms)``` and the text itself, for example: ```01:09:02,684 --> 01:09:03,601 Run Forrest, run!``` Your task is to write a function ```subs_offset_apply``` which takes such string and offset \ (integer) in miliseconds as arguments, and returns the string with the offset applied. \ Examples: ``` string = "01:09:02,684 --> 01:09:03,601 Run Forrest, run!" subs_offset_apply(string, 3663655) output: "02:10:06,339 --> 02:10:07,256 Run Forrest, run!" "00:43:22,074 --> 00:43:24,159 No, I am your father." subs_offset_apply(string, 1789) output: "00:43:23,863 --> 00:43:25,948 No, I am your father." "00:03:06,241 --> 00:03:07,618 I'll be back." subs_offset_apply(string, -21789) output: "00:02:44,452 --> 00:02:45,829 I'll be back." ``` Time constraints: ```00:00:00,000 <= t <= 99:59:59,999``` In case of too big negative or positive offset, which results in exceeding the constraints, \ the function should return a string "Invalid offset". \ You'll be given only valid strings. \ Have Fun!
reference
def subs_offset_apply(subs, offset): def parse(time): hours, minutes, seconds, milliseconds = map( int, time . replace(',', ':'). split(':')) return ((hours * 60 + minutes) * 60 + seconds) * 1000 + milliseconds def render(time, min=parse('00:00:00,000'), max=parse('99:59:59,999')): if not min <= time <= max: raise OverflowError seconds, milliseconds = divmod(time, 1000) minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) return f' { hours :0 2 } : { minutes :0 2 } : { seconds :0 2 } , { milliseconds :0 3 } ' try: start, _, stop, * text = subs . split() start, stop = parse(start), parse(stop) return f' { render ( start + offset )} --> { render ( stop + offset )} { " " . join ( text )} ' except OverflowError: return 'Invalid offset'
Apply offset to subtitles
5e454bf176551c002ee36486
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5e454bf176551c002ee36486
6 kyu
Binary with 0 and 1 is good, but binary with only 0 is even better! Originally, this is a concept designed by Chuck Norris to send so called unary messages. Can you write a program that can send and receive this messages? <h2><span style="color:LightSeaGreen">Rules</span></h2> <ul> <li>The input message consists of ASCII characters between 32 and 127 (7-bit)</li> <li>The encoded output message consists of blocks of <span style="color:LightSeaGreen">0</span></li> <li>A block is separated from another block by a space</li> <li>Two consecutive blocks are used to produce a series of same value bits (only 1 or 0 values):</li> <ul> <li>First block is always <span style="color:LightSeaGreen">0</span> or <span style="color:LightSeaGreen">00</span>. If it is <span style="color:LightSeaGreen">0</span>, then the series contains 1, if not, it contains <span style="color:LightSeaGreen">0</span></li> <li>The number of <span style="color:LightSeaGreen">0</span> in the second block is the number of bits in the series</li> </ul> </ul> <h2><span style="color:LightSeaGreen">Example</span></h2> Let’s take a simple example with a message which consists of only one character (Letter 'C').<br>'C' in binary is represented as 1000011, so with Chuck Norris’ technique this gives: <ul> <li><span style="color:LightSeaGreen">0 0</span> - the first series consists of only a single <span style="color:LightSeaGreen">1</span></li> <li><span style="color:LightSeaGreen">00 0000</span> - the second series consists of four <span style="color:LightSeaGreen">0</span></li> <li><span style="color:LightSeaGreen">0 00</span> - the third consists of two <span style="color:LightSeaGreen">1</span></li> </ul> So 'C' is coded as: <span style="color:LightSeaGreen">0 0 00 0000 0 00</span><br><br> Second example, we want to encode the message "CC" (i.e. the 14 bits <span style="color:LightSeaGreen">10000111000011</span>) : <ul> <li><span style="color:LightSeaGreen">0 0</span> - one single 1</li> <li><span style="color:LightSeaGreen">00 0000</span> - four 0</li> <li><span style="color:LightSeaGreen">0 000</span> - three 1</li> <li><span style="color:LightSeaGreen">00 0000</span> - four 0</li> <li><span style="color:LightSeaGreen">0 00</span> - two 1</li> </ul> So "CC" is coded as: <span style="color:LightSeaGreen">0 0 00 0000 0 000 00 0000 0 00</span> <h2><span style="color:LightSeaGreen">Note of thanks</span></h2> Thanks to the author of the original kata. I really liked this <a href=https://www.codingame.com/training/easy/chuck-norris>kata</a>. I hope that other warriors will enjoy it too.
reference
from re import compile REGEX1 = compile(r"0+|1+"). findall REGEX2 = compile(r"(0+) (0+)"). findall binary = "{:07b}" . format def send(s): temp = '' . join(binary(ord(c)) for c in s) return ' ' . join("0 " + '0' * len(x) if x[0] == '1' else "00 " + x for x in REGEX1(temp)) def receive(s): temp = '' . join(y if x == '00' else '1' * len(y) for x, y in REGEX2(s)) return '' . join(chr(int(temp[i: i + 7], 2)) for i in range(0, len(temp), 7))
Unary Messages
5e5ccbda30e9d0001ec77bb6
[ "Fundamentals" ]
https://www.codewars.com/kata/5e5ccbda30e9d0001ec77bb6
6 kyu
Your task is to write a function `calculate`, which accepts a string with a mathematical exprssion written in [prefix Polish notation](https://en.wikipedia.org/wiki/Polish_notation) and evaluates it. This means that all operations are placed before their operands. For example, the expression `3 + 5` is written in Polish notation as `+ 3 5`, and `(3 + 5) / (2 * 2)` is `/ + 3 5 * 2 2`. The only valid operations are `+`, `-`, `*` and `/`. The input string is guaranteed to be a valid expression. You can use `eval` or alternative if available in your language, but it is in no way needed for an idiomatic solution. ### Examples calculate('123.456') == 123.456 calculate('+ -5 5') == 0 calculate('* + 2 2 3') == 12 calculate('/ + 3 5 * 2 2') == 2 ### Input A non-empty string consisting of numbers and arithmetic operators separated by spaces. This string is a valid arithmetic expression written in prefix polish notation. ### Output A number, result of evaluating the expression.
reference
from operator import add, sub, mul, truediv def calculate(expression): stack = [] ops = {'+': add, '-': sub, '*': mul, '/': truediv} for a in reversed(expression . split()): stack . append(ops[a](stack . pop(), stack . pop()) if a in ops else float(a)) return stack . pop()
Evaluating prefix Polish notation
5e5b7f55c2e8ae0016f42339
[ "Parsing", "Mathematics", "Algorithms", "Lists", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5e5b7f55c2e8ae0016f42339
6 kyu
You have been presented with a cipher, your goal is to re-create the cipher with little information. Use the examples provided to see if you can find a solution to how this cipher is made. You will be given no hints, only the handful of phrases that have already been deciphered for you. Your only hint: Spaces are left alone, they are not altered in any way. Anytime there is a space, it should remain untouched and in place. I hope you enjoy, but this one should be genuinely infuriating.
games
def cipher(p): return '' . join(chr((ord(j) + i % 3 + (i - 1) / / 3 - 97) % 26 + 97) if j != ' ' and i != 0 else j for i, j in enumerate(p))
Rectangle Cipher Puzzle
5e539724dd38d0002992eaad
[ "Puzzles", "Ciphers", "Algorithms" ]
https://www.codewars.com/kata/5e539724dd38d0002992eaad
6 kyu
# Cellular Automata A cellular automata is a regular grid of cells, each with a state from a finite number of them (such as ON (1) and OFF (0)) and with a defined neighbourhood (which cells are considered adjacent to each cell). The automata is then given a initial state (a state for each of its cells) and rules to change it in each generation based on the state of its neighbourhood. Each cell evolves independently and simultaneously, meaning that it calculates its next state based on the current state of its adjacent cells, but does not change the value of other cells directly nor influences its decision with its own evolution. For example, we could consider an automata composed of 7 cells in a single line which can either be off or on, like so: ``` 1 0 1 1 0 1 1 ``` We can then define the rule where a cell will be 1 if and only if it was previously between two 1s, otherwise it will be 0. We can break down that rule into the two neighbourhoods that match that description and write it in a shorter form like so: `[1,0,1], [1,1,1]`. This means that any cell whose state (the center) and adjacent cells (left and right) matches those neighbourhoods will be 1 in the next generation. Any other neighbourhood will be 0, since no other rule has been defined. In the next generation the automata would look like: ``` 0 1 0 0 1 0 1 ``` Note that the automata loops around, meaning that the last cell is considered to be to the left of the first cell. # Your task In this kata, you will be programming a one-dimensional cellular automata, meaning the cells are arranged in a single row. For further simplicity, each cell will only be either on (1) or off (0). Your code will accept the parameters of the automata and a number of generations, and return the state of the automata after that many generations. ## Input parameters: * `rules`: The rules the automata will follow to evolve, described as neighbourhoods. This is an array of length > 0, containing arrays of the same odd length (1,3,5...). Each array in `rules` defines a neighbourhood configuration or "rule" that will result in a cell evolving to a 1. In each generation, we check all cells for matches against the rules in this parameter. If the current neighbourhood of a cell matches any of the defined in `rules`, then that cell will evolve to a 1 in the next generation; otherwise it will evolve to a 0. To check if a cell matches a rule, check that the number in the center of the rule matches the state of the cell, then check that the numbers on the left and right of the center number in the rule also match the states of the cells in the same relative position to the cell. For example, if we consider the rule `[1,1,0]` for the automata `[0,1,1,0,0]`, the cell at index 2 will match, but no other cell will. * `initial`: The initial state of the automata, given as an array of integers of length > 0. For example, `[0,0,1,1,0,1]`. * `generations`: The number of generations the automata must go through, given as an integer. ## Notes In this kata, the automata is considered to "loop around": that is, the last cell of the automata is considered to be to the left of the first, and vice versa. All rules in the `rules` parameter will have the same length. This length is not necessarily less than the length of the automata. Some rules in `rules` might be repeated, based on the random test generation. There is no special treatment needed for those cases. Some test cases use famous cellular automatons as their base. You can try to print your solution to screen and see it side-by-side with the examples on Wikipedia if you're struggling.
algorithms
def get_mask(xs): '''Convert iterable of 1s and 0s to a binary number''' d = 0 for x in xs: d = (d << 1) | x return d def automata(rules, initial, generations): automata = initial[:] # m: width of neighbourhood on either side m, n = len(rules[0]) / / 2, len(automata) # used to limit bitmask to width of rule mask = get_mask([1] * len(rules[0])) rules = list(map(get_mask, rules)) # rules converted to bitmasks temp = [0] * n # used for swapping for _ in range(generations): # neighbourhood at index 0 as a bitmask b = get_mask([automata[i % n] for i in range(- m, m + 1)]) for a in range(n): temp[a] = int(any(b == rule for rule in rules)) # match any rule # left-shift, push out MSB, push in next value b = (b << 1) & mask | automata[(a + m + 1) % n] automata, temp = temp, automata # swap buffers return automata
1 Dimensional cellular automata
5e52946a698ef0003252b526
[ "Algorithms", "Cellular Automata" ]
https://www.codewars.com/kata/5e52946a698ef0003252b526
6 kyu
Here's a way to construct a list containing every positive rational number: Build a binary tree where each node is a rational and the root is `1/1`, with the following rules for creating the nodes below: * The value of the left-hand node below `a/b` is `a/a+b` * The value of the right-hand node below `a/b` is `a+b/b` So the tree will look like this: ``` 1/1 / \ 1/2 2/1 / \ / \ 1/3 3/2 2/3 3/1 / \ / \ / \ / \ 1/4 4/3 3/5 5/2 2/5 5/3 3/4 4/1 ... ``` Now traverse the tree, breadth first, to get a list of rationals. ``` [ 1/1, 1/2, 2/1, 1/3, 3/2, 2/3, 3/1, 1/4, 4/3, 3/5, 5/2, .. ] ``` Every positive rational will occur, in its reduced form, exactly once in the list, at a finite index. ```if:haskell In the kata, we will use tuples of type `(Integer, Integer)` to represent rationals, where `(a, b)` represents `a / b` ``` ```if:javascript In the kata, we will use tuples of type `[ Number, Number ]` to represent rationals, where `[a,b]` represents `a / b` ``` Using this method you could create an infinite list of tuples: ```haskell allRationals :: [(Integer, Integer)] ``` ```javascript function* allRationals() => [Number,Number] // forever ``` matching the list described above: ```haskell allRationals = [(1,1), (1,2), (2,1), (1,3), (3,2), ...] ``` ```javascript allRationals => [ [1,1], [1,2], [2,1], [1,3], [3,2], .. ] ``` However, constructing the actual list is too slow for our purposes. Instead, study the tree above, and write two functions: ```haskell -- return the value at the given index ratAt :: Integer -> (Integer, Integer) -- return the index of the given rational indexOf :: (Integer, Integer) -> Integer ``` ```javascript // return the value at the given index function ratAt(BigInt) => [Number,Number] // return the index of the given rational function indexOf([Number,Number]) => BigInt ``` For example: ```haskell ratAt 10 = (5, 2) indexOf (3,5) = 9 ``` ```javascript ratAt(10n) = [5,2] indexOf([3,5]) = 9n ```
reference
def rat_at(n): a, b = 0, 1 for bit in f" { n + 1 : b } ": if bit == '1': a += b else: b += a return a, b def index_of(a, b): n, mask = 0, 1 while a != b: n += mask * (a > b) mask *= 2 a, b = (a, b - a) if b > a else (a - b, b) return n + mask - 1
List of all rationals - going further
5e529a6fb95d280032d04389
[ "Mathematics", "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/5e529a6fb95d280032d04389
7 kyu
Here's a way to construct a list containing every positive rational number: Build a binary tree where each node is a rational and the root is `1/1`, with the following rules for creating the nodes below: * The value of the left-hand node below `a/b` is `a/a+b` * The value of the right-hand node below `a/b` is `a+b/b` So the tree will look like this: ``` 1/1 / \ 1/2 2/1 / \ / \ 1/3 3/2 2/3 3/1 / \ / \ / \ / \ 1/4 4/3 3/5 5/2 2/5 5/3 3/4 4/1 ... ```` Now traverse the tree, breadth first, to get a list of rationals. ``` [ 1/1, 1/2, 2/1, 1/3, 3/2, 2/3, 3/1, 1/4, 4/3, 3/5, 5/2, .. ] ``` Every positive rational will occur, in its reduced form, exactly once in the list, at a finite index. ```if:haskell,fsharp In the kata, we will use tuples of type `(Integer, Integer)` to represent rationals, where `(a, b)` represents `a / b` ``` ```if:javascript In the kata, we will use tuples of type `[ Number, Number ]` to represent rationals, where `[a,b]` represents `a / b` ``` ```if:typescript,coffeescript In the kata, we will use tuples of type `[number, number]` to represent rationals, where `[a, b]` represents `a / b` ``` ```if:python In the kata, we will use tuples of type `(int, int)` to represent rationals, where `(a, b)` represents `a / b` ``` ```if:kotlin In the kata, we will use `Pair`s of type `Pair<Int, Int>` to represent rationals, where `Pair(a, b)` represents `a / b` ``` ```if:php In the kata, we will use tuples of type `[int, int]` to represent rationals, where `[a, b]` represents `a / b` ``` ```if:ruby In the kata, we will use arrays of type `[Integer, Integer]` to represent rationals, where `[a, b]` represents `a / b` ``` Use this method to create an infinite list of tuples: ```haskell allRationals :: [(Integer, Integer)] ``` ```javascript function* allRationals() => [Number,Number] // forever ``` ```coffeescript allRationals = -> # generator of [Number, Number]s ``` ```typescript function* allRationals(): IterableIterator<[number, number]> ``` ```python def all_rationals() -> Generator[(int, int)]: ``` ```php function allRationals() // : Generator<[int, int]> (generic types aren't supported in PHP) ``` ```ruby class AllRationals < Enumerator # Enumerator of [Integers, Integers]s ``` ```kotlin fun allRationals(): Iterator<Pair<Int, Int>> ``` matching the list described above: ```haskell allRationals = [ (1,1), (1,2), (2,1), (1,3), (3,2), .. ] ``` ```javascript allRationals => [ [1,1], [1,2], [2,1], [1,3], [3,2], .. ] ``` ```python all_rationals => [(1, 1), (1, 2), (2, 1), (1, 3), (3, 2), ...] ``` ```ruby AllRationals.new => [[1, 1], [1, 2], [2, 1], [1, 3], [3, 2], ...] ``` ```php allRationals() => [[1, 1], [1, 2], [2, 1], [1, 3], [3, 2], ...] ``` ```coffeescript allRationals() => [[1, 1], [1, 2], [2, 1], [1, 3], [3, 2], ...] ``` ```typescript allRationals() => [[1, 1], [1, 2], [2, 1], [1, 3], [3, 2], ...] ``` ```kotlin allRationals().asSequence().take(..).toList() => listOf(Pair(1, 1), Pair(1, 2), Pair(2, 1), Pair(1, 3), Pair(3, 2), ...) ```
reference
def all_rationals(): yield (1, 1) for a, b in all_rationals(): yield from [(a, a + b), (a + b, b)]
List of all Rationals
5e4e8f5a72d9550032953717
[ "Mathematics", "Lists", "Fundamentals" ]
https://www.codewars.com/kata/5e4e8f5a72d9550032953717
7 kyu
Let an array or a list `arr = [x(1), x(2), x(3), x(4), ..., x(i), x(i+1), ..., x(m), x(m+1)]` where all `x(i)` are positive integers. The length `lg` of this array will be a positive multiple of 4. Let `P = (x(1) ** 2 + x(2) ** 2) * (x(3) ** 2 + x(4) ** 2) * ... * (x(m) ** 2 + x(m+1) ** 2)`, `x ** y` means x raised to the power y. #### Task Given an array or list `arr` the task is to find: - two `nonnegative` integers A and B such as `P = A ** 2 + B ** 2 (1)`. The function `solve(arr)` should return an array or a list `[A, B]` or a tuple where A and B verify (1). #### Examples: ``` solve([2, 1, 3, 4]) returns [2, 11] : (2*2 + 1*1) * (3*3 + 4*4) = 5 * 25 = 125 and 2 * 2 + 11 * 11 = 125 solve([2, 1, 3, 4, 2, 2, 1, 5, 2, 3, 4, 5]) returns [2344, 2892] : (2*2 + 1*1) * (3*3 + 4*4) * (2*2 + 2*2) * (1*1 + 5*5) * (2*2 + 3*3) * (4*4 + 5*5) = 13858000 and 2344 * 2344 + 2892 * 2892 = 13858000 ``` #### Notes - The decomposition into `A ** 2 + B ** 2` is not unique: the testing function checks if (1) is verified. - Lengths of lists are less than 100 and elements of lists less than 30 ``` solve([21, 24, 15, 22, 1, 2]) can return [639, 1788] or [1431, 1248]; both return are correct. P is 3605265 A*A+B*B 3605265 ``` - Please ask before translating
reference
def solve(arr): a, b, c, d = arr[0: 4] # print(a, b, c, d) # print(arr[4:]) first4 = [abs(a * c - b * d), (a * d + b * c)] if len(arr) == 4: return first4 return solve(first4 + arr[4:])
Operations on sequences
5e4bb05b698ef0001e3344bc
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/5e4bb05b698ef0001e3344bc
5 kyu
# Types and classes Nowadays, types and classes are no foreign concepts for any programmer, as they tend to be present on most programming languages in one form or another. The thing is that functional languages tipically see types in a different way that imperative ones. The distinctive factor is that they can operate with types via addition and multiplication and call it **Algebraic Data Types**. Imagine we have the following types: ```python T1 = int | str T2 = int & str ``` We say that *T1* is a **sum type** and that *T2* is a **product type**, meaning that an instance of type *T1* can be either an int or a str and that an instance of type *T2* is a composition of an int and a str. You can see the second kind as a tuple where each value has a certain type. Where things get kind of messy is when we talk about **binding**. The question is: **given a list of possible implicit type conversions, can we always assign a value of type *A* to a variable of type *B* (i.e. is *A* bindable to *B*)?** The rules to solve this problem are as follows: * If *A* = *B*, then it is bindable * If there exists an implicit conversion between *A* and *B*, then it is bindable * If *A* = *A1* | *A2*, then both *A1* and *A2* must be bindable to *B* * If *B* = *B1* | *B2*, then *A* has to be bindable to *B1*, *B2* or both * If *A* = *A1* & *A2* and *B* = *B1* & *B2*, then all *An* have to be bindable to *Bn* * In any other case, it is not bindable Now, given a class ADT (for Algebraic Data Type) that has the following members: ```python ADT.is_simple() # True if it is a simple type ADT.is_sum() # True if it is a sum type ADT.is_product() # True if it is a product type ADT.subtypes # a str with the name of the type if it is a simple type # a list of ADT in the case of a complex type (may have more than 2) # Example: t = ADT('str') | ADT('int') t.is_sum() == True t.subtypes == [ADT('str'), ADT('int')] ``` Write a function ```bindable(from_type, to_type, bindings)``` that takes two ADTs and a set of available bindings and calculates whether or not *from_type* is bindable to *to_type*. **Note:** available bindings are given as a set of tuples with the following format: ```python example_bindings = { # (from_type, to_type) (ADT('int'), ADT('str')), # int can be converted to str (ADT('int'), ADT('float')), # int can be converted to float (ADT('list'), ADT('set')), # list can be converted to set ... } ```
algorithms
def bindable(a, b, bindings): if a == b or (a, b) in bindings: return True elif a . is_sum(): return all(bindable(x, b, bindings) for x in a . subtypes) elif b . is_sum(): return any(bindable(a, x, bindings) for x in b . subtypes) if a . is_product() and b . is_product(): asub, bsub = a . subtypes, b . subtypes return len(asub) == len(bsub) and all(bindable(x, y, bindings) for x, y in zip(asub, bsub)) return False
Binding of Algebraic Data Types
5e4cf596dc3099002a30cbb1
[ "Functional Programming", "Algorithms" ]
https://www.codewars.com/kata/5e4cf596dc3099002a30cbb1
6 kyu
### Task: Decoding The task of this kata is to take an exponential-Golomb encoded binary string and return the array of decoded integers it represents. ### Encoding An exponential-Golomb code is a way of representing an integer using bit patterns. To encode any non-negative integer `x` using the exponential-Golomb code: 1. Write down `x + 1` in binary, without leading zeroes. 2. Count ( all ) the bits written, subtract one, and add that many zeroes to the front of the bit string. ### Example The value for `3` would be: 3 → 100 ( 3 + 1 in binary ) → 00100 ( 100 with two 0s preceding it ) The value for `22` would be: 22 → 10111 → 000010111 As such, a sequence of nonnegative integers can be represented as sequence of exponential-Golomb codes: [3, 22, 0, 4, 12] → 00100 000010111 1 00101 0001101 Therefore, for this case, your function should take `"001000000101111001010001101"` and return `[3, 22, 0, 4, 12]`.
algorithms
def decoder(sequence): i = 0 out = [] while i < len(sequence): j = sequence . index('1', i) i = 2 * j + 1 - i out . append(int(sequence[j: i], 2) - 1) return out
Exponential-Golomb Decoder
5e4d8a53b499e20016b018a0
[ "Algorithms" ]
https://www.codewars.com/kata/5e4d8a53b499e20016b018a0
6 kyu
Given a non-negative number, return the next bigger polydivisible number, or an empty value like `null` or `Nothing`. A number is polydivisible if its first digit is cleanly divisible by `1`, its first two digits by `2`, its first three by `3`, and so on. There are finitely many polydivisible numbers.
algorithms
d, polydivisible, arr = 1, [], list(range(1, 10)) while arr: d += 1 polydivisible . extend(arr) arr = [n for x in arr for n in range(- (- x * 10 / / d) * d, (x + 1) * 10, d)] def next_num(n): from bisect import bisect idx = bisect(polydivisible, n) if idx < len(polydivisible): return polydivisible[idx]
Next polydivisible number
5e4a1a43698ef0002d2a1f73
[ "Algorithms" ]
https://www.codewars.com/kata/5e4a1a43698ef0002d2a1f73
6 kyu
# Welcome to Squareville! The king of these lands invited you to solve a problem that has been going on for ages now. Every citizen is assigned a square chunk of ground to cultivate their famous watermelons, but the distribution is becoming more and more tedious as the city grows in size. Every chunk is composed of n^2 subchunks with a fertility index that indicates how many watermelons can be grown there: ``` 0 0 1 2 1 2 2 3 3 1 0 2 3 3 2 (Example of a 5x5 chunk) 1 1 0 1 1 2 2 3 1 3 ``` Since every family is composed of a different number of individuals that are able to work the lands, the most fertile ones are given to the most capable families. This can become very tiring when the chunks are very large, so the king has given you the task of writing a function *w* (for Watermelon) that counts the number of watermelons that can be grown in a given chunk. The input will be given as a bidimensional array of ints. # Your task Write a function `w(arr: List[List[int]]) -> int` that returns the sum of all the numbers in `arr`. # Constraints The problem is that the only programming language that is allowed in Squareville is **Sqrton**, which is a subset of Python that only allows programs with a square shape (i.e the number of characters in each line **must be equal to the number of lines in the code**) and **no spacing characters** (spaces, tabs...). To help you, you have been provided with the Sqr Development Kit™: ```python def s(f, a): return lambda *args: f(a,*args) def q(f, a): return f(a[0]) + q(f,a[1:]) if a else 0 def r(f): return f ``` The last programmer the king hired tried to cheat, so the king **will only let you use functionalities from this SDK**. In any case, he is certain that it is possible to solve this problem with it. You will come to like these beautiful shapes as much as we do! # Example This is a valid Sqrton example that returns the function `s`: ```Python r(r( r(r( r(s) )))) ```
games
w = (s (q, s (q, r,)))
Real World Applications of Sqrton
5e498a51dc30990025221647
[ "Functional Programming", "Restricted", "Puzzles" ]
https://www.codewars.com/kata/5e498a51dc30990025221647
5 kyu
A grammar is a set of rules that let us define a language. These are called **production rules** and can be derived into many different tools. One of them is **String Rewriting Systems** (also called Semi-Thue Systems or Markov Algorithms). Ignoring technical details, they are a set of rules that substitute ocurrences in a given string by other strings. The rules have the following format: ``` str1 -> str2 ``` We define a rule application as the substitution of a substring following a rule. If this substring appears more than once, only one of this occurences is substituted and any of them is equally valid as an option: ```python 'a' -> 'c' # Substitution rule 'aba' # Base string 'cba' # One application on position 0 'abc' # One application on position 2 'cbc' # Two applications ``` Another valid example of rule application would be the following: ```python # Rules 'l' -> 'de' 'm' -> 'col' 'rr' -> 'wakr' 'akr' -> 'ars' # Application 'mrr' # Starting string 'colrr' # Second rule 'coderr' # First rule 'codewakr' # Third rule 'codewars' # Last rule ``` Note that this example is exhaustive, but Semi-Thue Systems can be potentially infinite: ```python # Rules 'a' -> 'aa' # Application 'a' # Starting string 'aa' # First application 'aaa' # Second application ... ``` The so called **Word Problem** is to decide whether or not a string can be derived from another using these rules. This is an **undecidable problem**, but if we restrict it to a certain number of applications, we can give it a solution. Your task is to write a function that solves the word problem given a maximum number of rule applications. **Python:** The rules are given as tuples where the left and the right handside of the rule correspond to the first and the second element respectively. **Notes:** * Two rules can have the same left handside and a different right handside. * You do not have to worry too much about performance yet. A simple, funtional answer will be enough.
algorithms
def word_problem(rules: List[Tuple[str, str]], from_str: str, to_str: str, applications: int) - > bool: def rec(s, n): return s == to_str or n and any(s[i:]. startswith(x) and rec( s[: i] + y + s[i + len(x):], n - 1) for i in range(len(s)) for x, y in rules) return rec(from_str, applications)
Semi-Thue Systems - The Word Problem [Part 1]
5e453b6476551c0029e275db
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5e453b6476551c0029e275db
6 kyu
Most of this problem is by the original author of [the harder kata](https://www.codewars.com/kata/556206664efbe6376700005c), I just made it simpler. I read a book recently, titled "Things to Make and Do in the Fourth Dimension" by comedian and mathematician Matt Parker ( [Youtube](https://www.youtube.com/user/standupmaths) ), and in the first chapter of the book Matt talks about problems he likes to solve in his head to take his mind off the fact that he is in his dentist's chair, we've all been there! The problem he talks about relates to polydivisible numbers, and I thought a kata should be written on the subject as it's quite interesting. (Well it's interesting to me, so there!) ### Polydivisib... huh what? So what are they? A polydivisible number is divisible in an unusual way. The first digit is cleanly divisible by `1`, the first two digits are cleanly divisible by `2`, the first three by `3`, and so on. ### Examples Let's take the number `1232` as an example. ``` 1 / 1 = 1 // Works 12 / 2 = 6 // Works 123 / 3 = 41 // Works 1232 / 4 = 308 // Works ``` `1232` is a polydivisible number. However, let's take the number `123220` and see what happens. ``` 1 /1 = 1 // Works 12 /2 = 6 // Works 123 /3 = 41 // Works 1232 /4 = 308 // Works 12322 /5 = 2464.4 // Doesn't work 123220 /6 = 220536.333... // Doesn't work ``` `123220` is not polydivisible. ### Your job: check if a number is polydivisible or not. Return `true` if it is, and `false` if it isn't. Note: All inputs will be valid numbers between `0` and `2^53-1 (9,007,199,254,740,991)` (inclusive). Note: All single digit numbers (including `0`) are trivially polydivisible. Except for `0`, no numbers will start with `0`.
algorithms
def polydivisible(x): for i in range(1, len(str(x)) + 1): if int(str(x)[: i]) % i != 0: return False return True
Polydivisible Numbers
5e4217e476126b000170489b
[ "Algorithms" ]
https://www.codewars.com/kata/5e4217e476126b000170489b
7 kyu
# How many urinals are free? In men's public toilets with urinals, there is this unwritten rule that you leave at least one urinal free between you and the next person peeing. For example if there are 3 urinals and one person is already peeing in the left one, you will choose the urinal on the right and not the one in the middle. That means that a maximum of 3 people can pee at the same time on public toilets with 5 urinals when following this rule (Only 2 if the first person pees into urinal 2 or 4). ![Imgur Urinals](https://i.imgur.com/imZE6xm.png) ## Your task: You need to write a function that returns the maximum of free urinals as an integer according to the unwritten rule. ### Input A String containing 1s and 0s (Example: `10001`) (1 <= Length <= 20) A one stands for a taken urinal and a zero for a free one. ### Examples `10001` returns 1 (10101) `1001` returns 0 (1001) `00000` returns 3 (10101) `0000` returns 2 (1001) `01000` returns 1 (01010 or 01001) ### Note When there is already a mistake in the input string (for example `011`), then return `-1` Have fun and don't pee into the wrong urinal ;)
reference
def get_free_urinals(urinals): return - 1 if '11' in urinals else sum(((len(l) - 1) / / 2 for l in f'0 { urinals } 0' . split('1')))
How many urinals are free?
5e2733f0e7432a000fb5ecc4
[ "Fundamentals" ]
https://www.codewars.com/kata/5e2733f0e7432a000fb5ecc4
7 kyu
You need to write a code that will return product ID from string representing URL for that product's page in your online shop. All URLs are formatted similarly, first there is a domain `exampleshop.com`, then we have name of a product separated by dashes(`-`), then we have letter `p` indicating start of product ID, then an actual ID (no limit on length), and lastly 8-digit long representation of date when product got added followed by `.html`.It can look like this: `exampleshop.com/fancy-coffee-cup-p-90764-12052019.html` >> productID is `90764` `exampleshop.com/dry-water-just-add-water-to-get-water-p-147-24122017.html` >> productID is 147 `exampleshop.com/public-toilet-proximity-radar-p-942312798-01012020.html` >> productID is `942312798` (NOTE: Product name can also contain letter p or digits) Your code needs to return the Product ID as a string. All URLs will be valid product URLs and all will follow above structure.
reference
def get_product_id(url): return url . split('-')[- 2]
Product ID from URL
5e2c7639b5d728001489d910
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5e2c7639b5d728001489d910
7 kyu
## Mighty Heroes Alyosha Popovich (Russian folk hero) stroke his sharp sword and cut the head of Zmey Gorynych (big Serpent with several heads)! He looked - and lo! - in its place immediately new heads appeared, exactly `n`. He stroke again, and where the second head was, `2*n` heads appeared! The third time it was `2*3*n` new heads, and after fourth swing it was `2*3*4*n` heads, and so forth. And thus Alyosha decided to call it a day, and instead called a fellow Mage for help. While the Mage agreed, he needs to know the exact number of heads that Zmey Gorynych now has. ## The task Given the initial number of heads, the heads-count multiplier, and the number of sword-swings, calculate how many heads Zmey Gorynych has in the end. ## Examples ``` initial = 2 multiplier = 1 swings = 1 result: 1 head appearead after the swing: 2 - 1 + 1 = 2 Zmey has 2 heads in the end ``` ``` initial = 5 multiplier = 10 swings = 3 result: 10 heads appearead after the first swing: 5 - 1 + 10 = 14 20 heads appearead after the second swing: 14 - 1 + 2 * 10 = 33 60 heads appearead after the third swing: 33 - 1 + 2 * 3 * 10 = 92 Zmey has 92 heads in the end ```
reference
from math import factorial def count_of_heads(heads, n, k): return sum(factorial(i) * n for i in range(1, k + 1)) + (heads - k)
Mighty Hero
5e2aec959bce5c001f090c4d
[ "Fundamentals", "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/5e2aec959bce5c001f090c4d
6 kyu
Given a board of `NxN`, distributed with tiles labeled `0` to `N² - 1`(inclusive): A solved grid will have the tiles in order of label, left to right, top to bottom. Return `true` if the board state is currently solved, and `false` if the board state is unsolved. Input will always be a square 2d array. For example, a 2x2 solved grid: ``` [ [0, 1], [2, 3] ] ``` A 2x2 unsolved grid: ``` [ [2, 1], [0, 3] ] ```
games
def is_solved(board): curr = 0 for r in board: for c in r: if c != curr: return False curr += 1 return True
Sliding Puzzle Verification
5e28b3ff0acfbb001f348ccc
[ "Games" ]
https://www.codewars.com/kata/5e28b3ff0acfbb001f348ccc
7 kyu
⚠️ The world is in quarantine! There is a new pandemia that struggles mankind. Each continent is isolated from each other but infected people have spread before the warning. ⚠️ 🗺️ You would be given a map of the world in a type of string: string s = "01000000X000X011X0X" '0' : uninfected '1' : infected 'X' : ocean ⚫ The virus can't spread in the other side of the ocean. ⚫ If one person is infected every person in this continent gets infected too. ⚫ Your task is to find the percentage of human population that got infected in the end. ☑️ Return the percentage % of the total population that got infected. ❗❗ The first and the last continent are not connected! 💡 Example: start: map1 = "01000000X000X011X0X" end: map1 = "11111111X000X111X0X" total = 15 infected = 11 percentage = 100*11/15 = 73.33333333333333 ➕ For maps without oceans "X" the whole world is connected. ➕ For maps without "0" and "1" return 0 as there is no population.
games
def infected(s): lands = s . split('X') total = sum(map(len, lands)) infected = sum(len(x) for x in lands if '1' in x) return infected * 100 / (total or 1)
Pandemia 🌡️
5e2596a9ad937f002e510435
[ "Strings", "Puzzles" ]
https://www.codewars.com/kata/5e2596a9ad937f002e510435
7 kyu
Ask a mathematician: "What proportion of natural numbers contain at least one digit `9` somewhere in their decimal representation?" You might get the answer "Almost all of them", or "100%". Clearly though, not all whole numbers contain a `9`. In this kata we ask the question: "How many `Integer`s in the range `[0..n]` contain at least one `9` in their decimal representation?" In other words, write the function: ```haskell nines :: Integer -> Integer ``` ```javascript nines :: BigInt => BigInt ``` ```elixir nines :: Integer -> Integer ``` Where, for example: ```haskell nines 1 = 0 nines 10 = 1 -- 9 nines 90 = 10 -- 9, 19, 29, 39, 49, 59, 69, 79, 89, 90 ``` ```javascript nines(1n) = 0n nines(10n) = 1n // 9 nines(90n) = 10n // 9, 19, 29, 39, 49, 59, 69, 79, 89, 90 ``` ```elixir nines(1) == 0 nines(10) == 1 # 9 nines(90) == 10 # 9, 19, 29, 39, 49, 59, 69, 79, 89, 90 ``` When designing your solution keep in mind that your function will be tested against some large numbers (up to `10^38`)
games
from re import sub def nines(n): return n - int(sub(r'9.*$', lambda m: '8' * len(m[0]), str(n)), 9)
How many nines?
5e18743cd3346f003228b604
[ "Mathematics", "Puzzles" ]
https://www.codewars.com/kata/5e18743cd3346f003228b604
6 kyu
You work in the best consumer electronics corporation, and your boss wants to find out which three products generate the most revenue. Given 3 lists of the same length like these: * products: `["Computer", "Cell Phones", "Vacuum Cleaner"]` * amounts: `[3, 24, 8]` * prices: `[199, 299, 399]` return the three product names with the highest revenue (`amount * price`). **Note**: if multiple products have the same revenue, order them according to their original positions in the input list.
reference
def top3(* args): return [item[0] for item in sorted(zip(* args), key=lambda x: x[1] * x[2], reverse=True)[: 3]]
Most sales
5e16ffb7297fe00001114824
[ "Fundamentals" ]
https://www.codewars.com/kata/5e16ffb7297fe00001114824
7 kyu
_Note: There is a harder version ([Sports League Table Ranking (with Head-to-head)](https://www.codewars.com/kata/5e0e17220d5bc9002dc4e9c4)) of this._ # Description You organize a sports league in a [round-robin-system](https://en.wikipedia.org/wiki/Round-robin_tournament). Each team meets all other teams. In your league a win gives a team `2 points`, a draw gives both teams `1 point`. After some games you have to compute the order of the teams in your league. You use the following criteria to arrange the teams: - Points - Scoring differential (the difference between goals scored and those conceded) - Goals scored First you sort the teams by their points. If two or more teams reached the same number of points, the second criteria comes into play and so on. Finally, if all criteria are the same, the teams share a place. ## Input - `number`: Number of teams in your league. - `games`: An array of arrays. Each item represents a played game with an array of four elements `[TeamA,TeamB,GoalA,GoalB]` (`TeamA` played against `TeamB` and scored `GoalA` goals and conceded `GoalB` goals ). ## Output - `positions`: An array of positions. The `i`-th item should be the position of the `i`-th team in your league. # Example ``` number = 6 games = [[0, 5, 2, 2], // Team 0 - Team 5 => 2:2 [1, 4, 0, 2], // Team 1 - Team 4 => 0:2 [2, 3, 1, 2], // Team 2 - Team 3 => 1:2 [1, 5, 2, 2], // Team 1 - Team 5 => 2:2 [2, 0, 1, 1], // Team 2 - Team 0 => 1:1 [3, 4, 1, 1], // Team 3 - Team 4 => 1:1 [2, 5, 0, 2], // Team 2 - Team 5 => 0:2 [3, 1, 1, 1], // Team 3 - Team 1 => 1:1 [4, 0, 2, 0]] // Team 4 - Team 0 => 2:0 ``` You may compute the following table: | Rank | Team | For : Against | GD | Points | | --- | --- | --- | --- | --- | | 1. | Team 4 | 5 : 1 | +4 | 5 | | 2. | Team 5 | 6 : 4 | +2 | 4 | | 3. | Team 3 | 4 : 3 | +1 | 4 | | 4. | Team 0 | 3 : 5 | -2 | 2 | | 4. | Team 1 | 3 : 5 | -2 | 2 | | 6. | Team 2 | 2 : 5 | -3 | 1 | Team 5 and Team 3 reached the same number of points. But since Team 5 got a better scoring differential, it ranks better than Team 3. All values of Team 0 and Team 1 are the same, so these teams share the fourth place. In this example you have to return the array `[4, 4, 6, 3, 1, 2]`.
algorithms
from typing import List class GameTable: def __init__(self, number_of_teams, games): self . teams = self . __create_teams(number_of_teams) self . matches = self . __read_matches(games) self . ranks = [1] * number_of_teams def __create_teams(self, number_of_teams): teams = [] for i in range(0, number_of_teams, 1): teams . append(Team(i)) return teams def __read_matches(self, games): matches = [] for match in games: home_team = self . teams[match[0]] away_team = self . teams[match[1]] new_match = Match(home_team=home_team, away_team=away_team, goals_home_team=match[2], goals_away_team=match[3]) matches . append(new_match) return matches def play_games(self): for match in self . matches: match . play() def rank(self): self . teams . sort(key=lambda team: ( team . points, team . score_diff, team . goals_made), reverse=True) rank = 1 same_rank = False counter = 0 for i in range(len(self . teams)): current_team = self . teams[i] if same_rank == True: counter += 1 else: rank += counter counter = 0 self . ranks[current_team . number] = rank if i < len(self . teams) - 1: last_team = self . teams[i + 1] if (current_team . points == last_team . points and current_team . score_diff == last_team . score_diff and current_team . goals_made == last_team . goals_made): self . ranks[current_team . number] = rank same_rank = True continue else: same_rank = False rank += 1 return self . ranks def print_final_table(self): print("\033[1mRank\tTeam\tFor:Against\tGD\tPoints\t\033[0m") for rank, team in zip(sorted(self . ranks), self . teams): print( f" { rank } \t\t { team . name } \t\t { team . goals_made } : { team . goals_received } \t { '+' + str ( team . score_diff ) if team . score_diff > 0 else team . score_diff } \t { team . points } \t") class Match: def __init__(self, home_team, away_team, goals_home_team, goals_away_team): self . home_team = home_team self . away_team = away_team self . goals_home_team = goals_home_team self . goals_away_team = goals_away_team def play(self) - > None: diff = self . score_diff() self . home_team . goals_made += self . goals_home_team self . away_team . goals_made += self . goals_away_team self . home_team . goals_received += self . goals_away_team self . away_team . goals_received += self . goals_home_team self . home_team . score_diff += diff self . away_team . score_diff += diff * - 1 if self . goals_home_team > self . goals_away_team: self . home_team . points += 2 elif self . goals_home_team == self . goals_away_team: self . home_team . points += 1 self . away_team . points += 1 else: self . away_team . points += 2 def score_diff(self) - > int: return self . goals_home_team - self . goals_away_team def __str__(self): return f" { self . home_team } played against { self . away_team } -> { self . goals_home_team } : { self . goals_away_team } " class Team: def __init__(self, number): self . number = number self . name = f"Team { number } " self . points = 0 self . score_diff = 0 self . goals_made = 0 self . goals_received = 0 def __eq__(self, value): return self . number == value . number def __str__(self): return f" { self . name } with a score of { self . points } and diff of { self . score_diff } " def compute_ranks(number: int, games: List[List[int]]) - > List: table = GameTable(number, games) table . play_games() ranks = table . rank() table . print_final_table() return ranks if __name__ == "__main__": number = 6 games = [[0, 5, 2, 2], # Team 0 - Team 5 = > 2:2 [1, 4, 0, 2], # Team 1 - Team 4 = > 0:2 [2, 3, 1, 2], # Team 2 - Team 3 = > 1:2 [1, 5, 2, 2], # Team 1 - Team 5 = > 2:2 [2, 0, 1, 1], # Team 2 - Team 0 = > 1:1 [3, 4, 1, 1], # Team 3 - Team 4 = > 1:1 [2, 5, 0, 2], # Team 2 - Team 5 = > 0:2 [3, 1, 1, 1], # Team 3 - Team 1 = > 1:1 [4, 0, 2, 0]] # Team 4 - Team 0 = > 2:0 compute_ranks(number, games) print() compute_ranks(8, [[0, 7, 2, 0]])
Sports League Table Ranking
5e0baea9d772160032022e8c
[ "Fundamentals", "Algorithms", "Arrays", "Sorting" ]
https://www.codewars.com/kata/5e0baea9d772160032022e8c
5 kyu
You are given three piles of casino chips: white, green and black chips: * the first pile contains only white chips * the second pile contains only green chips * the third pile contains only black chips Each day you take exactly two chips of different colors and head to the casino. You can choose any color, but you are not allowed to take two chips of the same color in a day. You will be given an array representing the number of chips of each color and your task is to return the maximum number of days you can pick the chips. Each day you need to take exactly two chips. ### Examples (input -> output) ``` * [1,1,1] -> 1, because after you pick on day one, there will be only one chip left * [1,2,1] -> 2, you can pick twice; you pick two chips on day one then on day two * [4,1,1] -> 2 ``` More examples in the test cases. Good luck! Brute force is not the way to go here. Look for a simplifying mathematical approach.
reference
def solve(xs): x, y, z = sorted(xs) return min(x + y, (x + y + z) / / 2)
Casino chips
5e0b72d2d772160011133654
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5e0b72d2d772160011133654
6 kyu
At the casino you are presented with a wide array of games to play. You are there for fun, but you want to be economical about it by playing the game that maximises your profits (minimises your losses, let's be real). To do this, you will pick the game with the highest expected value (EV). If you are unfamiliar with the concept, you can read the article on [investopedia](https://www.investopedia.com/terms/e/expected-value.asp). You will get a `tuple` containing instances of `namedtuple` `Game`. Each instance of `Game` has a field `name` and `outcomes`. `name` is just the name of the game represented as a string. `outcomes` is a `tuple` of `tuples` where each inner `tuple` represents a single possible outcome. Example `Game` instance: ``` g1 = Game("Breakeven Steven", ((0.5, 20), (0.5, -20))) ``` For each outcome (inner tuple), the first value represent the probability of occurrence while the second value represent the reward. In the above example there is a 50% chance of winning 20, and 50% chance of losing 20. The function which you will construct should return the name of the game with the highest expected value of playing. Constraints: 2 <= N <= 20 Notes: - Each input has one clear winner. - Namedtuple Game has been preloaded. Game namedtuple: ```python Game = namedtuple("Game", ["name", "outcomes"]) ``` Example with explanation: ```python g1 = Game("Breakeven Steven", ((0.5, 20), (0.5, -20))) g2 = Game("Go big or go home", ((0.99, -10), (0.01, 980))) find_best_game((g1, g2)) # => "Breakeven Steven" ``` `Breakeven Steven` has a higher EV than `Go big or go home` (`0` vs `-0.1`) and therefore the function should return that name.
reference
def find_best_game(games): return max(games, key=lambda g: sum(p * v for p, v in g . outcomes)). name
Picking the best casino game
5dfd129673aa2c002591f65d
[ "Probability", "Mathematics", "Fundamentals", "Data Science", "Statistics" ]
https://www.codewars.com/kata/5dfd129673aa2c002591f65d
7 kyu
In this kata, you will be given a string of text and valid parentheses, such as `"h(el)lo"`. You must return the string, with only the text inside parentheses reversed, so `"h(el)lo"` becomes `"h(le)lo"`. However, if said parenthesized text contains parenthesized text itself, then that too must reversed back, so it faces the original direction. When parentheses are reversed, they should switch directions, so they remain syntactically correct (i.e. `"h((el)l)o"` becomes `"h(l(el))o"`). This pattern should repeat for however many layers of parentheses. There may be multiple groups of parentheses at any level (i.e. `"(1) (2 (3) (4))"`), so be sure to account for these. For example: ```javascript reverseInParens("h(el)lo") == "h(le)lo"; reverseInParens("a ((d e) c b)") == "a (b c (d e))"; reverseInParens("one (two (three) four)") == "one (ruof (three) owt)"; reverseInParens("one (ruof ((rht)ee) owt)") == "one (two ((thr)ee) four)"; ``` Input parentheses will always be valid (i.e. you will never get `"(()"`). Blank string will also be considered as valid, and should return blank string.
reference
def reverse_in_parentheses(s): stack = [] for i in s: stack . append(i) if i == ')': opening = len(stack) - stack[:: - 1]. index('(') - 1 stack . append('' . join( [i[:: - 1]. translate(str . maketrans('()', ')(')) for i in stack[opening:][:: - 1]])) del stack[opening: - 1] return '' . join(stack)
Reverse Inside Parentheses (Inside Parentheses)
5e07b5c55654a900230f0229
[ "Strings", "Fundamentals", "Recursion", "Parsing" ]
https://www.codewars.com/kata/5e07b5c55654a900230f0229
5 kyu
Consider a sequence, which is formed by the following rule: next term is taken as the smallest possible non-negative integer, which is not yet in the sequence, so that no 3 terms of sequence form an arithmetic progression. ## Example `f(0) = 0` -- smallest non-negative `f(1) = 1` -- smallest non-negative, which is not yet in the sequence `f(2) = 3` -- since `0, 1, 2` form an arithmetic progression `f(3) = 4` -- neither of `0, 1, 4`, `0, 3, 4`, `1, 3, 4` form an arithmetic progression, so we can take smallest non-negative, which is larger than `3` `f(4) = 9` -- `5, 6, 7, 8` are not good, since `1, 3, 5`, `0, 3, 6`, `1, 4, 7`, `0, 4, 8` are all valid arithmetic progressions. etc... ## The task Write a function `f(n)`, which returns the `n-th` member of sequence. ## Limitations There are `1000` random tests with `0 <= n <= 10^9`, so you should consider algorithmic complexity of your solution.
algorithms
def sequence(n): return int(format(n, 'b'), 3)
No arithmetic progressions
5e0607115654a900140b3ce3
[ "Algorithms" ]
https://www.codewars.com/kata/5e0607115654a900140b3ce3
6 kyu
Given two integers `a` and `x`, return the minimum non-negative number to **add to** / **subtract from** `a` to make it a multiple of `x`. ```prolog minimum(9, 8, Result) % Result = 1 % 9-1 = 8 which is a multiple of 4 ``` ```javascript minimum(10, 6) //= 2 10+2 = 12 which is a multiple of 6 ``` ```python minimum(10, 6) #= 2 10+2 = 12 which is a multiple of 6 ``` ## Note - 0 is always a multiple of `x` ## Constraints **1 <= a <= 10<sup>6</sup>** **1 <= x <= 10<sup>5</sup>**
reference
def minimum(a, x): return min(a % x, - a % x)
Minimum to multiple
5e030f77cec18900322c535d
[ "Fundamentals" ]
https://www.codewars.com/kata/5e030f77cec18900322c535d
7 kyu
A parity bit, or check bit, is a bit added to a string of bits to ensure that the total number of 1-bits in the string is even or odd. Parity bits are used as the simplest form of error detecting code. You have two parameters, one being the wanted parity (always 'even' or 'odd'), and the other being the binary representation of the number you want to check. Your task is to return an integer (`0` or `1`), whose parity bit you need to add to the binary representation so that the parity of the resulting string is as expected. Example: ``` Parity: 'even' Bin: '0101010' Result: 1 ``` Because there is an odd number of 1-bits (3) you need to put another `1` to it to get an even number of 1-bits. For more information: https://en.wikipedia.org/wiki/Parity_bit
reference
def check_parity(parity, bin_str): return [0, 1][bin_str . count("1") % 2 == (parity == "even")]
Calculate Parity bit!
5df261342964c80028345a0a
[ "Fundamentals" ]
https://www.codewars.com/kata/5df261342964c80028345a0a
7 kyu
You've decided to try to create a test framework that allows for easy testing of [Pathfinder Ability Score](https://www.d20pfsrd.com/basics-ability-scores/ability-scores/) arrays, and their validity, using 25 points. You will write a function that takes an array of 6 scores (integers) and will return a boolean if they add up in 25 points or less. Each score will be in range 1 <= x <= 20. You must comply with the table below, and values where x < 7 and x > 18 should return False. Each score costs a certain amount of points. For example, a score of 16 costs 10 points, but a score of 7 would give 4 back. ![score table](https://db4sgowjqfwig.cloudfront.net/campaigns/145740/assets/635596/abilityScoreCosts.png?1472672582) Python: ```python def pathfinder_scores(scores): ``` Examples: ```python pathfinder_scores([18, 13, 7, 12, 15, 10]) => True (Cost 25) pathfinder_scores([13, 12, 14, 12, 15, 11]) => True (Cost 20) pathfinder_scores([6, 19, 10, 10, 10, 10]) => False (Scores >18 and <7) ```
algorithms
def pathfinder_scores(scores): pathpoints = {'7': - 4, '8': - 2, '9': - 1, '10': 0, '11': 1, '12': 2, '13': 3, '14': 5, '15': 7, '16': 10, '17': 13, '18': 17} points = [] for x in scores: if str(x) in pathpoints: points . append(pathpoints . get(str(x))) elif str(x) not in pathpoints: return False print(sum(points)) if sum(points) > 25: return False return True
Pathfinder Ability Scores Calculator
5df0041acec189002d06101f
[ "Algorithms" ]
https://www.codewars.com/kata/5df0041acec189002d06101f
7 kyu
I'm afraid you're in a rather unfortunate situation. You've injured your leg, and are unable to walk, and a number of zombies are shuffling towards you, intent on eating your brains. Luckily, you're a crack shot, and have your trusty rifle to hand. The zombies start at `range` metres, and move at `0.5` metres per second. Each second, you first shoot one zombie, and then the remaining zombies shamble forwards another `0.5` metres. If any zombies manage to get to `0` metres, you get eaten. If you run out of ammo before shooting all the zombies, you'll also get eaten. To keep things simple, we can ignore any time spent reloading. Write a function that accepts the total number of zombies, a range in metres, and the number of bullets you have. If you shoot all the zombies, return `"You shot all X zombies."` If you get eaten before killing all the zombies, and before running out of ammo, return `"You shot X zombies before being eaten: overwhelmed."` If you run out of ammo before shooting all the zombies, return `"You shot X zombies before being eaten: ran out of ammo."` (If you run out of ammo at the same time as the remaining zombies reach you, return `"You shot X zombies before being eaten: overwhelmed."`.) Good luck! (I think you're going to need it.)
reference
def zombie_shootout(z, r, a): s = min(r * 2, a) return f"You shot all { z } zombies." if s >= z else f"You shot { s } zombies before being eaten: { 'overwhelmed' if s == 2 * r else 'ran out of ammo' } ."
Will you survive the zombie onslaught?
5deeb1cc0d5bc9000f70aa74
[ "Games", "Fundamentals" ]
https://www.codewars.com/kata/5deeb1cc0d5bc9000f70aa74
7 kyu
In this Kata, you will be given a string and your task is to return the most valuable character. The value of a character is the difference between the index of its last occurrence and the index of its first occurrence. Return the character that has the highest value. If there is a tie, return the alphabetically lowest character. `[For Golang return rune]` All inputs will be lower case. ``` For example: solve('a') = 'a' solve('ab') = 'a'. Last occurrence is equal to first occurrence of each character. Return lexicographically lowest. solve("axyzxyz") = 'x' ``` More examples in test cases. Good luck!
reference
def solve(st): return min(set(st), key=lambda c: (st . index(c) - st . rindex(c), c))
Most valuable character
5dd5128f16eced000e4c42ba
[ "Fundamentals" ]
https://www.codewars.com/kata/5dd5128f16eced000e4c42ba
7 kyu
Given the sum and gcd of two numbers, return those two numbers in ascending order. If the numbers do not exist, return `-1`, (or `NULL` in C, `tuple (-1,-1)` in C#, `pair (-1,-1)` in C++,`None` in Rust, `array {-1,-1} ` in Java and Golang). ``` For example: Given sum = 12 and gcd = 4... solve(12,4) = [4,8]. The two numbers 4 and 8 sum to 12 and have a gcd of 4. solve(12,5) = -1. No two numbers exist that sum to 12 and have gcd of 5. solve(10,2) = [2,8]. Note that [4,6] is also a possibility but we pick the one with the lower first element: 2 < 4, so we take [2,8]. ``` More examples in test cases. Good luck!
reference
def solve(s, g): return - 1 if s % g else (g, s - g)
GCD sum
5dd259444228280032b1ed2a
[ "Fundamentals" ]
https://www.codewars.com/kata/5dd259444228280032b1ed2a
7 kyu
# Fun fact Tetris was the first video game played in outer space In 1993, Russian cosmonaut Aleksandr A. Serebrov spent 196 days on the Mir space station with a very special distraction: a gray Game Boy loaded with Tetris. During that time the game orbited the Earth 3,000 times and became the first video game played in space. The Game Boy was sold in a Bonhams auction for $1,220 during the Space History Sale in 2011. # Task Parse the game log and determine how many lines have been cleared through the game. The game ends if all commands from input were interpreted or the maximum field height (30 units) is reached. A horizontal line, according to the rules of classic Tetris, is considered cleared if it represents a solid line without gaps formed by falling blocks. When such a line is formed, it disappears and any blocks above it fall down to fill the space. # Input ```python ['4L2', '3R4', '4L3', '3L4', '4R0', '1L2'] # example ``` As an argument, you are given gamelog - an array of commands which you need to interpret. Each command has the same form: * The first character - the type of block (integer from 1 to 4, as in this kata we have only 4 types of blocks). Block types are described below. * The second - the direction of movement (`"R"` or `"L"` - right or left). * The third is an offset (integer from 0 to 4, as width of our field 9 units and new block always appears at the center of the field) relative to the starting position. Thus, `L4` means the leftmost position, and `R4` the rightmost, and `L0` is equivalent to `R0`. # Output The total number of cleaned horizontal lines (`int`) to the end of the game. Note, if the field height is exceeded, then the game ends immediately. # Blocks In this kata we have only 4 types of blocks. Yes, this is not a classic set of shapes, but this is only for simplicity. ``` # and their graphical representation: ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ---+---+---+--- #1 #2 #3 #4 ``` # Field Gamefield (a rectangular vertical shaft) has width 9 units and height 30 units. <style> table, th, td { border: 1px solid; } </style> Indices can be represented as: <table style="width: 60%"> <tr> <td>L4</td> <td>L3</td> <td>L2</td> <td>L1</td> <td>L0/R0</td> <td>R1</td> <td>R2</td> <td>R3</td> <td>R4</td> </tr> </table> # Example 1 ```python >>> gamelog = ['1R4', '2L3', '3L2', '4L1', '1L0', '2R1', '3R2', '4R3', '1L4'] >>> tetris(gamelog) 1 ``` Gamefield before last command (_ means empty space): ``` ___■___■_ __■■__■■_ _■■■_■■■_ _■■■■■■■■ ``` Gamefield after all commands: ``` ___■___■_ __■■__■■_ _■■■_■■■_ ``` As you can see, one solid line was cleared. So, answer is 1. # Example 2 ```python >>> gamelog = ['1L2', '4R2', '3L3', '3L1', '1L4', '1R4'] >>> tetris(gamelog) 0 ``` Gamefield after all commands: ``` _____■__ _■_■__■__ _■_■__■__ ■■■■__■_■ ``` As you can see, there is no solid lines, so nothing to clear. Our answer is 0, zero cleaned lines. # Note Since there is no rotation of blocks in our model and all blocks are very simple, do not overthink the task. # Other If you like the idea: leave feedback, and there will be more katas in the Tetris series. * <div class="item-title"><div class="small-hex is-extra-wide is-inline mrm is-white-rank" border="false"><div class="inner-small-hex is-extra-wide "><span>7 kyu</span></div></div><a href="/kata/5da9af1142d7910001815d32">Tetris Series #1 — Scoring System</a></div> * <div class="item-title"><div class="small-hex is-extra-wide is-inline mrm is-yellow-rank" border="false"><div class="inner-small-hex is-extra-wide "><span>6 kyu</span></div></div><a href="/kata/5db8a241b8d7260011746407">Tetris Series #2 — Primitive Gameplay</a></div> * <div class="item-title"><div class="small-hex is-extra-wide is-inline mrm is-yellow-rank" border="false"><div class="inner-small-hex is-extra-wide "><span>6 kyu</span></div></div>Tetris Series #3 — Adding Rotation (TBA)</div> * <div class="item-title"><div class="small-hex is-extra-wide is-inline mrm is-yellow-rank" border="false"><div class="inner-small-hex is-extra-wide "><span>5 kyu</span></div></div>Tetris Series #4 — New Block Types (TBA)</div> * <div class="item-title"><div class="small-hex is-extra-wide is-inline mrm is-blue-rank" border="false"><div class="inner-small-hex is-extra-wide "><span>4 kyu</span></div></div>Tetris Series #5 — Complex Block Types (TBA?)</div>
reference
class Game (): def __init__(self, arr): self . comands = arr self . score = 0 self . step = None self . fild = [- 1] * 9 self . over = lambda x: max(x) >= 29 def __break__(self): while - 1 not in self . fild: self . score += 1 self . fild = [e - 1 for e in self . fild] return self . over(self . fild) def __values__(self, comand): self . step = 4 + {'R': lambda m: + int(m), 'L': lambda m: - int(m)}[comand[1]](comand[2]) return int(comand[0]) def game(self): for comand in self . comands: block = self . __values__(comand) self . fild[self . step] += block if self . __break__(): break return self . score def tetris(arr) - > int: play = Game(arr) return play . game()
Tetris Series #2 — Primitive Gameplay
5db8a241b8d7260011746407
[ "Fundamentals", "Games", "Algorithms", "Arrays", "Logic" ]
https://www.codewars.com/kata/5db8a241b8d7260011746407
6 kyu
In this kata, you need to make a (simplified) LZ78 encoder and decoder. [LZ78](https://en.wikipedia.org/wiki/LZ77_and_LZ78#LZ78) is a dictionary-based compression method created in 1978. You will find a detailed explanation about how it works below. The input parameter will always be a non-empty string of upper case alphabetical characters. The maximum decoded string length is 1000 characters. # Instructions *If anyone has any ideas on how to make the instructions shorter / clearer, that would be greatly appreciated.* If the below explanation is too confusing, just leave a comment and I'll be happy to help. --- The input is looked at letter by letter. Each letter wants to be matched with the longest dictionary substring at that current time. The output is made up of tokens. Each token is in the format `<index, letter>` where `index` is the index of the longest dictionary value that matches the current substring and `letter` is the current letter being looked at. Here is how the string `'ABAABABAABAB'` is encoded: * First, a dictionary is initialised with the 0th item pointing to an empty string: ```md Dictionary Input Output 0 | '' ABAABABAABAB ``` * The first letter is `A`. As it doesn't appear in the dictionary, we add `A` to the next avaliable index. The token `<0, A>` is added to the output: ```md Dictionary Input Output 0 | '' ABAABABAABAB <0, A> 1 | A ^ ``` * The second letter is `B`. It doesn't appear in the dictionary, so we add `B` to the next avaliable index. The token `<0, B>` is added to the output: ```md Dictionary Input Output 0 | '' ABAABABAABAB <0, A> <0, B> 1 | A ^ 2 | B ``` * The third letter is `A` again: it already appears in the dictionary at position `1`. We add the next letter which is also `A`. `AA` doesn't appear in the dictionary, so we add it to the next avaliable index. The token `<1, A>` is added to the output: ```md Dictionary Input Output 0 | '' ABAABABAABAB <0, A> <0, B> <1, A> 1 | A ^^ 2 | B 3 | AA ``` * The next letter is `B` again: it already appears in the dictionary at position `2`. We add the next letter which is `A`. `BA` doesn't appear in the dictionary, so we add it to the next avaliable index. The token `<2, A>` is added to the output: ```md Dictionary Input Output 0 | '' ABAABABAABAB <0, A> <0, B> <1, A> <2, A> 1 | A ^^ 2 | B 3 | AA 4 | BA ``` * The next letter is `B`: it already appears in the dictionary and at position `2`. We add the next letter which is `A`. `BA` already appears in the dictionary at position `4`. We add the next letter which is `A`. `BAA` doesn't appear in the dictionary, so we add it to the next avaliable index. The token `<4, A>` is added to the output: ```md Dictionary Input Output 0 | '' ABAABABAABAB <0, A> <0, B> <1, A> <2, A> <4, A> 1 | A ^^^ 2 | B 3 | AA 4 | BA 5 | BAA ``` * The next letter is `B`. It already appears in the dictionary at position `2`. We add the next letter which is `A`. `BA` already appears in the dictionary at position `4`. We add the next letter which is `B`. `BAB` doesn't appear in the dictionary, so we add it to the next avaliable index. The token `<4, B>` is added to the output: ```md Dictionary Input Output 0 | '' ABAABABAABAB <0, A> <0, B> <1, A> <2, A> <4, A> <4, B> 1 | A ^^^ 2 | B 3 | AA 4 | BA 5 | BAA 6 | BAB ``` * We have now reached the end of the string. We have the output tokens: `<0, A> <0, B> <1, A> <2, A> <4, A> <4, B>`. Now we just return the tokens without the formatting: `'0A0B1A2A4A4B'` **Note:** If the string ends with a match in the dictionary, the last token should only contain the index of the dictionary. For example, `'ABAABABAABABAA'` (same as the example but with `'AA'` at the end) should return `'0A0B1A2A4A4B3'` (note the final `3`). To decode, it just works the other way around. # Examples Some more examples: ``` Decoded Encoded ABBCBCABABCAABCAABBCAA 0A0B2C3A2A4A6B6 AAAAAAAAAAAAAAA 0A1A2A3A4A ABCABCABCABCABCABC 0A0B0C1B3A2C4C7A6 ABCDDEFGABCDEDBBDEAAEDAEDCDABC 0A0B0C0D4E0F0G1B3D0E4B2D10A1E4A10D9A2C ``` Good luck :)
algorithms
import re def encoder(s): d, out, it = {}, [], iter(s) for c in it: i, k = 0, c while k in d: i, c = d[k], next(it, '') if not c: break k += c d[k] = len(d) + 1 out . append(f' { i }{ c } ') return '' . join(out) def decoder(s): d = [''] for m in re . finditer(r'(\d+)(\D?)', s): d . append(d[int(m[1])] + m[2]) return '' . join(d)
LZ78 compression
5db42a943c3c65001dcedb1a
[ "Algorithms" ]
https://www.codewars.com/kata/5db42a943c3c65001dcedb1a
5 kyu