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
In this kata, your task is to implement what I call **Iterative Rotation Cipher (IRC)**. To complete the task, you will create an object with two methods, `encode` and `decode`. (For non-JavaScript versions, you only need to write the two functions without the enclosing dict) <h2 style='color:#f66'>Input</h2> <p>The <code>encode</code> method will receive two arguments β€” a positive integer <code>n</code> and a string value.</p> <p>The <code>decode</code> method will receive one argument β€” a string value.</p> <h2 style='color:#f66'>Output</h2> <p>Each method will return a string value.</p> <h2 style='color:#f66'>How It Works</h2> <p>Encoding and decoding are done by performing a series of character and substring rotations on a string input.</p> <p><strong style='color:#95c4ffff'>Encoding:</strong> The number of rotations is determined by the value of <code>n</code>. The sequence of rotations is applied in the following order:<br/>  Step 1: remove all spaces in the string (but remember their positions)<br/>  Step 2: shift the order of characters in the new string to the right by <code>n</code> characters<br/>  Step 3: put the spaces back in their original positions<br/>  Step 4: shift the characters of each substring (separated by one or more consecutive spaces) to the right by <code>n</code><br/> </p> <p>Repeat this process until it has been completed <code>n</code> times in total.<br/> The value <code>n</code> is then prepended to the resulting string with a space.</p> <p><strong style='color:#95c4ffff'>Decoding:</strong> Decoding simply reverses the encoding process.</p> <h2 style='color:#f66'>Test Example</h2> ```javascript let quote = `If you wish to make an apple pie from scratch, you must first invent the universe.`; let solution = `10 hu fmo a,ys vi utie mr snehn rni tvte .ysushou teI fwea pmapi apfrok rei tnocsclet`; IterativeRotationCipher.encode(10,quote) === solution; //true /* Step-by-step breakdown: Step 1 β€” remove all spaces: `Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventtheuniverse.` Step 2 β€” shift the order of string characters to the right by 10: `euniverse.Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventth` Step 3 β€” place the spaces back in their original positions: `eu niv erse .I fyou wi shtom ake anap plepiefr oms crat ch,yo umustf irs tinventth` Step 4 β€” shift the order of characters for each space-separated substring to the right by 10: `eu vni seer .I oufy wi shtom eak apan frplepie som atcr ch,yo ustfum sir htinventt` Repeat the steps 9 more times before returning the string with `10 ` prepended. */ ``` ```haskell quote = "If you wish to make an apple pie from scratch, you must first invent the universe." solution = "10 hu fmo a,ys vi utie mr snehn rni tvte .ysushou teI fwea pmapi apfrok rei tnocsclet" IterativeRotationCipher.encode(10,quote) == solution -- True {- Step-by-step breakdown: Step 1 β€” remove all spaces: "Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventtheuniverse." Step 2 β€” shift the order of string characters to the right by 10: "euniverse.Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventth" Step 3 β€” place the spaces back in their original positions: "eu niv erse .I fyou wi shtom ake anap plepiefr oms crat ch,yo umustf irs tinventth" Step 4 β€” shift the order of characters for each space-separated substring to the right by 10: "eu vni seer .I oufy wi shtom eak apan frplepie som atcr ch,yo ustfum sir htinventt" Repeat the steps 9 more times before returning the string with "10 " prepended. -} ``` ```python quote = 'If you wish to make an apple pie from scratch, you must first invent the universe.' solution = '10 hu fmo a,ys vi utie mr snehn rni tvte .ysushou teI fwea pmapi apfrok rei tnocsclet' IterativeRotationCipher['encode'](10,quote) == solution #True '''Step-by-step breakdown: Step 1 β€” remove all spaces: 'Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventtheuniverse.' Step 2 β€” shift the order of string characters to the right by 10: 'euniverse.Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventth' Step 3 β€” place the spaces back in their original positions: 'eu niv erse .I fyou wi shtom ake anap plepiefr oms crat ch,yo umustf irs tinventth' Step 4 β€” shift the order of characters for each space-separated substring to the right by 10: 'eu vni seer .I oufy wi shtom eak apan frplepie som atcr ch,yo ustfum sir htinventt' Repeat the steps 9 more times before returning the string with '10 ' prepended. ''' ``` ```ruby quote = 'If you wish to make an apple pie from scratch, you must first invent the universe.' solution = '10 hu fmo a,ys vi utie mr snehn rni tvte .ysushou teI fwea pmapi apfrok rei tnocsclet' encode(10,quote) == solution # true Step 1 β€” remove all spaces: 'Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventtheuniverse.' Step 2 β€” shift the order of string characters to the right by 10: 'euniverse.Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventth' Step 3 β€” place the spaces back in their original positions: 'eu niv erse .I fyou wi shtom ake anap plepiefr oms crat ch,yo umustf irs tinventth' Step 4 β€” shift the order of characters for each space-separated substring to the right by 10: 'eu vni seer .I oufy wi shtom eak apan frplepie som atcr ch,yo ustfum sir htinventt' Repeat the steps 9 more times before returning the string with '10 ' prepended. ``` ```go quote := `If you wish to make an apple pie from scratch, you must first invent the universe.`; solution := `10 hu fmo a,ys vi utie mr snehn rni tvte .ysushou teI fwea pmapi apfrok rei tnocsclet`; IterativeRotationCipher.encode(10,quote) == solution; //true /* Step-by-step breakdown: Step 1 β€” remove all spaces: `Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventtheuniverse.` Step 2 β€” shift the order of string characters to the right by 10: `euniverse.Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventth` Step 3 β€” place the spaces back in their original positions: `eu niv erse .I fyou wi shtom ake anap plepiefr oms crat ch,yo umustf irs tinventth` Step 4 β€” shift the order of characters for each space-separated substring to the right by 10: `eu vni seer .I oufy wi shtom eak apan frplepie som atcr ch,yo ustfum sir htinventt` Repeat the steps 9 more times before returning the string with `10 ` prepended. */ ``` ```elixir phrase = "If you wish to make an apple pie from scratch, you must first invent the universe." solution = "10 hu fmo a,ys vi utie mr snehn rni tvte .ysushou teI fwea pmapi apfrok rei tnocsclet" IterativeRotationCipher.encode(10,phrase) == solution ##true # Step-by-step breakdown: # Step 1 β€” remove all spaces: # "Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventtheuniverse." # Step 2 β€” shift the order of string characters to the right by 10: # "euniverse.Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventth" # Step 3 β€” place the spaces back in their original positions: # "eu niv erse .I fyou wi shtom ake anap plepiefr oms crat ch,yo umustf irs tinventth" # Step 4 β€” shift the order of characters for each space-separated substring to the right by 10: # "eu vni seer .I oufy wi shtom eak apan frplepie som atcr ch,yo ustfum sir htinventt" # Repeat the steps 9 more times before returning the string with "10 " prepended. ``` ```csharp string phrase = "If you wish to make an apple pie from scratch, you must first invent the universe."; string solution = "10 hu fmo a,ys vi utie mr snehn rni tvte .ysushou teI fwea pmapi apfrok rei tnocsclet"; IterativeRotationCipher.Encode(10,phrase) == solution // true /* Step-by-step breakdown: Step 1 β€” remove all spaces: "Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventtheuniverse." Step 2 β€” shift the order of string characters to the right by 10: "euniverse.Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventth" Step 3 β€” place the spaces back in their original positions: "eu niv erse .I fyou wi shtom ake anap plepiefr oms crat ch,yo umustf irs tinventth" Step 4 β€” shift the order of characters for each space-separated substring to the right by 10: "eu vni seer .I oufy wi shtom eak apan frplepie som atcr ch,yo ustfum sir htinventt" Repeat the steps 9 more times before returning the string with "10 " prepended. */ ``` ```kotlin val phrase = "If you wish to make an apple pie from scratch, you must first invent the universe." val solution = "10 hu fmo a,ys vi utie mr snehn rni tvte .ysushou teI fwea pmapi apfrok rei tnocsclet" IterativeRotationCipher.encode(10,phrase) == solution // true /* Step-by-step breakdown: Step 1 β€” remove all spaces: "Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventtheuniverse." Step 2 β€” shift the order of string characters to the right by 10: "euniverse.Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventth" Step 3 β€” place the spaces back in their original positions: "eu niv erse .I fyou wi shtom ake anap plepiefr oms crat ch,yo umustf irs tinventth" Step 4 β€” shift the order of characters for each space-separated substring to the right by 10: "eu vni seer .I oufy wi shtom eak apan frplepie som atcr ch,yo ustfum sir htinventt" Repeat the steps 9 more times before returning the string with "10 " prepended. */ ``` ```rust let phrase = "If you wish to make an apple pie from scratch, you must first invent the universe."; let solution = "10 hu fmo a,ys vi utie mr snehn rni tvte .ysushou teI fwea pmapi apfrok rei tnocsclet"; &irc::encode(10,phrase) == solution // true /* Step-by-step breakdown: Step 1 β€” remove all spaces: "Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventtheuniverse." Step 2 β€” shift the order of string characters to the right by 10: "euniverse.Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventth" Step 3 β€” place the spaces back in their original positions: "eu niv erse .I fyou wi shtom ake anap plepiefr oms crat ch,yo umustf irs tinventth" Step 4 β€” shift the order of characters for each space-separated substring to the right by 10: "eu vni seer .I oufy wi shtom eak apan frplepie som atcr ch,yo ustfum sir htinventt" Repeat the steps 9 more times before returning the string with "10 " prepended. */ ``` <h2 style='color:#f66'>Technical Details</h2> - Input will always be valid. - The characters used in the strings include any combination of alphanumeric characters, the space character, the newline character, and any of the following: `_!@#$%^&()[]{}+-*/="'<>,.?:;`. If you enjoyed this kata, be sure to check out [my other katas](https://www.codewars.com/users/docgunthrop/authored).
algorithms
def shift(string, step): i = (step % len(string)) if string else 0 return f" { string [ - i :]}{ string [: - i ]} " def encode(n, string): for _ in range(n): shifted = shift(string . replace(" ", ""), n) l = [len(word) for word in string . split(" ")] string = " " . join( shift(shifted[sum(l[: i]): sum(l[: i + 1])], n) for i in range(len(l))) return f" { n } { string } " def decode(string): n, string = int(string . partition(" ")[0]), string . partition(" ")[2] for _ in range(n): shifted = shift("" . join(shift(word, - n) for word in string . split(" ")), - n) l = [len(word) for word in string . split(" ")] string = " " . join(shifted[sum(l[: i]): sum(l[: i + 1])] for i in range(len(l))) return string
Iterative Rotation Cipher
5a3357ae8058425bde002674
[ "Strings", "Ciphers", "Algorithms" ]
https://www.codewars.com/kata/5a3357ae8058425bde002674
5 kyu
![Reference Image](https://i.imgur.com/OLFUBvV.png) In this kata, your task is to implement what I call **Interlaced Spiral Cipher (ISC)**. *Encoding* a string using ISC is achieved with the following steps: 1. Form a square large enough to fit all the string characters 2. Starting with the top-left corner, place string characters in the corner cells moving in a clockwise direction 3. After the first cycle is complete, continue placing characters in the cells following the last one in its respective row/column 4. When the outer cells are filled, repeat steps `2` through `4` for the remaining inner squares (refer to the example below for further clarification) 5. Fill up any unused cells with a space character and return the rows joined together. ## Input A string comprised of any combination of alphabetic characters, the space character, and any of the following characters `_!@#$%^&()[]{}+-*/="'<>,.?:;`. Arguments passed to the `encode` method will never have any trailing spaces. ## Output The `encode` method should return the encoded message as a `string` The `decode` method should return the decoded message as a `string` with no trailing spaces ## Test Examples ```javascript let phrase1 = `Romani ite domum`; InterlacedSpiralCipher.encode(phrase1); // `Rntodomiimuea m` let phrase2 = `Stsgiriuar i ninmd l otac`; InterlacedSpiralCipher.decode(phrase2); // `Sic transit gloria mundi` /* Encoding sequence for a 5 x 5 square: [ 1 5 9 13 2] [16 17 21 18 6] [12 24 25 22 10] [ 8 20 23 19 14] [ 4 15 11 7 3] */ ``` ```python phrase1 = 'Romani ite domum' InterlacedSpiralCipher['encode'](phrase1) #'Rntodomiimuea m' phrase2 = 'Stsgiriuar i ninmd l otac' InterlacedSpiralCipher['decode'](phrase2) #'Sic transit gloria mundi' ''' Encoding sequence for a 5 x 5 square: [ 1 5 9 13 2] [16 17 21 18 6] [12 24 25 22 10] [ 8 20 23 19 14] [ 4 15 11 7 3] ''' ``` ```go phrase1 := "Romani ite domum" InterlacedSpiralCipher["encode"](phrase1) // "Rntodomiimuea m" phrase2 := "Stsgiriuar i ninmd l otac" InterlacedSpiralCipher["decode"](phrase2) // "Sic transit gloria mundi" /* Encoding sequence for a 5 x 5 square: [ 1 5 9 13 2] [16 17 21 18 6] [12 24 25 22 10] [ 8 20 23 19 14] [ 4 15 11 7 3] */ ``` ```elixir phrase1 = "Romani ite domum" InterlacedSpiralCipher.encode(phrase1) # "Rntodomiimuea m" phrase2 = "Stsgiriuar i ninmd l otac" InterlacedSpiralCipher.decode(phrase2) # "Sic transit gloria mundi" # Encoding sequence for a 5 x 5 square: # [ 1 5 9 13 2] # [16 17 21 18 6] # [12 24 25 22 10] # [ 8 20 23 19 14] # [ 4 15 11 7 3] ``` ```csharp string phrase1 = "Romani ite domum"; InterlacedSpiralCipher.Encode(phrase1) // "Rntodomiimuea m" string phrase2 = "Stsgiriuar i ninmd l otac"; InterlacedSpiralCipher.Decode(phrase2) // "Sic transit gloria mundi" /* Encoding sequence for a 5 x 5 square: [ 1 5 9 13 2] [16 17 21 18 6] [12 24 25 22 10] [ 8 20 23 19 14] [ 4 15 11 7 3] */ ``` ```kotlin val phrase1 = "Romani ite domum"; InterlacedSpiralCipher.encode(phrase1) // "Rntodomiimuea m" val phrase2 = "Stsgiriuar i ninmd l otac"; InterlacedSpiralCipher.decode(phrase2) // "Sic transit gloria mundi" /* Encoding sequence for a 5 x 5 square: [ 1 5 9 13 2] [16 17 21 18 6] [12 24 25 22 10] [ 8 20 23 19 14] [ 4 15 11 7 3] */ ``` ```rust let phrase1 = "Romani ite domum"; isc::encode(phrase1) // "Rntodomiimuea m" let phrase2 = "Stsgiriuar i ninmd l otac"; isc::decode(phrase2) // "Sic transit gloria mundi" /* Encoding sequence for a 5 x 5 square: [ 1 5 9 13 2] [16 17 21 18 6] [12 24 25 22 10] [ 8 20 23 19 14] [ 4 15 11 7 3] */ ``` ## Technical Details - Input will always be valid. If you enjoyed this kata, be sure to check out [my other katas](https://www.codewars.com/users/docgunthrop/authored).
algorithms
def interlaced_spiral(s): n = int((s - 1) * * .5) + 1 for x, r in enumerate(range(n, 0, - 2)): for y in range(x, x + r - (r > 1)): for _ in range(4): yield x * n + y if r == 1: return x, y = y, n - x - 1 def encode(s): table = {j: i for i, j in enumerate(interlaced_spiral(len(s)))} return '' . join(s[i] if i < len(s) else ' ' for i in map(table . get, range(len(table)))) def decode(s): return '' . join(s[i] for i in interlaced_spiral(len(s))). rstrip()
Interlaced Spiral Cipher
5a24a35a837545ab04001614
[ "Ciphers", "Strings", "Algorithms" ]
https://www.codewars.com/kata/5a24a35a837545ab04001614
5 kyu
The prime `149` has 3 permutations which are also primes: `419`, `491` and `941`. There are 3 primes below `1000` with three prime permutations: ```python 149 ==> 419 ==> 491 ==> 941 179 ==> 197 ==> 719 ==> 971 379 ==> 397 ==> 739 ==> 937 ``` ```javascript 149 ==> 419 ==> 491 ==> 941 179 ==> 197 ==> 719 ==> 971 379 ==> 397 ==> 739 ==> 937 ``` But there are 9 primes below `1000` with two prime permutations: ```python 113 ==> 131 ==> 311 137 ==> 173 ==> 317 157 ==> 571 ==> 751 163 ==> 613 ==> 631 167 ==> 617 ==> 761 199 ==> 919 ==> 991 337 ==> 373 ==> 733 359 ==> 593 ==> 953 389 ==> 839 ==> 983 ``` ```javascript 113 ==> 131 ==> 311 137 ==> 173 ==> 317 157 ==> 571 ==> 751 163 ==> 613 ==> 631 167 ==> 617 ==> 761 199 ==> 919 ==> 991 337 ==> 373 ==> 733 359 ==> 593 ==> 953 389 ==> 839 ==> 983 ``` Finally, we can find 34 primes below `1000` with only one prime permutation: ```python [13, 17, 37, 79, 107, 127, 139, 181, 191, 239, 241, 251, 277, 281, 283, 313, 347, 349, 367, 457, 461, 463, 467, 479, 563, 569, 577, 587, 619, 683, 709, 769, 787, 797] ``` ```javascript [13, 17, 37, 79, 107, 127, 139, 181, 191, 239, 241, 251, 277, 281, 283, 313, 347, 349, 367, 457, 461, 463, 467, 479, 563, 569, 577, 587, 619, 683, 709, 769, 787, 797] ``` Each set of permuted primes are represented by its smallest value, for example the set `149, 419, 491, 941` is represented by `149`, and the set has 3 permutations. **Notes** * the original number (`149` in the above example) is **not** counted as a permutation; * permutations with leading zeros are **not valid** ## Your Task Your task is to create a function that takes two arguments: * an upper limit (`n_max`) and * the number of prime permutations (`k_perms`) that the primes should generate **below** `n_max` The function should return the following three values as a list: * the number of permutational primes below the given limit, * the smallest prime such prime, * and the largest such prime If no eligible primes were found below the limit, the output should be `[0, 0, 0]` ## Examples Let's see how it would be with the previous cases: ```python permutational_primes(1000, 3) ==> [3, 149, 379] ''' 3 primes with 3 permutations below 1000, smallest: 149, largest: 379 ''' permutational_primes(1000, 2) ==> [9, 113, 389] ''' 9 primes with 2 permutations below 1000, smallest: 113, largest: 389 ''' permutational_primes(1000, 1) ==> [34, 13, 797] ''' 34 primes with 1 permutation below 1000, smallest: 13, largest: 797 ''' ``` ```javascript permutational_primes(1000, 3) ==> [3, 149, 379] // 3 primes with 3 permutations below 1000, smallest: 149, largest: 379 permutational_primes(1000, 2) ==> [9, 113, 389] // 9 primes with 2 permutations below 1000, smallest: 113, largest: 389 permutational_primes(1000, 1) ==> [34, 13, 797] // 34 primes with 1 permutation below 1000, smallest: 13, largest: 797 ``` Happy coding!!
algorithms
from collections import Counter def permutational_primes(n_max, k_perms): print(n_max, k_perms) # list of primes P = [2] + [n for n in range(2, n_max) if all(n % i != 0 for i in range(2, int(n * * (0.5)) + 2))] A = ["" . join(sorted(str(p))) for p in P] # convert e.g. 839 to 389 B = Counter(A). items() # count repetition of converted versions # only primes with wanted repetition C = [a for (a, b) in B if b == k_perms + 1] if C == []: return [0, 0, 0] # is there any? D = [P[A . index(c)] for c in C] # save first accurance in P return [len(D), D[0], D[- 1]]
Permutational Primes
55eec0ee00ae4a8fa0000075
[ "Algorithms", "Sorting", "Permutations", "Mathematics", "Memoization", "Data Structures" ]
https://www.codewars.com/kata/55eec0ee00ae4a8fa0000075
4 kyu
# Task Here are 10 ribbons. The length of each ribbon is 11 units with a unique pattern (number 0-9). Now let's put these ribbons on a 11x11 table. Every time a ribbon is placed, horizontal or vertical. The next ribbon and the last one are in different directions, and ensure that any two ribbons are not completely overlapped. # Note - All inputs are valid. - The first ribbon can be placed either horizontally or vertically. # For example: An empty 11x11 table: ``` ........... ........... ........... ........... ........... ........... ........... ........... ........... ........... ........... ``` We put a ribbon with pattern 1 on the table: ``` ........... 11111111111 ........... ........... ........... ........... ........... ........... ........... ........... ........... ``` Then, put a ribbon with pattern 2 on the table: ``` .2......... 12111111111 .2......... .2......... .2......... .2......... .2......... .2......... .2......... .2......... .2......... ``` Note that their intersection will be covered with the ribbon above. Then, continue to put other ribbons.. Finally, we get a pattern like the following: ``` 62.0.4..8.. 62101411811 62.0.4..8.. 65505555855 63303433833 62.0.4..8.. 77707777877 62.0.4..8.. 99909999999 62.0.4..8.. 62.0.4..8.. ``` Given the final pattern `ribbons`, your task is to return the order of these ribbons(from the bottom to the top). For the example above, should return `"1234567890"`. Notice that not all the ribbons will be placed on the table, but at least 1 ribbon. Still not understand the task? Look at the following example ;-) # Examples For `ribbons = ` ``` ........... 11111111111 ........... ........... ........... ........... ........... ........... ........... ........... ........... ``` the output should be `"1"`. For `ribbons = ` ``` .2......... 12111111111 .2......... .2......... .2......... .2......... .2......... .2......... .2......... .2......... .2......... ``` the output should be `"12"`. For `ribbons = ` ``` .2......... 12111111111 .2......... .2......... 33333333333 .2......... .2......... .2......... .2......... .2......... .2......... ``` the output should be `"123"`. For `ribbons = ` ``` .2...4..... 12111411111 .2...4..... .2...4..... 33333433333 .2...4..... .2...4..... .2...4..... .2...4..... .2...4..... .2...4..... ``` the output should be `"1234"`. For `ribbons = ` ``` 62.0.4..8.. 62101411811 62.0.4..8.. 65505555855 63303433833 62.0.4..8.. 77707777877 62.0.4..8.. 99909999999 62.0.4..8.. 62.0.4..8.. ``` the output should be `"1234567890"`. <br> Happy Coding `^_^`
reference
from collections import Counter def the_order_of(ribbons): def extractH(row): return next( (d for d, n in Counter(row). items() if n > 1 and d != '.'), None) horz = {d for d in map(extractH, ribbons . split('\n')) if d} cnt = Counter(filter(str . isdigit, ribbons)) tic = max(cnt . items(), key=lambda it: it[1])[0] in horz cnt = sorted(cnt . items(), key=lambda it: (it[1], tic != (it[0] in horz))) return '' . join(d for d, _ in cnt)
Simple Fun #389: The Order Of Ribbons
5a4adff7e626c53463000015
[ "Fundamentals" ]
https://www.codewars.com/kata/5a4adff7e626c53463000015
5 kyu
Complete the function that takes a list of numbers (`nums`), as the only argument to the function. Take each number in the list and *square* it if it is even, or *square root* the number if it is odd. Take this new list and return the *sum* of it, rounded to two decimal places. The list will never be empty and will only contain values that are greater than or equal to zero. Good luck!
reference
def sum_square_even_root_odd(nums): return round(sum(n * * 2 if n % 2 == 0 else n * * 0.5 for n in nums), 2)
Sum - Square Even, Root Odd
5a4b16435f08299c7000274f
[ "Fundamentals" ]
https://www.codewars.com/kata/5a4b16435f08299c7000274f
7 kyu
<img src="https://i.imgur.com/ta6gv1i.png?1" /> <!-- Featured 9/6/2021 --> --- # Background If your phone buttons have letters, then it is easy remember long phone numbers by making words from the substituted digits. https://en.wikipedia.org/wiki/Phoneword <img src="https://i.imgur.com/VJU55cg.png" title="source: imgur.com" /> This is common for 1-800 numbers # 1-800 number format This format probably varies for different countries, but for the purpose of this Kata here are **my** rules: A 1-800 number is an 11 digit phone number which starts with a `1-800` prefix. The remaining 7 digits can be written as a combination of 3 or 4 letter words. e.g. * `1-800-CODE-WAR` * `1-800-NEW-KATA` * `1-800-GOOD-JOB` The `-` are included just to improve the readability. # Story A local company has decided they want to reserve a 1-800 number to help with advertising. They have already chosen what words they want to use, but they are worried that maybe that same phone number could spell out other words as well. Maybe bad words. Maybe embarrassing words. They need somebody to check for them so they can avoid any accidental PR scandals! That's where you come in... # Kata Task There is a preloaded array of lots of 3 and 4 letter (upper-case) words: ```if:java,javascript,csharp `Preloaded.WORDS` ``` ```if:python,ruby * For Python it is: `WORDS` ``` ```if:cpp * For C++ it is `preloaded::words` ``` Given the 1-800 (phone word) number that the company wants to use, you need to check against all known words and return the set of all possible 1-800 numbers which can be formed using those same digits. # Notes * The desired phone-word number provided by the company is formatted properly. No need to check. * All the letters are upper-case. No need to check. * Only words in the list are allowed. <hr/> <div style='color:orange'> Good luck!<br> DM </div>
algorithms
from collections import defaultdict TABLE = str . maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "22233344455566677778889999") NUMS = defaultdict(list) for w in WORDS: NUMS[w . translate(TABLE)]. append(w) def check1800(s): num = s[6:]. replace('-', ''). translate(TABLE) return {f'1-800- { a } - { b } ' for s, e in ((num[: i], num[i:]) for i in (3, 4) if NUMS[num[: i]] and NUMS[num[i:]]) for a in NUMS[s] for b in NUMS[e]}
1-800-CODE-WAR
5a3267b2ee1aaead3d000037
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/5a3267b2ee1aaead3d000037
5 kyu
You are stacking some boxes containing gold weights on top of each other. If a box contains more weight than the box below it, it will crash downwards and combine their weights. e.g. If we stack `[2]` on top of `[1]`, it will crash downwards and become a single box of weight `[3]`. ``` [2] [1] --> [3] ``` Given an array of arrays, return the bottom row (i.e. the last array) after all crashings are complete. ``` crashing_weights([[1, 2, 3], --> [[1, 2, ], [[1, , ], [2, 3, 1], --> [2, 3, 4], --> [2, 2, ], [3, 1, 2]]) [3, 1, 2]] --> [3, 4, 6]] therefore return [3, 4, 6] ``` ## More details boxes can be stacked to any height, and the crashing effect can snowball: ``` [3] [2] [5] [4] --> [4] --> [9] ``` Crashing should always start from as high up as possible -- this can alter the outcome! e.g. ``` [3] [3] [2] [5] [2] [3] [1] --> [1] --> [6], not [1] --> [3] ``` Weights will always be integers. The matrix (array of arrays) may have any height or width `>= 1`, and may not be square, but it will always be "nice" (all rows will have the same number of columns, etc). ~~~if:lambdacalc ## Encodings purity: `LetRec` numEncoding: `Scott` export constructors `nil, cons` and deconstructor `foldl` for your `List` encoding ~~~
reference
from functools import reduce def crashing_weights(weights): return reduce(lambda a, b: [a1 + b1 if a1 > b1 else b1 for a1, b1 in zip(a, b)], weights)
Crashing Boxes
5a4a167ad8e1453a0b000050
[ "Fundamentals" ]
https://www.codewars.com/kata/5a4a167ad8e1453a0b000050
6 kyu
Similarly to the [previous kata](https://www.codewars.com/kata/string-subpattern-recognition-i/), you will need to return a boolean value if the base string can be expressed as the repetition of one subpattern. This time there are two small changes: * if a subpattern has been used, it will be present at least twice, meaning the subpattern has to be shorter than the original string; * the strings you will be given might or might not be created repeating a given subpattern, then shuffling the result. For example: ```cpp hasSubpattern("a") == false; //no repeated shorter sub-pattern, just one character hasSubpattern("aaaa") == true; //just one character repeated hasSubpattern("abcd") == false; //no repetitions hasSubpattern("babababababababa") == true; //repeated "ba" hasSubpattern("bbabbaaabbaaaabb") == true; //same as above, just shuffled ``` ```javascript hasSubpattern("a") === false; //no repeated shorter sub-pattern, just one character hasSubpattern("aaaa") === true; //just one character repeated hasSubpattern("abcd") === false; //no repetitions hasSubpattern("babababababababa") === true; //repeated "ba" hasSubpattern("bbabbaaabbaaaabb") === true; //same as above, just shuffled ``` ```python has_subpattern("a") == False #no repeated shorter sub-pattern, just one character has_subpattern("aaaa") == True #just one character repeated has_subpattern("abcd") == False #no repetitions has_subpattern("babababababababa") == True #repeated "ba" has_subpattern("bbabbaaabbaaaabb") == True #same as above, just shuffled ``` ```ruby has_subpattern("a") == false #no repeated shorter sub-pattern, just one character has_subpattern("aaaa") == true #just one character repeated has_subpattern("abcd") == false #no repetitions has_subpattern("babababababababa") == true #repeated "ba" has_subpattern("bbabbaaabbaaaabb") == true #same as above, just shuffled ``` ```crystal has_subpattern("a") == false #no repeated shorter sub-pattern, just one character has_subpattern("aaaa") == true #just one character repeated has_subpattern("abcd") == false #no repetitions has_subpattern("babababababababa") == true #repeated "ba" has_subpattern("bbabbaaabbaaaabb") == true #same as above, just shuffled ``` ```csharp HasSubpattern("a") == false; //no repeated shorter sub-pattern, just one character HasSubpattern("aaaa") == true; //just one character repeated HasSubpattern("abcd") == false; //no repetitions HasSubpattern("babababababababa") == true; //repeated "ba" HasSubpattern("bbabbaaabbaaaabb") == true; //same as above, just shuffled ``` Strings will never be empty and can be composed of any character (just consider upper- and lowercase letters as different entities) and can be pretty long (keep an eye on performances!). If you liked it, go for either the [previous kata](https://www.codewars.com/kata/string-subpattern-recognition-i/) or the [next kata](https://www.codewars.com/kata/string-subpattern-recognition-iii/) of the series!
reference
from collections import Counter from functools import reduce from math import gcd def has_subpattern(string): return reduce(gcd, Counter(string). values()) != 1
String subpattern recognition II
5a4a391ad8e145cdee0000c4
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/5a4a391ad8e145cdee0000c4
6 kyu
In this kata you need to build a function to return either `true/True` or `false/False` if a string can be seen as the repetition of a simpler/shorter subpattern or not. For example: ```cpp,java hasSubpattern("a") == false; //no repeated pattern hasSubpattern("aaaa") == true; //created repeating "a" hasSubpattern("abcd") == false; //no repeated pattern hasSubpattern("abababab") == true; //created repeating "ab" hasSubpattern("ababababa") == false; //cannot be entirely reproduced repeating a pattern ``` ```javascript hasSubpattern("a") === false; //no repeated pattern hasSubpattern("aaaa") === true; //created repeating "a" hasSubpattern("abcd") === false; //no repeated pattern hasSubpattern("abababab") === true; //created repeating "ab" hasSubpattern("ababababa") === false; //cannot be entirely reproduced repeating a pattern ``` ```haskell hasSubpattern "a" == False -- no repeated pattern hasSubpattern "aaaa" == True -- created repeating "a" hasSubpattern "abcd" == False -- no repeated pattern hasSubpattern "abababab" == True -- created repeating "ab" hasSubpattern "ababababa" == False -- cannot be entirely reproduced repeating a pattern ``` ```python has_subpattern("a") == False #no repeated pattern has_subpattern("aaaa") == True #created repeating "a" has_subpattern("abcd") == False #no repeated pattern has_subpattern("abababab") == True #created repeating "ab" has_subpattern("ababababa") == False #cannot be entirely reproduced repeating a pattern ``` ```ruby has_subpattern("a") == false #no repeated pattern has_subpattern("aaaa") == true #created repeating "a" has_subpattern("abcd") == false #no repeated pattern has_subpattern("abababab") == true #created repeating "ab" has_subpattern("ababababa") == false #cannot be entirely reproduced repeating a pattern ``` ```crystal has_subpattern("a") == false #no repeated pattern has_subpattern("aaaa") == true #created repeating "a" has_subpattern("abcd") == false #no repeated pattern has_subpattern("abababab") == true #created repeating "ab" has_subpattern("ababababa") == false #cannot be entirely reproduced repeating a pattern ``` ```csharp HasSubpattern("a") == false; //no repeated pattern HasSubpattern("aaaa") == true; //created repeating "a" HasSubpattern("abcd") == false; //no repeated pattern HasSubpattern("abababab") == true; //created repeating "ab" HasSubpattern("ababababa") == false; //cannot be entirely reproduced repeating a pattern ``` Strings will never be empty and can be composed of any character (just consider upper- and lowercase letters as different entities) and can be pretty long (keep an eye on performances!). If you liked it, go for the [next kata](https://www.codewars.com/kata/string-subpattern-recognition-ii/) of the series!
reference
def has_subpattern(string): return (string * 2). find(string, 1) != len(string)
String subpattern recognition I
5a49f074b3bfa89b4c00002b
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/5a49f074b3bfa89b4c00002b
6 kyu
The Catalan Numbers are defined by the formula: <a href="http://imgur.com/dpDsgz2"><img src="http://i.imgur.com/dpDsgz2.png?1" title="source: imgur.com" /></a> The first nine Catalan Numbers are: ``` Catalan Number Ordinal Term 1 0 1 1 2 2 5 3 14 4 42 5 132 6 429 7 1430 8 ``` The Hankel Matrix is filled with the Catalan Numbers repeating the same term along the diagonals that have the direction UP-RIGHT to DOWN-LEFT, and have a courious property, its determinant is equal to 1. The following is a 4 x 4 Hankel matrix, and as we said before, its determinant value equals to 1. <a href="http://imgur.com/8fiCuvt"><img src="http://i.imgur.com/8fiCuvt.png?1" title="source: imgur.com" /></a> The task for this kata is to create a code that may build a Hankel Matrix with the distribution of terms given above. For more information about Catalan Numbers and the Hankel Matrix you may check at Wikipedia, <a href = "https://en.wikipedia.org/wiki/Catalan_numberhere"> Here</a>. Features of the random Tests: ``` number of tests = 80 2 <= n <= 100 // n, dimension of the matrix ```
reference
s, n = [], 1 for i in range(200): s . append(n) n = 2 * n * (2 * i + 1) / / (i + 2) def hankel_matrix_maker (n ): return [s [i : i + n ] for i in range ( n )]
#10 Matrices: Creating Hankel Matrices
5a48c7e1e626c56fb7000092
[ "Fundamentals", "Mathematics", "Arrays", "Matrix" ]
https://www.codewars.com/kata/5a48c7e1e626c56fb7000092
6 kyu
Each test case will generate a variable whose value is 777. Find the name of the variable.
games
def find_variable(): return next(k for k, v in globals(). items() if v == 777)
Find the name of the lucky variable
5a47d5ddd8e145ff6200004e
[ "Puzzles" ]
https://www.codewars.com/kata/5a47d5ddd8e145ff6200004e
7 kyu
In the sys module there is a function ```sys.setrecursionlimit``` and ```sys.getrecursionlimit```. These two functions set and get the recursion limit. If function calls stack is larger than this limit it will raise a ```RuntimeError``` Examples of these two functions: ```python import sys sys.setrecursionlimit(905) sys.getrecursionlimit() # returns 905 sys.setrecursionlimit(89) sys.getrecursionlimit() # returns 89 ``` <h1>Task</h1> Write a function ```fetch_recursion_limit``` that acts the same as ```sys.getrecursionlimit``` without importing any libraries.<br><br> ```10 >= Recursion Limit <= 15000```<br> Hint: Write a separate recursive function <h1 align='center'> <strong>Good Luck </strong></h1>
reference
def fetch_recursion_limit(): try: return 1 + fetch_recursion_limit() except RuntimeError: return 2
Get recursion limit
5a1e1b69697598459d000057
[ "Fundamentals" ]
https://www.codewars.com/kata/5a1e1b69697598459d000057
6 kyu
We'll think that a "mirror" section in an array is a group of contiguous elements ( > 1) such that somewhere in the array, the same group appears in reverse order. For example, the largest mirror section in [1, 2, 3, 8, 9, 3, 2, 1] is length 3 (the ...```1, 2, 3```... part). Return the length of the largest mirror section in the given array. If the mirror doesn't exist or array is empty, return 0. Some examples: ``` maxMirror([1, 2, 3, 8, 9, 3, 2, 1, 9, 8]) β†’ 3 maxMirror([1, 2, 2, 1]) β†’ 4 // palindrome maxMirror([1, 2, 1, 4]) β†’ 3 // palindrome part (1, 2, 1) maxMirror([7, 1, 2, 9, 7, 2, 1]) β†’ 2 maxMirror([1, 2, 3, 6, 7, 3, 2, 1, 5]) β†’ 3 maxMirror([1, 2, 2]) β†’ 2 // palindrome part (2, 2) maxMirror([1, 2, 3]) β†’ 0 maxMirror([1, 5]) β†’ 0 maxMirror([1]) β†’ 0 ```
algorithms
def max_mirror(arr): n, r_arr = len(arr), arr[:: - 1] for i in range(n, 1, - 1): s1, s2 = set(), set() for j in range(n - i + 1): s1 . add(tuple(arr[j: j + i])) s2 . add(tuple(r_arr[j: j + i])) if s1 & s2: return i return 0
The largest "mirror"
5a3f61bab6cfd7acbc000001
[ "Algorithms", "Arrays" ]
https://www.codewars.com/kata/5a3f61bab6cfd7acbc000001
6 kyu
In this kata, we want to discover a small property of numbers. We say that a number is a **dd** number if it contains d occurences of a digit d, (d is in [1,9]). ## Examples * 664444309 is a **dd** number, as it contains 4 occurences of the number 4 * 30313, 122 are **dd** numbers as they respectively contain 3 occurences of the number 3, and (1 occurence of the number 1 AND 2 occurences of the number 2) * 123109, 0, 56542 are not **dd** numbers ## Task Your task is to implement a function called `is_dd` (`isDd` in javascript) that takes a **positive** number (type depends on the language) and returns a boolean corresponding to whether the number is a **dd** number or not.
reference
from collections import Counter def is_dd(n): return any(value == count for value, count in Counter(int(x) for x in str(n)). items())
Numbers with d occurences of digit d
5a40fc7ce1ce0e34440000a3
[ "Fundamentals" ]
https://www.codewars.com/kata/5a40fc7ce1ce0e34440000a3
7 kyu
The citizens of Codeland read each word from right to left, meaning that lexicographical comparison works differently in their language. Namely, string ```a``` is <i>lexicographically smaller</i> than string ```b``` if either: ```a``` is a suffix of ```b``` (in common sense, i.e. ```b``` ends with a substring equal to ```a```); or their last ```k``` characters are the same but the ```(k + 1)th``` character from the right in string ```a``` is smaller than the same character in string ```b```. Given an array of words in Codeland language, sort them lexicographically according to Codeland's unique rules. For ```words = ["nigeb", "ta", "eht", "gninnigeb"]```, the output should be ```unusualLexOrder(words) = ["ta", "nigeb", "gninnigeb", "eht"]```. In particular, ```"ta" < "nigeb"``` because ```'a' < 'b'``` and ```"nigeb" < "gninnigeb"``` because the former word is a suffix of the latter. S: <i>codefights.com</i>
algorithms
def unusual_lex_order(a): return sorted(a, key=lambda k: k[:: - 1])
Unusual Lex Order
5a438bc1e1ce0e129100005a
[ "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/5a438bc1e1ce0e129100005a
7 kyu
In input string ```word```(1 word): * replace the vowel with the nearest left consonant. * replace the consonant with the nearest right vowel. P.S. To complete this task imagine the alphabet is a circle (connect the first and last element of the array in the mind). For example, 'a' replace with 'z', 'y' with 'a', etc.(see below) For example: ``` 'codewars' => 'enedazuu' 'cat' => 'ezu' 'abcdtuvwxyz' => 'zeeeutaaaaa' ``` It is preloaded: ``` const alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] const consonants = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']; const vowels = ['a','e','i','o','u']; ``` P.S. You work with lowercase letters only.
reference
def replace_letters(word): return word . translate(str . maketrans('abcdefghijklmnopqrstuvwxyz', 'zeeediiihooooonuuuuutaaaaa'))
Replace letters
5a4331b18f27f2b31f000085
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/5a4331b18f27f2b31f000085
6 kyu
For an integer ```k``` rearrange all the elements of the given array in such way, that: all elements that are less than ```k``` are placed before elements that are not less than ```k```;<br> all elements that are less than ```k``` remain in the same order with respect to each other;<br> all elements that are not less than ```k``` remain in the same order with respect to each other.<br> For ```k = 6``` and ```elements = [6, 4, 10, 10, 6]```, the output should be ```splitByValue(k, elements) = [4, 6, 10, 10, 6]```. For ```k``` = 5 and ```elements = [1, 3, 5, 7, 6, 4, 2]```, the output should be ```splitByValue(k, elements) = [1, 3, 4, 2, 5, 7, 6]```. S: <i>codefights.com</i>
algorithms
def split_by_value(k, elements): return sorted(elements, key=lambda x: x >= k)
Split By Value
5a433c7a8f27f23bb00000dc
[ "Algorithms" ]
https://www.codewars.com/kata/5a433c7a8f27f23bb00000dc
7 kyu
Given an `array` of numbers, return a new array of length `number` containing the last even numbers from the original array (in the same order). The original array will be not empty and will contain at least "number" even numbers. For example: ``` ([1, 2, 3, 4, 5, 6, 7, 8, 9], 3) => [4, 6, 8] ([-22, 5, 3, 11, 26, -6, -7, -8, -9, -8, 26], 2) => [-8, 26] ([6, -25, 3, 7, 5, 5, 7, -3, 23], 1) => [6] ```
reference
def even_numbers(arr, n): return [i for i in arr if i % 2 == 0][- n:]
Even numbers in an array
5a431c0de1ce0ec33a00000c
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/5a431c0de1ce0ec33a00000c
7 kyu
## Task **_Given_** *an array of integers* , **_Find_** **_the maximum product_** *obtained from multiplying 2 adjacent numbers in the array*. ____ # Notes * **_Array/list_** size is *at least 2*. * **_Array/list_** numbers could be a *mixture of positives, negatives also zeroes* . ___ # Input >> Output Examples ```cpp adjacentElementsProduct([1, 2, 3]); ==> return 6 ``` ```prolog adjacent_elements_product([1, 2, 3], 6). ``` ## **_Explanation_**: * **_The maximum product_** *obtained from multiplying* ` 2 * 3 = 6 `, and **_they're adjacent numbers in the array_**. ___ ```cpp adjacentElementsProduct([9, 5, 10, 2, 24, -1, -48]); ==> return 50 ``` ```prolog adjacent_elements_product([9, 5, 10, 2, 24, -1, -48], 50). ``` ## **_Explanation_**: **_Max product_** obtained *from multiplying* ``` 5 * 10 = 50 ```. ___ ```cpp adjacentElementsProduct([-23, 4, -5, 99, -27, 329, -2, 7, -921]) ==> return -14 ``` ```prolog adjacent_elements_product([-23, 4, -5, 99, -27, 329, -2, 7, -921], -14). ``` ## **_Explanation_**: * **_The maximum product_** *obtained from multiplying* ` -2 * 7 = -14 `, and **_they're adjacent numbers in the array_**. ___ ___ ___ # [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers) # [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays) # [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored) ___ ## ALL translations are welcomed ## Enjoy Learning !! # Zizou
reference
def adjacent_element_product(array): return max(a * b for a, b in zip(array, array[1:]))
Maximum Product
5a4138acf28b82aa43000117
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/5a4138acf28b82aa43000117
7 kyu
Given a string, return the minimal number of parenthesis reversals needed to make balanced parenthesis. For example: ```if-not:rust ~~~ solve(")(") = 2 Because we need to reverse ")" to "(" and "(" to ")". These are 2 reversals. solve("(((())") = 1 We need to reverse just one "(" parenthesis to make it balanced. solve("(((") = -1 Not possible to form balanced parenthesis. Return -1. ~~~ ``` ```if:rust ~~~ solve(")(") = Some(2) // Because we need to reverse ")" to "(" and "(" to ")". These are 2 reversals. solve("(((())") = Some(1) // We need to reverse just one "(" parenthesis to make it balanced. solve("(((") = None // Not possible to form balanced parentheses. ~~~ ``` Parenthesis will be either `"("` or `")"`. More examples in the test cases. Good luck.
reference
def solve(s): if len(s) % 2: return - 1 # imagine a simple symmetric random walk; '(' is a step up and ')' is a step down. We must stay above the original position height = 0 counter = 0 for x in s: if x == '(': height += 1 else: height -= 1 if height < 0: counter += 1 height += 2 # counter is the number of flips from ')' to '(', height//2 number of opposite flips return counter + height / / 2
Simple reversed parenthesis
5a3f2925b6cfd78fb0000040
[ "Fundamentals" ]
https://www.codewars.com/kata/5a3f2925b6cfd78fb0000040
6 kyu
# Task Christmas is coming. In the [previous kata](https://www.codewars.com/kata/5a405ba4e1ce0e1d7800012e), we build a custom Christmas tree with the specified characters and the specified height. Now, we are interested in the center of the Christmas tree. Please imagine that we build a Christmas tree with `chars = "abc" and n = Infinity`, we got: ``` a b c a b c a b c a b c a b c a b c a b c a b c a b c a b c a b c a b c a b c a b c a b a b c a b c a b a b c a b c a b a b c a b c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | | . . ``` If we keep only the center part of leaves, we will got: ``` a b a a b a . . . ``` As you can see, it's a infinite string, but it has a repeat substring "aba"(spaces will be removed). If we join them together, it looks like:`"abaabaabaabaaba......"`. So, your task is to find the repeat substring of the center part of leaves. # Inputs: - `chars`: the specified characters. In this kata, they always be lowercase letters. # Output: - The repeat substring that satisfy the above conditions. Still not understand the task? Look at the following example ;-) # Examples For `chars = "abc"`,the output should be `"aba"` ``` center leaves sequence: "abaabaabaabaabaaba....." ``` For `chars = "abab"`,the output should be `a` ``` center leaves sequence: "aaaaaaaaaa....." ``` For `chars = "abcde"`,the output should be `aecea` ``` center leaves sequence: "aeceaaeceaaecea....." ``` For `chars = "aaaaaaaaaaaaaa"`,the output should be `a` ``` center leaves sequence: "aaaaaaaaaaaaaa....." ``` For `chars = "abaabaaab"`,the output should be `aba` ``` center leaves sequence: "abaabaabaaba....." ```
reference
def center_of(chars): if not chars: return '' res, ln, nxt, step = [chars[0]], len(chars), 4, 4 while len(res) < len(chars) or len(res) % 2 or res[: len(res) / / 2] != res[len(res) / / 2:]: res . append(chars[nxt % ln]) step += 4 nxt += step ind = next(k for k in range(1, len(res) / / 2 + 1) if len(res) % k == 0 and res == res[: k] * (len(res) / / k)) return '' . join(res[: ind])
Custom Christmas Tree III: the center of leaves
5a4076f3e1ce0ee6d4000010
[ "Puzzles", "Strings", "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5a4076f3e1ce0ee6d4000010
6 kyu
This is a simplified version of [Racing #2: Accelerated Drag Race](https://www.codewars.com/kata/5a42c4cf8f27f25c3700009f). Anna and Bob are good friends, but also rival drag racers. Bob just got his engine reconditioned and wants to prove that he is the fastest of the two. In this kata, you will simulate a drag race between Anna and Bob and determine the winner. You will do this by implementing the function ```dragRace``` (or ```drag_race``` in Python). *Input* You are given the length of the track in meters (```len``` in JavaScript, ```length``` in Python). Also, you are given the two competing cars (```anna``` and ```bob```). The cars are Car objects. In JavaScript, they have the following properties. ``` speed -> the speed of the car in m/s reactionTime -> the reaction time of its driver in s ``` In Python, these are the properties of Car objects. ``` speed -> the speed of the car in m/s reaction_time -> the reaction time of its driver in s ``` The reaction time indicates how long it takes before the driver starts to drive after the start of the race. For example if Anna has a reaction time of 1s, and Bob has a reaction time of 2s, Bob starts driving one second later than Anna. The cars do not require any time to accelerate to their speed. In other words, the cars go from zero to their speed in literally no time. *Output* If there is no winner, return the string ```It's a draw```. If there *is* a winner, return the string ```[name] is the winner```.
reference
def drag_race(d, * cars): def fullTime(car): return d / car . speed + car . reaction_time t1, t2 = map(fullTime, cars) return ("It's a draw" if abs(t1 - t2) < 1e-10 else "{} is the winner" . format("Anna" if t1 < t2 else "Bob"))
Racing #1: Simplified Drag Race
5a40f5b01f7f70ed7600001e
[ "Games", "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5a40f5b01f7f70ed7600001e
7 kyu
You drop a ball from a given height. After each bounce, the ball returns to some fixed proportion of its previous height. If the ball bounces to height 1 or less, we consider it to have stopped bouncing. Return the number of bounces it takes for the ball to stop moving. ``` bouncingBall(initialHeight, bouncingProportion) boucingBall(4, 0.5) After first bounce, ball bounces to height 2 After second bounce, ball bounces to height 1 Therefore answer is 2 bounces boucingBall(30, 0.3) After first bounce, ball bounces to height 9 After second bounce, ball bounces to height 2.7 After third bounce, ball bounces to height 0.81 Therefore answer is 3 bounces ``` Initial height is an integer in range [2,1000] Bouncing Proportion is a decimal in range [0, 1)
reference
def bouncing_ball(initial, proportion): count = 0 while initial > 1: initial = initial * proportion count = count + 1 return count
Bouncing Ball
5a40c250c5e284a76400008c
[ "Fundamentals" ]
https://www.codewars.com/kata/5a40c250c5e284a76400008c
7 kyu
# Task Christmas is coming, and your task is to build a custom Christmas tree with the specified characters and the specified height. # Inputs: - `chars`: the specified characters. - `n`: the specified height. A positive integer greater than 2. # Output: - A multiline string. Each line is separated by `\n`. A tree contains two parts: leaves and trunks. The leaves should be `n` rows. The first row fill in 1 char, the second row fill in 3 chars, and so on. A single space will be added between two adjust chars, and some of the necessary spaces will be added to the left side, to keep the shape of the tree. No space need to be added to the right side. The trunk should be at least 1 unit height, it depends on the value of the `n`. The minimum value of n is 3, and the height of the tree trunk is 1 unit height. If `n` increased by 3, and the tree trunk increased by 1 unit. For example, when n is 3,4 or 5, trunk should be 1 row; when n is 6,7 or 8, trunk should be 2 row; and so on. Still not understand the task? Look at the following example ;-) # Examples For `chars = "*@o" and n = 3`,the output should be: ``` * @ o * @ o | ``` For `chars = "*@o" and n = 6`,the output should be: ``` * @ o * @ o * @ o * @ o * @ o * @ o * @ o | | ``` For `chars = "1234" and n = 6`,the output should be: ``` 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 | | ``` For `chars = "123456789" and n = 3`,the output should be: ``` 1 2 3 4 5 6 | ```
games
def custom_christmas_tree(chars, n): from itertools import cycle it = cycle(chars) tree = [' ' . join(next(it) for j in range(i)). center( 2 * n). rstrip() for i in range(1, n + 1)] tree . extend('|' . center(2 * n). rstrip() for _ in range(n / / 3)) return '\n' . join(tree)
Custom Christmas Tree
5a405ba4e1ce0e1d7800012e
[ "Strings", "ASCII Art", "Puzzles" ]
https://www.codewars.com/kata/5a405ba4e1ce0e1d7800012e
6 kyu
In this Kata, you will be given a expression string and your task will be to remove all braces as follows: ``` solve("x-(y+z)") = "x-y-z" solve("x-(y-z)") = "x-y+z" solve("u-(v-w-(x+y))-z") = "u-v+w+x+y-z" solve("x-(-y-z)") = "x+y+z" ``` There are no spaces in the expression. Only two operators are given: `"+" or "-"`. More examples in test cases. Good luck!
algorithms
from functools import reduce def solve(st): res, s, k = [], "", 1 for ch in st: if ch == '(': res . append(k) k = 1 elif ch == ')': res . pop() k = 1 elif ch == '-': k = - 1 elif ch == '+': k = 1 else: s += '-' + ch if (reduce(lambda a, b: a * b, res, 1) * (1 if k == 1 else - 1) < 0) else '+' + ch return s if s[0] == '-' else s[1:]
Simple parenthesis removal
5a3bedd38f27f246c200005f
[ "Strings", "Logic", "Algorithms" ]
https://www.codewars.com/kata/5a3bedd38f27f246c200005f
5 kyu
In this Kata your task will be to return the count of pairs that have consecutive numbers as follows: ```Haskell pairs([1,2,5,8,-4,-3,7,6,5]) = 3 The pairs are selected as follows [(1,2),(5,8),(-4,-3),(7,6),5] --the first pair is (1,2) and the numbers in the pair are consecutive; Count = 1 --the second pair is (5,8) and are not consecutive --the third pair is (-4,-3), consecutive. Count = 2 --the fourth pair is (7,6), also consecutive. Count = 3. --the last digit has no pair, so we ignore. ``` More examples in the test cases. Good luck! Please also try [Simple time difference](https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2)
reference
def pairs(ar): res = 0 for i in range(1, len(ar), 2): if abs(ar[i] - ar[i - 1]) == 1: res += 1 return res
Simple consecutive pairs
5a3e1319b6486ac96f000049
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5a3e1319b6486ac96f000049
7 kyu
The first input array is the key to the correct answers to an exam, like `["a", "a", "b", "d"]`. The second one contains a student's submitted answers. The two arrays are not empty and are the same length. Return the score for this array of answers, giving `+4` for each correct answer, `-1` for each incorrect answer, and `+0` for each blank answer, represented as an empty string (in C the space character is used). If the score < 0, return `0`. For example: ``` Correct answer Β  | Student's answer | Result ---------------------|-----------------------|----------- ["a", "a", "b", "b"] ["a", "c", "b", "d"] β†’ 6 ["a", "a", "c", "b"] ["a", "a", "b", "" ] β†’ 7 ["a", "a", "b", "c"] ["a", "a", "b", "c"] β†’ 16 ["b", "c", "b", "a"] ["" , "a", "a", "c"] β†’ 0 ```
reference
def check_exam(arr1, arr2): return max(0, sum(4 if a == b else - 1 for a, b in zip(arr1, arr2) if b))
Check the exam
5a3dd29055519e23ec000074
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/5a3dd29055519e23ec000074
7 kyu
You must design a function `mangle` that β€” given an array of 6 distinct numbers in [-59, 60] β€” returns an array consisting of 5 of those 6 numbers. Then you must design a function `guess` that β€” given the result of `mangle` β€” returns the 6th value. ```if:javascript `console` is the only global object you will have access to. ```
games
guesses = {} def guess(mangled): return guesses[* mangled] def mangle(integers): global guesses for i, guess in enumerate(integers): mangled = integers[: i] + integers[i + 1:] if tuple(mangled) not in guesses: guesses[* mangled] = guess return mangled
Compression : impossible
5a2950621f7f70c12d000073
[ "Mathematics", "Puzzles" ]
https://www.codewars.com/kata/5a2950621f7f70c12d000073
5 kyu
The written representation of a number (with 4 or more digits) can be split into three parts in various different ways. For example, the written number 1234 can be split as [1&nbsp;|&nbsp;2&nbsp;|&nbsp;34] or [1&nbsp;|&nbsp;23&nbsp;|&nbsp;4] or [12&nbsp;|&nbsp;3&nbsp;|&nbsp;4]. Given a written number, find the highest possible product from splitting it into three parts and multiplying those parts together. For example: - product of [1&nbsp;|&nbsp;2&nbsp;|&nbsp;34] = 1 \* 2 \* 34 = 68 - product of [1&nbsp;|&nbsp;23&nbsp;|&nbsp;4] = 1 \* 23 \* 4 = 92 - product of [12&nbsp;|&nbsp;3&nbsp;|&nbsp;4] = 12 \* 3 \* 4 = 144 So maximumProductOfParts(1234) = 144 For a longer string there will be many possible different ways to split it into parts. For example, 8675309 could be split as: - [8 | 6 | 75309] - [867 | 530 | 9] - [8 | 67 | 5309] - [86 | 75 | 309] or any other option that splits the string into three parts each containing at least one digit.
reference
from functools import reduce from operator import mul def maximum_product_of_parts(n): s = str(n) return max(reduce(mul, map(int, (s[: i], s[i: j], s[j:]))) for i in range(1, len(s) - 1) for j in range(i + 1, len(s)))
Maximum Product of Parts
5a3a95c2e1ce0efe2c0001b0
[ "Algorithms" ]
https://www.codewars.com/kata/5a3a95c2e1ce0efe2c0001b0
6 kyu
## Task Write a function called `hungarian_numeral()` which takes a non-negative integer `n` and returns the corresponding Hungarian numeral to it. ## Precondition 1. `n` is always an __int__ 2. `0 <= n < 1000000` ## Rules for Hungarian cardinal numerals (simplified) General rules for constructing numerals is similar to that in English: you simply attach the numerals in a decreasing order, indicating thousands and hundreds: ```python 12345 = 'twelve thousand three hundred forty five' ''' 12 1000 3 100 40 5 ''' ``` Obviously, there are some "tricks", that's what this kata is about :-) ### Numbers 0 to 9 The numerals for the units in Hungarian are the following (available preloaded): ```python UNITS = [ u'nulla', u'egy', u'kettΕ‘', u'hΓ‘rom', u'nΓ©gy', u'ΓΆt', u'hat', u'hΓ©t', u'nyolc', u'kilenc' ] ''' 0 1 2 3 4 5 6 7 8 9 ''' ``` ```go var Units = []string{"nulla", "egy", "kettΕ‘", "hΓ‘rom", "nΓ©gy", "ΓΆt", "hat", "hΓ©t", "nyolc", "kilenc"} " 0 1 2 3 4 5 6 7 8 9 " ``` NOTE: the word `'kettΕ‘'` (2) is used **<u>only</u>** when it's in the last decimal place (`xxx2`); in all other places use `'kΓ©t'` instead. ### Numbers 10 to 99 Take the numeral of the tens and append the numeral of the unit to it. The tens in Hungarian are (available preloaded): ```python TENS = [ u'tΓ­z', u'hΓΊsz', u'harminc', u'negyven', u'ΓΆtven', u'hatvan', u'hetven', u'nyolcvan', u'kilencven' ] ''' 10 20 30 40 50 60 70 80 90 ''' ``` ```go var Tens := []string{'tΓ­z', 'hΓΊsz', 'harminc', 'negyven', 'ΓΆtven', 'hatvan', 'hetven', 'nyolcvan', 'kilencven' ] " 10 20 30 40 50 60 70 80 90 " ``` NOTE: the words `'tΓ­z'` (10) and `'hΓΊsz'` (20) are used **<u>only</u>** when the number ends exactly with them (`xx10`, `xx20`); otherwise use `'tizen'` (`xx1x`) and `'huszon'` (`xx2x`) instead. *Examples:* ```python 44 = 'negyvennΓ©gy' # 'negyven' (40) + 'nΓ©gy' (4) 25 = 'huszonΓΆt' # 'huszon' (2x) + 'ΓΆt' (5) # REMINDER: 'huszon', not 'hΓΊsz' ``` ## Hundreds Take the digit of the hundreds, append the word `'szΓ‘z'` (hundred) to it, then append the numeral for the part under hundred. *Examples:* ```python 200 = 'kΓ©tszΓ‘z' # 'kΓ©t' (2) + 'szΓ‘z' (100) # REMINDER: 'kΓ©t', not 'kettΕ‘' 645 = 'hatszΓ‘znegyvenΓΆt' # 'hat' (6) + 'szΓ‘z' (100) + 'negyvenΓΆt' (45) ``` NOTE: for `100` the word `'szΓ‘z'` is used, **<u>not</u>** `'egyszΓ‘z'` ## Thousands Treat the thousands part as number below 1000 and append the word `'ezer'` (thousand) to it. If there is a part under 1000 **<u>and</u>** `n` > 2000, append that part with a dash (`-`). **NOTE:** for `1000` the word `'ezer'` is used, **<u>not</u>** `'egyezer'`. From this follows that for numbers `1000` to `1999` you need to drop `egy` (e.g. `1200` is <s>egy</s>**ezerkΓ©tszΓ‘z**). *Examples:* ```python 1056 = 'ezerΓΆtvenhat' # 'ezer' (1000) + 'ΓΆtvenhat' (56) # REMINDER: 'ezer', not 'egyezer' and no dash (n < 2000) 17501 = 'tizenhΓ©tezer-ΓΆtszΓ‘zegy' # 'tizenhΓ©t' (17) + 'ezer' (1000) + '-' + 'ΓΆtszΓ‘zegy' (501) ''' thousands part dash part under thousand ''' ``` ## General Note You may use [this site](http://helyesiras.mta.hu/helyesiras/default/numerals) to create or verify test cases. Write the number in the grey input field after the question mark, then click the `'Mehet'` button. See the result in the green rectangle(s) below.
reference
import copy first = {0: 'nulla', 1: 'egy', 2: 'kettΕ‘', 3: 'hΓ‘rom', 4: 'nΓ©gy', 5: 'ΓΆt', 6: 'hat', 7: 'hΓ©t', 8: 'nyolc', 9: 'kilenc'} second = {0: '', 1: 'tizen', 2: 'huszon', 3: 'harminc', 4: 'negyven', 5: 'ΓΆtven', 6: 'hatvan', 7: 'hetven', 8: 'nyolcvan', 9: 'kilencven'} third = {0: '', 1: 'szΓ‘z', 2: 'kΓ©tszΓ‘z', 3: 'hΓ‘romszΓ‘z', 4: 'nΓ©gyszΓ‘z', 5: 'ΓΆtszΓ‘z', 6: 'hatszΓ‘z', 7: 'hΓ©tszΓ‘z', 8: 'nyolcszΓ‘z', 9: 'kilencszΓ‘z'} def hungarian_numeral(n): first_b = copy . deepcopy(first) second_b = copy . deepcopy(second) third_b = copy . deepcopy(third) places = (first_b, second_b, third_b) res = "" n_list_str = list(str(n)) # reverse the list, the numbers will be treated from right to left, it seems way easier n_list_str . reverse() n_list = [int(i) for i in n_list_str] # if at least two digits, rid "first" of the "0" case and check if "10" or "20" if n > 9: first_b[0] = '' if n_list[0] == 0: second_b . update({1: 'tΓ­z', 2: 'hΓΊsz'}) # for the first three from the right, ready the res variable for the return for i, c in zip(n_list[0: 3], places): res = c[i] + res # end early if it should if n < 1000: return res # put a "-" before the thousands if needed if n >= 2000 and int("" . join(n_list_str[: 3])) != 0: res = "-" + res # adding the 'ezer' and taking care of edgecases res = 'ezer' + res if n < 2000: first_b[1] = '' first_b[2] = 'kΓ©t' if n_list[3] == 0: second_b . update({1: 'tΓ­z', 2: 'hΓΊsz'}) else: second_b . update({1: 'tizen', 2: 'huszon'}) # from the fourth to the sixth included, from the right, ready the res variable for the return for i, c in zip(n_list[3:], places): res = c[i] + res return res
Hungarian Cardinal Numerals
58008f9897917feeec000a3e
[ "Fundamentals" ]
https://www.codewars.com/kata/58008f9897917feeec000a3e
6 kyu
We like parsed SQL or PL/SQL blocks... You need to write function that return list of literals indices from source block, excluding "in" comments, OR return empty list if no literals found. input: some fragment of sql or pl/sql code output: list of literals indices [(start, end), ...] OR empty list Sample: ``` get_textliterals("'this' is sample") -> [(0,6)] get_textliterals("'this' is sample 'too'") -> [(0, 6), (15, 20)] ``` Text literal: any text between single quotes Sample: ``` s := 'i am literal' ``` Single-line comment: any text started with "--" Sample: ``` a := 1; -- this is single-line comment ``` Multy-line comment: any text between /* */ ``` a := 1; /* this is long multy-line comment */ ``` Note: 1) handle single quote inside literal ``` s := 'we can use quote '' in literal' ``` 2) multy-line literal ``` s := ' this is literal too '; ``` 3) skip literal inside comment ``` s := 'test'; --when comment started - this is not 'literal' ``` 4) any unclosed literal should be closed with last symbol of the source fragment ``` s := 'test ``` There is one literal in this code: "'test"
algorithms
import re SKIPERS = re . compile(r'|' . join(["\\\*.*?\*/", "--.*?(\n|$)", "''"])) def get_textliterals(code): code = SKIPERS . sub(lambda m: "x" * len(m . group()), code . rstrip()) if code . count("'") % 2: code += "'" return [(m . start(), m . end()) for m in re . finditer(r"'.+?'", code, flags=re . DOTALL)]
Little PL/SQL parser - get text literals
5536552b372553087d000086
[ "Algorithms", "Strings" ]
https://www.codewars.com/kata/5536552b372553087d000086
5 kyu
In this Kata, you will be given a string of numbers in sequence and your task will be to return the missing number. If there is no number missing or there is an error in the sequence, return `-1`. For example: ```Haskell missing("123567") = 4 missing("899091939495") = 92 missing("9899101102") = 100 missing("599600601602") = -1 -- no number missing missing("8990919395") = -1 -- error in sequence. Both 92 and 94 missing. ``` The sequence will always be in ascending order. More examples in the test cases. Good luck!
algorithms
def missing(seq): for digits in range(1, len(seq) / / 2 + 1): my_seq = last = seq[: digits] n = int(my_seq) missing = None while len(my_seq) < len(seq): n += 1 my_seq += str(n) if not seq . startswith(my_seq): if missing == None: missing = n my_seq = last else: break else: last = my_seq if my_seq == seq and missing: return missing return - 1
Simple number sequence
5a28cf591f7f7019a80000de
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/5a28cf591f7f7019a80000de
5 kyu
Write a code that orders collection of Uris based on it's domain next way that it will returns fisrt Uris with domain "com", "gov", "org" (in alphabetical order of their domains) and then all other Uris ordered in alphabetical order of their domains In addition to that 1. content of Uri should not be changed, 2. other part of Uri doesn't affect sorting. (uris "c.com","b.com","a.com" can be placed in any order inside their group, so both "c.com","b.com","a.com" and "a.com","c.com","b.com" are correct, till they are stand before *.org) e.g. ``` "http://www.google.en/?x=jsdfkj" "http://www.google.de/?x=jsdfkj" "http://www.google.com/?x=jsdfkj" "http://www.google.com/?x=jsdfkj" "http://www.google.org/?x=jsdfkj" "http://www.google.gov/?x=jsdfkj" ``` should be sorted into ``` "http://www.google.com/?x=jsdfkj" "http://www.google.com/?x=jsdfkj" "http://www.google.gov/?x=jsdfkj" "http://www.google.org/?x=jsdfkj" "http://www.google.de/?x=jsdfkj" "http://www.google.en/?x=jsdfkj" ``` ___ ```if:python In the final tests consecutive addresses with the same domain will be grouped and sorted before comparison, i.e.: Given your solution returns `["b.com", "a.com", "c.gov"]`, the tests will do this: 1. Split the addresses into groups: `[["b.com", "a.com"], ["c.gov"]]` 2. Sort each group: `[["a.com", "b.com"], ["c.gov"]]` 3. Flatten them: `["a.com", "b.com", "c.gov"]` ```
reference
def order_by_domain(addresses): def weights(a): _, d = a . rsplit('.', 1) return {'com': 0, 'gov': 1, 'org': 2}. get(d[: 3], 3), d return sorted(addresses, key=weights)
"com", "gov", "org" first
57f21fcd69e09cb0d2000088
[ "Fundamentals", "Algorithms", "Sorting" ]
https://www.codewars.com/kata/57f21fcd69e09cb0d2000088
6 kyu
Your task is to return the number of visible dots on a die after it has been rolled(that means the total count of dots that would not be touching the table when rolled) 6, 8, 10, 12, 20 sided dice are the possible inputs for "numOfSides" topNum is equal to the number that is on top, or the number that was rolled. for this exercise, all opposite faces add up to be 1 more than the total amount of sides Example: 6 sided die would have 6 opposite 1, 4 opposite 3, and so on. for this exercise, the 10 sided die starts at 1 and ends on 10. Note: topNum will never be greater than numOfSides
algorithms
def totalAmountVisible(topNum, numOfSides): return numOfSides * (numOfSides + 1) / 2 - (numOfSides - topNum + 1)
Visible Dots On a Die
5a39724945ddce2223000800
[ "Algorithms" ]
https://www.codewars.com/kata/5a39724945ddce2223000800
7 kyu
LΠ΅t's create function to play cards. You receive 3 arguments: `card1` and `card2` are cards from a single deck; `trump` is the main suit, which beats all others. You have a preloaded `deck` (in case you need it): ``` deck = ["joker","2♣","3♣","4♣","5♣","6♣","7♣","8♣","9♣","10♣","J♣","Q♣","K♣","A♣", "2♦","3♦","4♦","5♦","6♦","7♦","8♦","9♦","10♦","J♦","Q♦","K♦","A♦", "2β™₯","3β™₯","4β™₯","5β™₯","6β™₯","7β™₯","8β™₯","9β™₯","10β™₯","Jβ™₯","Qβ™₯","Kβ™₯","Aβ™₯", "2β™ ","3β™ ","4β™ ","5β™ ","6β™ ","7β™ ","8β™ ","9β™ ","10β™ ","Jβ™ ","Qβ™ ","Kβ™ ","Aβ™ "] ``` ### Game rules * If both cards have the same suit, the higher one wins * If both cards have trump, the higher one wins * If the cards have different suits and no one has trump, return `"Let us play again."` * If one card has trump, but not the other, the one with the trump wins * If there is a winner, return `"The first/second card won."` * If the two cards are the same, return `"Someone cheats."` * The joker always wins ### Examples ``` "3♣", "Q♣", "♦" --> "The second card won." "5β™₯", "A♣", "♦" --> "Let us play again." "8β™ ", "8β™ ", "♣" --> "Someone cheats." "2♦", "Aβ™ ", "♦" --> "The first card won." "joker", "joker", "♦" --> "Someone cheats." ```
algorithms
def card_game(card_1, card_2, trump): deck = ['joker', '2♣', '3♣', '4♣', '5♣', '6♣', '7♣', '8♣', '9♣', '10♣', 'J♣', 'Q♣', 'K♣', 'A♣', '2♦', '3♦', '4♦', '5♦', '6♦', '7♦', '8♦', '9♦', '10♦', 'J♦', 'Q♦', 'K♦', 'A♦', '2β™₯', '3β™₯', '4β™₯', '5β™₯', '6β™₯', '7β™₯', '8β™₯', '9β™₯', '10β™₯', 'Jβ™₯', 'Qβ™₯', 'Kβ™₯', 'Aβ™₯', '2β™ ', '3β™ ', '4β™ ', '5β™ ', '6β™ ', '7β™ ', '8β™ ', '9β™ ', '10β™ ', 'Jβ™ ', 'Qβ™ ', 'Kβ™ ', 'Aβ™ '] if card_1 == card_2: return "Someone cheats." if card_1 == "joker": return "The first card won." if card_2 == "joker": return "The second card won." if card_1[- 1] == card_2[- 1]: return "The first card won." if deck . index(card_1) > deck . index(card_2) else "The second card won." if card_1[- 1] == trump: return "The first card won." if card_2[- 1] == trump: return "The second card won." return "Let us play again."
Card game
5a3141fe55519e04d90009d8
[ "Algorithms", "Games", "Strings" ]
https://www.codewars.com/kata/5a3141fe55519e04d90009d8
6 kyu
You will be given a string and you task is to check if it is possible to convert that string into a palindrome by removing a single character. If the string is already a palindrome, return `"OK"`. If it is not, and we can convert it to a palindrome by removing one character, then return `"remove one"`, otherwise return `"not possible"`. The order of the characters should not be changed. For example: ```Haskell solve("abba") = "OK". -- This is a palindrome solve("abbaa") = "remove one". -- remove the 'a' at the extreme right. solve("abbaab") = "not possible". ``` More examples in the test cases. Good luck! If you like this Kata, please try [Single Character Palindromes II](https://www.codewars.com/kata/5a66ea69e6be38219f000110)
algorithms
def solve(s): def isOK(x): return x == x[:: - 1] return ("OK" if isOK(s) else "remove one" if any(isOK(s[: i] + s[i + 1:]) for i in range(len(s))) else "not possible")
Single character palindromes
5a2c22271f7f709eaa0005d3
[ "Algorithms" ]
https://www.codewars.com/kata/5a2c22271f7f709eaa0005d3
6 kyu
You have two arguments: ```string``` - a string of random letters(only lowercase) and ```array``` - an array of strings(feelings). Your task is to return how many specific feelings are in the ```array```. For example: ``` string -> 'yliausoenvjw' array -> ['anger', 'awe', 'joy', 'love', 'grief'] output -> '3 feelings.' // 'awe', 'joy', 'love' string -> 'griefgriefgrief' array -> ['anger', 'awe', 'joy', 'love', 'grief'] output -> '1 feeling.' // 'grief' string -> 'abcdkasdfvkadf' array -> ['desire', 'joy', 'shame', 'longing', 'fear'] output -> '0 feelings.' ``` If the feeling can be formed once - plus one to the answer. If the feeling can be formed several times from different letters - plus one to the answer. Eeach letter in ```string``` participates in the formation of all feelings. 'angerw' -> 2 feelings: 'anger' and 'awe'.
reference
from collections import Counter def countFeelings(letters, feelings): counter = Counter(letters) result = sum(not (Counter(feeling) - counter) for feeling in feelings) return "{} feeling{}." . format(result, "s" if result != 1 else "")
How many feelings?
5a33ec23ee1aaebecf000130
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/5a33ec23ee1aaebecf000130
6 kyu
# Background A spider web is defined by * "rings" numbered out from the centre as `0`, `1`, `2`, `3`, `4` * "radials" labelled clock-wise from the top as `A`, `B`, `C`, `D`, `E`, `F`, `G`, `H` Here is a picture to help explain: <img src="https://i.imgur.com/tGeWQVq.png" title="source: imgur.com" /> # Web Coordinates As you can see, each point where the rings and the radials intersect can be described by a "web coordinate". So in this example the spider is at `H3` and the fly is at `E2` # Kata Task Our friendly jumping spider is resting and minding his own spidery business at web-coordinate `spider`. An inattentive fly bumbles into the web at web-coordinate `fly` and gets itself stuck. Your task is to calculate and return <span style='color:orange; font-weight:bold; font-size:1.1em;'>**the distance**</span> the spider must jump to get to the fly. # Example The solution to the scenario described by the picture is ``4.63522`` # Notes * The centre of the web will always be referred to as `A0` * The rings intersect the radials at **evenly** spaced distances of **1 unit** ____ <div style= 'color:red'> Good Luck!<br/>DM </div>
algorithms
import math def spider_to_fly(spider, fly): web = {'A': 0, 'B': 45, 'C': 90, 'D': 135, 'E': 180, 'F': 225, 'G': 270, 'H': 315} angle = min(abs(web[spider[0]] - web[fly[0]]), 360 - abs(web[spider[0]] - web[fly[0]])) sideA, sideB = int(spider[1]), int(fly[1]) return math . sqrt(sideA * * 2 + sideB * * 2 - 2 * sideA * sideB * math . cos(angle * math . pi / 180))
The Spider and the Fly (Jumping Spider)
5a30e7e9c5e28454790000c1
[ "Algorithms" ]
https://www.codewars.com/kata/5a30e7e9c5e28454790000c1
6 kyu
Given a string that contains only letters, you have to find out the number of **unique** strings (including the string itself) that can be produced by re-arranging the letters of the string. Strings are case **insensitive**. HINT: Generating all the unique strings and calling `length` on that isn't a great solution for this problem. It can be done a lot faster... ## Examples ```python uniqcount("AB") = 2 # "AB", "BA" uniqcount("ABC") = 6 # "ABC", "ACB", "BAC", "BCA", "CAB", "CBA" uniqcount("ABA") = 3 # "AAB", "ABA", "BAA" uniqcount("ABBb") = 4 # "ABBB", "BABB", "BBAB", "BBBA" uniqcount("AbcD") = 24 # "ABCD", etc. ``` ```javascript uniqCount("AB") = 2n // "AB", "BA" uniqCount("ABC") = 6n // "ABC", "ACB", "BAC", "BCA", "CAB", "CBA" uniqCount("ABA") = 3n // "AAB", "ABA", "BAA" uniqCount("ABBb") = 4n // "ABBB", "BABB", "BBAB", "BBBA" uniqCount("AbcD") = 24n // "ABCD", etc. // Note that you should return a BigInt, not a Number ```
algorithms
from operator import mul from functools import reduce from collections import Counter from math import factorial as fact def uniq_count(s): return fact(len(s)) / / reduce(mul, map(fact, Counter(s . lower()). values()), 1)
Unique Strings
586c7cd3b98de02ef60001ab
[ "Algorithms" ]
https://www.codewars.com/kata/586c7cd3b98de02ef60001ab
6 kyu
Your task is to get Zodiac Sign using input ```day``` and ```month```. For example: ```javascript getZodiacSign(1,5) => 'Taurus' getZodiacSign(10,10) => 'Libra' ``` ```ruby get_zodiac_sign(1,5) => 'Taurus' get_zodiac_sign(10,10) => 'Libra' ``` ```python get_zodiac_sign(1,5) => 'Taurus' get_zodiac_sign(10,10) => 'Libra' ``` Correct answers are (preloaded): ```javascript const signs = ['Capricorn', 'Aquarius', 'Pisces', 'Aries', 'Taurus', 'Gemini', 'Cancer', 'Leo', 'Virgo', 'Libra', 'Scorpio', 'Sagittarius'] ``` ```ruby SIGNS = ['Capricorn', 'Aquarius', 'Pisces', 'Aries', 'Taurus', 'Gemini', 'Cancer', 'Leo', 'Virgo', 'Libra', 'Scorpio', 'Sagittarius'] ``` ```python SIGNS = ['Capricorn', 'Aquarius', 'Pisces', 'Aries', 'Taurus', 'Gemini', 'Cancer', 'Leo', 'Virgo', 'Libra', 'Scorpio', 'Sagittarius'] ``` P.S. Each argument is correct integer number. WESTERN ASTROLOGY STAR SIGN DATES * Aries (March 21-April 19) * Taurus (April 20-May 20) * Gemini (May 21-June 20) * Cancer (June 21-July 22) * Leo (July 23-August 22) * Virgo (August 23-September 22) * Libra (September 23-October 22) * Scorpio (October 23-November 21) * Sagittarius (November 22-December 21) * Capricorn (December 22-January 19) * Aquarius (January 20 to February 18) * Pisces (February 19 to March 20)
reference
SIGNS . append('Capricorn') CUTOFFS = [19, 18, 20, 19, 20, 20, 22, 22, 22, 22, 21, 21] def get_zodiac_sign(day, month): return SIGNS[month] if day > CUTOFFS[month - 1] else SIGNS[month - 1]
Get Zodiac Sign
5a376259b6cfd77ca000006b
[ "Fundamentals" ]
https://www.codewars.com/kata/5a376259b6cfd77ca000006b
7 kyu
Given an integer, take the (mean) average of each pair of consecutive digits. Repeat this process until you have a single integer, then return that integer. e.g. Note: if the average of two digits is not an integer, round the result **up** (e.g. the average of 8 and 9 will be 9) ## Examples ``` digitsAverage(246) ==> 4 original: 2 4 6 \ / \ / 1st iter: 3 5 \ / 2nd iter: 4 digitsAverage(89) ==> 9 original: 8 9 \ / 1st iter: 9 ``` p.s. for a bigger challenge, check out the [one line version](https://www.codewars.com/kata/one-line-task-digits-average) of this kata by myjinxin2015!
algorithms
def digits_average(input): digits = [int(c) for c in str(input)] while len(digits) > 1: digits = [(a + b + 1) / / 2 for a, b in zip(digits, digits[1:])] return digits[0]
Digits Average
5a32526ae1ce0ec0f10000b2
[ "Algorithms" ]
https://www.codewars.com/kata/5a32526ae1ce0ec0f10000b2
7 kyu
Create a function that returns the CSV representation of a two-dimensional numeric array. Example: ``` input: [[ 0, 1, 2, 3, 4 ], [ 10,11,12,13,14 ], [ 20,21,22,23,24 ], [ 30,31,32,33,34 ]] output: '0,1,2,3,4\n' +'10,11,12,13,14\n' +'20,21,22,23,24\n' +'30,31,32,33,34' ``` Array's length > 2. More details here: https://en.wikipedia.org/wiki/Comma-separated_values Note: you shouldn't escape the `\n`, it should work as a new line.
reference
def toCsvText(array): return '\n' . join(',' . join(map(str, line)) for line in array)
CSV representation of array
5a34af40e1ce0eb1f5000036
[ "Fundamentals", "Arrays", "Strings" ]
https://www.codewars.com/kata/5a34af40e1ce0eb1f5000036
8 kyu
Create an identity matrix of the specified size( >= 0). Some examples: ``` (1) => [[1]] (2) => [ [1,0], [0,1] ] [ [1,0,0,0,0], [0,1,0,0,0], (5) => [0,0,1,0,0], [0,0,0,1,0], [0,0,0,0,1] ] ```
reference
def get_matrix(n): return [[1 if i == j else 0 for i in range(n)] for j in range(n)]
Matrix creation
5a34da5dee1aae516d00004a
[ "Fundamentals", "Arrays", "Matrix", "Linear Algebra", "Mathematics", "Language Features" ]
https://www.codewars.com/kata/5a34da5dee1aae516d00004a
7 kyu
You need to swap the head and the tail of the specified array: the head (the first half) of array moves to the end, the tail (the second half) moves to the start. The middle element (if it exists) leaves on the same position. Return new array. For example: ``` [ 1, 2, 3, 4, 5 ] => [ 4, 5, 3, 1, 2 ] \----/ \----/ head tail [ -1, 2 ] => [ 2, -1 ] [ 1, 2, -3, 4, 5, 6, -7, 8 ] => [ 5, 6, -7, 8, 1, 2, -3, 4 ] ```
algorithms
def swap_head_tail(a): r, l = (len(a) + 1) / / 2, len(a) / / 2 return a[r:] + a[l: r] + a[: l]
Swap the head and the tail
5a34f087c5e28462d9000082
[ "Algorithms", "Arrays" ]
https://www.codewars.com/kata/5a34f087c5e28462d9000082
7 kyu
Hello! Let us have a list `L` ``` l = [1,2,3] ``` Now, if we cycle it and will take consequent pairs, we'll get ``` (1,2), (2, 3), (3, 1), (1, 2) ... ``` and so on. Your task is to create a generator `gen(n, iterable)` which will iterate over n-tuples of cycled iterable.
reference
from itertools import cycle def gen(n, iterable): iter, r = cycle(iterable), () while True: while len(r) < n: r += (next(iter),) yield r r = r[1:]
Shifted cycles
5a31a71c1f7f705a93000005
[ "Iterators", "Fundamentals" ]
https://www.codewars.com/kata/5a31a71c1f7f705a93000005
6 kyu
In this kata you will have to modify a sentence so it meets the following rules: convert every word backwards that is: longer than 6 characters OR has 2 or more 'T' or 't' in it convert every word uppercase that is: exactly 2 characters long OR before a comma convert every word to a "0" that is: exactly one character long NOTES: Punctuation must not be touched. if a word is 6 characters long, and a "." is behind it, it counts as 6 characters so it must not be flipped, but if a word is 7 characters long, it must be flipped but the "." must stay at the end of the word. ----------------------------------------------------------------------------------------- Only the first transformation applies to a given word, for example 'companions,' will be 'snoinapmoc,' and not 'SNOINAPMOC,'. ----------------------------------------------------------------------------------------- As for special characters like apostrophes or dashes, they count as normal characters, so e.g 'sand-colored' must be transformed to 'deroloc-dnas'.
reference
import re def spiner(s, p): return (s[:: - 1] if len(s) > 6 or s . lower(). count('t') > 1 else s . upper() if len(s) == 2 or p == ',' else '0' if len(s) == 1 else s) + p def spin_solve(sentence): return re . sub(r"((?:\w|['-])+)(\W)?", lambda m: spiner(m . group(1), m . group(2) or ''), sentence)
Spin the sentence
5a3277005b2f00a11b0011c4
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5a3277005b2f00a11b0011c4
6 kyu
## Preface This is the performance version of the [Prime Ant]( https://www.codewars.com/kata/prime-ant) kata. If you did not complete it yet, you should begin there. ## Description The "prime ant" is an obstinate animal that navigates the integers and divides them until there are only primes left! Initially, we have an infinite array `A` containing all the integers >= 2 : `[2, 3, 4, 5, 6, ... ]` Let `p` be the position of the ant on the array. Initially, `p = 0` (the array is 0-indexed) Each turn, the ant will move as follows: * if `A[p]` is prime, the ant moves to the next position : `p += 1` * else, if `A[p]` is a composite number, let `q` be its smallest divisor > 1. We divide `A[p]` by `q`, and we add `q` to `A[p-1]`. The ant moves to the previous position: `p -= 1` Here are the first moves for the ant: ``` 2 3 4 5 6 7 8 9 ... # 2 is prime: go on ^ 2 3 4 5 6 7 8 9 ... # 3 is prime: go on ^ 2 3 4 5 6 7 8 9 ... # 4 is composite: go back and update ^ 2 5 2 5 6 7 8 9 ... # 5 is prime: go on ^ 2 5 2 5 6 7 8 9 ... # 2 is prime: go on ^ 2 5 2 5 6 7 8 9 ... # 5 is prime: go on ^ etc. ``` ## Your task Your function should return the **full list** of integers up to (and including) the ant's position after `n` moves (that is `A[0 .. p+1]`) ## Examples ```python 0 --> [2] # list size = 1 10 --> [2, 5, 2, 7, 3, 7, 8] # size = 7 100 --> [2, 5, 5, 5, 3, 3, 2, 3, 5, 3, 3, 5, 2, 7, 2, 13, 6] # size = 17 1000 --> [..., 5, 5, 2, 5, 3, 2, 7, 5, 3, 3] # size = 83 10000 --> [..., 7, 2, 7, 2, 5, 2, 3, 5, 5, 72] # size = 513 100000 --> [..., 2, 2, 7, 5, 3, 7, 7, 3, 5, 932] # size = 3675 1000000 --> [..., 2, 3, 5, 2, 5, 5, 7, 13, 113, 7161] # size = 28643 10000000 --> [..., 2, 2, 2, 7, 2, 3, 2, 7, 2, 4] # size = 233369 ``` ## Tests As this is a performance kata, the tests start where the other kata stopped: `10 000 < n < 1 000 000`. There are 200 random tests in the 10<sup>4</sup> - 10<sup>5</sup> range, and another 20 tests in the 10<sup>5</sup> - 10<sup>6</sup> range. ## Epilogoue If you're up to the challenge, try the advanced version of this kata: [Prime Ant - Crazy Version](https://www.codewars.com/kata/prime-ant-crazy-version/) --- ## My other katas If you enjoyed this kata then please try [my other katas](https://www.codewars.com/users/anter69/authored)! :-) #### *Translations are welcome!*
algorithms
n = 10 * * 6 s = list(range(n + 1)) s[4:: 2] = ((n - 4) / / 2 + 1) * [2] for i in range(3, int((n + 1) * * .5) + 1, 2): if s[i] == i: for j in range(i * i, n + 1, i): if s[j] == j: s[j] = i def prime_ant(n): d, a = 2, list(range(n + 1)) for _ in range(n): if s[a[d]] == a[d]: d += 1 else: a[d - 1], a[d], d = a[d - 1] + s[a[d]], a[d] / / s[a[d]], d - 1 return a[2: d + 1]
Prime Ant - Performance Version
5a2e96f1c5e2849eef00014a
[ "Performance", "Algorithms" ]
https://www.codewars.com/kata/5a2e96f1c5e2849eef00014a
5 kyu
It's 3AM and you get the dreaded call from a customer: the program your company sold them is hanging. You eventually trace the problem down to a call to a function named `mystery`. Usually, `mystery` works fine and produces an integer result for an integer input. However, on certain inputs, the `mystery` function just locks up. Unfortunately, the `mystery` function is part of a third-party library, and you don't have access to the source code. Uck. It may take a while to get support from the provider of the library, and in the meantime, your customer is getting frustrated. Your mission, should you choose to accept it, is to create a new function called `wrap_mystery` that returns the same results as `mystery`, but does not hang. Since you're not sure exactly what values `mystery` should be returning for hangs, just have `wrap_mystery` return -1 for problematic input. Your customer is counting on you! `wrap_mystery` will only be called with positive integers less than 1,000,000.
reference
from signal import * def signal_handler(signum, frame): raise Exception def wrap_mystery(n): signal(SIGALRM, signal_handler) setitimer(ITIMER_REAL, .01) try: return mystery(n) except: return - 1
Program hangs!
55f9439929875c58a500007a
[ "Fundamentals" ]
https://www.codewars.com/kata/55f9439929875c58a500007a
5 kyu
## Objective As the number of published katas on Codewars grows, so does the likelihood of a newly published kata being a duplicate of an existing one. This is most prevalent among the simpler white katas (those ranked 7 or 8 kyu). Concerned with the ever-increasing number of duplicates, you've decided to start work on an automated process that filters out beginner-level duplicate katas. Your goal is to write a function that will find the duplicates in a list of newly published katas. Your function will serve as a preliminary filter; it should identify the most obvious duplicates in a list by passing arguments to the authors' solutions and comparing the outputs. ### Input Your function will receive an array of functions. These functions are the authors' solutions for their newly published katas. ### Output Your function must return a 2D array. Each subarray will consist of the index values of the functions that are duplicates of each other. The array will be sorted in ascending order based on the index value of the first duplicate that appears for its respective group. If there are no duplicates, return an empty array. ### Technical Details - Each function accepts only one argument - an integer value ranging from `0` to `255`, inclusive. - The functions are all [pure functions](https://en.wikipedia.org/wiki/Pure_function), so there won't be instances of functions that involve `Date` methods or anything of the like. - Maximum array length is `50` - Inputs will always be valid. ### Test Example ```javascript const functionList = [ x => x * 2, x => x ** 2, x => x + 20, x => x / 1000, x => x * x, x => Math.pow(x,2), x => x % 2 ]; dupeDetect(functionList); // [[1, 4, 5]] ``` ```python function_list = [ lambda x: x * 2, lambda x: x ** 2, lambda x: x + 20, lambda x: x / 1000, lambda x: x * x, lambda x: pow(x, 2), lambda x: x % 2 ] dupe_detect(function_list) # [[1, 4, 5]] ``` If you enjoyed this kata, be sure to check out [my other katas](https://www.codewars.com/users/docgunthrop/authored).
reference
from collections import Counter def dupe_detect(functions): results = [tuple(map(f, range(256))) for f in functions] repeated = [tup for tup, v in Counter(results). items() if v > 1] return [[i for i, t in enumerate(results) if t == f] for f in repeated]
Meta-Kata: Duplicate Detector v0.1
5a2f92621f7f701e02000097
[ "Fundamentals" ]
https://www.codewars.com/kata/5a2f92621f7f701e02000097
6 kyu
Your task it to return ```true``` if the fractional part (rounded to 1 digit) of the result (```a``` / ```b```) exists, more than ```0``` and is multiple of ```n```. Otherwise return ```false```. (For Python return True or False) All arguments are positive digital numbers. Rounding works like toFixed() method. (if more than...5 rounds up) Find exapmles below: ``` isMultiple(5, 2, 3) -> false // 2.5 -> 5 is not multiple of 3 isMultiple(5, 3, 4) -> false // 1.7 -> 7 is not multiple of 4 isMultiple(5, 4, 3) -> true // 1.3 -> 3 is multiple of 3 isMultiple(666, 665, 2) -> false // 1.0 -> return false ```
reference
def isMultiple(a, b, n): remainder = int((a / b + 0.05) * 10) % 10 return remainder > 0 and remainder % n == 0
Multiple remainder of the division
5a2f83daee1aae4f1c00007e
[ "Fundamentals" ]
https://www.codewars.com/kata/5a2f83daee1aae4f1c00007e
7 kyu
## Task Write a function that returns `true` if the number is a "Very Even" number. If a number is a single digit, then it is simply "Very Even" if it itself is even. If it has 2 or more digits, it is "Very Even" if the sum of its digits is "Very Even". ## Examples ``` number = 88 => returns false -> 8 + 8 = 16 -> 1 + 6 = 7 => 7 is odd number = 222 => returns true -> 2 + 2 + 2 = 6 => 6 is even number = 5 => returns false number = 841 => returns true -> 8 + 4 + 1 = 13 -> 1 + 3 => 4 is even ``` Note: The numbers will always be 0 or positive integers!
reference
def is_very_even_number(n): while len(str(n)) > 1: n = sum(int(x) for x in str(n)) return True if n % 2 == 0 else False
"Very Even" Numbers.
58c9322bedb4235468000019
[ "Fundamentals", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/58c9322bedb4235468000019
7 kyu
You are presented with a single knight on a chess board. Your task is to count the number of unique positions that knight could reach using exactly two moves. In chess a knight can move either 2 squares horizonally and 1 square vertically OR 2 squares vertically and one square horizontally. It must stay on the board at all times (8x8 squares). The chess board will be presented as a 2D array. The knight's position is indicated by a "K" and empty squares "0" ``` [ [ '0', '0', '0', '0', '0', '0', '0', '0' ], [ '0', '0', '0', '0', '0', '0', '0', '0' ], [ '0', '0', '0', '0', '0', 'K', '0', '0' ], [ '0', '0', '0', '0', '0', '0', '0', 'I' ], [ '0', '0', '0', '0', '0', '0', '0', '0' ], [ '0', '0', 'V', '0', '0', '0', '0', '0' ], [ '0', '0', '0', '0', '0', '0', '0', '0' ], [ '0', '0', '0', '0', '0', '0', '0', '0' ] ] ``` Make sure to return the number of unique end positions for the knight as it may be able to reach the same location via different routes. Also bear in mind the kinght can return to its starting position. Do not count positions the knight can reach in one move but not in two. For example, in the above grid, the cell marked with an 'I' can be reached in one move, but a second move will take the knight away from this square, making this an invalid endpoint. The position marked with a 'V' is an example of a valid endpoint.
algorithms
# (1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1), (-2, 1), (-1, 2) def moves(pos: tuple): from itertools import product x, y = pos pos = list() for move in list(product((1, - 1), (2, - 2))) + list(product((2, - 2), (1, - 1))): if 0 <= x + move[0] <= 7 and 0 <= y + move[1] <= 7: pos . append((x + move[0], y + move[1])) return tuple(pos) # tuple def get_pos(board: list): for x in range(8): if 'K' in board[x]: return (x, board[x]. index('K')) def count(board: list): all = list() for move1 in moves(get_pos(board)): all . extend(moves(move1)) return len(set(all))
Valid Chess Moves
5707bf345699a1e98800004b
[ "Algorithms", "Arrays" ]
https://www.codewars.com/kata/5707bf345699a1e98800004b
5 kyu
In this Kata, you will be given a ```number```, two indexes (```index1``` and ```index2```) and a ```digit``` to look for. Your task will be to check if the ```digit``` exists in the ```number```, within the ```indexes``` given. Be careful, the ```index2``` is not necessarily more than the ```index1```. ``` index1 == 2 and index2 == 5 -> snippet from 2 to 5 positons; index1 == 5 and index2 == 2 -> snippet from 2 to 5 positons; number.length = 14; 0 <= index1 < 14; 0 <= index2 < 14; index2 is inclusive in search snippet; 0 <= digit <= 9; ``` Find more details below: ``` checkDigit(12345678912345, 1, 0, 1) -> true, 1 exists in 12 checkDigit(12345678912345, 0, 1, 2) -> true, 2 exists in 12 checkDigit(67845123654000, 4, 2, 5) -> true, 5 exists in 845 checkDigit(66688445364856, 0, 0, 6) -> true, 6 exists in 6 checkDigit(87996599994565, 2, 5, 1) -> false, 1 doesn't exist in 9965 ```
reference
def check_digit(n, i1, i2, d): return str(d) in str(n)[min(i1, i2): max(i1, i2) + 1]
Check digit
5a2e8c0955519e54bf0000bd
[ "Fundamentals", "Strings", "Puzzles" ]
https://www.codewars.com/kata/5a2e8c0955519e54bf0000bd
7 kyu
In this kata, you will be given a grid and a point, and you will want to return the numbers in the row, column and both the diagonals that point is on, like a queen's move in chess. For example, given the grid: ``` [[ 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 0], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]] ``` The origin starts at the top left square. The points are 0-indexed so the first point is `[0, 0]` which would be the top left point. In the case of the grid above, it would be `1` If given the point `[2, 3]`, you should return the numbers on the row, column and both the diagonals containing that point. The `[2, 3]` point contains the number `18` The row containing the `[2, 3]` point contains the numbers `[16, 17, 18, 19, 20]` The column containing the `[2, 3]` point contains the numbers `[3, 8, 13, 18, 23]` The top-left to bottom-right diagonal containing the `[2, 3]` point contains the numbers `[6, 12, 18, 24]` The top-right to bottom-left diagonal containing the `[2, 3]` point contains the numbers `[0, 14, 18, 22]` And you should return them in the order: `[row, column, top-left to bottom-right diag, top-right to bottom-left diag]` Therefore, in this case, you should return `[[16, 17, 18, 19, 20], [3, 8, 13, 18, 23], [6, 12, 18, 24], [0, 14, 18, 22]]` as a list of the lines. The order inside each row, column or diagonal doesnt matter, but you do have to return the lines in the same order as the one stated above. You will be given the grid as a list, the position of the point as a list, and the size of the grid as an int: ```python def check_grid(grid, pos, size): ``` * The grids will always be square * The sizes of the grids tested will be `2 <= size <= 100`. There will be no grids smaller than 2. Good luck!
algorithms
def check_grid(grid, pos, size): c, r = pos return [ grid[r], [row[c] for row in grid], [grid[r2][c - r + r2] for r2 in range(len(grid)) if 0 <= c - r + r2 < len(grid)], [grid[r2][c + r - r2] for r2 in range(len(grid)) if 0 <= c + r - r2 < len(grid)] ]
Find the lines!
5a2d376ec5e2845ec20000bd
[ "Algorithms", "Arrays", "Lists", "Logic" ]
https://www.codewars.com/kata/5a2d376ec5e2845ec20000bd
6 kyu
### Isograms > An isogram (also known as a "nonpattern word") is a logological term for a word or phrase without a repeating letter. > > Isograms can be useful as keys in ciphers, since isogram sequences of the same length make for simple one-to-one mapping between the symbols. Ten-letter isograms like PATHFINDER, DUMBWAITER, and BLACKHORSE are commonly used by salespeople of products where the retail price is typically negotiated, such as used cars, jewelry, or antiques. > > For example, using the PATHFINDER cipher, `P` represents `1`, `A` represents `2` and so on. The price tag for an item selling for $1200 may also bear the cryptic letters `FRR`, written on the back or bottom of the tag. A salesman familiar with the PATHFINDER cipher will know that the original cost of the item was $500. (source: https://en.wikipedia.org/wiki/Isogram) ### Task Complete the functions, in order to encode/decode the input numbers/codes with the provided isogram keys. Note: the key is case-insensitive (it may be upper- or lowercase). For the input, you should accept numbers in integer or string format (encode function), or a string (decode function). Return the result as an **uppercase string**. If the provided input and/or key is incorrect, empty or missing, return `'Incorrect key or input!'` ### Examples ``` 500, "PATHFINDER" --> "FRR" "500", "PATHFINDER" --> "FRR" "FRR", "PATHFINDER" --> "500" 500, "PATHFIND" --> "Incorrect key or input!" 500, "PATHFINDEE" --> "Incorrect key or input!" "LOL", "PATHFINDER" --> "Incorrect key or input!" ``` See some more examples in the sample tests. --- ### My other katas If you enjoyed this kata then please try [my other katas](https://www.codewars.com/collections/katas-created-by-anter69)! :-) #### *Translations are welcome!*
algorithms
def isogram_encode(input=None, key=None): try: assert input and len(key) == len(set(key)) == 10 trans = dict(zip('1234567890', key . upper())) return '' . join([trans[d] for d in str(input)]) except: return 'Incorrect key or input!' def isogram_decode(input=None, key=None): try: assert input and len(key) == len(set(key)) == 10 trans = dict(zip(key . upper(), '1234567890')) return '' . join([trans[c] for c in input . upper()]) except: return 'Incorrect key or input!'
Isogram Cipher
58fbc832e86f5e905300007f
[ "Ciphers", "Algorithms" ]
https://www.codewars.com/kata/58fbc832e86f5e905300007f
6 kyu
In this Kata, two players, Alice and Bob, are playing a palindrome game. Alice starts with `string1`, Bob starts with `string2`, and the board starts out as an empty string. Alice and Bob take turns; during a turn, a player selects a letter from his or her string, removes it from the string, and appends it to the board; if the board becomes a palindrome (of length >= 2), the player wins. Alice makes the first move. Since Bob has the disadvantage of playing second, then he wins automatically if letters run out or the board is never a palindrome. Note also that each player can see the other player's letters. The problem will be presented as `solve(string1,string2)`. Return 1 if Alice wins and 2 it Bob wins. For example: ```Haskell solve("abc","baxy") = 2 -- There is no way for Alice to win. If she starts with 'a', Bob wins by playing 'a'. The same case with 'b'. If Alice starts with 'c', Bob still wins because a palindrome is not possible. Return 2. solve("eyfjy","ooigvo") = 1 -- Alice plays 'y' and whatever Bob plays, Alice wins by playing another 'y'. Return 1. solve("abc","xyz") = 2 -- No palindrome is possible, so Bob wins; return 2 solve("gzyqsczkctutjves","hpaqrfwkdntfwnvgs") = 1 -- If Alice plays 'g', Bob wins by playing 'g'. Alice must be clever. She starts with 'z'. She knows that since she has two 'z', the win is guaranteed. Note that she also has two 's'. But she cannot play that. Can you see why? solve("rmevmtw","uavtyft") = 1 -- Alice wins by playing 'm'. Can you see why? ``` Palindrome lengths should be at least `2` characters. More examples in the test cases. Good luck!
algorithms
from collections import Counter def solve(* args): c1, c2 = map(Counter, args) return 2 - any(c1[k] - c2[k] >= 2 and k not in c2 for k in c1)
Simple palindrome game
5a26af968882f3523100003d
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/5a26af968882f3523100003d
6 kyu
In this kata, you will be given a string containing numbers from **a** to **b**, one number can be missing from these numbers, then the string will be shuffled, you're expected to return an array of all possible missing numbers. ## Examples (input => output) Here's a string with numbers from 1 - 21, its missing one number and the string is then shuffled, your'e expected to return a list of possible missing numbers. ``` 1, 21, "2198765123416171890101112131415" => [ 12, 21 ] ``` You won't be able to tell if its `21` or `12`, you must return all possible values in an array. ## Another Example ``` 5, 10, "578910" => [ 6 ] ``` #### Documentation: The parameters will be in order two numbers and a string: - start **=>** from - stop **=>** to - string **=>** numbers from **start** to **stop** in string form (shuffled), but missing one number Note: - if there're no missing numbers return an empty list Too easy ? Try [Range of Integers in an Unsorted String](https://www.codewars.com/kata/5b6b67a5ecd0979e5b00000e)
games
from collections import Counter from itertools import permutations def find_number(start, stop, s): miss = Counter('' . join(map(str, range(start, stop + 1)))) - Counter(s) intValues = {int(v) for v in map('' . join, permutations( '' . join(c * n for c, n in miss . items()))) if v and v[0] != '0'} return [v for v in intValues if start <= v <= stop]
Find the missed number
5a1d86dbba2a142e040000ee
[ "Mathematics", "Puzzles", "Algorithms", "Logic" ]
https://www.codewars.com/kata/5a1d86dbba2a142e040000ee
6 kyu
In this kata, your task is to write a function `to_bytes(n)` (or `toBytes(n)` depending on language) that produces a list of bytes that represent a given non-negative integer `n`. Each byte in the list is represented by a string of `'0'` and `'1'` of length 8. The most significant byte is first in the list. The example test cases should provide you with all the details. You may assume that the argument `n` is valid.
reference
def to_bytes(n): if not n: return ['00000000'] res = [] while n: res . append('{:08b}' . format(n % 256)) n / /= 256 return res[:: - 1]
Number to Bytes
5705601c5eef1fad69000674
[ "Fundamentals" ]
https://www.codewars.com/kata/5705601c5eef1fad69000674
7 kyu
This kata is part of the collection [Mary's Puzzle Books](https://www.codewars.com/collections/marys-puzzle-books). # Zero Terminated Sum Mary has another puzzle book, and it's up to you to help her out! This book is filled with zero-terminated substrings, and you have to find the substring with the largest sum of its digits. For example, one puzzle looks like this: ``` "72102450111111090" ``` Here, there are 4 different substrings: `721`, `245`, `111111`, and `9`. The sums of their digits are `10`, `11`, `6`, and `9` respectively. Therefore, the substring with the largest sum of its digits is `245`, and its sum is `11`. Write a function `largest_sum` which takes a string and returns the maximum of the sums of the substrings. In the example above, your function should return `11`. ### Notes: - A substring can have length 0. For example, `123004560` has three substrings, and the middle one has length 0. - All inputs will be valid strings of digits, and the last digit will always be `0`.
reference
def largest_sum(s): return max(sum(map(int, x)) for x in s . split('0'))
Zero Terminated Sum
5a2d70a6f28b821ab4000004
[ "Fundamentals" ]
https://www.codewars.com/kata/5a2d70a6f28b821ab4000004
7 kyu
A **prime number** (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. You will be given the `lower` and `upper` limits: the program will look for any prime number that exists between the lower limit to the upper limit (included). Your objective is to sum all the primes between the given limits. * If the limits are primes, then they are included * -100000 <= `lower` < `upper` <= 100000 * If `lower` is greater than `upper`, it should return `0` ### Example You are given a lower limit of `4` and an upper limit of `20`. So the prime numbers from 4 to 20 will be: ```5, 7, 11, 13, 17, 19``` and if you add them up, the result will be `72`. ```python sum_primes(4, 20) = 72 # 5 + 7 + 11 + 13 + 17 + 19 = 72 sum_primes(20, 4) = 0 # since lower is greater than upper sum_primes(2, 7) = 17 # 2 + 3 + 5 + 7 = 17 sum_primes(11, 11) = 11 # it consists of one prime number sum_primes(60, 60) = 0 # since 60 is not a prime number ```
algorithms
# generate primes up to limit limit = 10 * * 6 sieve = [0] + list(range(3, limit + 1, 2)) for n in sieve: if n: for i in range(n * n, limit + 1, n * 2): sieve[i / / 2] = 0 primes = [2] + list(n for n in sieve if n) def sumPrimes(lower, upper): return sum(p for p in primes if lower <= p <= upper)
Sum of Primes
5902ea9b378a92a990000016
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5902ea9b378a92a990000016
7 kyu
Check if it is a vowel(a, e, i, o, u,) on the ```n``` position in a string (the first argument). Don't forget about uppercase. A few cases: ``` { checkVowel('cat', 1) -> true // 'a' is a vowel checkVowel('cat', 0) -> false // 'c' is not a vowel checkVowel('cat', 4) -> false // this position doesn't exist } ``` P.S. If n < 0, return false
reference
def check_vowel(s, i): return 0 <= i < len(s) and s[i] in "aieouAEIOU"
Is it a vowel on this position?
5a2b7edcb6486a856e00005b
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/5a2b7edcb6486a856e00005b
7 kyu
In this Kata, you will be given a string and your task will be to return a list of ints detailing the count of uppercase letters, lowercase, numbers and special characters, as follows. ```Haskell Solve("*'&ABCDabcde12345") = [4,5,5,3]. --the order is: uppercase letters, lowercase, numbers and special characters. ``` More examples in the test cases. Good luck!
reference
def solve(s): uc, lc, num, sp = 0, 0, 0, 0 for ch in s: if ch . isupper(): uc += 1 elif ch . islower(): lc += 1 elif ch . isdigit(): num += 1 else: sp += 1 return [uc, lc, num, sp]
Simple string characters
5a29a0898f27f2d9c9000058
[ "Fundamentals" ]
https://www.codewars.com/kata/5a29a0898f27f2d9c9000058
7 kyu
Final kata of the series (highly recommended to compute [layers](https://www.codewars.com/kata/progressive-spiral-number-position/) and [branch](https://www.codewars.com/kata/progressive-spiral-number-branch/) first to get a good idea), this is a blatant ripoff of [the one offered on AoC](http://adventofcode.com/2017/day/3). Given a number, return the Manhattan distance considering the core of the spiral (the `1` cell) as 0 and counting each step up, right, down or left to reach a given cell. For example, using our beloved 5x5 square: ``` 17 16 15 14 13 4 3 2 3 4 18 05 04 03 12 3 2 1 2 3 19 06 01 02 11 => 2 1 0 1 2 20 07 08 09 10 3 2 1 2 3 21 22 23 24 25 4 3 2 3 4 ``` And thus your code should behave like this: ```javascript distance(1) === 0 distance(5) === 2 distance(25) === 4 distance(30) === 5 distance(50) === 7 ``` ```python distance(1) == 0 distance(5) == 2 distance(25) == 4 distance(30) == 5 distance(50) == 7 ``` ```ruby distance(1) == 0 distance(5) == 2 distance(25) == 4 distance(30) == 5 distance(50) == 7 ``` ```crystal distance(1) == 0 distance(5) == 2 distance(25) == 4 distance(30) == 5 distance(50) == 7 ``` ```cpp distance(1) == 0 distance(5) == 2 distance(25) == 4 distance(30) == 5 distance(50) == 7 ``` ```csharp Distance(1) == 0 Distance(5) == 2 Distance(25) == 4 Distance(30) == 5 Distance(50) == 7 ``` Just be ready for larger numbers, as usual always positive. *[Dedicated to [swiftest learner I met in a long while](https://www.codewars.com/users/irbekrm/)]*
reference
def distance(n): if n == 1: return 0 r = 0 - (1 - n * * .5) / / 2 d, m = divmod(n - (2 * r - 1) * * 2 - 1, 2 * r) z = (r * (1 + 1j) - m - 1) * 1j * * d return abs(z . real) + abs(z . imag)
Progressive Spiral Number Distance
5a27e3438882f334a10000e3
[ "Mathematics", "Number Theory", "Fundamentals" ]
https://www.codewars.com/kata/5a27e3438882f334a10000e3
6 kyu
In this Kata, you will be given a list of strings and your task will be to find the strings that have the same characters and return the sum of their positions as follows: ```Haskell solve(["abc","abbc", "ab", "xyz", "xy", "zzyx"]) = [1,8] -- we see that the elements at indices 0 and 1 have the same characters, as do those at indices 3 and 5. -- we therefore return [1,8] because [0+1,3+5] = [1,8]. This result is sorted. -- ignore those that don't have at least one matching partner, such as "ab" and "xy". Another example... solve(["wkskkkkkk","fokoo","wkskk","uizzzz","fokooff","wkskkkk","uizzzzzzz"]),[5,7,9]); --The element at index 0 is similar to those at indices 2 and 5; so 0 + 2 + 5 = 7. --The element at index 1 is similar to that at index 4; so 1 + 4 = 5. --The element at index 3 is similar to that at index 6; so 3 + 6 = 9. --The result must be sorted. We get [5,7,9]. ``` More examples in the test cases. Good luck!
algorithms
from collections import defaultdict def solve(arr): dct = defaultdict(list) for i, fs in enumerate(map(frozenset, arr)): dct[fs]. append(i) return sorted(sum(lst) for lst in dct . values() if len(lst) > 1)
Arrays of Lists of Sets
5a296b571f7f70b0b3000100
[ "Strings", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/5a296b571f7f70b0b3000100
6 kyu
# Base reduction ## Input A positive integer: ``` 0 < n < 1000000000 ``` ## Output The end result of the base reduction. If it cannot be fully reduced (reduced down to a single-digit number), return -1. Assume that if 150 conversions from base 11 take place in a row, the number cannot be fully reduced. ## Description Base reduction is a process where a number is inputted, repeatedly converted into another base, and then outputted if it cannot be reduced anymore. If it cannot be fully reduced, return -1. During the base conversions, the number is converted from the lowest base it can be converted from into base 10. For example, 123 would be converted from base 4 to base 10, since base 4 is the lowest base that 123 can be in (123 base 3 is impossible; in base 3, there is no digit 3). If the lowest possible base the number can be converted into is 10, convert the number from base 11 to base 10. For example, 53109 would be converted from base 11 to base 10, since base 10 is the lowest base it can be in. In the end, you should get a number that cannot be reduced by this process (a single digit number). ## Example Starting with 5312: ``` 5312 base 6 = 1196 base 10 1196 base 11 = 1557 base 10 1557 base 8 = 879 base 10 879 base 11 = 1054 base 10 1054 base 6 = 250 base 10 250 base 6 = 102 base 10 102 base 3 = 11 base 10 11 base 2 = 3 base 10 ``` The output would be 3.
algorithms
def basereduct(x): for _ in range(150): x = int(str(x), int(max(str(x))) + 1 + ('9' in str(x))) if x < 10: return x return - 1
Base Reduction
5840e31f770be1636e0000d3
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/5840e31f770be1636e0000d3
6 kyu
Your task is determine the lowest number base system in which the input `n` ( base 10 ), expressed in this number base system, is all `1`s in its digits. See some examples: `7` in base 2 is `111` - fits! answer is `2` `21` in base 2 is `10101` - contains `0`, does not fit `21` in base 3 is `210` - contains `0` and `2`, does not fit `21` in base 4 is `111` - contains only `1` it fits! answer is `4` `n` is always less than `Number.MAX_SAFE_INTEGER` or equivalent.
reference
def get_min_base(number): for ln in range(number . bit_length(), 2, - 1): b = int(number * * (1 / (ln - 1))) if b * * ln - 1 == number * (b - 1): return b else: return number - 1
Lowest base system
58bc16e271b1e4c5d3000151
[ "Performance" ]
https://www.codewars.com/kata/58bc16e271b1e4c5d3000151
4 kyu
Each time the function is called it should invert the passed triangle. Make upside down the given triangle and invert the chars in the triangle. ``` if a char = " ", make it = "#" if a char = "#", make it = " " ``` ``` # ### ##### ####### ######### // normal // inverted # # ## ## ### ### #### #### #### #### ### ### ## ## # # // normal ######### // inverted ####### ##### ### # ``` maketri() is at your disposal.
reference
# invert the triangle # maketri(size_of_triangle) can be called for convenience def invert_triangle(t): return t[:: - 1]. translate(str . maketrans('# ', ' #'))
Invert The Triangle
5a224a15ee1aaef6e100005a
[ "Puzzles", "Fundamentals" ]
https://www.codewars.com/kata/5a224a15ee1aaef6e100005a
7 kyu
In number theory, Euler's totient is an arithmetic function, introduced in 1763 by Euler, that counts the positive integers less than or equal to `n` that are relatively prime to `n`. Thus, if `n` is a positive integer, then `Ο†(n)`, notation introduced by Gauss in 1801, is the number of positive integers `k ≀ n` for which `gcd(n, k) = 1`. The totient function is important in number theory, mainly because it gives the order of the multiplicative group of integers modulo `n`. The totient function also plays a key role in the definition of the RSA encryption system. For example `let n = 9`. Then `gcd(9, 3) = gcd(9, 6) = 3` and `gcd(9, 9) = 9`. The other six numbers in the range `1 ≀ k ≀ 9` i.e. `1, 2, 4, 5, 7, 8` are relatively prime to `9`. Therefore, `Ο†(9) = 6`. As another example, `Ο†(1) = 1` since `gcd(1, 1) = 1`. There are generally two approaches to this function: * Iteratively counting the numbers `k ≀ n` such that `gcd(n,k) = 1`. * Using the Euler product formula. This is an explicit formula for calculating `Ο†(n)` depending on the prime divisor of `n`: `Ο†(n) = n * Product (1 - 1/p)` where the product is taken over the primes `p ≀ n` that divide `n`. For example: `Ο†(36) = 36 * (1 - 1/2) * (1 - 1/3) = 36 * 1/2 * 2/3 = 12`. This second method seems more complex and not likely to be faster, but in practice we will often look for `Ο†(n)` with `n` prime. It correctly gives `Ο†(n) = n - 1` if `n` is prime. You have to code the Euler totient function, that takes an integer `1 ≀ n` as input and returns `Ο†(n)`. ```if:javascript,python,ruby You do have to check if `n` is a number, is an integer and that `1 ≀ n`; if that is not the case, the function should return `0`. ``` ```if:racket `n` is always a positive integer. ``` Input range: `1 ≀ n ≀ 1e10`
algorithms
def totient(n): if not isinstance(n, int) or n < 1: return 0 phi = n >= 1 and n for p in range(2, int(n * * .5) + 1): if not n % p: phi -= phi / / p while not n % p: n / /= p if n > 1: phi -= phi / / n return phi
Euler Totient Function
53c9157c689f841d16000c03
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/53c9157c689f841d16000c03
5 kyu
## Task Write a function which accepts a sequence of unique integers ( `0 <= x < 32` ) as an argument and returns a 32-bit integer such that the integer, in its binary representation, has `1` at only those indices, numbered from right to left, which are in the sequence. ## Examples `[0, 1] -> 3` `[1, 2, 0, 4] -> 23` Because `23` in binary is 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 1 1 . . . . . 5 4 3 2 1 0 <- indices ^ ^ ^ ^ these bits are 1 due to the corresponding indices being in the given sequence ## FAQ The function name contains `sort` because this simulates [radix sort](https://en.wikipedia.org/wiki/Radix_sort).
algorithms
def sort_by_bit(seq): return sum(2 * * i for i in seq)
Construct a bit vector set
52f5424d0531259cfc000d04
[ "Algorithms" ]
https://www.codewars.com/kata/52f5424d0531259cfc000d04
7 kyu
Find the area of a generic n-sided polygon. The area_polygon will receive in input a list of n (x, y) tuples which are the coordinates of the n vertices and shall output the area of the polygon rounded to 1 decimal place. The input will always be at least 3 points, and the polygon will not be self-intersecting.
reference
def area_polygon(vertex): vertex . append(vertex[0]) return round(abs(sum([((vertex[i][0] * vertex[i + 1][1]) - (vertex[i][1] * vertex[i + 1][0])) for i in range(0, len(vertex) - 1)]) / 2), 1)
Area of an n-sided polygon
5727500a20c7f837fc001869
[ "Geometry", "Algebra", "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5727500a20c7f837fc001869
6 kyu
Take a number and check each digit if it is divisible by the digit on its left checked and return an array of booleans. The booleans should always start with false becase there is no digit before the first one. ## Examples ``` 73312 => [false, false, true, false, true] 2026 => [false, true, false, true] 635 => [false, false, false] ``` *** Remember 0 is evenly divisible by all integers but not the other way around ***
algorithms
def divisible_by_last(n): l = list(map(int, f"0 { n } ")) return [x and not y % x for x, y in zip(l, l[1:])]
Divisible by previous digit?
5a2809dbe1ce0e07f800004d
[ "Algorithms" ]
https://www.codewars.com/kata/5a2809dbe1ce0e07f800004d
7 kyu
Similar setting of the [previous](https://www.codewars.com/kata/progressive-spiral-number-position/), this time you are called to identify in which "branch" of the spiral a given number will end up. Considering a square of numbers disposed as the 25 items in [the previous kata](https://www.codewars.com/kata/progressive-spiral-number-position/), the branch are numbered as it follows: ``` 17 16 15 14 13 1 1 1 1 0 18 05 04 03 12 2 1 1 0 0 19 06 01 02 11 => 2 2 0 0 0 20 07 08 09 10 2 2 3 3 0 21 22 23 24 25 2 3 3 3 3 ``` Meaning that, for example, numbers in the `10-13` range will be in branch `0`, numbers in the range `14-17` are inside branch `1`, all those nice numbers in the `18-21` can call branch `2` their house and finally the `21-25` team all falls under the `3` branch. Your function must return the number of the index of each number [`1` being a special case you might consider equivalent to being in the first branch, `0`], as per examples: ```javascript branch(1) === 0 //kind of special case here branch(5) === 1 branch(25) === 3 branch(30) === 0 branch(50) === 0 ``` ```python branch(1) == 0 #kind of special case here branch(5) == 1 branch(25) == 3 branch(30) == 0 branch(50) == 0 ``` ```ruby branch(1) == 0 #kind of special case here branch(5) == 1 branch(25) == 3 branch(30) == 0 branch(50) == 0 ``` ```crystal branch(1) == 0 #kind of special case here branch(5) == 1 branch(25) == 3 branch(30) == 0 branch(50) == 0 ``` ```cpp branch(1) == 0 //kind of special case here branch(5) == 1 branch(25) == 3 branch(30) == 0 branch(50) == 0 ``` It might help A LOT to both solve the [previous kata](https://www.codewars.com/kata/progressive-spiral-number-position/) and to visualize the diagonals of the square. Be ready for big numbers and, as usual, inspired by [AoC](http://adventofcode.com/2017/day/3). Finally, when ready, go to compute [the distance](https://www.codewars.com/kata/progressive-spiral-number-distance/) of the series.
games
def branch(n): k = int((- 1 + (n) * * .5) / 2 - 10 * * - 5) return (n - 4 * k * (k + 1) - 2) / / (2 * (k + 1)) if n > 1 else 0
Progressive Spiral Number Branch
5a26ca51e1ce0e987b0000ee
[ "Mathematics", "Number Theory", "Puzzles" ]
https://www.codewars.com/kata/5a26ca51e1ce0e987b0000ee
6 kyu
# Task You are a lonely frog. You live on an integer array. The meaning of your life is to jump and jump.. Now, here comes your new task. You are given an integer array `arr` and a positive integer `n`. You will jump following the rules below: - Your initial position at `arr[0]`. arr[0] will always be `0`. - You will jump according to the number of current position(arr[i]) - That is, if the number is a positive integer, let say 3, you will jump forward 3 steps; If the number is a negative integer, let say -3, you will jump backward 3 steps; If the number is 0, you will stay here for a little rest. - The number of current position(arr[i]) will increase decrease by 1 after each turn (jump or stay). - That is, if the number of current position(arr[i]) is greater than or equal to `n`, the number will decrease 1; if the number at current position(arr[i]) is less than `n`, the number will increase 1. You will stop jumping when you reach the exit (your position greater than or equal to arr.length). Please tell me, at the moment, how many elements in `arr` are equal to `n`? # Note - `3 <= arr.length <= 1000`, `1 <= n <= 9` - Frog will never jump backward out of `arr`. # Example For `arr = [0,3,0,1,-3], n = 3`, the output should be `2`. ``` Let us jump softly: [0,3,0,1,-3] ^--You are here, current number is 0, you stay here. currect number 0 < n, so 0 -> 1 [1,3,0,1,-3] ^--You are here, current number is 1, you will jump forward to position 1. current number 1 < n, so 1 -> 2 [2,3,0,1,-3] ^--You are here, current number is 3, you will jump forward to position 4. current number 3 >= n, so 3 -> 2 [2,2,0,1,-3] ^--You are here, current number is -3, you will jump backward to position 1. current number -3 < n, so -3 -> -2 [2,2,0,1,-2] ^--You are here, current number is 2, you will jump forward to position 3. current number 2 < n, so 2 -> 3 [2,3,0,1,-2] ^--You are here, current number is 1, you will jump forward to position 3. current number 1 < n, so 1 -> 2 [2,3,0,2,-2] ^--You are here, current number is -2, you will jump backward to position 2. current number -2 < n, so -2 -> -1 [2,3,0,2,-1] ^--You are here, current number is 0, you stay here. current number 0 < n, so 0 -> 1 [2,3,1,2,-1] ^--You are here, current number is 1, you will jump forward to position 3. current number 1 < n, so 1 -> 2 [2,3,2,2,-1] ^--You are here, current number is 2, you will jump forward to position 5. current number 2 < n, so 2 -> 3 [2,3,2,3,-1] exit ^--You are here, you reach to the exit. At the moment, arr[1] and arr[3] are equal to n. So, the output should be 2. ``` For `arr = [0,-1,-2,-3,-4], n = 4`, the output should be `2`. ``` Let's us jump fast ;-) [0,-1,-2,-3,-4] ^ [1,-1,-2,-3,-4] ^ [2,-1,-2,-3,-4] ^ [2, 0,-2,-3,-4] ^ [3, 0,-2,-3,-4] ^ [3, 0,-1,-3,-4] ^ [4, 0,-1,-3,-4] ^ [4, 0,-1,-2,-4] ^ [3, 0,-1,-2,-4] ^ [3, 0,-1,-2,-3] ^ [4, 0,-1,-2,-3] ^ [4, 0,-1,-1,-3] ^ [4, 1,-1,-1,-3] ^ [4, 2,-1,-1,-3] ^ [4, 2, 0,-1,-3] ^ [4, 3, 0,-1,-3] ^ [4, 3, 0, 0,-3] ^ [4, 3, 1, 0,-3] ^ [4, 3, 2, 0,-3] ^ [4, 3, 2, 1,-3] ^ [4, 3, 2, 2,-3] ^ [4, 3, 2, 2,-2] ^ [4, 4, 2, 2,-2] ^ [4, 4, 2, 2,-1] ^ [4, 4, 3, 2,-1] ^ [4, 4, 3, 2, 0] ^ [4, 4, 3, 3, 0] exit ^ At the moment, arr[0] and arr[1] are equal to n. So, the output should be 2. ``` For `arr = [0,-1,-2,-3,-4], n = 3`, the output should be `0`. ``` Let's jump fast ;-) [0,-1,-2,-3,-4] ^ [1,-1,-2,-3,-4] ^ [2,-1,-2,-3,-4] ^ [2, 0,-2,-3,-4] ^ [3, 0,-2,-3,-4] ^ [3, 0,-1,-3,-4] ^ [2, 0,-1,-3,-4] ^ [2, 0,-1,-2,-4] ^ [3, 0,-1,-2,-4] ^ [3, 0, 0,-2,-4] ^ [3, 1, 0,-2,-4] ^ [3, 2, 0,-2,-4] ^ [3, 2, 1,-2,-4] ^ [3, 2, 2,-2,-4] ^ [3, 2, 2,-1,-4] ^ [3, 3, 2,-1,-4] ^ [3, 3, 2, 0,-4] ^ [3, 3, 3, 0,-4] ^ [3, 3, 3, 0,-3] ^ [2, 3, 3, 0,-3] ^ [2, 3, 3, 1,-3] ^ [2, 3, 3, 2,-3] ^ [2, 3, 3, 2,-2] ^ [2, 2, 3, 2,-2] ^ [2, 2, 3, 2,-1] ^ [2, 2, 2, 2,-1] exit ^ At the moment, there is no element equal to n. So, the output should be 0. ``` [Base idea taken from [here](https://adventofcode.com/2017/day/5)]
reference
def jumping(arr, n): i = 0 while i < len(arr): x = arr[i] arr[i] += 1 if x < n else - 1 i += x return arr . count(n)
Simple Fun #387: Lonely Frog IV
5a274c9fc5e284a9f7000072
[ "Fundamentals" ]
https://www.codewars.com/kata/5a274c9fc5e284a9f7000072
6 kyu
In this Kata, you will be given two strings `a` and `b` and your task will be to return the characters that are not common in the two strings. For example: ```Haskell solve("xyab","xzca") = "ybzc" --The first string has 'yb' which is not in the second string. --The second string has 'zc' which is not in the first string. ``` Notice also that you return the characters from the first string concatenated with those from the second string. More examples in the tests cases. Good luck! Please also try [Simple remove duplicates](https://www.codewars.com/kata/5ba38ba180824a86850000f7)
reference
def solve(a, b): s = set(a) & set(b) return '' . join(c for c in a + b if c not in s)
Unique string characters
5a262cfb8f27f217f700000b
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5a262cfb8f27f217f700000b
7 kyu
Assume that you started to store items in progressively expanding square location, like this for the first 9 numbers: ``` 05 04 03 06 01 02 07 08 09 ``` And like this for the expanding to include up to the first 25 numbers: ``` 17 16 15 14 13 18 05 04 03 12 19 06 01 02 11 20 07 08 09 10 21 22 23 24 25 ``` You might easily notice that the first - and innermost - layer containes only one number (`01`), the second one - immediately around it - contains 8 numbers (number in the `02-09` range) and so on. Your task is to create a function that given a number `n` simply returns the number of layers required to store up to `n` (included). ```javascript layers(1) === 1 layers(5) === 2 layers(25) === 3 layers(30) === 4 layers(50) === 5 ``` ```python layers(1) == 1 layers(5) == 2 layers(25) == 3 layers(30) == 4 layers(50) == 5 ``` ```ruby layers(1) == 1 layers(5) == 2 layers(25) == 3 layers(30) == 4 layers(50) == 5 ``` ```crystal layers(1) == 1 layers(5) == 2 layers(25) == 3 layers(30) == 4 layers(50) == 5 ``` ```cpp layers(1) == 1 layers(5) == 2 layers(25) == 3 layers(30) == 4 layers(50) == 5 ``` ```csharp Layers(1) == 1 Layers(5) == 2 Layers(25) == 3 Layers(30) == 4 Layers(50) == 5 ``` **Fair warning:** you will always and only get positive integers, but be ready for bigger numbers in the tests! If you had fun with this, also try some follow up kata: [progressive spiral number branch](https://www.codewars.com/kata/progressive-spiral-number-branch/) and [progressive spiral number distance](https://www.codewars.com/kata/progressive-spiral-number-distance/). *[Base idea taken from [here](http://adventofcode.com/2017/day/3)]*
reference
from math import ceil, sqrt def layers(n): return ceil(sqrt(n)) / / 2 + 1
Progressive Spiral Number Position
5a254114e1ce0ecf6a000168
[ "Mathematics", "Number Theory", "Fundamentals" ]
https://www.codewars.com/kata/5a254114e1ce0ecf6a000168
7 kyu
In this Kata, you will be given a string with brackets and an index of an opening bracket and your task will be to return the index of the matching closing bracket. Both the input and returned index are 0-based **except in Fortran where it is 1-based**. An opening brace will always have a closing brace. Return `-1` if there is no answer (in Haskell, return `Nothing`; in Fortran, return `0`; in Go, return an error) ### Examples ```c solve("((1)23(45))(aB)", 0) = 10 // the opening brace at index 0 matches the closing brace at index 10 solve("((1)23(45))(aB)", 1) = 3 solve("((1)23(45))(aB)", 2) = -1 // there is no opening bracket at index 2, so return -1 solve("((1)23(45))(aB)", 6) = 9 solve("((1)23(45))(aB)", 11) = 14 solve("((>)|?(*'))(yZ)", 11) = 14 ``` ```python solve("((1)23(45))(aB)", 0) = 10 -- the opening brace at index 0 matches the closing brace at index 10 solve("((1)23(45))(aB)", 1) = 3 solve("((1)23(45))(aB)", 2) = -1 -- there is no opening bracket at index 2, so return -1 solve("((1)23(45))(aB)", 6) = 9 solve("((1)23(45))(aB)", 11) = 14 solve("((>)|?(*'))(yZ)", 11) = 14 ``` ```haskell solve("((1)23(45))(aB)", 0) = Just 10 -- the opening brace at index 0 matches the closing brace at index 10 solve("((1)23(45))(aB)", 2) = Nothing -- there is no opening bracket at index 2, so return "Nothing" instead of -1 ``` ```fortran solve("((1)23(45))(aB)", 1) ! => 11 (the opening brace at index 1 matches the closing brace at index 11) solve("((1)23(45))(aB)", 2) ! => 4 solve("((1)23(45))(aB)", 3) ! => 0 (there is no opening bracket at index 3, so return 0) solve("((1)23(45))(aB)", 7) ! => 10 solve("((1)23(45))(aB)", 12) ! => 15 solve("((>)|?(*'))(yZ)", 12) ! => 15 ``` Input will consist of letters, numbers and special characters, but no spaces. The only brackets will be `(` and `)`. More examples in the test cases. Good luck! ~~~if:fortran *NOTE: In Fortran, you may assume that the input string will not contain any leading/trailing whitespace.* ~~~
algorithms
def solve(s, idx): stack = [] for i, c in enumerate(s): if c == '(': stack += [i] if c == ')': if not stack: break if stack . pop() == idx: return i return - 1
Simple string indices
5a24254fe1ce0ec2eb000078
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/5a24254fe1ce0ec2eb000078
6 kyu
# Largest Rectangle in Background Imagine a photo taken to be used in an advertisement. The background on the left of the motive is whitish and you want to write some text on that background. So you scan the photo with a high resolution scanner and, for each line, count the number of pixels from the left that are sufficiently white and suitable for being written on. Your job is to find the area of the largest text box you can place on those pixels. Example: In the figure below, the whitish background pixels of the scanned photo are represented by asterisks. ``` ********************************* ********* ******* ****** ****** ****** ************** ************** ************** *************** ********************* ``` If you count the pixels on each line from the left you get the list (or array, depending on which language you are using) `[33, 9, 7, 6, 6, 6, 14, 14, 14, 15, 21]`. The largest reactangle that you can place on these pixels has an area of 70, and is represented by the dots in the figure below. ``` ********************************* ********* ******* ****** ****** ****** .............. .............. .............. ..............* ..............******* ``` Write a function that, given a list of the number whitish pixels on each line in the background, returns the area of the largest rectangle that fits on that background.
reference
# nice kata! def largest_rect(n): x, res, i = [], 0, 0 while i < len(n): if not x or n[i] >= n[x[- 1]]: x . append(i) i += 1 else: res = max(res, n[x . pop()] * (check(i, x))) while x: res = max(res, n[x . pop()] * (check(i, x))) return res def check(i, x): return i - x[- 1] - 1 if x else i
Largest rectangle in background
595db7e4c1b631ede30004c4
[ "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/595db7e4c1b631ede30004c4
5 kyu
Hi there! Welcome to "Building an Adaboost model with Sklearn (Introductory Machine Learning)". If you get stuck at any point I **strongly recommend** you read the relevant documentation: http://scikit-learn.org/stable/index.html This kata can be broken up into the following steps: 1. Import the relevant sklearn libraries (i.e. AdaBoostClassifier, train_test_split) 2. Create the "train_ada_boost" function (more details below) 3. Split the data (X) into a test set and a training set (you **MUST USE** sklearns train_test_split for this) 4. **TRAIN** an adaBoostClassfier (Once again, you **MUST USE** sklearn for this). 5. Your "train_ada_boost" function **must return a three element tuple** (more details below). The "train_ada_boost" function accepts the following arguments: * X -- This would normally be a dataset (but in this kata it is a 1D numpy array) * Target -- This is a 1D numpy array consisting of 1's and 0's. This argument is the set of values we are trying to predict with our model * estimators -- **KEYWORD ARGUMENT** if no argument is passed in the default value should be set to **3**. * random_seed -- **KEYWORD ARGUMENT** if no argument is passed in the default value should be set to **0**. Your function should return a 3 element tuple consisting of the following values **in this exact order**: * A **TRAINED** AdaBoostClassifer (return the actual model) * A test set (1D numpy array, which was built by sklearns test_train_split function) * A target array (1D numpy array, which was built by sklearns test_train_split function)) Details: * Your model should be trained using the specified number of estimators, with a random state equal to seed. * When splitting the data, be sure to set the random state equal to seed. * ALL other parameters not mentioned here for both 'test_train_split' and 'AdaBoost' should be set to default values. * Even though you are handling Numpy arrays there is no need to actually manipulate the arrays yourself (let sklearn to it for you!). Good Luck! *Note, in actual machine learning it is highly unlikely we would ever use AdaBoost with such a small number of estimators. However building models can be very time consuming and codewars.com has a 5000ms timeout.
algorithms
from sklearn . ensemble import AdaBoostClassifier from sklearn . model_selection import train_test_split def train_ada_boost(X, target, estimators=3, random_seed=0): x_train, x_test, target_train, target_test = train_test_split( X, target, random_state=random_seed) model = AdaBoostClassifier( n_estimators=estimators, random_state=random_seed) model . fit(x_train, target_train) return model, x_test, target_test
Building an Adaboost model with Sklearn (Introductory Machine Learning)
5a21bd361f7f7098e800000c
[ "Machine Learning", "Algorithms", "Tutorials", "Data Science" ]
https://www.codewars.com/kata/5a21bd361f7f7098e800000c
7 kyu
## Acknowledgments: I thank [yvonne-liu](https://www.codewars.com/users/yvonne-liu) for the idea and for the example tests :) ## Description: Encrypt this! You want to create secret messages which can be deciphered by the [Decipher this!](https://www.codewars.com/kata/decipher-this) kata. Here are the conditions: 1. Your message is a string containing space separated words. 2. You need to encrypt each word in the message using the following rules: * The first letter must be converted to its ASCII code. * The second letter must be switched with the last letter 3. Keepin' it simple: There are no special characters in the input. ## Examples: ```haskell encryptThis "Hello" == "72olle" encryptThis "good" == "103doo" encryptThis "hello world" == "104olle 119drlo" ``` ```python encrypt_this("Hello") == "72olle" encrypt_this("good") == "103doo" encrypt_this("hello world") == "104olle 119drlo" ``` ```ruby encrypt_this("Hello") == "72olle" encrypt_this("good") == "103doo" encrypt_this("hello world") == "104olle 119drlo" ``` ```groovy Kata.encryptThis("Hello") == "72olle" Kata.encryptThis("good") == "103doo" Kata.encryptThis("hello world") == "104olle 119drlo" ``` ```scala Encrypt.encryptThis("Hello") == "72olle" Encrypt.encryptThis("good") == "103doo" Encrypt.encryptThis("hello world") == "104olle 119drlo" ``` ```java Kata.encryptThis("Hello") => "72olle" Kata.encryptThis("good") => "103doo" Kata.encryptThis("hello world") => "104olle 119drlo" ``` ```javascript encryptThis("Hello") === "72olle" encryptThis("good") === "103doo" encryptThis("hello world") === "104olle 119drlo" ``` ```coffeescript encryptThis("Hello") === "72olle" encryptThis("good") === "103doo" encryptThis("hello world") === "104olle 119drlo" ``` ```c encrypt_this("Hello") == "72olle" encrypt_this("good") == "103doo" encrypt_this("hello world") == "104olle 119drlo" ``` ```cpp encrypt_this("Hello") == "72olle" encrypt_this("good") == "103doo" encrypt_this("hello world") == "104olle 119drlo" ``` ```go EncryptThis("Hello") == "72olle" EncryptThis("good") == "103doo" EncryptThis("hello world") == "104olle 119drlo" ``` ```csharp Kata.EncryptThis("Hello") == "72olle" Kata.EncryptThis("good") == "103doo" Kata.EncryptThis("hello world") == "104olle 119drlo" ``` ```vb Kata.EncryptThis("Hello") = "72olle" Kata.EncryptThis("good") = "103doo" Kata.EncryptThis("hello world") = "104olle 119drlo" ``` ```clojure (= (encrypt-this "Hello") "72olle") (= (encrypt-this "good" ) "103doo") (= (encrypt-this "hello world") "104olle 119drlo") ``` ```rust encrypt_this("Hello") == "72olle" encrypt_this("good") == "103doo" encrypt_this("hello world") == "104olle 119drlo" ``` ```lua solution.encrypt_this("Hello") == "72olle" solution.encrypt_this("good") == "103doo" solution.encrypt_this("hello world") == "104olle 119drlo" ``` ```php encryptThis("Hello") === "72olle" encryptThis("good") === "103doo" encryptThis("hello world") === "104olle 119drlo" ```
reference
def encrypt_this(text): result = [] for word in text . split(): # turn word into a list word = list(word) # replace first letter with ascii code word[0] = str(ord(word[0])) # switch 2nd and last letters if len(word) > 2: word[1], word[- 1] = word[- 1], word[1] # add to results result . append('' . join(word)) return ' ' . join(result)
Encrypt this!
5848565e273af816fb000449
[ "Fundamentals", "Strings", "Regular Expressions", "Arrays", "Ciphers", "Algorithms", "Cryptography", "Security" ]
https://www.codewars.com/kata/5848565e273af816fb000449
6 kyu
In this Kata, we are going to determine if the count of each of the characters in a string can be equal if we remove a single character from that string. For example: ``` solve('abba') = false -- if we remove any character, the count of each character will not be equal. solve('abbba') = true -- if we remove one b, the count of each character becomes 2. solve('aaaa') = true -- if we remove one character, the remaining characters have same count. solve('wwwf') = true -- if we remove f, the remaining letters have same count. ``` More examples in the test cases. Empty string is not tested. Good luck!
algorithms
from collections import Counter def solve(s): return any(len(set(Counter(s . replace(c, '', 1)). values())) == 1 for c in s)
String character frequency
5a1a514effe75fd63b0000f2
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/5a1a514effe75fd63b0000f2
6 kyu
Write a function ```find_replaced``` that -takes as an argument a shuffled list of integers from ```1``` to ```n``` (inclusive) where one element was deleted and another number between 1 and n (inclusive) was inserted in its place -returns a tuple ```(deleted_element, inserted_element)``` See examples for more details. Expected complexity: `O(n)`, expected memory usage `O(1)`. You will be pleased to know that most of the memory will be unavailable to you and that three values of `n` close to 5500000 will be tested. This is my first Kata; any feedback is welcome!
algorithms
def find_replaced(arr): """ s = len(arr) sum a_i - duplicate + missing = s * (s + 1) // 2 sum a_i^2 - dumplicate^2 + missing^2 = s * (s + 1) * (2 * s + 1) // 6 """ s = len(arr) a = s * (s + 1) / / 2 - sum(arr) b = s * (s + 1) * (2 * s + 1) / / 6 - sum(n * n for n in arr) d = (b - a * a) / / (2 * a) m = a + d return m, d
Untangle list deletion/insertion
5a179d4346d843ff1200000c
[ "Mathematics", "Performance", "Algorithms" ]
https://www.codewars.com/kata/5a179d4346d843ff1200000c
6 kyu
# Task Determine the client's membership level based on the invested `amount` of money and the given thresholds for membership levels. There are four membership levels (from highest to lowest): `Platinum, Gold, Silver, Bronze` The minimum investment is the threshold limit for `Bronze` membership. If the given amount is less than the `Bronze` treshold limit return `Not a member`. A client belongs to a membership level when his invested amount is greater than or equal the level's threshold amount. # Examples: ``` |--------+----------+------+--------+--------+--------------+------------------| | Amount | Platinum | Gold | Silver | Bronze | Result | Explanations | |--------+----------+------+--------+--------+--------------+------------------| | 7000 | 10000 | 8000 | 6000 | 4000 | Silver | Amount >= Silver | | 3000 | 10000 | 8000 | 6000 | 5000 | Not a member | Amount < Bronze | | 8000 | 12000 | 8000 | 7000 | 5000 | Gold | Amount >= Gold | |--------+----------+------+--------+--------+--------------+------------------| ``` # Restrictions 1. The first line of your code has to be `def membership(amount, platinum, gold, silver, bronze):` 2. Your code except for the firt line mustn't contain the words `platinum, gold, silver, bronze` or they reversed forms (e.g. `dlog`) or any string which contains these words or they reversed forms. (The check is **case-insensitive**.) 3. Must not contain: `+, %, {, }`. # Disclaimer This kata is about creativity not proper coding style. Your colleagues/boss won't like you if you make production code like this. :) #### Don't forget to rate the kata after you finish it. :) Happy coding! suic
reference
def membership(amount, platinum, gold, silver, bronze): ordered = reversed(sorted((v, k) for k, v in locals(). items() if k != 'amount')) return next((level . capitalize() for threshold, level in ordered if amount >= threshold), 'Not a member')
Membership (with restrictions)
5a21dcc48f27f2afa1000065
[ "Puzzles", "Restricted" ]
https://www.codewars.com/kata/5a21dcc48f27f2afa1000065
6 kyu
```if:python In this kata, you will take the keys and values of a `dict` and swap them around. ``` ```if:javascript In this kata, you will take the keys and values of an `object` and swap them around. ``` ```if:haskell In this kata, you will take the keys and values of a `Map` and swap them around. ``` You will be given a dictionary, and then you will want to return a dictionary with the old values as the keys, and list the old keys as values under their original keys. For example, given the dictionary: ```{'Ice': 'Cream', 'Age': '21', 'Light': 'Cream', 'Double': 'Cream'}```, you should return: ```{'Cream': ['Ice', 'Double', 'Light'], '21': ['Age']}``` # Notes: * The dictionary given will only contain strings * The dictionary given will not be empty * You do not have to sort the items in the lists
reference
def switch_dict(dic): result = {} for key, value in dic . items(): result . setdefault(value, []). append(key) return result
Swap items in a dictionary
5a21e090f28b824def00013c
[ "Fundamentals", "Arrays", "Logic" ]
https://www.codewars.com/kata/5a21e090f28b824def00013c
7 kyu
Take debugging to a whole new level: Given a string, remove every *single* bug. This means you must remove all instances of the word 'bug' from within a given string, *unless* the word is plural ('bugs'). For example, given 'obugobugobuoobugsoo', you should return 'ooobuoobugsoo'. Another example: given 'obbugugo', you should return 'obugo'. Note that all characters will be lowercase. Happy squishing!
reference
import re def debug(s): return re . sub(r'bug(?!s)', '', s)
Bug Squish!
5a21f943c5e284d4340000cb
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5a21f943c5e284d4340000cb
7 kyu
Following from the previous kata and taking into account how cool psionic powers are compare to the Vance spell system (really, the idea of slots to dumb down the game sucks, not to mention that D&D became a smash hit among geeks, so...), your task in this kata is to create a function that returns how many power points you get as a psion [because psions are the coolest, they allow for a lot of indepth tactic playing and adjusting for psychic warriors or wilders or other non-core classes would be just an obnoxious core]. Consider both [the psion power points/days table](http://www.dandwiki.com/wiki/SRD:Psion#Making_a_Psion) and [bonus power points](http://www.d20pfsrd.com/psionics-unleashed/classes/#Table_Ability_Modifiers_and_Bonus_Power_Points) to figure out the correct reply, returned as an integer; the usual interpretation is that bonus power points stop increasing after level 20, but for the scope of this kata, we will pretend they keep increasing as they did before. To compute the total, you will be provided, both as non-negative integers: * class level (assume they are all psion levels and remember the base power points/day halts after level 20) * manifesting attribute score (Intelligence, to be more precise) to determine the total, provided the score is high enough for the character to manifest at least one power. Some examples: ```javascript psionPowerPoints(1,0) === 0 psionPowerPoints(1,10) === 0 psionPowerPoints(1,11) === 2 psionPowerPoints(1,20) === 4 psionPowerPoints(21,30) === 448 ``` ```python psion_power_points(1,0) == 0 psion_power_points(1,10) == 0 psion_power_points(1,11) == 2 psion_power_points(1,20) == 4 psion_power_points(21,30) == 448 ``` ```ruby psion_power_points(1,0) == 0 psion_power_points(1,10) == 0 psion_power_points(1,11) == 2 psion_power_points(1,20) == 4 psion_power_points(21,30) == 448 ``` ```crystal psion_power_points(1,0) == 0 psion_power_points(1,10) == 0 psion_power_points(1,11) == 2 psion_power_points(1,20) == 4 psion_power_points(21,30) == 448 ``` ```csharp PsionPowerPoints(1,0) == 0 PsionPowerPoints(1,10) == 0 PsionPowerPoints(1,11) == 2 PsionPowerPoints(1,20) == 4 PsionPowerPoints(21,30) == 448 ``` *Note: I didn't explain things in detail and just pointed out to the table on purpose, as my goal is also to train the pattern recognition skills of whoever is going to take this challenges, so do not complain about a summary description. Thanks :)* In the same series: * [D&D Character generator #1: attribute modifiers and spells](https://www.codewars.com/kata/d-and-d-character-generator-number-1-attribute-modifiers-and-spells/) * [D&D Character generator #2: psion power points](https://www.codewars.com/kata/d-and-d-character-generator-number-2-psion-power-points/) * [D&D Character generator #3: carrying capacity](https://www.codewars.com/kata/d-and-d-character-generator-number-3-carrying-capacity/)
reference
def psion_power_points(l, s): return [0, 2, 6, 11, 17, 25, 35, 46, 58, 72, 88, 106, 126, 147, 170, 195, 221, 250, 280, 311, 343][min(l, 20)] + (s - 10) / / 2 * l / / 2 if l and s > 10 else 0
D&D Character generator #2: psion power points
596b1d44224071b9f5000010
[ "Fundamentals" ]
https://www.codewars.com/kata/596b1d44224071b9f5000010
6 kyu
**Background** You most probably know, that the *kilo* used by IT-People differs from the *kilo* used by the rest of the world. Whereas *kilo* in kB is (mostly) intrepreted as 1024 Bytes (especially by operating systems) the non-IT *kilo* denotes the factor 1000 (as in "1 kg is 1000g"). The same goes for the prefixes mega, giga, tera, peta and so on. To avoid misunderstandings (like your hardware shop selling you a 1E+12 Byte harddisk as 1 TB, whereas your Windows states that it has only 932 GB, because the shop uses factor 1000 whereas operating systems use factor 1024 by default) the International Electrotechnical Commission has proposed to use **kibibyte** for 1024 Byte.The according unit symbol would be **KiB**. Other Prefixes would be respectivly: ``` 1 MiB = 1024 KiB 1 GiB = 1024 MiB 1 TiB = 1024 GiB ``` **Task** Your task is to write a conversion function between the kB and the KiB-Units. The function receives as parameter a memory size including a unit and converts into the corresponding unit of the other system: ``` memorysizeConversion ( "10 KiB") -> "10.24 kB" memorysizeConversion ( "1 kB") -> "0.977 KiB" memorysizeConversion ( "10 TB") -> "9.095 TiB" memorysizeConversion ( "4.1 GiB") -> "4.402 GB" ``` **Hints** - the parameter always contains a (fractioned) number, a whitespace and a valid unit - units are case sensitive, valid units are **kB MB GB TB KiB MiB GiB TiB** - result must be rounded to 3 decimals (round half up,no trailing zeros) see examples above **Resources** If you want to read more on ...ibi-Units: https://en.wikipedia.org/wiki/Kibibyte
reference
def memorysize_conversion(memorysize): [value, unit] = memorysize . split(" ") kibis = ["KiB", "MiB", "GiB", "TiB"] kilos = ["kB", "MB", "GB", "TB"] if unit in kibis: return (str(round(float(value) * pow(1.024, kibis . index(unit) + 1), 3)) + " " + kilos[kibis . index(unit)]) else: return (str(round(float(value) / pow(1.024, kilos . index(unit) + 1), 3)) + " " + kibis[kilos . index(unit)])
Conversion between Kilobyte and KibiByte
5a115ff080171f9651000046
[ "Mathematics", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5a115ff080171f9651000046
6 kyu
You have been hired by a major MP3 player manufacturer to implement a new music compression standard. In this kata you will implement the ENCODER, and its companion kata deals with the <a href="https://www.codewars.com/kata/a-simple-music-decoder">DECODER</a>. It can be considered a harder version of <a href="https://www.codewars.com/kata/range-extraction">Range Extraction</a>. # Specification The input signal is represented as an array of integers. Several cases of regularities can be shortened. * A sequence of 2 or more identical numbers is shortened as ```number*count``` * A sequence of 3 or more consecutive numbers is shortened as ```first-last```. This is true for both ascending and descending order * A sequence of 3 or more numbers with the same interval is shortened as ```first-last/interval```. Note that the interval does NOT need a sign * Compression happens left to right # Examples * ```[1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]``` is compressed to ```"1,3-5,7-11,14,15,17-20"``` * ```[0, 2, 4, 5, 7, 8, 9]``` is compressed to ```"0-4/2,5,7-9"``` * ```[0, 2, 4, 5, 7, 6, 5]``` is compressed to ```"0-4/2,5,7-5"``` * ```[0, 2, 4, 5, 7, 6, 5, 5, 5, 5, 5]``` is compressed to ```"0-4/2,5,7-5,5*4"``` # Input A non-empty array of integers # Output A string of comma-separated integers and sequence descriptors
algorithms
def compress(raw): # initialize stack stack = [raw[0], raw[1]] # calculate inital difference between the first two elements! difference = stack[1] - stack[0] out = [] for value in raw[2:] + [float("inf")]: if (value - stack[- 1]) == difference: stack . append(value) elif len(stack) > 1 and difference == 0: out . append(f" { stack [ 0 ]} * { len ( stack )} ") stack = [value] elif len(stack) > 2: absolute_difference = str(abs(difference)) out . append( f" { stack [ 0 ]} - { stack [ - 1 ]}{ absolute_difference != '1' and '/' + absolute_difference or '' } ") difference = value - stack[- 1] stack = [value] else: if len(stack) == 2: out . append(stack[0]) difference = value - stack[- 1] stack = [stack[- 1], value] # Handling possible leftovers in the stack if not isinstance((f := stack[0]), float): out . append(f) return ',' . join(map(str, out))
A Simple Music Encoder
58db9545facc51e3db00000a
[ "Algorithms" ]
https://www.codewars.com/kata/58db9545facc51e3db00000a
5 kyu
### Making palindromes Many numbers can be formed into [palindromic numbers](https://en.wikipedia.org/wiki/Palindromic_number) (a number that remains the same when its digits are reversed) by applying the [**196-algorithm**](http://mathworld.wolfram.com/196-Algorithm.html): >Take any positive integer, reverse the digits, and add to the original number. Repeat until the result is a palindrome. ####Examples ######starting with 48: ``` 48 + 84 = 132 132 + 231 = 363 => Afters 2 iterations, we get the palindrome 363 ``` ######starting with 59: ``` 59 + 95 = 154 154 + 451 = 605 605 + 506 = 1111 ``` ######starting with 23: ``` 23 + 32 = 55 ``` ######starting with 55: ``` 55 + 55 = 110 110 + (0)11 = 121 => Leading zeros can be ignored; the reverse of 110 is 11 => We have to do at least one iteration; that is, we can't just return the original number even though it's already a palindrome ``` ######starting with 1: ``` 1 + 1 = 2 => One-digit numbers are always palindromes ``` ### Lychrel numbers A [Lychrel number](https://en.wikipedia.org/wiki/Lychrel_number) is a natural number that cannot form a palindrome using the 196-algorithm. That is, the algorithm will never stop since it won't ever generate a palindrome. For base 10 numbers, no number has mathematically been proven to be a Lychrel number. But there are numbers for which, despite millions of iterations, the 196-algorithm hasn't come to an end. The smallest number for which no solution has yet been found is **196**, giving the algorithm its name. ### Your task - Implement the 196-algorithm: Write a function that reverses a number **n **and adds to the original, until the result is a palindromic number (at least one iteration is required; don't just return the starting number if it's palindromic). - **n** will always be **between 1 and 9999**, inclusive. - Your code should be able to handle **Lychrel number candidates** (numbers for which the 196-algorithm won't stop in a reasonable amount of time). **Hint**: The number **1,186,060,307,891,929,990** takes **261 iterations** in order to end up in a 119-digit palindrome which is the record for every number successfully calculated by anyone so far. - The function should return the **resulting palindrome as an integer** or **-1** if the number is a Lychrel number candidate.
algorithms
def alg196(n): for _ in range(261): # Set a reasonable upper limit for iterations n += int(str(n)[:: - 1]) if str(n) == str(n)[:: - 1]: return n return - 1
The 196-algorithm and Lychrel numbers
55e079b1e00f75e1cd00013b
[ "Algorithms" ]
https://www.codewars.com/kata/55e079b1e00f75e1cd00013b
6 kyu
**Dear Mr overseer,** we are delighted that they have still managed to us in time. We have a big problem. Mankind will be extinct in the near future. The cause!? - wars, diseases, natural disasters, aliens ... figure it out. But that’s not the point! Vault-Tec has started to build vaults around the world. These are huge underground bunkers that allows us to survive. Your task is to select people and to populate with them these Vaults. We give you a population capacity and expect you to return the number of people that you want to put in these vaults. However, there are several conditions that must be adhered to: - A male overseer must always be present unless the capacity is `0` - If more than `50` dwellers move in, the overseer must have a wife (a "second overseer") - With an even number of dwellers, the total number of men and women should be equal - With an odd number of dwellers, the last free spot should be occupied by a woman The mankind bets on you. Good Luck **Your Vault-Tec Company** _**Vault-Tec Brochure**_ ## Examples ``` 5 people => 1 Mr. Overseer, 3 female dwellers, 1 male dweller 51 people => 1 Mr. Overseer, 1 Mrs. Overseer, 25 female dwellers, 24 male dwellers ``` ~~~if:csharp Your solution should return a list of the `Dweller` class instances according to the following spec: ``` public enum Gender { Mr, Mrs } public enum Position { overseer, none } public class Dweller { public Gender Sex { get; set; } public Position Work { get; set; } public Dweller() : this(Gender.Mr, Position.none) { } public Dweller(Gender sex) : this(sex, Position.none) { } public Dweller(Gender sex, Position work) { Sex = sex; Work = work; } } ``` ~~~ ___ *Imagine further "Vault experience":* - [Vault experience (1): Enough water for how many days?](https://www.codewars.com/kata/576d209bed916d2ea30000f7) - [Vault experience (2): Hack my terminal!](https://www.codewars.com/kata/57723e8010a0a66d1b0000a0) - Vault experience (3): Populate the vaults
reference
def populate_my_vault(n): if n < 2: return (n, 0, 0) half, odd = divmod(n, 2) crowded = n > 50 return 1 + crowded, half + odd - crowded, half - 1
Vault experience (3): Populate the vaults
57adadd36b34faea6b00031b
[ "Fundamentals" ]
https://www.codewars.com/kata/57adadd36b34faea6b00031b
6 kyu
Your task is to determine the top 3 place finishes in a pole vault competition involving several different competitors. This is isn't always so simple, and it is often a source of confusion for people who don't know the actual rules. Here's what you need to know: As input, you will receive an array of objects. Each object contains the respective competitor's name (as a string) and his/her results at the various bar heights (as an array of strings): [{name: "Sergey", results: ["", "O", "XO", "O", "XXO", "XXX", "", ""]}<br>{name: "Jan", results: ["", "", "", "O", "O", "XO", "XXO", "XXX"]}<br>{name: "Bruce", results: ["", "XO", "XXO", "XXX", "", "", "", ""]}<br>{name: "HerrWert", results: ["XXX", "", "", "", "", "", "", ""]}] In the array of strings described above, each string represents the vaulter's performance at a given height. The possible values are based on commonly used written notations on a pole vault scoresheet: <ul><li>An empty string indicates that the vaulter did not jump at this height for a variety of possible reasons ("passed" at this height, was temporarily called away to a different track and field event, was already eliminated from competition, or withdrew due to injury, for example).</li><li>An upper-case X in the string represents an unsuccessful attempt at the height. (As you may know, the vaulter is eliminated from the competition after three consecutive failed attempts.)</li><li>An upper-case O represents a successful attempt. If present at all, this will be the final character in the string, because it indicates that the vaulter has now successfully completed this height and is ready to move on.</li></ul> All vaulters will have a result string (though possibly empty) for every height involved in the competition, making it possible to match up the results of different vaulters with less confusion. Obviously, your first task is to determine who cleared the greatest height successfully. In other words, who has a "O" mark at a higher array element than any other competitor? You might want to work through the arrays from right to left to determine this. In the most straightforward case, you would first determine the winner, then second place, and finally third place by this simple logic. But what if there's a tie for one of these finishing places? Proceed as follows (according to American high school rules, at least): <ul><li>First trace backwards to find the greatest height that both vaulters cleared successfully. Then determine who had the fewest unsuccessful attempts at this height (i.e., the fewest X's in the string for this height). This person wins the tie-break.</li><li>But what if they're still tied with one another? <b> Do NOT continue to trace backwards through the heights!</b> Instead, compare their total numbers of unsuccessful attempts at <i>all</i> heights in the competition. The vaulter with the fewest total misses wins the tie-break.</li><li>But what if they're <i>still</i> tied? It depends on the finishing place:<ul><li>If it's for second or third place, the tie stands (i.e., is not broken).</li><li>But if it's for first place, there must be a jump-off (like overtime or penalty kicks in other sports) to break the tie and determine the winner. (This jump-off occurs - hypothetically - after your code runs and is thus not a part of this kata.)</li></ul></li></ul> Return a single object as your result. Each place-finish that is included in the results (including at least first place as property "1st" and possibly second and third places as properties "2nd" and "3rd") should have as its value the respective vaulter's name. In the event of a tie, the value of the property is the names of all tied vaulters, in alphabetical order, separated by commas, and followed by the notation "(jump-off)" if the tie is for first place or "(tie)" if it's for second or third place. Here are some possible outcomes to show you what I mean: <ul><li>{1st: "Jan", 2nd: "Sergey"; 3rd: "Bruce"} (These results correspond to the sample input data given above.)</li><li>{1st: "Julia", 2nd: "Madi, Emily (tie)}"</li><li>{1st: "Caleb, Dustin (jump-off)", 3rd: "Sam"}</li><li>{1st: "Meredith", 2nd: "Maddy", 3rd: "Cierra, Sara (tie)"}</li><li>{1st: "Alex, Basti, Max (jump-off)"}</li></ul> If you are familiar with the awarding of place finishes in sporting events or team standings in a league, then you know that there won't necessarily be a 2nd or 3rd place, because ties in higher places "bump" all lower places downward accordingly. One more thing: You really shouldn't change the array of objects that you receive as input. This represents the physical scoresheet. We need this "original document" to be intact, so that we can refer back to it to resolve a disputed result! Have fun with this! - - - - - Notes for the Python version: The rules for the Python version are the same as the original JavaScript version. The input and output will look the same as the JavaScript version. But, the JavaScript objects will be replaced by Python dictionaries. The JavaScript arrays will be replaced by Python lists. The Python function name was changed to include underscores as is customary with Python names. The example below should help clarify all of this. The input for the Python version will be a list containing dictionaries with the competitors' names and results. The names in the dictionaries are strings. The results are lists with a list of strings. And example follows. score_pole_vault([ {"name": "Linda", "results": ["XXO", "O","XXO", "O"]}, {"name": "Vickie", "results": ["O","X", "", ""]}, {"name": "Debbie", "results": ["XXO", "O","XO", "XXX"]}, {"name": "Michelle", "results": ["XO","XO","XXX",""]}, {"name": "Carol", "results": ["XXX", "","",""]} ]) The returned results should be in a dictionary with one to three elements. Examples of possible returned results: {'1st': 'Linda', '2nd': 'Debbie', '3rd': 'Michelle'} {'1st': 'Green, Hayes (jump-off)', '3rd': 'Garcia'} Note: Since first place was tied in this case, there is no 2nd place awarded. {'1st': 'Wilson', '2nd': 'Laurie', '3rd': 'Joyce, Moore (tie)'} I have tried to create test cases that have every concievable tie situation. Have fun with this version, as well!
reference
def score_pole_vault(vaulter_list): popytki = len(vaulter_list[0]["results"]) temp = {} res = {} for mas in vaulter_list: i = popytki - 1 while i >= 0 and mas [ "results" ][ i ]. find ( 'O' ) == - 1 : i -= 1 if i < 0 : n = 0 m = '' . join ( mas [ "results" ]). count ( 'X' ) else : n = mas [ "results" ][ i ]. count ( 'X' ) m = '' . join ( mas [ "results" ][: i ]). count ( 'X' ) new_key = ( popytki - i , n , m ) temp [ new_key ] = temp . get ( new_key , []) + [ mas [ "name" ]] k = iter ( sorted ( temp )) i = 0 while i < 3 : key = next ( k ) if i == 0 and len ( temp [ key ]) == 1 : res [ '1st' ] = temp [ key ][ 0 ] i += 1 elif i == 0 and len ( temp [ key ]) > 1 : res [ '1st' ] = ', ' . join ( sorted ( temp [ key ])) + ' (jump-off)' i += len ( temp [ key ]) elif i == 1 and len ( temp [ key ]) == 1 : res [ '2nd' ] = temp [ key ][ 0 ] i += 1 elif i == 1 and len ( temp [ key ]) > 1 : res [ '2nd' ] = ', ' . join ( sorted ( temp [ key ])) + ' (tie)' i += len ( temp [ key ]) elif i == 2 and len ( temp [ key ]) == 1 : res [ '3rd' ] = temp [ key ][ 0 ] i += 1 elif i == 2 and len ( temp [ key ]) > 1 : res [ '3rd' ] = ', ' . join ( sorted ( temp [ key ])) + ' (tie)' i += len ( temp [ key ]) return res
Determine Results of Pole Vault Competition
579294724be9121e4d00018f
[ "Arrays", "Sorting", "Fundamentals" ]
https://www.codewars.com/kata/579294724be9121e4d00018f
5 kyu
We all know about Roman Numerals, and if not, here's a nice [introduction kata](http://www.codewars.com/kata/5580d8dc8e4ee9ffcb000050). And if you were anything like me, you 'knew' that the numerals were not used for zeroes or fractions; but not so! I learned something new today: the [Romans did use fractions](https://en.wikipedia.org/wiki/Roman_numerals#Special_values) and there was even a glyph used to indicate zero. So in this kata, we will be implementing Roman numerals and fractions. Although the Romans used base 10 for their counting of units, they used base 12 for their fractions. The system used dots to represent twelfths, and an `S` to represent a half like so: * <sup>1</sup>/<sub>12</sub> = `.` * <sup>2</sup>/<sub>12</sub> = `:` * <sup>3</sup>/<sub>12</sub> = `:.` * <sup>4</sup>/<sub>12</sub> = `::` * <sup>5</sup>/<sub>12</sub> = `:.:` * <sup>6</sup>/<sub>12</sub> = `S` * <sup>7</sup>/<sub>12</sub> = `S.` * <sup>8</sup>/<sub>12</sub> = `S:` * <sup>9</sup>/<sub>12</sub> = `S:.` * <sup>10</sup>/<sub>12</sub> = `S::` * <sup>11</sup>/<sub>12</sub> = `S:.:` * <sup>12</sup>/<sub>12</sub> = `I` (as usual) Further, zero was represented by `N` ## Kata Complete the method that takes two parameters: an integer component in the range 0 to 5000 inclusive, and an optional fractional component in the range 0 to 11 inclusive. You must return a string with the encoded value. Any input values outside the ranges given above should return `"NaR"` (i.e. "Not a Roman" :-) ## Examples ```python roman_fractions(-12) #=> "NaR" roman_fractions(0, -1) #=> "NaR" roman_fractions(0, 12) #=> "NaR" roman_fractions(0) #=> "N" roman_fractions(0, 3) #=> ":." roman_fractions(1) #=> "I" roman_fractions(1, 0) #=> "I" roman_fractions(1, 5) #=> "I:.:" roman_fractions(1, 9) #=> "IS:." roman_fractions(1632, 2) #=> "MDCXXXII:" roman_fractions(5000) #=> "MMMMM" roman_fractions(5001) #=> "NaR" ```
algorithms
FRACTIONS = " . : :. :: :.: S S. S: S:. S:: S:.:" . split(" ") UNITS = " I II III IV V VI VII VIII IX" . split(" ") TENS = " X XX XXX XL L LX LXX LXXX XC" . split(" ") HUNDREDS = " C CC CCC CD D DC DCC DCCC CM" . split(" ") THOUSANDS = " M MM MMM MMMM MMMMM" . split(" ") def roman_fractions(n, f=0): return ("NaR" if n < 0 or n > 5000 or f < 0 or f > 11 else "N" if n + f == 0 else THOUSANDS[n / / 1000] + HUNDREDS[n % 1000 / / 100] + TENS[n % 100 / / 10] + UNITS[n % 10] + FRACTIONS[f])
Roman numerals, Zeroes and Fractions
55832eda1430b01275000059
[ "Algorithms" ]
https://www.codewars.com/kata/55832eda1430b01275000059
5 kyu
# Word Search Create a program to solve a word search puzzle. In word search puzzles you get a square of letters and have to find specific words in them. For example: ``` jefblpepre camdcimgtc oivokprjsm pbwasqroua rixilelhrs wolcqlirpc screeaumgr alxhpburyi jalaycalmp clojurermt ``` There are several programming languages hidden in the above square. Words can be hidden in all kinds of directions: left-to-right, right-to-left, vertical and diagonal. Create a program that given a puzzle and a list of words returns the location of the first and last letter of each word. You will be provided with a Point(x, y) class which will be used to display the points of the first and last words of the found words. You will be required to create a method `search` of class WordSearch that takes in a parameter `word` and searches through the provided grid for this word. It must return the Points of thw first and last letter of the word if found else return None. An e.g. ``` python puzzle = ('jefblpepre\n' 'camdcimgtc\n' 'oivokprjsm\n' 'pbwasqroua\n' 'rixilelhrs\n' 'wolcqlirpc\n' 'screeaumgr\n' 'alxhpburyi\n' 'jalaycalmp\n' 'clojurermt') >>> example = WordSearch(puzzle) >>> example.search('clojure') (Point(0, 9), Point(6, 9)) ``` From the above, from the word `clojure`, **c** can be found at point 0,9 and the last letter **e** can be found at poin 6, 9 Note: indexes start counting from 0.
reference
from collections import defaultdict class Point (object): def __init__(self, x, y): self . x = x self . y = y def __eq__(self, other): return self . x == other . x and self . y == other . y class WordSearch (object): def __init__(self, puzzle): self . grid = defaultdict(list) for r, row in enumerate(puzzle . split()): for c, col in enumerate(row): self . grid[col]. append((r, c)) def search(self, word): for sr, sc in self . grid[word[0]]: for dr, dc in [(1, 0), (0, 1), (- 1, 0), (0, - 1), (- 1, - 1), (1, 1), (- 1, 1), (1, - 1)]: rr, cc = sr, sc for l in word[1:]: rr, cc = rr + dr, cc + dc if (rr, cc) not in self . grid[l]: break else: return Point(sc, sr), Point(cc, rr)
Word Search Grid
58bcdf9a7288983803000042
[ "Algorithms", "Puzzles", "Fundamentals" ]
https://www.codewars.com/kata/58bcdf9a7288983803000042
5 kyu
Wikipedia: [Combination lock](https://en.wikipedia.org/wiki/Combination_lock#Single-dial_locks) > ***Customarily, a lock of this type is opened by rotating the dial clockwise to the first numeral, counterclockwise to the second, and so on in an alternating fashion until the last numeral is reached.*** --- In this kata, you must create a function that returns a list/array showing the initial `dial` after each rotation in the `combination`. * `dial` -> ***a square or diamond shaped list/array of any size greater than 2*** ```java # Square [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # Diamond (the above list rotated 45 degrees clockwise) [[1], [4, 2], [7, 5, 3], [8, 6], [9]] Note for java users: A static method DisplayDial.print(int[][] dial) has been preloaded for you to have a "rough" display of a dial in the console. You may use it as you wish. ``` ```python # Square [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # Diamond (the above list rotated 45 degrees clockwise) [[1], [4, 2], [7, 5, 3], [8, 6], [9]] ``` ```javascript // Square [[1, 2, 3], [4, 5, 6], [7, 8, 9]] // Diamond (the above array rotated 45 degrees clockwise) [[1], [4, 2], [7, 5, 3], [8, 6], [9]] ``` * `combination` -> ***a list/array of integers randomly chosen from the degrees in the picture below*** <div style="width: 345px; height: 139px;"> <a href="https://en.wikipedia.org/wiki/Azimuth#Navigation"> <img style="background-color: white;" src="https://i0.wp.com/gisgeography.com/wp-content/uploads/2015/04/azimuth.png"> </a> </div> <br> --- # Examples ```java Note for Java users: outputs type will be List<int[][]> but for the sake of simplicity, they are represented below as a list of lists of lists of integer. > combination_lock([[1, 2], [3, 4]], [45, 315, 135]) [ [[1], [3, 2], [4]] , [[2], [1, 4], [3]] , [[3], [4, 1], [2]] ] > combination_lock([[1], [3, 2], [4]], [225, 90, 270]) [ [[2, 4], [1, 3]] , [[3], [4, 1], [2]] , [[2], [1, 4], [3]] ] > combination_lock([[1, 2], [3, 4]], list(range(0, 316, 45))) [ [[1, 2], [3, 4]] , # 0 degrees [[1], [3, 2], [4]] , # 45 degrees [[3, 1], [4, 2]] , # 90 degrees [[3], [4, 1], [2]] , # 135 degrees [[4, 3], [2, 1]] , # 180 degrees [[4], [2, 3], [1]] , # 225 degrees [[2, 4], [1, 3]] , # 270 degrees [[2], [1, 4], [3]] ] # 315 degrees ``` ```python > combination_lock([[1, 2], [3, 4]], [45, 315, 135]) [[[1], [3, 2], [4]], [[2], [1, 4], [3]], [[3], [4, 1], [2]]] > combination_lock([[1], [3, 2], [4]], [225, 90, 270]) [[[2, 4], [1, 3]], [[3], [4, 1], [2]], [[2], [1, 4], [3]]] > combination_lock([[1, 2], [3, 4]], list(range(0, 316, 45))) [[[1, 2], [3, 4]], # 0 degrees [[1], [3, 2], [4]], # 45 degrees [[3, 1], [4, 2]], # 90 degrees [[3], [4, 1], [2]], # 135 degrees [[4, 3], [2, 1]], # 180 degrees [[4], [2, 3], [1]], # 225 degrees [[2, 4], [1, 3]], # 270 degrees [[2], [1, 4], [3]]] # 315 degrees ``` ```javascript > combinationLock([[1, 2], [3, 4]], [45, 315, 135]) [ [ [ 1 ], [ 3, 2 ], [ 4 ] ], [ [ 2 ], [ 1, 4 ], [ 3 ] ], [ [ 3 ], [ 4, 1 ], [ 2 ] ] ] > combinationLock([[1], [3, 2], [4]], [225, 90, 270]) [ [ [ 2, 4 ], [ 1, 3 ] ], [ [ 3 ], [ 4, 1 ], [ 2 ] ], [ [ 2 ], [ 1, 4 ], [ 3 ] ] ] > combinationLock([[1, 2], [3, 4]], [0, 45, 90, 135, 180, 225, 270, 315]) [ [ [ 1, 2 ], [ 3, 4 ] ], // 0 degrees [ [ 1 ], [ 3, 2 ], [ 4 ] ], // 45 degrees [ [ 3, 1 ], [ 4, 2 ] ], // 90 degrees [ [ 3 ], [ 4, 1 ], [ 2 ] ], // 135 degrees [ [ 4, 3 ], [ 2, 1 ] ], // 180 degrees [ [ 4 ], [ 2, 3 ], [ 1 ] ], // 225 degrees [ [ 2, 4 ], [ 1, 3 ] ], // 270 degrees [ [ 2 ], [ 1, 4 ], [ 3 ] ] ] // 315 degrees ``` --- ***If you have any feedback, feel free to leave a comment and/or raise an issue!***
reference
def rotate_square_clockwise_90(lst): return list(map(list, zip(* lst[:: - 1]))) def square_to_diamond_clockwise_45(lst): return [[lst[x - y][y] for y in range( len(lst)) if 0 <= x - y < len(lst)] for x in range(len(lst) * 2 - 1)] def diamond_to_square_cc_45(lst, sqLen): return [ [lst[x + y][sqLen - x - 1 if x + y >= sqLen else y] for y in range(sqLen)] for x in range(sqLen)] def combination_lock(dial, combination): pos, isD = {}, len(dial[0]) == 1 lst = dial if not isD else diamond_to_square_cc_45(dial, (len(dial) + 1) / / 2) # generate all positions, based on the first dial, adapting initial angle depending on the type of shape of the dial for n in range(0 - 45 * isD, 271, 90): pos[n % 360] = lst # accumulate squares # accumulate diamonds pos[(n + 45) % 360] = square_to_diamond_clockwise_45(lst) lst = rotate_square_clockwise_90(lst) return [pos[n] for n in combination]
Combination Lock
585b7bd53d357b12280003a3
[ "Fundamentals" ]
https://www.codewars.com/kata/585b7bd53d357b12280003a3
5 kyu
For this game of `BINGO`, you will receive a single array of 10 numbers from 1 to 26 as an input. Duplicate numbers within the array are possible. Each number corresponds to their alphabetical order letter (e.g. 1 = A. 2 = B, etc). Write a function where you will win the game if your numbers can spell `"BINGO"`. They do not need to be in the right order in the input array. Otherwise you will lose. Your outputs should be `"WIN"` or `"LOSE"` respectively. ~~~if:lambdacalc #### Preloaded `WIN, LOSE` are `Preloaded` for your convenience. You should return one of these values, as appropriate. #### Encodings purity: `LetRec` numEncoding: `Church` export constructors `nil, cons` for your `List` encoding ~~~
reference
def bingo(array): return "WIN" if {2, 7, 9, 14, 15}. issubset(set(array)) else "LOSE"
Bingo ( Or Not )
5a1ee4dfffe75f0fcb000145
[ "Games", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5a1ee4dfffe75f0fcb000145
7 kyu
Work out what number day of the year it is. ``` toDayOfYear([1, 1, 2000]) => 1 ``` The argument passed into the function is an array with the format `[D, M, YYYY]`, e.g. `[1, 2, 2000]` for February 1st, 2000 or `[22, 12, 1999]` for December 22nd, 1999. Don't forget to check for whether it's a [leap year](https://en.wikipedia.org/wiki/Leap_year)! Three criteria must be taken into account to identify leap years: - The year can be evenly divided by 4; - If the year can be evenly divided by 100, it is NOT a leap year, unless; - The year is also evenly divisible by 400. Then it is a leap year.
reference
def to_day_of_year(date): # Define the number of days in each month, accounting for leap years days_in_month = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] day, month, year = date # Check if it's a leap year and update February's days if ((year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)): days_in_month[2] = 29 # Calculate the day of the year day_of_year = sum(days_in_month[: month]) + day return day_of_year
Day of the Year
5a1ebe0d46d843454100004c
[ "Fundamentals" ]
https://www.codewars.com/kata/5a1ebe0d46d843454100004c
7 kyu
In this kata you will be given a sequence of the dimensions of rectangles ( sequence with width and length ) and circles ( radius - just a number ). Your task is to return a new sequence of dimensions, sorted ascending by area. For example, ```javascript const array = [ [4.23, 6.43], 1.23, 3.444, [1.342, 3.212] ]; // [ rectangle, circle, circle, rectangle ] sortByArea(array) => [ [ 1.342, 3.212 ], 1.23, [ 4.23, 6.43 ], 3.444 ] ``` ```python seq = [ (4.23, 6.43), 1.23, 3.444, (1.342, 3.212) ] # [ rectangle, circle, circle, rectangle ] sort_by_area(seq) => [ ( 1.342, 3.212 ), 1.23, ( 4.23, 6.43 ), 3.444 ] ``` ```ruby seq = [ [4.23, 6.43], 1.23, 3.444, [1.342, 3.212] ] # [ rectangle, circle, circle, rectangle ] sort_by_area(seq) => [ [1.342, 3.212], 1.23, [4.23, 6.43], 3.444 ] ``` ```haskell list = [ Rectangle 4.23 6.43, Circle 1.23, Circle 3.444, Rectangle 1.342 3.212 ] sortByArea list -> [ Rectangle 1.342 3.212, Circle 1.23, Rectangle 4.23 6.43, Circle 3.444 ] ``` ```c seq = { {4.23, 6.43}, {1.23, 0.0}, {3.444, 0.0}, {1.342, 3.212} } // { rectangle, circle, circle, rectangle } sort_by_area(seq) => { {1.342, 3.212}, {1.23, 0.0}, {4.23, 6.43}, {3.444, 0.0} } ``` ```cpp seq = { {4.23, 6.43}, {1.23, 0}, {3.444, 0}, {1.342, 3.212} } // { rectangle, circle, circle, rectangle } sort_by_area(seq) => { {1.342, 3.212}, {1.23, 0}, {4.23, 6.43}, {3.444, 0} } ``` ```ocaml shapes = [ Rectangle (4.23, 6.43); Circle 1.23; Circle 3.444; Rectangle (1.342, 3.212) ] sort_by_area shapes -> [ Rectangle (1.342, 3.212); Circle 1.23; Rectangle (4.23, 6.43); Circle 3.444 ] ``` ```factor { { 4.23 6.43 } 1.23 3.444 { 1.342 3.212 } } ! { rectangle circle circle rectangle } sort-by-area -> { { 1.342 3.212 } 1.23 { 4.23 6.43 } 3.444 } ``` ```lua seq = { {4.23, 6.43}, 1.23, 3.444, {1.342, 3.212} } -- { rectangle, circle, circle, rectangle } sort_by_area(seq) --> { {1.342, 3.212}, 1.23, {4.23, 6.43}, 3.444 } ``` ```rust seq = &[ Either::Left((4.23, 6.43)), Either::Right(1.23), Either::Right(3.444), Either::Left((1.342, 3.212)) ] // ( rectangle, circle, circle, rectangle ) sort_by_area(seq) => &[ Either::Left((1.342, 3.212)), Either::Right(1.23), Either::Left((4.23, 6.43)), Either::Right(3.444) ]; ``` This kata inspired by [Sort rectangles and circles by area](https://www.codewars.com/kata/sort-rectangles-and-circles-by-area/).
reference
def sort_by_area(seq): def func(x): if isinstance(x, tuple): return x[0] * x[1] else: return 3.14 * x * x return sorted(seq, key=func)
Sort rectangles and circles by area II
5a1ebc2480171f29cf0000e5
[ "Fundamentals", "Algorithms", "Sorting", "Mathematics", "Geometry" ]
https://www.codewars.com/kata/5a1ebc2480171f29cf0000e5
7 kyu
# Story It was nearly midnight when I staggered sleepily into the kitchen to get a glass of milk... I turned on the light and...&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style='font-size:2em;color:orange'>**AARRRGGHHHHH!!!!**</span> Damn bugs scatter in all directions! <img src="http://www.animatedimages.org/data/media/538/animated-cockroach-image-0010.gif" border="0" alt="animated-cockroach-image-0010" /> *I really hate cockroaches* # Kata Task The cockroaches run and hide in the numbered holes. Return array/list showing how many cockroaches end up in each hole (index matches the hole number) # Notes **About cockroaches:** * There are 0 or more cockroaches in the room * Cockroaches firstly run in a straight line in the direction they are facing * When they hit a wall they always turn LEFT and then they follow the wall until they can find a hole to crawl into! * Cockroaches do not bump into each other * There are no cockroaches outside the room **About the room:** * The room is a closed rectangle * There are 1 or more holes (conveniently numbered by a single digit) * Hole numbers are random but not repeated **Legend:** * `+`, `|`, `-` = walls of the room * `0` - `9` = holes for cockroaches to hide in * `U`,`D`,`L`,`R` = cockroaches with initial directions facing UP, DOWN, LEFT, RIGHT # Example Input: <pre> +----------------0---------------+ | | | | | U D | | L | | R | | L | | U 1 3 U D | | L R | | | +----------------2---------------+ </pre> Output: (always 10 elements) ``[1, 2, 2, 5, 0, 0, 0, 0, 0, 0]``
algorithms
def cockroaches(room): WALLS = {'L': '' . join(r[0] for r in room), 'D': room[- 1], 'R': '' . join(r[- 1] for r in room), 'U': room[0]} def hole(d, i=0): wall = WALLS[d][i:] if d in 'LD' else WALLS[d][: i + 1][:: - 1] if i else WALLS[d][:: - 1] for c in wall: if c . isdigit(): return int(c) return hole({'L': 'D', 'D': 'R', 'R': 'U', 'U': 'L'}[d]) # try next wall holes = [hole(d, r if d in 'LR' else c) for r, row in enumerate(room) for c, d in enumerate(row) if d in 'LDRU'] return [holes . count(i) for i in range(10)]
Cockroach Bug Scatter
59aac7a9485a4dd82e00003e
[ "Algorithms" ]
https://www.codewars.com/kata/59aac7a9485a4dd82e00003e
5 kyu
# Story `Joe Stoy`, in his book "Denotational Semantics", tells following story: ``` The decision which way round the digits run is, of course, mathematically trivial. Indeed, one early British computer had numbers running from right to left (because the spot on an oscilloscope tube runs from left to right, but in serial logic the least significant digits are dealt with first). Turing used to mystify audiences at public lectures when, quite by accident, he would slip into this mode even for decimal arithmetic, and write things like 73+42=16. The next version of the machine was made more conventional simply by crossing the x-deflection wires: this, however, worried the engineers, whose waveforms were all backwards. That problem was in turn solved by providing a little window so that the engineers(who tended to be behind the computer anyway) could view the oscilloscope screen from the back. [C. Strachey - private communication.] ``` You will play the role of the audience and judge on the truth value of `Turing's equations`. # Task You are given a string `s`. It's an equation such as `"a+b=c"`, where a, b, c are numbers made up of the digits 0 to 9. This includes possible leading or trailing zeros. The equations will not contain any spaces. Your task is to determine whether `s` is a valid Turing equation. Return `true` or `false`, respectively, in Turing's interpretation, i.e. the numbers being read backwards. Still struggling to understand the task? Look at the following examples ;-) # Examples For `s = "73+42=16"`, the output should be `true`. ``` 73 -> 37 42 -> 24 16 -> 61 37+24==61 ``` For `s = "5+8=13"`, the output should be `false`. ``` 5 -> 5 8 -> 8 13 -> 31 5+8!=31 ``` For `s = "10+20=30"`, the output should be `true`. ``` 10 -> 01 -> 1 20 -> 02 -> 2 30 -> 03 -> 3 1+2==3 ``` # Note - All the numbers a,b,c no more than 10 digits, excluding leading zeros(read backwards) - `s` contains only digits, "+" and "=", `"-","*" or "/"` will not appear in the string. - Happy Coding `^_^`
reference
import re def is_turing_equation(s): a, b, c = (int(n[:: - 1]) for n in re . split('[+=]', s)) return a + b == c
Simple Fun #384: Is Turing's Equation?
5a1e6323ffe75f71ae000026
[ "Fundamentals", "Strings", "Mathematics" ]
https://www.codewars.com/kata/5a1e6323ffe75f71ae000026
7 kyu
<div style='float: right; width: 180px; padding-left: 20px'> ![Alice](http://i.imgur.com/KuY6dIV.png "Foxy Alice")</div> ## Story Bob is sailing on his boat. The weather is very stormy and gloomy. Bob calls Alice. After some talk, Alice and Bob play a game on the phone. Alice has a piece of paper with coordinate mesh. She puts a point on the paper and then draws a triangle. She tells Bob the coordinates of the point and the coordinates of the triangle vertices. Bob has to guess whether the point is inside or outside the triangle. Help Bob to impress Alice! Your function must give a quick answer to the problem. ## Caveats Bob knows Alice too well... He is aware that she likes to be such a wily fox. * He knows she can try to trick him by giving him a list of coordinates that cannot form a triangle. * He expects her to choose some points on a triangle side (which is neither inside nor outside!) too, so your function must check for that as well. * Alice has a thin pencil, but the line still has some minimal thickness. Because of that, points which are very close to a line are considered belonging to that line. ## Arguments * `triangle` is a list of three coordinate pairs on a 2D plane: e. g. [[0, 0], [5, 5], [5, 0]]. * `point` is a pair of coordinates: e. g. [3, 1] ## Return * Return `1` for a point inside the trianle or `-1` for a point outside the triangle. * If the point belongs to any side of the triangle, return `0`. * If the coordinates given for the triangle are invalid, raise an exception. ## Examples * `triangle = [[0, 0], [5, 5], [5, 0]]` and `point = [3, 1]` return `1`, because the point is inside the triangle. * `triangle = [[0, 0], [5, 5], [5, 0]]` and `point = [6, 6]` return `-1`, because the point is outside the triangle. * `triangle = [[0, 0], [5, 5], [5, 0]]` and `point = [2, 0]` return `0`, because the point is on a side of the triangle. * `triangle = [[0, 0], [5, 5], [2, 2]]` and `point = [2, 0]` results in exception, because it is not a valid triangle.
algorithms
def triangle_area(a, b, c): (xa, ya), (xb, yb), (xc, yc) = a, b, c return abs(xa * (yb - yc) + xb * (yc - ya) + xc * (ya - yb)) def point_vs_triangle(point, triangle): area = triangle_area(* triangle) assert area > 1e-9 a, b, c = triangle pab, pbc, pca = triangle_area(point, a, b), triangle_area( point, b, c), triangle_area(point, c, a) if abs(pab + pbc + pca - area) > 1e-9: return - 1 else: return bool(pab > 1e-9 and pbc > 1e-9 and pca > 1e-9)
[Geometry B -1] Point in a triangle?
55675eb82a2ca0bcd300006d
[ "Geometry", "Algorithms" ]
https://www.codewars.com/kata/55675eb82a2ca0bcd300006d
5 kyu
Removed due to copyright infringement. <!--- # Task Consider a `bishop`, a `knight` and a `rook` on an `n Γ— m` chessboard. They are said to form a `triangle` if each piece attacks exactly one other piece and is attacked by exactly one piece. Calculate the number of ways to choose positions of the pieces to form a triangle. Note that the bishop attacks pieces sharing the common diagonal with it; the rook attacks in horizontal and vertical directions; and, finally, the knight attacks squares which are two squares horizontally and one square vertically, or two squares vertically and one square horizontally away from its position. ![](https://codefightsuserpics.s3.amazonaws.com/tasks/chessTriangle/img/moves.png?_tm=1473934712872) # Example For `n = 2 and m = 3`, the output should be `8`. ![](https://codefightsuserpics.s3.amazonaws.com/tasks/chessTriangle/img/combinations.png?_tm=1473934713038) # Input/Output - `[input]` integer `n` Constraints: `1 ≀ n ≀ 40.` - `[input]` integer `m` Constraints: `1 ≀ m ≀ 40, 3 ≀ n x m`. - `[output]` an integer --->
games
def chess_triangle(n, m): return sum(8 * (n - x + 1) * (m - y + 1) for dims in {(3, 4), (3, 3), (2, 4), (2, 3)} for x, y in [dims, dims[:: - 1]] if x <= n and y <= m)
Chess Fun #7: Chess Triangle
5897eebff3d21495a70000df
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/5897eebff3d21495a70000df
5 kyu