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
You're given a string containing a sequence of words separated with whitespaces. Let's say it is a sequence of patterns: a name and a corresponding number - like this: ```"red 1 yellow 2 black 3 white 4"``` You want to turn it into a different **string** of objects you plan to work with later on - like this: ```"[{name : 'red', id : '1'}, {name : 'yellow', id : '2'}, {name : 'black', id : '3'}, {name : 'white', id : '4'}]"``` Doing this manually is a pain. So you've decided to write a short function that would make the computer do the job for you. Keep in mind, the pattern isn't necessarily a word and a number. Consider anything separeted by a whitespace, just don't forget: an array of objects with two elements: name and id. As a result you'll have a string you may just copy-paste whenever you feel like defining a list of objects - now without the need to put in names, IDs, curly brackets, colon signs, screw up everything, fail searching for a typo and begin anew. This might come in handy with large lists.
reference
import re def words_to_object(s): return "[" + re . sub("([^ ]+) ([^ ]+)", r"{name : '\1', id : '\2'},", s). strip(',') + "]"
Creating a string for an array of objects from a set of words
5877786688976801ad000100
[ "Fundamentals", "Strings", "Regular Expressions" ]
https://www.codewars.com/kata/5877786688976801ad000100
6 kyu
Because my other two parts of the serie were pretty well received I decided to do another part. # Puzzle Tiles You will get two **Integer** `n`(width) and `m` (height) and your task is to draw following pattern. Each line is seperated with `'\n'`. - Both integers are equal or greater than 1. No need to check for invalid parameters. - There are no whitespaces at the end of each line. For example, for `width = 4` and `height = 3`, you should draw the following pattern: ``` _( )__ _( )__ _( )__ _( )__ _| _| _| _| _| (_ _ (_ _ (_ _ (_ _ (_ |__( )_|__( )_|__( )_|__( )_| |_ |_ |_ |_ |_ _) _ _) _ _) _ _) _ _) |__( )_|__( )_|__( )_|__( )_| _| _| _| _| _| (_ _ (_ _ (_ _ (_ _ (_ |__( )_|__( )_|__( )_|__( )_| ``` For more informations take a look in the test cases! ### Serie: ASCII Fun [ASCII Fun #1: X-Shape](https://www.codewars.com/kata/ascii-fun-number-1-x-shape) [ASCII Fun #2: Funny Dots](https://www.codewars.com/kata/ascii-fun-number-2-funny-dots) [ASCII Fun #3: Puzzle Tiles](https://www.codewars.com/kata/ascii-fun-number-3-puzzle-tiles) [ASCII Fun #4: Build a pyramid](https://www.codewars.com/kata/ascii-fun-number-4-build-a-pyramid)
algorithms
def puzzle_tiles(width, height): def f(): yield ' ' + ' _( )__' * width for i in range(height): if i % 2 == 0: yield ' _|' + ' _|' * width yield '(_' + ' _ (_' * width yield ' |' + '__( )_|' * width else: yield ' |_' + ' |_' * width yield ' _)' + ' _ _)' * width yield ' |' + '__( )_|' * width return '\n' . join(f())
ASCII Fun #3: Puzzle Tiles
5947d86e07693bcf000000c4
[ "ASCII Art" ]
https://www.codewars.com/kata/5947d86e07693bcf000000c4
6 kyu
Motivation --------- When compressing sequences of symbols, it is useful to have many equal symbols follow each other, because then they can be encoded with a run length encoding. For example, RLE encoding of `"aaaabbbbbbbbbbbcccccc"` would give something like `4a 11b 6c`. (Look [here](http://www.codewars.com/kata/run-length-encoding/) for learning more about the run-length-encoding.) Of course, RLE is interesting only if the string contains many identical consecutive characters. But what bout human readable text? Here comes the Burrows-Wheeler-Transformation. Transformation ------------- There even exists a transformation, which brings equal symbols closer together, it is called the **Burrows-Wheeler-Transformation**. The forward transformation works as follows: Let's say we have a sequence with length n, first write every shift of that string into a *n x n* matrix: ``` Input: "bananabar" b a n a n a b a r r b a n a n a b a a r b a n a n a b b a r b a n a n a a b a r b a n a n n a b a r b a n a a n a b a r b a n n a n a b a r b a a n a n a b a r b ``` Then we sort that matrix by its rows. The output of the transformation then is the **last column** and the **row index** in which the original string is in: ``` .-. a b a r b a n a n a n a b a r b a n a n a n a b a r b a r b a n a n a b b a n a n a b a r <- 4 b a r b a n a n a n a b a r b a n a n a n a b a r b a r b a n a n a b a '-' Output: ("nnbbraaaa", 4) ``` ```if:java To handle the two kinds of output data, we will use the preloaded class `BWT`, whose contract is the following: public class BWT { public String s; public int n; public BWT(String s, int n) @Override public String toString() @Override public boolean equals(Object o) @Override public int hashCode() } ``` Of course we want to restore the original input, therefore you get the following hints: 1. The output contains the last matrix column. 2. The first column can be acquired by sorting the last column. 3. **For every row of the table:** Symbols in the first column follow on symbols in the last column, in the same way they do in the input string. 4. You don't need to reconstruct the whole table to get the input back. Goal ---- The goal of this Kata is to write both, the `encode` and `decode` functions. Together they should work as the identity function on lists. (*Note:* For the empty input, the row number is ignored.) Further studies -------------- You may have noticed that symbols are not always consecutive, but just in proximity, after the transformation. If you're interested in how to deal with that, you should have a look at [this Kata](http://www.codewars.com/kata/move-to-front-encoding/).
algorithms
def encode(s): lst = sorted(s[i or len(s):] + s[: i or len(s)] for i in reversed(range(len(s)))) return '' . join(ss[- 1] for ss in lst), s and lst . index(s) or 0 def decode(s, n): out, lst = [], sorted((c, i) for i, c in enumerate(s)) for _ in range(len(s)): c, n = lst[n] out . append(c) return '' . join(out)
Burrows-Wheeler-Transformation
54ce4c6804fcc440a1000ecb
[ "Lists", "Puzzles", "Algorithms" ]
https://www.codewars.com/kata/54ce4c6804fcc440a1000ecb
4 kyu
If you like Taco Bell, you will be familiar with their signature doritos locos taco. They're very good. Why can't everything be a taco? We're going to attempt that here, turning every word we find into the taco bell recipe with each ingredient. We want to input a word as a string, and return a list representing that word as a taco. ***Key*** all vowels (except 'y') = beef t = tomato l = lettuce c = cheese g = guacamole s = salsa ***NOTE*** We do not care about case here. 'S' is therefore equivalent to 's' in our taco. Ignore all other letters; we don't want our taco uneccesarily clustered or else it will be too difficult to eat. Note that no matter what ingredients are passed, our taco will always have a shell.
reference
import re TACODICT = { 't': 'tomato', 'l': 'lettuce', 'c': 'cheese', 'g': 'guacamole', 's': 'salsa' } def tacofy(word): return ['shell'] + [TACODICT . get(c, 'beef') for c in re . sub('[^aeioutlcgs]+', '', word . lower())] + ['shell']
Turn any word into a beef taco
59414b46d040b7b8f7000021
[ "Fundamentals" ]
https://www.codewars.com/kata/59414b46d040b7b8f7000021
7 kyu
Find the difference between two collections. The difference means that either the character is present in one collection or it is present in other, but not in both. Return a sorted list with the difference. The collections can contain any character and can contain duplicates. ## Example ``` A = [a, a, t, e, f, i, j] B = [t, g, g, i, k, f] difference = [a, e, g, j, k] ```
algorithms
def diff(a, b): return sorted(set(a) ^ set(b))
Difference between two collections
594093784aafb857f0000122
[ "Fundamentals", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/594093784aafb857f0000122
7 kyu
Given an array of numbers, return a string made up of four parts: * a four character 'word', made up of the characters derived from the first two and last two numbers in the array. order should be as read left to right (first, second, second last, last), * the same as above, post sorting the array into ascending order, * the same as above, post sorting the array into descending order, * the same as above, post converting the array into ASCII characters and sorting alphabetically. The four parts should form a single string, each part separated by a hyphen (`-`). Example format of solution: `"asdf-tyui-ujng-wedg"` ### Examples ``` [111, 112, 113, 114, 115, 113, 114, 110] --> "oprn-nors-sron-nors" [66, 101, 55, 111, 113] --> "Beoq-7Boq-qoB7-7Boq" [99, 98, 97, 96, 81, 82, 82] --> "cbRR-QRbc-cbRQ-QRbc" ```
reference
def extract(arr): return '' . join(arr[: 2] + arr[- 2:]) def sort_transform(arr): arr = list(map(chr, arr)) w1 = extract(arr) arr . sort() w2 = extract(arr) return f' { w1 } - { w2 } - { w2 [:: - 1 ]} - { w2 } '
Sort and Transform
57cc847e58a06b1492000264
[ "Fundamentals", "Strings", "Arrays", "Sorting", "Algorithms" ]
https://www.codewars.com/kata/57cc847e58a06b1492000264
7 kyu
# Introduction There is a war and nobody knows - the alphabet war! There are two groups of hostile letters. The tension between left side letters and right side letters was too high and the war began. The letters have discovered a new unit - a priest with Wo lo looooooo power. <img src="https://i.imgur.com/AUaPiip.jpg"/> # Task Write a function that accepts `fight` string consists of only small letters and return who wins the fight. When the left side wins return `Left side wins!`, when the right side wins return `Right side wins!`, in other case return `Let's fight again!`. The left side letters and their power: ``` w - 4 p - 3 b - 2 s - 1 t - 0 (but it's priest with Wo lo loooooooo power) ``` The right side letters and their power: ``` m - 4 q - 3 d - 2 z - 1 j - 0 (but it's priest with Wo lo loooooooo power) ``` The other letters don't have power and are only victims. The priest units `t` and `j` change the adjacent letters from hostile letters to friendly letters with the same power. ``` mtq => wtp wjs => mjz ``` A letter with adjacent letters `j` and `t` is not converted i.e.: ``` tmj => tmj jzt => jzt ``` The priests (`j` and `t`) do not convert the other priests ( `jt => jt `). # Example ```csharp AlphabetWar("z") //=> "z" => "Right side wins!" AlphabetWar("tz") //=> "ts" => "Left side wins!" AlphabetWar("jz") //=> "jz" => "Right side wins!" AlphabetWar("zt") //=> "st" => "Left side wins!" AlphabetWar("azt") //=> "ast" => "Left side wins!" AlphabetWar("tzj") //=> "tzj" => "Right side wins!" ``` ```javascript alphabetWar("z") //=> "z" => "Right side wins!" alphabetWar("tz") //=> "ts" => "Left side wins!" alphabetWar("jz") //=> "jz" => "Right side wins!" alphabetWar("zt") //=> "st" => "Left side wins!" alphabetWar("azt") //=> "ast" => "Left side wins!" alphabetWar("tzj") //=> "tzj" => "Right side wins!" ``` ```python alphabet_war("z") #=> "z" => "Right side wins!" alphabet_war("tz") #=> "ts" => "Left side wins!" alphabet_war("jz") #=> "jz" => "Right side wins!" alphabet_war("zt") #=> "st" => "Left side wins!" alphabet_war("azt") #=> "ast" => "Left side wins!" alphabet_war("tzj") #=> "tzj" => "Right side wins!" ``` ```c alphabet_war("z") //=> "z" => "Right side wins!" alphabet_war("tz") //=> "ts" => "Left side wins!" alphabet_war("jz") //=> "jz" => "Right side wins!" alphabet_war("zt") //=> "st" => "Left side wins!" alphabet_war("azt") //=> "ast" => "Left side wins!" alphabet_war("tzj") //=> "tzj" => "Right side wins!" ``` ```java AlphabetWars.woLoLoooooo("z") //=> "z" => "Right side wins!" AlphabetWars.woLoLoooooo("tz") //=> "ts" => "Left side wins!" AlphabetWars.woLoLoooooo("jz") //=> "jz" => "Right side wins!" AlphabetWars.woLoLoooooo("zt") //=> "st" => "Left side wins!" AlphabetWars.woLoLoooooo("azt") //=> "ast" => "Left side wins!" AlphabetWars.woLoLoooooo("tzj") //=> "tzj" => "Right side wins!" ``` # Alphabet war Collection <table border="0" cellpadding="0" cellspacing="0"> <tr> <td ><a href="https://www.codewars.com/kata/59377c53e66267c8f6000027" target="_blank">Alphabet war </a></td> </tr> <tr> <td ><a href="https://www.codewars.com/kata/5938f5b606c3033f4700015a" target="_blank">Alphabet war - airstrike - letters massacre</a></td> </tr> <tr> <td ><a href="https://www.codewars.com/kata/alphabet-wars-reinforces-massacre" target="_blank">Alphabet wars - reinforces massacre</a></td> </tr> <tr> <td ><a href="https://www.codewars.com/kata/59437bd7d8c9438fb5000004" target="_blank">Alphabet wars - nuclear strike</a></td> </tr> <tr> <td ><a href="https://www.codewars.com/kata/59473c0a952ac9b463000064" target="_blank">Alphabet war - Wo lo loooooo priests join the war</a></td> </tr> </table>
reference
SWAP = {'j': {'w': 'm', 'p': 'q', 'b': 'd', 's': 'z'}, 't': {'m': 'w', 'q': 'p', 'd': 'b', 'z': 's'}} def alphabet_war(fight): s = 0 for l, c, r in zip(' ' + fight, fight, fight[1:] + ' '): if l + r not in 'tjt': c = SWAP . get(l, {}). get(c, c) c = SWAP . get(r, {}). get(c, c) s += {'w': 4, 'p': 3, 'b': 2, 's': 1, 'm': - 4, 'q': - 3, 'd': - 2, 'z': - 1}. get(c, 0) return ["Right side wins!", "Left side wins!"][s > 0] if s else "Let's fight again!"
Alphabet war - Wo lo loooooo priests join the war
59473c0a952ac9b463000064
[ "Strings", "Regular Expressions" ]
https://www.codewars.com/kata/59473c0a952ac9b463000064
5 kyu
*This is the second Kata in the Ciphers series. This series is meant to test our coding knowledge.* ## Ciphers #2 - The reversed Cipher This is a lame method I use to write things such that my friends don't understand. It's still fairly readable if you think about it. ## How this cipher works First, you need to reverse the string. Then, the last character in the original string (the first character in the reversed string) needs to be moved to the back. Words will be separated by spaces, and punctuation marks can be counted as part of the word. ## Example ```javascript encode("Hello World!"); // => "lleHo dlroW!" ``` This is because `"Hello"` reversed is `"olleH"` and `"o"` is moved to the back, and so on. The exclamation mark is considered to be part of the word `"World"`. Have fun (en)coding!
reference
def encode(s): return ' ' . join(w[- 2:: - 1] + w[- 1] for w in s . split())
Ciphers #2 - The reversed Cipher
59474c656ff02b21e20000fc
[ "Fundamentals" ]
https://www.codewars.com/kata/59474c656ff02b21e20000fc
6 kyu
In this exercise, you will have to create a function named tiyFizzBuzz. This function will take on a string parameter and will return that string with some characters replaced, depending on the value: - If a letter is a upper case consonants, replace that character with "Iron". - If a letter is a lower case consonants or a non-alpha character, do nothing to that character - If a letter is a upper case vowel, replace that character with "Iron Yard". - If a letter is a lower case vowel, replace that character with "Yard". Ready?
reference
def tiy_fizz_buzz(s): return "" . join(("Iron " * c . isupper() + "Yard" * (c . lower() in "aeiou")). strip() or c for c in s)
TIY-FizzBuzz
5889177bf148eddd150002cc
[ "Fundamentals" ]
https://www.codewars.com/kata/5889177bf148eddd150002cc
7 kyu
# Find the gatecrashers on CocoBongo parties CocoBongo is a club with very nice parties. However, you only can get inside if you know at least one other guest. Unfortunately, some gatecrashers can appear at those parties. The gatecrashers do not know any other party member and should not be at our amazing party! We will give to you a collection with all party members and a collection with some guests and their invitations. Your mission is to find out those gatecrashers and give us a sorted array of them. Note that invitations are undirectional relations, so if guest `A` invites `B`, we can consider that `B` also knows `A`. Once the relation `(A, {B})` appears on the invitations collection, the reverse relation `(B, {A})` may or may not appear in the input. You need to take care of that. ## Example ```python party_members = [0,1,2,3,4] invitations = [ (0, [1,2]), (2, [3]) ] gatecrashers = [4] ``` ## Explanation We have `invitations = [ (0, [1,2]), (2, [3]) ]`. Guest `0` has invited guests `1` and `2`; also, guest `2` has invited guest `3`. However, noone has invited guest `4`, so he is a gatecrasher.
reference
def find_gatecrashers(people, invitations): crashersSet = {elt for i, li in invitations for elt in [i] + li} return [p for p in people if p not in crashersSet]
Find the gatecrashers on CocoBongo parties
5945fe7d9b33194f960000df
[ "Arrays", "Performance", "Fundamentals", "Graph Theory" ]
https://www.codewars.com/kata/5945fe7d9b33194f960000df
6 kyu
Every Friday and Saturday night, farmer counts amount of sheep returned back to his farm (sheep returned on Friday stay and don't leave for a weekend). Sheep return in groups each of the days -> you will be given two arrays with these numbers (one for Friday and one for Saturday night). Entries are always positive ints, higher than zero. Farmer knows the total amount of sheep, this is a third parameter. You need to return the amount of sheep lost (not returned to the farm) after final sheep counting on Saturday. Example 1: Input: {1, 2}, {3, 4}, 15 --> Output: 5 Example 2: Input: {3, 1, 2}, {4, 5}, 21 --> Output: 6 Good luck! :-)
reference
def lost_sheep(friday, saturday, total): return total - (sum(friday) + sum(saturday))
Count all the sheep on farm in the heights of New Zealand
58e0f0bf92d04ccf0a000010
[ "Fundamentals", "Mathematics", "Algorithms", "Algebra" ]
https://www.codewars.com/kata/58e0f0bf92d04ccf0a000010
7 kyu
Construct a function 'coordinates', that will return the distance between two points on a cartesian plane, given the x and y coordinates of each point. There are two parameters in the function, ```p1``` and ```p2```. ```p1``` is a list ```[x1,y1]``` where ```x1``` and ```y1``` are the x and y coordinates of the first point. ```p2``` is a list ```[x2,y2]``` where ```x2``` and ```y2``` are the x and y coordinates of the second point. The distance between the two points should be rounded to the `precision` decimal if provided, otherwise to the nearest integer.
reference
def coordinates(p1, p2, precision=0): return round(sum((b - a) * * 2 for a, b in zip(p1, p2)) * * .5, precision)
Distance Between 2 Points on a Cartesian Plane
5944f3f8d7b6a5748d000233
[ "Mathematics", "Algebra", "Fundamentals" ]
https://www.codewars.com/kata/5944f3f8d7b6a5748d000233
7 kyu
Write a function that always returns `5` Sounds easy right? Just bear in mind that you can't use any of the following characters: `0123456789*+-/` Good luck :)
reference
def unusual_five(): return len("five!")
5 without numbers !!
59441520102eaa25260000bf
[ "Restricted", "Fundamentals", "Puzzles" ]
https://www.codewars.com/kata/59441520102eaa25260000bf
8 kyu
Most substitution ciphers involve the use of a shift value. The simplest ones apply the same shift value to all letters. Some are slightly more sophisticated, but there is still a consistent rule governing the shift. This kata is different. Your task here is to create a random substitution cipher. There is no input to the function. The output from your code should be an object in which the keys are simply all the letters of the English alphabet, in lower case and in alphabetical order. The value of each key will also be a lower-case letter, which you should select at random. Because it is random, it is also possible that the original letter and the substituted letter will be the same, as you can see in the following example of possible output: {"a":"c", "b":"p", "c":"j", "d":"a", "e":"v", "f":"d", "g":"g", "h":"u", "i":"l", "j":"t", "k":"n", "l":"w", "m":"m", "n":"o", "o":"i", "p":"s", "q":"f", "r":"r", "s":"x", "t":"b", "u":"h", "v":"y", "w":"q", "x":"e", "y":"k", "z":"z"} The output from your solution will be tested for a high probability of randomness. Special thanks to @halcarleton and @Vaults for showing me how to do this. There might be a clever way to cheat, but where's the fun in that?
reference
from random import * def random_sub(): s = 'abcdefghijklmnopqrstuvwxyz' return dict(zip(s, sample(s, k=26)))
Random Substitution Cipher
5943bf2895d5f74cfb000032
[ "Fundamentals" ]
https://www.codewars.com/kata/5943bf2895d5f74cfb000032
6 kyu
Write a function that takes a positive integer and returns the next smaller positive integer containing the same digits. For example: ```javascript nextSmaller(21) == 12 nextSmaller(531) == 513 nextSmaller(2071) == 2017 ``` ```haskell nextSmaller(21) == 12 nextSmaller(531) == 513 nextSmaller(2071) == 2017 ``` ```csharp nextSmaller(21) == 12 nextSmaller(531) == 513 nextSmaller(2071) == 2017 ``` ```python next_smaller(21) == 12 next_smaller(531) == 513 next_smaller(2071) == 2017 ``` ```ruby next_smaller(21) == 12 next_smaller(531) == 513 next_smaller(2071) == 2017 ``` ```rust next_smaller(21) == Some(12) next_smaller(531) == Some(513) next_smaller(2071) == Some(2017) ``` Return -1 (for `Haskell`: return `Nothing`, for `Rust`: return `None`), when there is no smaller number that contains the same digits. Also return -1 when the next smaller number with the same digits would require the leading digit to be zero. ```javascript nextSmaller(9) == -1 nextSmaller(111) == -1 nextSmaller(135) == -1 nextSmaller(1027) == -1 // 0721 is out since we don't write numbers with leading zeros ``` ```csharp nextSmaller(9) == -1 nextSmaller(111) == -1 nextSmaller(135) == -1 nextSmaller(1027) == -1 // 0721 is out since we don't write numbers with leading zeros ``` ```haskell nextSmaller(9) == Nothing nextSmaller(135) == Nothing nextSmaller(1027) == Nothing -- 0721 is out since we don't write numbers with leading zeros ``` ```python next_smaller(9) == -1 next_smaller(135) == -1 next_smaller(1027) == -1 # 0721 is out since we don't write numbers with leading zeros ``` ```ruby next_smaller(9) == -1 next_smaller(135) == -1 next_smaller(1027) == -1 # 0721 is out since we don't write numbers with leading zeros ``` ```rust next_smaller(9) == None next_smaller(135) == None next_smaller(1027) == None // 0721 is out since we don't write numbers with leading zeros ``` * some tests will include very large numbers. * test data only employs positive integers. *The function you write for this challenge is the inverse of this kata: "[Next bigger number with the same digits](http://www.codewars.com/kata/next-bigger-number-with-the-same-digits)."*
algorithms
def next_smaller(n): s = list(str(n)) i = j = len(s) - 1 while i > 0 and s[i - 1] <= s[i]: i -= 1 if i <= 0: return - 1 while s[j] >= s[i - 1]: j -= 1 s[i - 1], s[j] = s[j], s[i - 1] s[i:] = reversed(s[i:]) if s[0] == '0': return - 1 return int('' . join(s))
Next smaller number with the same digits
5659c6d896bc135c4c00021e
[ "Strings", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5659c6d896bc135c4c00021e
4 kyu
# Introduction There is a war and nobody knows - the alphabet war! The letters hide in their nuclear shelters. The nuclear strikes hit the battlefield and killed a lot of them. # Task Write a function that accepts `battlefield` string and returns letters that survived the nuclear strike. - The `battlefield` string consists of only small letters, `#`,`[` and `]`. - The nuclear shelter is represented by square brackets `[]`. The letters inside the square brackets represent letters inside the shelter. - The `#` means a place where nuclear strike hit the battlefield. If there is at least one `#` on the battlefield, all letters outside of shelter die. When there is no any `#` on the battlefield, all letters survive (but do not expect such scenario too often ;-P ). - The shelters have some durability. When 2 or more `#` hit close to the shelter, the shelter is destroyed and all letters inside evaporate. The 'close to the shelter' means on the ground between the shelter and the next shelter (or beginning/end of battlefield). The below samples make it clear for you. # Example ``` abde[fgh]ijk => "abdefghijk" (all letters survive because there is no # ) ab#de[fgh]ijk => "fgh" (all letters outside die because there is a # ) ab#de[fgh]ij#k => "" (all letters dies, there are 2 # close to the shellter ) ##abde[fgh]ijk => "" (all letters dies, there are 2 # close to the shellter ) ##abde[fgh]ijk[mn]op => "mn" (letters from the second shelter survive, there is no # close) #ab#de[fgh]ijk[mn]op => "mn" (letters from the second shelter survive, there is no # close) #abde[fgh]i#jk[mn]op => "mn" (letters from the second shelter survive, there is only 1 # close) [a]#[b]#[c] => "ac" [a]#b#[c][d] => "d" [a][b][c] => "abc" ##a[a]b[c]# => "c" ``` # Alphabet war Collection <table border="0" cellpadding="0" cellspacing="0"> <tr> <td ><a href="https://www.codewars.com/kata/59377c53e66267c8f6000027" target="_blank">Alphavet war </a></td> </tr> <tr> <td ><a href="https://www.codewars.com/kata/5938f5b606c3033f4700015a" target="_blank">Alphabet war - airstrike - letters massacre</a></td> </tr> <tr> <td ><a href="https://www.codewars.com/kata/alphabet-wars-reinforces-massacre" target="_blank">Alphabet wars - reinforces massacre</a></td> </tr> <tr> <td ><a href="https://www.codewars.com/kata/59437bd7d8c9438fb5000004" target="_blank">Alphabet wars - nuclear strike</a></td> </tr> <tr> <td ><a href="https://www.codewars.com/kata/59473c0a952ac9b463000064" target="_blank">Alphabet war - Wo lo loooooo priests join the war</a></td> </tr> </table>
reference
import re def alphabet_war(b): if '#' not in b: return re . sub(r"[\[\]]", "", b) p = re . compile('([a-z#]*)\[([a-z]+)\](?=([a-z#]*))') return '' . join(e[1] if (e[0] + e[2]). count('#') < 2 else '' for e in p . findall(b))
Alphabet wars - nuclear strike
59437bd7d8c9438fb5000004
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/59437bd7d8c9438fb5000004
5 kyu
Just another day in the world of Minecraft, Steve is getting ready to start his next exciting project -- building a railway system! ![Alt text](http://static.planetminecraft.com/files/resource_media/screenshot/1506/2015-02-02_0156508603066.jpg) But first, Steve needs to melt some iron ores in the furnace to get the main building blocks of rails -- iron ingots. ![ironingot_icon32](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACMAAAAjBAMAAADs965qAAAAIVBMVEX///+CgoJ/f39ycnI1NTVoaGiWlpbY2Nj///+oqKhERERvzmC2AAAAAXRSTlMAQObYZgAAAIZJREFUKFO1zssNgzAQRVGvs6MFt+AUwMItQANI00E0JTAlxCUwVTLP4SMsW2HD290j+ePcI3up/iPrJaWLlaTW35mZTyvJOokADrtFSiLyax5ssa+SUM6PJdlaxIQTI5pCaJC97HNOAWtQ12UCDDFGfPUWwTwueW9dJzOP7veuk9Oi6/TgVghdg26nybMQAAAAAElFTkSuQmCC) Each iron ingot takes 11 seconds* to produce. Steve needs a lot of them, and he has the following fuel options to add into the furnace: * Buckets of lava, each lasts 800 seconds* ![bucketL](data:image/gif;base64,R0lGODlhHgAeAPfPABwfJhwjKRgkMSEtLywsLSUnMCQpNS0vMTAuMiwzNjIyMjM1ODQ4Oj07O1guJ041L101LU06MUA/PlRFNVFLN2NGM2BKOGRbPkRERElGRk1MREBGSUpLTFFPQ11NRFRSQ1lWQVlYQkxMUFJTU1VaW1paWmZPQ2JRRWFeRWFTSHxeWGViTXBnQHNgT394TWZoU2xgWnRjWnJqWXNwWmxsbHprYnxxbmpydG52eG94enJycnJ9f396eLs1HbA2INoxCsctFcU1F8I1HdU6FNo7HdA8IohbOLZvPKV2P751M8dKLs1QJ8lRKMlRNNdkLt1lMdFpMdpvOOJ/NphfUqZbQYRmT4t6Ro1lXJVhVJZrV5Z1WJ5wXrNiQ7xjT6VxQr96QrBqWolrY4JwZoV7ZZd5Y4N1cql+bbh4aKV9da98ccNdRMprQ8RiSdxkSNZ/QMZsUsF7VMd4XdZwWOqCMuKGO+WMPvGPPuWVP+6WOvCQN42CTKieW4SBZqqGbKuXbqyDcK2KcbCPdLWPebaRcaykbsyOQtKWRNyURt6bRsGCU8KNV+GdRvadSd+hSN+uTt6xTsOjXd26UemiR+GhSOS1TeC1UeC6Uem5U8K0YcO5Y9/GVtLIX9rMWd/UXODCVuLUXOjUWuXYXODcYOngYP/uaXh/gH2BgoeKi4yNjZuJhpaNj4uVm46ZnJOTlJqYl5GWmJqamqCfnpKeoJehpKWkpKCoqq2traSusbu6t7q6us6pg8Ojjs6mjNSpiMu3hNPKh7i9wsXEw8nHxsrKysbN0tTU1Nvb29/g4ePj4+rq6vXr6frx7/Pz8/X3+Pv7+////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEKAM8ALAAAAAAeAB4AAAj+AJ8JHEiwoMGDCBMqXMiwIcIDEBEQYCCioggODgt62JgCxYoZMmLEqAHDIQKIB8gA+gOIkEs/fwTxqrHh4kIQKE6YoMIFjiJMmDJBSgTnzRYxY/hoQKgAgYs9WrL0CCLlTqirlOg4ARJnl69fHRAcxIDhQwgvXwoZcvSokaNOniodirKGTZUXEhQcHDFiQYAkeUCN+qSJzqJPnURdYvSEiIMAChbs5dAqV4sKF1hwisQECiJEkpBYqADBBioMeg2O4JDL2YgAAxR0siRkSR06dowISDDgVC4NBPZmsGVsWLBguEJQeBBhwoQIVjYd8RHGVN7JxJElY2asAQIGDBb+MDCgh5SbIlduXFc9/FixYs2UNVGTq34uYLrwDFLFQwfqybQM854zy7QhxzAIBkNML3MEsooONDSQ2l4j5GKMM84UIwwttNhCyy1nDDFFDhlMiNBqFm6HTDG2eEhLLWkocQWJJu4lgoXFXNhMMcPQEksrrchiin81qiYCLsbk6MyOPf6YChplELnQasGsqGNxtMDCChg/TLFDBsEtJEIrARaTTDI8cvgKGl2oQMJ/DGHAgTBJvtckkLOQEGZDfNGCy3vFBAOLK0C6UsKeDIkwAiqwGHMMMsO0AsuktJRQ5EIllAAhhJmOUAIJImQ0EAESEWDqqaaKquqqrLaqUEAAOw==) * Blaze rod, each lasts 120 seconds ![blazerod](data:image/gif;base64,R0lGODlhHgAeAOMMAJMyAKw7AJlVB69aEL1ZAKZsG7FqGbeRHNWsJvy/APzwLPz1ff///////////////yH5BAEKAA8ALAAAAAAeAB4AAASB8MlJq704Y2OE0GDFeWFYFIpyHABQZme6tq/FLcsaBPV154ddj3LCIRAEwrBSXByTSwlHdoBGpQaqdRlTVZXXR3e1HTbJ4Ov5e516hWG3jhflJBLz8MOOD9K5KG9/UWN+bQZ3eXGIfXBLAwNaaVGQknocT5OHmXoSLY6dn4OdpBQRADs=) * Coals, each lasts 80 seconds ![coal](data:image/gif;base64,R0lGODlhHgAeAIQeAAMDAwgICAkJCQoKCgsLCwwMDA0NDQ8PDxAQEBERERQUFBUVFRYWFhcXFxgYGBkZGRsbGx4eHh8fHyAgICMjIyUlJScnJykpKSoqKisrKywsLC0tLTIyMjU1Nf///////yH+EUNyZWF0ZWQgd2l0aCBHSU1QACH5BAEKAB8ALAAAAAAeAB4AAAX24CeOZGmeaKquJOC+LPvCMeo+DwRJklubt9yuB/iNXI3G5dLp6HS+H1LJdD6jNVckgsFsNt0nBLvScr1gjJiscukymW/3O5lAi2XAO56m28d4NnoQHBxdFhYVFV1JOgsLbEeDhYeJixiNEI+RIlNdGho6Cgo6CAiPBQWcH54YoKKkEKaoqoElbhAUFHVijgujj5u2nYO6vL2PwMGRuL1PDAzBwdDMg8460NKP1MOsAI8JCQ4O2gsEBAICBgYBAdXg4uTa5+nr7asu0gMD5+frpgcOrCKmj1+/fwgCDpTUj0CSGTOyAGj4EOJCIBCNCIqosaNHjyEAADs=) * Blocks of Wood, each lasts 15 seconds ![logs](data:image/gif;base64,R0lGODlhJAAqAPf/ALSOWTwxHaSmpTotEJKTkaSKUjMpFBQLAjMjEmZkXLGMVUpMSYuJhr6YYpWUi5x8TSgeCWtsaUQyFLeRXKKDTcCZYwoCARUOBZyETCIXBpqCSlpcWR0VCYVsQjwwEjYrDRgRCaWFUScnJEo6IjkrDiUgCnpiPCUcDWJdXCIbEWdQLiATB7yWYA4JB0Y6IS0kFkE2Ig0GBIyNinZ1dCkgEqqLVK2OVycZCkQ3H46QjSwjFZuWlIWDeDo5NyIVC0s7FWZoZSMaCZqcmTImDk9EGDgtGqmEUFE/JykfCwsEA1RBKpGNiBoVDjovHCwiD0E1HDAnGTcsGRIRB1pGKRMUEmVQMnp2b1U/GJSXlCgfEYtxRzEoGnJbN15cVh4QA0Q6FWJkYWVmZC4lFxwUBZmWjmZPLWtUMWhpZBsTBGJNMJ2ASgcAAGZaRxkTDFVYVWRlYx8YDAwLDW10cxsWERQSDJybkzklE2diYTYmD4WMg0k2FREMCi4oDhkQABgVBV5gXRoYF5SZjh8SBmplY6+QWb2VWrKTXBIIALSUXXlsVK6PWF1IK5F1RkIyIK6JVE87GDUrGGlSL3x9ex4aBlZRUEJAPy8kCxsOCGxVMhocHKeIUjAhD2BLLmhTNVJNTJZ+R7KSW1FSThEHAHNuakEwGZ+hnkM3JG9YNSsmDBkXCGFLKWFML4aOjIBmPR0RDCocD25wbTUsHTopGCAcC4uHgi4fDUA0G25XNEg3ICIYDrWUV3xkQIOCgLaQWygbDSkkCDAsKi0jEH18ci4jCiIeDr+YXE9CKbiYYZd5SVdCJFhEJywdCSEdHEUzHGpVNx8hHUQzIREPE6Wgn4iGip2ipDciDAgFC15cYEc1HoyVkDQrHGNhZUAwHnB5dCYfFT0tHF1UWiMbCzAcCzIwD19RNzwtGyohEyolEC4sMExQTE5TVUtBMllPP32DeUMwD1ZUWD82ElhTUmdZPgULDpWMkmRpa15IJigjDmVjZzIjCyElI11lYRkMBWROK3Z/ev///yH/C05FVFNDQVBFMi4wAwEAAAAh+QQJyAD/ACwAAAAAJAAqAAAI/wD/CRxIsKDBgwgTJowUSaFDhVUMGHOkoJEBMw8zCjTVQYEuDWoUGOlQRmPCJkWKTACgRgMAGxgwAJiwqEgTkwRHmECmgIIGGxUmTKhQ41MIRVrMGICksYyZSIUAFKCgiMXKmUIbaFJTwBEAM2YwKWxiwMQDGyEwHKvQAEANCjZqaLIxswIiDCFsPLhlgNPBIi6KAdAQooZQAAo0YKjAgkUFTTKFPsbgsoKJhgJvlen0oEbLY23dFmYRGgAAxpryCm2MQRMiIyZO/XOyiJMWIxQwUEBkdQJkDIgaZEVEWNPMBsQp1DCCLNKRfxKCfOh0igsLmBRIm1akGLlPAI4cTf9ApOYTgEKYAjQ5weEfPHge9CRTlaaDEU2EbQgHgF95XRu51RBCK2bgkAUaJwTzDwkfPPKBBI8M0QQnJvCnxmIVzGQVW2qoQcgEu3DSBBpoOIGHE5P8w8cHAzD4wQcnNDGCGR3wp0ENhJBGCH41AJCULQaAcAIJTpyQyiz//ELMPSQM0CKREGTwFCMK1FBAARrA5UgrTh3AQRCbOEGHH6n88sE/HnzxyyQleNDiABIMMEkUtowwRQWK2FDMIjg0IwEeQUDgBAcg+IHKByXc888AX4xDxD1BWGLAm3o4AQEERRjACCONQIIHHkOUAAESEKABwTgGQHBCBu69OAARXwz/cQIEJAT6yCN6IDFEGcqwd+msgmYQxAn3IJHKGCD8o8cjA3wwxBe4DmEpikNIIIEBElyQAR4QlFDCqlKcsAkEs4AwRhAD/PPiIxBIikQtj3gwxA8/TELML9biMe6ofvix7SZjBGyiHRD8c4ITHlhyAhyWZHBCtWkS8QEqJUir6iRSlGAAHkhcAEIQToQc5T9BBJEBCfBEOECRJwzTLBE/fDFrv6l8AAkEIHBwwomXlpoKmgYM6sSkDMYbqBMDROzHPfd8AOkJQVRsMgSEtquuBxJc8esH7erhAalBDPEBCRDw8cvFIFDNQSqjwsGHAYqW0KIHV+gxDAQGeIAu1hJk/4CEB92WwAEaH0M9xKVOBIPKPX7MNoubA+gh+RBXeMCgO3pcYQngJdjBwTAGBMFBuyeUcA7FqSQrgdckkAA5MSUw6GSLVzxiCbcQiG5uKlKsiMokfpi6qB5DWDJEkx4QsaLrRR6vh6pBgCAkqI/zcU/uGVz6jx2uD0ur6zB/IQE8wPYtPQgGGIDEOQZ4Oyr0BVsS9hUSyDqEm/D88B48EpBwwgWBIoElRAWBe0AtCJNIRSpmpa5LDQFOj5hWs1AGD8nxoQROIBWpLjU4v+kMCSUTSHyQYID70U99LXLCBe8xAG8RMEp+0JWlwoSznw3EcK1bVpzkBUIIfGAW/mLPGHA4MAA8WGJaqkLICYgGJ2mJjQRwCEK/nABAJGxigz17SIuiUL8jIiFp8rMDEgTYw/fhxEkkkICbWCSBDZ7gjaMrGE4E4jrXeWBsV4CakDKABhvOsSBOemL0cIaGPypkVk4IAhIUZMiH3OAEjYykQwICACH5BAnIAP8ALAAAAAAkACoAAAj/AP8JHEiwoMGDCBMihBEpEgyFEBNWMQDDkYJGBsxE3PiviKkOCnRpUKPASIcyZTgibNKkyAQAajQAsIEBA4AJi4o0UTkQxggTyBRQ0GCjwoQJFWp8CqFIixkDkDiWMROpEIACFBSxeHnzaANNago4AmDGDCaFTQyYeGAjBIZjFRoAqEHBRg1NNm5WAIUhhI0HtwxwMlikiItiADSEqHEUgAINGCqwYFFBk82jlTFo6FXBBEqBt8p0elAj5jG5cxezQA2AMwtNfo9OxqAJkRETp/5pq8JJixEKGCgg2jrBMgZQDbyCUqzpZgNDGijUMIKsjLJ/YkzB6HSKCwuaFFYD/wCgCPLzoQAcOZoASs0nAIUwcQvQRMc/HQFMVZlyJE0HI5ooZkNyAAQonV42AFdDCK1EYkwAUEQBxz/mNDHCCSfQsEgUaZhQoBqRVXDTVnGpoQYhE+zCSX2xZJGChP/E0kQzWWSIyyIBLKJCBwVqUAMhqxESYA0AaBFJAAG8cIIpOrw4YQA62GJOFDgEYI4YVZqhAiMK1FBAAdHZ4EgrZahgABNFMJECJC6a0sY/AdCAQxZNwFBfAFVA0YgyI7gwRQWK2FDMIjhEIYaS5uCgpjY0pIALCP+Y8oILzQRwhAHmNFKFOTAocYQpAYjBCCMBUGkOHC5woIOiKcyZgimQ0v+HAwy4HLEFDXjS8EQVuEThAg6RTGEoHBzAgYOqrMKQBRxFvGnKEUgqoYQLLgSggpwjBLAFlZ3QoQMUbWQBxbH4zZHCEycwC+kIVayqxCoBwGCLC1nAAO8WLZUBgjnmMHFCLFGouoWatpzAQbP/sPuqMZzEawqTOKQBYQBFlHEBDf3qAEksULwABRMuppACwgqbooTESM5pisT4bVHFBXCkMMcWsYihwwtRMGFOCjR8y0TCVaTgghKLHHFECqrQAMMUUBYhxhFQwOENztDoYA4dzXBAg85ipPnPFml4YwvRkEyRggpZKKHMN+Zs8YISOkitQxGN8MuEC0yAS8MWzfz/DMURJ8CAQ58BnKBM2lHocAIkWL5gjg5dB8CE5AbM8bE5UODi99EwPIFDE+a8gIM5ykChgw5u4/DC6VAg2Ua/UIAgBshQYAOpAUHbYkozRSRqijn9ZEHlFjq4gLoYUBQRQBumQ0EnE3s/+g8ki3CQnwugt5RCGcLj0LHx0LyAbxQBzCEGCDQ00QYNL2Rhnw64NBFvlS6/2Ik5RXgPxQg6wCDGFv/DhqrQpz5x6Y5CtjjCr3AgCx1UgQNRwAT+TFEEKCiBU6YTA5Ycta8Ctu4CcNKUOSABgwBkAQcvcsYJ8vcNC5oDGhoUHy5ScDkd+AtnHBBIp2gQBVM0ARIu2AKeq7JgmCZsYRFw2MLU/ocL5lktCiA4wQtsRpAsGMCHL2gCLgKwihP4KgpQKEMbbjVFKMAgBS8oQhqj+AKE2II+SMNBI7yoPzNcgHinE4OE2oANDUIKIoWbAgzM4EVTNAIKnbgADL6lQQkxQYM8EVwyFoeDKiiBExfomNag4Lyf8WQgT1jTE+CXAiakEWSh++RBDPAEm9kOdf5SpUI8NwI4fEuWGzmCN3DJS4gEBAAh+QQFyAD/ACwAAAAAJAAqAAAI/wD/CRxIsKDBgwgTJowUSaFDhVUMGHOkoJEBMw8zCjTVQYEuDWoUGOlQRmPCJk2KTACgRgMAGxgwAJiwqEgTkwRHmECmgIIGGxUmTKhQ41MIRVrMGICksYyZSIUAFKCgiMXKmUIbaFJTwBEAM2YwKWxiwMQDGyEwHKvQAEANCjZqaLIxswIoDCFsPLhlgNPBIi6KAdAQooZQAAo0YKjAgkUFTTKFPsagoVcFEw0FnirT6UGNlsfaui3MQjQAyyw05RXaGIMmREZMnPoHYsoqLUYoYKCAyOoEyBhANcgKirCmmQ0MaaBQwwgyFUf+HfLCodMpLixgUigNAIAixcl9Av9w5GgCKDWfABTCFKCJjwP/YlBHIKuZig5GNBG2MRyAfuZ12aBbDSG0YgYu4RzgShLxgQCHBUkksUwTaZjgnxqLVTCTVWypoQYhE+zCSRMHgHCAKAv+cwEIaEQYwwriZIGLGR34p0ENhJRGiH41AJCULOYccMgNJ4LAIAjyxXDBCpfE0IIgFzDEiAI1FFDAcjY40koZKhxgARoWiGKiKDesQVsSKyQBgiBIeoHAAX3U58IUFShiQzFT4PICHAe0cMANFsRgYgyA/sNBDHBwAAKRMaCBQAyC3OCDD7IYwAgjFr1HqAV/BspooWiAwIEXPjDqaAxj2PHeCjekcQSfSUD/GA6ngBJ6QAxtWPAPq3148Yovk3phB6q5mLikHWsccIEFh1zgA6cPxpDLIbjqegMConDwCgJeeIFGBkkIssklyl5QTbJeHgJCrsqG6UMMFuT6TwZ2WMCBL5t0uwIcMXCAgCsHXHIJAuhyCgIIF7QrZAzV/uMDAvZu68XBHIT7bwzkIhuoBQcnXCKnMRzQ7rz1+vDKJjcAuol8tTR5SQs3XJCEnyC852UunHJ6wBi6HoBAEmjcUMsBy1iAB6HLINknkTPvbLMFsy6rbKF/hjvGDRm0uEwMvlwQQxJ92izyGCtY8CwIFkh9QaEwWyDIGD7I3MIKMSxzq58tjCGyshw8/+vlsmqX+Y/PX3IwhtcrpJkP2F7c+h7CF5C9RsIJC8Lp2mYeUMsaaPSNZB/L4pHEBRyE/ecFS9acNqeWi3wIfDH4AIIXgvjwcr0XHE266XGjvjanybbu7A3xBQ1H4vzEgMfksigJxwUwHxC3yGsTmizPyq5gJhqnHiBIk2VfYMfoskf/fMKLKqkzswoy+I8XvoyuqPQliu6siZuoSf2iaYuMdsgJIwjYOHABdfnAC/m7wPMOUA2O+WlqojgAGiLHPoSgYWIWyIcgWrQkkRlgDQjbH7xidgEzOcRItfCC/ZjUAmTlolwXWJDOcEKdVzDODiebnJfK5SWcDMRwnPJC7CMswCmevQ4+PjTIzqjFgWQtSxRJVEi3MgDAKGaESFbMokMCAgAh+QQFyAD/ACwBAAMAIwAmAAAI/wD/CRxIsKBADBQGqjDIsCFDDAanOJxIcSAFGx0EGqj4b+G/YgNtMKxgMJIZjv8SCiTp0BBBTP9WTURIEADEihgAFIykwllBlikFshioc6LLf5hGJZIosMC/owQNsaxgiObKfzcFqpLnIFAOFZhOFRz6zwZEsgWhFjNDytQgIASwOBBCK5G9gTfRZm2ois0oOW8GycDCgEEOBzkMyKQIVOCqchFgRUgABEVcAjkYTMuxQ1giVXgHsszaN0E9IKjDhEGxQ0A2B2QcECAgY7AzFVoI7l0I5A8Yyp7+hEmwoY6QPHKKy6YXyIGAJWxICRQpkBS7LguAbHvje8HwQc8yzf+YAcsNIDeSlsiQXUoAtXVOBDYxFQFImDNvUPxBgeJMgj9d7CFCJsbxIEw0VKCTGRZkkBEIFjx0Qg5lKFxzDQph3HHHIHf8sV8ma3ThgHMCEADMM1RIswQWo9ACWw7dLJAAGCiAAYQnlezhCRhvvBEBCsDAIsMMtBAghDQ5SGKNCEsQQAYvtJGBxR2qAREBIC3EEQcVYES2ASWD/MGLMCXOtqIAG2TmQB20MeAACqhtoE8PVDzTgyRhANHhfn8U5uIOBLgoRIk75OFmDjIssYFk6WzgBiVAwNKbjRHU9wcZmQkgjRCGMcCKDAKUyAAKXQhxBxAbZCcZjfu40cUgb4D/ccYdwsyWTXs7yEBAKQyQUYoQMjDTgwwdJiCHZAuAAYYckG4HRJc51EGLDDkQsMMOpexgBRaBymENE8CIAEgP9r2xAQoRnArGW2F0ORuiMjAwQzel0ENGXAzwIoAIVAAiwoxgdBgZqX8AccYfnqAwaA6BEFCYw1ZYS4A0AsiwQw5xdIFCApUCwaGMkbmRjifCDjobAbzIIAQP055c2w6VBHdsZaF0OWMXGyy6BzBL5HExA3IELYQD3HLLiqceogALjaGcYd+zgXWRSZbMuNEcou3IIdegWDR8GDjKgrGfJ25kp9odwABSSQtC9KDPyVjoSnQeSwhh7bUA7weGJ+mAsaHaICjEA6kI/8S9QCkOlDIkAbIt4Y8kWFCDRSj2+f2GG2C4UfACVPSgtBwDieAGiSlzuwMvM5Sezh1vhOGhhzX/UYkId6DAUKKt0cbmtQtgkQOPsODTI8ewDLIaGBQ1eXEcM1Ri5zM9SnaG08eO8gYQKP0T1zvPeDIIE3Wqs4Hfeb6xYfYDYTGNA4PMQOeWa5+h+R/oM1QYndHMozYgC9Q/kQBC6AK5IuA/jtQBedkLCAA7) * Sticks, each lasts 1 second* ![stick](data:image/gif;base64,R0lGODlhHgAeAMIFACceC0g1FWdNHodmJ4uLi////////////yH+EUNyZWF0ZWQgd2l0aCBHSU1QACH5BAEKAAcALAAAAAAeAB4AAANWeLrc/jDKSV8IANR685bXMHgfFI5a2ZykugZi6x6XIMgzHdi4yqY5xS+o4wGDtdvRNSTqYkvfTuksUpEwVLWZS/aY0++Hi4USyd2suJRZq9rRqnyuSAAAOw==) In Ruby: Write a function `calc_fuel` that calculates the **minimum** amount of fuel needed to produce a certain number of iron ingots. This function should return a hash of the form `{:lava => 2, :blaze_rod => 1, :coal => 1, :wood => 0, :stick => 0}` In JavaScript: Write a function `calcFuel` that calculates the **minimum** amount of fuel needed to produce a certain number of iron ingots. This function should return an object of the form `{lava: 2, blazeRod: 1, coal: 1, wood: 0, stick: 0}` In Python: Write a function `calc_fuel` that calculates the **minimum** amount of fuel needed to produce a certain number of iron ingots. This function should return a dictionary of the form `{"lava": 2, "blaze rod": 1, "coal": 1, "wood": 0, "stick": 0}` --- *fictional values To all the Minecraft players out there: feel free to expand this series or let me know if you have any ideas related to Minecraft that can be turned into codewars puzzles. Some ideas I have that might potentially be turned into katas: * distance traveled in real world vs. in Nether * shortest path problems related to mining diamonds/gold/goodies that appears in different levels under ground * growth of animal population from breeding * redstone stuff?! If you do end up expanding this series, please send me a link of your kata so I can check it out and include a link to your kata here :-) * [Minecraft Series #1: Steve wants to build a beacon pyramid](https://www.codewars.com/kata/minecraft-series-number-1-steve-wants-to-build-a-beacon-pyramid/ruby) * [Minecraft Series #3: Lava is amazing! ](https://www.codewars.com/kata/583a23d40cf946ec380002c2) * [Minecraft Series #4: Lava is amazing, however...](https://www.codewars.com/kata/583a6b0b171f3a3c3f0003e3)
reference
t = ((800, "lava"), (120, "blaze rod"), (80, "coal"), (15, "wood"), (1, "stick")) def calc_fuel(n): s, r = n * 11, {} for d, e in t: r[e], s = divmod(s, d) return r
[Minecraft Series #2] Minimum amount of fuel needed to get some iron ingots
583a02740b0a9fdf5900007c
[ "Fundamentals" ]
https://www.codewars.com/kata/583a02740b0a9fdf5900007c
6 kyu
Write three functions `add`, `subtract`, and `multiply` such that each require two invocations. For example: ```javascript add(3)(4) // 7 subtract(3)(4) // -1 multiply(3)(4) // 12 ``` ```python add(3)(4) # 7 subtract(3)(4) # -1 multiply(3)(4) # 12 ``` Once you have done this. Write a function `apply` that takes one of these functions as an argument and invokes it. For example: ```javascript apply(add)(3)(4) // 7 apply(subtract)(3)(4) // -1 apply(multiply)(3)(4) // 12 ``` ```python apply(add)(3)(4) # 7 apply(subtract)(3)(4) # -1 apply(multiply)(3)(4) # 12 ``` This kata is based on the following talk by Douglas Crockford: [https://youtu.be/hRJrp17WnOE](https://youtu.be/hRJrp17WnOE)
reference
def add(a): return lambda b: a + b def subtract(a): return lambda b: a - b def multiply(a): return lambda b: a * b def apply(op): return op
The Crockford Invocation
57e7d21f6603f6e31f00007c
[ "Fundamentals" ]
https://www.codewars.com/kata/57e7d21f6603f6e31f00007c
7 kyu
## A Man and his Umbrellas ## Each morning a man walks to work, and each afternoon he walks back home. If it is raining in the morning and he has an umbrella at home, he takes an umbrella for the journey so he doesn't get wet, and stores it at work. Likewise, if it is raining in the afternoon and he has an umbrella at work, he takes an umbrella for the journey home. ---------------------- Given an array of the weather conditions, **your task** is to work out the **minimum number of umbrellas** he needs to start with in order that he never gets wet. He can start with some umbrellas at home and some at work, but the **output** is a single integer, the minimum total number. The **input** is an array/list of consecutive half-day weather forecasts. So, e.g. the first value is the 1st day's morning weather and the second value is the 1st day's afternoon weather. The options are: Without umbrella: * "clear", * "sunny", * "cloudy", * "overcast", * "windy". With umbrella: * "rainy", * "thunderstorms". e.g. for three days, 6 values: ``` weather = ["rainy", "cloudy", "sunny", "sunny", "cloudy", "thunderstorms"] ``` **N.B.** He never takes an umbrella if it is not raining. #### Examples: * ``` minUmbrellas(["rainy", "clear", "rainy", "cloudy"]) ``` should return 2 Because on the first morning, he needs an umbrella to take, and he leaves it at work. So on the second morning, he needs a second umbrella. * ``` minUmbrellas(["sunny", "windy", "sunny", "clear"]) ``` should return 0 Because it doesn't rain at all * ``` minUmbrellas(["rainy", "rainy", "rainy", "rainy", "thunderstorms", "rainy"]) ``` should return 1 Because he only needs 1 umbrella which he takes on every journey. ~~~if:java #### Note for Java users The following enum is preloaded for you: ```java public enum Weather { CLEAR, SUNNY, CLOUDY, RAINY, OVERCAST, WINDY, THUNDERSTORMS; } ``` ~~~
reference
def min_umbrellas(weather): home = work = 0 for i, w in enumerate(weather): if w not in ['rainy', 'thunderstorms']: continue if i % 2 == 0: work += 1 home = max(home - 1, 0) else: home += 1 work = max(work - 1, 0) return home + work
A Man and his Umbrellas
58298e19c983caf4ba000c8d
[ "Logic", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/58298e19c983caf4ba000c8d
5 kyu
![alt text](https://2.bp.blogspot.com/-DNNiOXduuvQ/Vh-FR-qbKXI/AAAAAAAAEOA/HT0IzJ36zW4/s1600/voz.jpg) Create a class called `Warrior` which calculates and keeps track of their level and skills, and ranks them as the warrior they've proven to be. <b><span style="color:#00BFFF">Business Rules:</span></b> - A warrior starts at level <span style="color:#e4d00a">1</span> and can progress all the way to <span style="color:#e4d00a">100</span>. - A warrior starts at rank `"Pushover"` and can progress all the way to `"Greatest"`. - The only acceptable range of rank values is `"Pushover", "Novice", "Fighter", "Warrior", "Veteran", "Sage", "Elite", "Conqueror", "Champion", "Master", "Greatest"`. - Warriors will compete in battles. Battles will always accept an enemy level to match against your own. - With each battle successfully finished, your warrior's experience is updated based on the enemy's level. - The experience earned from the battle is relative to what the warrior's current level is compared to the level of the enemy. - A warrior's experience starts from <span style="color:#e4d00a">100</span>. Each time the warrior's experience increases by another <span style="color:#e4d00a">100</span>, the warrior's level rises to the next level. - A warrior's experience is <span style="color:#e4d00a">cumulative</span>, and does not reset with each rise of level. The only exception is when the warrior reaches level <span style="color:#e4d00a">100</span>, with which the experience stops at <span style="color:#e4d00a">10000</span> - At every <span style="color:#e4d00a">10</span> levels, your warrior will reach a new rank tier. (ex. levels <span style="color:#e4d00a">1-9</span> falls within `"Pushover"` tier, levels <span style="color:#e4d00a">80-89</span> fall within `"Champion"` tier, etc.) - A warrior cannot progress beyond level <span style="color:#e4d00a">100</span> and rank `"Greatest"`. <b><span style="color:#00BFFF">Battle Progress Rules & Calculations:</span></b> - If an enemy level does not fall in the range of 1 to 100, the battle cannot happen and should return `"Invalid level"`. - Completing a battle against an enemy with the same level as your warrior will be worth <span style="color:#e4d00a">10</span> experience points. - Completing a battle against an enemy who is one level lower than your warrior will be worth <span style="color:#e4d00a">5</span> experience points. - Completing a battle against an enemy who is two levels lower or more than your warrior will give <span style="color:#e4d00a">0</span> experience points. - Completing a battle against an enemy who is one level higher or more than your warrior will accelarate your experience gaining. The greater the difference between levels, the more experinece your warrior will gain. The formula is `20 * diff * diff` where `diff` equals the difference in levels between the enemy and your warrior. - However, if your warrior is at least one rank lower than your enemy, and at least 5 levels lower, your warrior cannot fight against an enemy that strong and must instead return `"You've been defeated"`. - Every successful battle will also return one of three responses: `"Easy fight", "A good fight", "An intense fight"`. Return `"Easy fight"` if your warrior is 2 or more levels higher than your enemy's level. Return `"A good fight"` if your warrior is either 1 level higher or equal to your enemy's level. Return `"An intense fight"` if your warrior's level is lower than the enemy's level. <b><span style="color:#00BFFF">Logic Examples:</span></b> - If a warrior level <span style="color:#e4d00a">1</span> fights an enemy level <span style="color:#e4d00a">1</span>, they will receive <span style="color:#e4d00a">10</span> experience points. - If a warrior level <span style="color:#e4d00a">1</span> fights an enemy level <span style="color:#e4d00a">3</span>, they will receive <span style="color:#e4d00a">80</span> experience points. - If a warrior level <span style="color:#e4d00a">5</span> fights an enemy level <span style="color:#e4d00a">4</span>, they will receive <span style="color:#e4d00a">5</span> experience points. - If a warrior level <span style="color:#e4d00a">3</span> fights an enemy level <span style="color:#e4d00a">9</span>, they will receive <span style="color:#e4d00a">720</span> experience points, resulting in the warrior rising up by at least <span style="color:#e4d00a">7</span> levels. - If a warrior level <span style="color:#e4d00a">8</span> fights an enemy level <span style="color:#e4d00a">13</span>, they will receive <span style="color:#e4d00a">0</span> experience points and return `"You've been defeated"`. (Remember, difference in rank & enemy level being <span style="color:#e4d00a">5</span> levels higher or more must be established for this.) - If a warrior level <span style="color:#e4d00a">6</span> fights an enemy level <span style="color:#e4d00a">2</span>, they will receive <span style="color:#e4d00a">0</span> experience points. <b><span style="color:#00BFFF"> Training Rules & Calculations:</span></b> - In addition to earning experience point from battles, warriors can also gain experience points from training. - Training will accept an array of three elements (except in java where you'll get 3 separated arguments): the description, the experience points your warrior earns, and the minimum level requirement. - If the warrior's level meets the minimum level requirement, the warrior will receive the experience points from it and store the description of the training. It should end up returning that description as well. - If the warrior's level does not meet the minimum level requirement, the warrior doesn not receive the experience points and description and instead returns `"Not strong enough"`, without any archiving of the result. <b><span style="color:#00BFFF"> Code Examples:</span></b> ```javascript var bruce_lee = new Warrior(); bruce_lee.level(); // => 1 bruce_lee.experience(); // => 100 bruce_lee.rank(); // => "Pushover" bruce_lee.achievements(); // => [] bruce_lee.training(["Defeated Chuck Norris", 9000, 1]); // => "Defeated Chuck Norris" bruce_lee.experience(); // => 9100 bruce_lee.level(); // => 91 bruce_lee.rank(); // => "Master" bruce_lee.battle(90); // => "A good fight" bruce_lee.experience(); // => 9105 bruce_lee.achievements(); // => ["Defeated Chuck Norris"] ``` ```ruby bruce_lee = Warrior.new bruce_lee.level # => 1 bruce_lee.experience # => 100 bruce_lee.rank # => "Pushover" bruce_lee.achievements # => [] bruce_lee.training(["Defeated Chuck Norris", 9000, 1]) # => "Defeated Chuck Norris" bruce_lee.experience # => 9100 bruce_lee.level # => 91 bruce_lee.rank # => "Master" bruce_lee.battle(90) # => "A good fight" bruce_lee.experience # => 9105 bruce_lee.achievements # => ["Defeated Chuck Norris"] ``` ```python bruce_lee = Warrior() bruce_lee.level # => 1 bruce_lee.experience # => 100 bruce_lee.rank # => "Pushover" bruce_lee.achievements # => [] bruce_lee.training(["Defeated Chuck Norris", 9000, 1]) # => "Defeated Chuck Norris" bruce_lee.experience # => 9100 bruce_lee.level # => 91 bruce_lee.rank # => "Master" bruce_lee.battle(90) # => "A good fight" bruce_lee.experience # => 9105 bruce_lee.achievements # => ["Defeated Chuck Norris"] ``` ```java // Note: all numeric values are integers. Warrior bruce_lee = new Warrior(); bruce_lee.level(); // => 1 bruce_lee.experience(); // => 100 bruce_lee.rank(); // => "Pushover" bruce_lee.achievements(); // => [] (as List<String>) bruce_lee.training("Defeated Chuck Norris", 9000, 1); // => "Defeated Chuck Norris" bruce_lee.experience(); // => 9100 bruce_lee.level(); // => 91 bruce_lee.rank(); // => "Master" bruce_lee.battle(90); // => "A good fight" bruce_lee.experience(); // => 9105 bruce_lee.achievements(); // => ["Defeated Chuck Norris"] (as List<String>) ```
algorithms
class Warrior (): def __init__(self): self . _experience = 100 self . rs = ["Pushover", "Novice", "Fighter", "Warrior", "Veteran", "Sage", "Elite", "Conqueror", "Champion", "Master", "Greatest"] self . achievements = [] def training(self, train): if (train[2] > self . level): return "Not strong enough" self . _experience += train[1] self . achievements . append(train[0]) return train[0] def battle(self, lvl): diff = lvl - self . level if (0 >= lvl or lvl > 100): return "Invalid level" if (diff >= 5 and (lvl / / 10) > (self . level / / 10)): return "You've been defeated" if (diff > 0): self . _experience += 20 * diff * diff return "An intense fight" if (diff > - 2): self . _experience += 5 if diff == - 1 else 10 return "A good fight" return "Easy fight" @ property def level(self): return self . experience / / 100 @ property def rank(self): return self . rs[self . experience / / 1000] @ property def experience(self): return min(10000, self . _experience)
The Greatest Warrior
5941c545f5c394fef900000c
[ "Algorithms", "Object-oriented Programming" ]
https://www.codewars.com/kata/5941c545f5c394fef900000c
4 kyu
## Welcome to my (amazing) kata! You are given a gigantic number to decode. Each number is a code that alternates in a pattern between encoded text and a smaller, encoded number. The pattern's length varies with every test, but the alternation between encoded text and an encoded number will always be there. Following this rule, each number tested begins with encoded text and ends with an encoded number. ## How the encoding works Now, we should probably review how the string of numbers is formed - considering you have to unform it. So, first, some text is taken, and encoded. The system of encoding is taking each letter's position in the alphabet and adding 100 to it. For example, `m` in the real text would be `113` in the code-number. After the text, there is a binary number. You should convert this number to a normal, base 10 decimal (all of them can be converted into whole, non-negative numbers). Separating encoded text and encoded numbers, there is a `98`. Because the numbers are in binary, the only digits they use are '0' and '1', and each letter of the alphabet, encoded, is between 101-127, all instances of `98` are to indicate a separation between encoded text and encoded numbers. There may also be a `98` at the very end of the number. When you return your final answer, the text and numbers should always be separated by a comma (`,`) ## Example ```python decode(103115104105123101118119981001098113113113981000) = "codewars, 18, mmm, 8" ``` The part of the code until the first `98` can be decoded to `"codewars"`. `10010` is binary for `18`. `113113113` translates to `"mmm"`. And `1000` is binary for `8`. Here is a visualisation of the example: ```javascript 103 115 104 105 123 101 118 119 98 10010 98 113 113 113 98 1000 c o d e w a r s , 18 , m m m , 8 ``` Good luck!
reference
def decode(number): return ', ' . join( str(int(w, 2)) if i % 2 else '' . join(chr(int(w[x: x + 3]) - 4) for x in range(0, len(w), 3)) for i, w in enumerate(str(number). strip('98'). split('98')) )
Number Decoding
5940ec284aafb87ef3000028
[ "Fundamentals" ]
https://www.codewars.com/kata/5940ec284aafb87ef3000028
6 kyu
Most languages have a `split` function that lets you turn a string like `“hello world”` into an array like`[“hello”, “world”]`. But what if we don't want to lose the separator? Something like `[“hello”, “ world”]`. #### Task: Your job is to implement a function, (`split_without_loss` in Ruby/Crystal, and `splitWithoutLoss` in JavaScript/CoffeeScript), that takes two arguments, `str` (`s` in Python), and `split_p`, and returns the string, split by `split_p`, but with the separator intact. There will be one '|' marker in `split_p`. `str` or `s` will never have a '|' in it. All the text before the marker is moved to the first string of the split, while all the text that is after it is moved to the second one. **Empty strings must be removed from the output, and the input should NOT be modified.** When tests such as `(str = "aaaa", split_p = "|aa")` are entered, do not split the string on overlapping regions. For this example, return `["aa", "aa"]`, not `["aa", "aa", "aa"]`. #### Examples (see example test cases for more): ```ruby split_without_loss("hello world!", " |") #=> ["hello ", "world!"] split_without_loss("hello world!", "o|rl") #=> ["hello wo", "rld!"] split_without_loss("hello world!", "h|ello world!") #=> ["h", "ello world!"] split_without_loss("hello world! hello world!", " |") #=> ["hello ", "world! ", "hello ", "world!"] split_without_loss("hello world! hello world!", "o|rl") #=> ["hello wo", "rld! hello wo", "rld!"] split_without_loss("hello hello hello", " | ") #=> ["hello ", " hello ", " hello"] split_without_loss(" hello world", " |") #=> [" ", "hello ", "world"] split_without_loss(" hello hello hello", " |") #=> [" ", " ", "hello ", "hello ", "hello"] split_without_loss(" hello hello hello ", " |") #=> [" ", " ", "hello ", "hello ", "hello ", " "] split_without_loss(" hello hello hello", "| ") #=> [" ", " hello", " hello", " hello"] ``` ```python split_without_loss("hello world!", " |") #=> ["hello ", "world!"] split_without_loss("hello world!", "o|rl") #=> ["hello wo", "rld!"] split_without_loss("hello world!", "h|ello world!") #=> ["h", "ello world!"] split_without_loss("hello world! hello world!", " |") #=> ["hello ", "world! ", "hello ", "world!"] split_without_loss("hello world! hello world!", "o|rl") #=> ["hello wo", "rld! hello wo", "rld!"] split_without_loss("hello hello hello", " | ") #=> ["hello ", " hello ", " hello"] split_without_loss(" hello world", " |") #=> [" ", "hello ", "world"] split_without_loss(" hello hello hello", " |") #=> [" ", " ", "hello ", "hello ", "hello"] split_without_loss(" hello hello hello ", " |") #=> [" ", " ", "hello ", "hello ", "hello ", " "] split_without_loss(" hello hello hello", "| ") #=> [" ", " hello", " hello", " hello"] ``` ```crystal split_without_loss("hello world!", " |") #=> ["hello ", "world!"] split_without_loss("hello world!", "o|rl") #=> ["hello wo", "rld!"] split_without_loss("hello world!", "h|ello world!") #=> ["h", "ello world!"] split_without_loss("hello world! hello world!", " |") #=> ["hello ", "world! ", "hello ", "world!"] split_without_loss("hello world! hello world!", "o|rl") #=> ["hello wo", "rld! hello wo", "rld!"] split_without_loss("hello hello hello", " | ") #=> ["hello ", " hello ", " hello"] split_without_loss(" hello world", " |") #=> [" ", "hello ", "world"] split_without_loss(" hello hello hello", " |") #=> [" ", " ", "hello ", "hello ", "hello"] split_without_loss(" hello hello hello ", " |") #=> [" ", " ", "hello ", "hello ", "hello ", " "] split_without_loss(" hello hello hello", "| ") #=> [" ", " hello", " hello", " hello"] ``` ```javascript splitWithoutLoss("hello world!", " |") #=> ["hello ", "world!"] splitWithoutLoss("hello world!", "o|rl") #=> ["hello wo", "rld!"] splitWithoutLoss("hello world!", "h|ello world!") #=> ["h", "ello world!"] splitWithoutLoss("hello world! hello world!", " |") #=> ["hello ", "world! ", "hello ", "world!"] splitWithoutLoss("hello world! hello world!", "o|rl") #=> ["hello wo", "rld! hello wo", "rld!"] splitWithoutLoss("hello hello hello", " | ") #=> ["hello ", " hello ", " hello"] splitWithoutLoss(" hello world", " |") #=> [" ", "hello ", "world"] splitWithoutLoss(" hello hello hello", " |") #=> [" ", " ", "hello ", "hello ", "hello"] splitWithoutLoss(" hello hello hello ", " |") #=> [" ", " ", "hello ", "hello ", "hello ", " "] splitWithoutLoss(" hello hello hello", "| ") #=> [" ", " hello", " hello", " hello"] ``` ```coffeescript splitWithoutLoss("hello world!", " |") #=> ["hello ", "world!"] splitWithoutLoss("hello world!", "o|rl") #=> ["hello wo", "rld!"] splitWithoutLoss("hello world!", "h|ello world!") #=> ["h", "ello world!"] splitWithoutLoss("hello world! hello world!", " |") #=> ["hello ", "world! ", "hello ", "world!"] splitWithoutLoss("hello world! hello world!", "o|rl") #=> ["hello wo", "rld! hello wo", "rld!"] splitWithoutLoss("hello hello hello", " | ") #=> ["hello ", " hello ", " hello"] splitWithoutLoss(" hello world", " |") #=> [" ", "hello ", "world"] splitWithoutLoss(" hello hello hello", " |") #=> [" ", " ", "hello ", "hello ", "hello"] splitWithoutLoss(" hello hello hello ", " |") #=> [" ", " ", "hello ", "hello ", "hello ", " "] splitWithoutLoss(" hello hello hello", "| ") #=> [" ", " hello", " hello", " hello"] ``` Also check out my other creations — [Identify Case](https://www.codewars.com/kata/identify-case), [Adding Fractions](https://www.codewars.com/kata/adding-fractions), [Random Integers](https://www.codewars.com/kata/random-integers), [Implement String#transpose](https://www.codewars.com/kata/implement-string-number-transpose), [Implement Array#transpose!](https://www.codewars.com/kata/implement-array-number-transpose), [Arrays and Procs #1](https://www.codewars.com/kata/arrays-and-procs-number-1), and [Arrays and Procs #2](https://www.codewars.com/kata/arrays-and-procs-number-2) If you notice any issues/bugs/missing test cases whatsoever, do not hesitate to report an issue or suggestion. Enjoy!
reference
def split_without_loss(s, split_p): return [i for i in s . replace(split_p . replace('|', ''), split_p). split('|') if i]
Split Without Loss
581951b3704cccfdf30000d2
[ "Fundamentals" ]
https://www.codewars.com/kata/581951b3704cccfdf30000d2
6 kyu
>When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said # Description Given a list of integers `A`, for each pair of integers `(first, last)` in list `ranges`, calculate the sum of the values in `A` between indices `first` and `last` (both inclusive), and return the greatest resulting sum. ## Example ``` A = [1, -2, 3, 4, -5, -4, 3, 2, 1] ranges = [(1, 3), (0, 4), (6, 8)] result = 6 ``` * For `ranges[0] = (1, 3)` the sum is `A[1] + A[2] + A[3] = 5` * For `ranges[1] = (0, 4)` the sum is `A[0] + A[1] + A[2] + A[3] + A[4] = 1` * For `ranges[2] = (6, 8)` the sum is `A[6] + A[7] + A[8] = 6` * The greatest sum is `6` ## Notes - The list of `ranges` will never be empty; - This is a challenge version, you should implement an efficient algorithm to avoid timing out; - If this task is too difficult for you, [try the simple version](https://www.codewars.com/kata/the-maximum-sum-value-of-ranges-simple-version/). ### About random testcases ```if:javascript - Small tests: 100 testcases - each integers-list : 5-100 elements - each ranges-list : 1-6 elements - Big tests: 100 testcases - each integers-list : 100000 elements - each ranges-list : 10000 elements ``` ```if:haskell - Small tests: 100 testcases - each integers-list : 5-100 elements - each ranges-list : 1-6 elements - Big tests: 100 testcases - each integers-list : 50000 elements - each ranges-list : 5000 elements ``` ```if:python - Small tests: 100 testcases - each integers-list : 5-20 elements - each ranges-list : 1-6 elements - Big tests: 50 testcases - each integers-list : 100000 elements - each ranges-list : 10000 elements ``` ```if:cobol - Small tests: 100 testcases - each integers-list : 5-20 elements - each ranges-list : 1-6 elements - Big tests: 20 testcases - each integers-list : 100000 elements - each ranges-list : 10000 elements ``` ```if:rust - Small tests: 100 testcases - each integers-list : 5-20 elements - each ranges-list : 1-6 elements - Big tests: 100 testcases - each integers-list : 100_000-150_000 elements - each ranges-list : 10_000 elements ```
algorithms
from itertools import accumulate def max_sum(a, ranges): prefix = list(accumulate(a, initial=0)) return max(prefix[j + 1] - prefix[i] for i, j in ranges)
The maximum sum value of ranges -- Challenge version
583d171f28a0c04b7c00009c
[ "Algorithms" ]
https://www.codewars.com/kata/583d171f28a0c04b7c00009c
5 kyu
You are given two positive integers ```a``` and ```b```. You can perform the following operations on ```a``` so as to obtain ```b``` : ``` (a-1)/2 (if (a-1) is divisible by 2) a/2 (if a is divisible by 2) a*2 ``` ```b``` will always be a power of 2. You are to write a function ```operation(a,b)``` that efficiently returns the minimum number of operations required to transform ```a``` into ```b```. For example : ``` operation(2,8) -> 2 2*2 = 4 4*2 = 8 operation(9,2) -> 2 (9-1)/2 = 4 4/2 = 2 operation(1024,1024) -> 0 ```
reference
from math import log2 def operation(a, b, n=0): while log2(a) % 1: n += 1 a / /= 2 return n + abs(log2(a / b))
Operation Transformation
579ef9607cb1f38113000100
[ "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/579ef9607cb1f38113000100
6 kyu
The number `1035` is the smallest integer that exhibits a non frequent property: one its multiples, `3105 = 1035 * 3`, has its same digits but in different order, in other words, `3105`, is one of the permutations of `1035`. The number `125874` is the first integer that has this property when the multiplier is `2`, thus: `125874 * 2 = 251748` Make the function `search_perm_mult()`, that receives an upper bound, n_max and a factor k and will output the amount of pairs bellow n_max that are permuted when an integer of this range is multiplied by `k`. The pair will be counted if the multiple is less than `n_max`, too Let'see some cases: ```python search_perm_mult(10000, 7) === 1 # because we have the pair 1359, 9513 search_perm_mult(5000, 7) === 0 # no pairs found, as 9513 > 5000 search_perm_mult(10000, 4) === 2 # we have two pairs (1782, 7128) and (2178, 8712) search_perm_mult(8000, 4) === 1 # only the pair (1782, 7128) search_perm_mult(5000, 3) === 1 # only the pair (1035, 3105) search_perm_mult(10000, 3) === 2 # found pairs (1035, 3105) and (2475, 7425) ``` Features of the random Tests: ``` 10000 <= n_max <= 100000 3 <= k <= 7 ``` Enjoy it and happy coding!!
reference
def search_perm_mult(n, k): # your code here return len([x for x in range(n, 0, - 1) if x % k == 0 and sorted([i for i in str(x)]) == sorted([i for i in str(x / / k)])])
Multiples by permutations
55f1a53d9c77b0ed4100004e
[ "Algorithms", "Data Structures", "Permutations", "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/55f1a53d9c77b0ed4100004e
6 kyu
# Task: Write a function that accepts an integer `n` and returns **the sum of the factorials of the first **`n`** Fibonacci numbers** ## Examples: ```python sum_fib(2) = 2 # 0! + 1! = 2 sum_fib(3) = 3 # 0! + 1! + 1! = 3 sum_fib(4) = 5 # 0! + 1! + 1! + 2! = 5 sum_fib(10) = 295232799039604140898709551821456501251 ``` ### Constraints: * #### **2 ≤ N ≤ 22** ### sum_fib(20) This number is so huge I need to make a separate area for it. Imagine 13327 digits! ``` 9928653736262172352930533186343606575520531508610803533683326075968136836106350614826845352855570180756973824478534264089418647583107409466601215858252808236817361583456160496394166392410547995403042278974310114004141591601125139374352094580791191335923364709192884677516337340735050881286173599870564102712009609362158555666371456178005624986162914384584598007577943876091903963220099151890758003938219580565595866639676742143436946382515603496736416191925126418083343340908123949271116414372895379936522832969271267219171603692063390922740887154834642883418078697433844957096133230670087609525899715090691322695345079984538282381903048400947073982647280054266073789965460433047857017505687076923579845694132377682637618524059408549961585446566386749648079936292462747327064278025936833852772820299004299329077053469978825203826210884509837054861371491763507148619862842220021938679732909047841993934844856085744100351944344480585890290250085308697867587494410223336675757135854894845396425849420198283310099448776692798687481179912663086426339803620627092430027074704170368638261753987720152882719584784119598849406922924689237689926900078407444035651263294341956188553177164034897593127788055904780959305194343754348362747235880809190571905064483247723280356903363273241766440842763193066919213539785095871192842692606421239731101161179953784088918780253218968714702754970829196110362712748304472981190172500985036212056008891512591715943529551666297020022545295013332792029190680584871918615789039963992955251102495832888908303508388573326404660045192343910036894576606739730009404643996768381324201684887436118525239127918313553446868369481959060346542929206914045558764481873495640902563179558939454794340645147348060531077758039291288086539035415235329745191164122884847642770184833096074380462004442126123365493535546141814052180207088441639235818177571560268970986584233066266137330817682751586180172379386539800887659067848801273458632884775993286485484439351593802875301531090263420030865043190820277288432453055603535891328518532472449422812847812206507267553254100339388907930703639015107310091345807422502366958709485299235918761467136442743369888930513387650766763462776291319611127078630770724931725881342103399855411445441188237512840869746255207308016566589688534903275723847299298209564223805258400310594489734280193445659519455562310520491149958624344934211797374144961111640480148905676602815443575797732307104495619074264135486973016187707950128055114948820599535099679109555889216345748610077647038880403151577406059562593147843869890405711177041285027897889931238424843771839668578406584337138036502578265544323641251936896555091101607304143924267167989381908487109769177267670477745652098457926314829160306769275674574505876030756947193130860459470049677851491438841393371237021867397838867622968179206043665794525786404777882878983626520891642985016057443885367272159103317999854174850166653191065899629941564603607349293929463834182817010865551370318689093045295273014513651114980596016288564139508160223681895369473793067699648316416302076351892391386318727894912644697323236666722014926057739887981902928069436545050881089761801947608921676288125099672683893303628766282286071020514503204784363394425893771312553400523338226656860526601867846681464250014432098804255258409462661142745585676872567552984225734281537836768738643384329354537747601939266791282620595759045030975407087098471302910701633632781330935697522455112544012901202754384296311873717589131299138478696753402583090947639011550806512977687205411210423316357849301559385649862307435379578361959385902196221298989933642572954710917937173791252391211314915429148069552456217875732295478439265973312228825699583169423554478095943591601486823980520979265181478839539380948270674857590218785329717118958128773306424518493835759217896759252043662826058100229991427857320674702720821115426296389687870062246589055989156285445842889514677789950880262321031452650063434014552214195771536371460986901844425547128476897052339867931194407773355276248222367620387453020534516758695700339849976170385897724159339596299051507023173489852153597518144384372166769725171047242043337130754559091790174484804816919563293006386286162511392343605301231338083421373138513205330685737005312467158986197119463173814408851556062519779146343332176587827731764626043557406516022682254455376553317636367696281143328957263465277529147227703544139848485810423066580665196185757661150648436815382333297246538979549584038243489967689778029975720307976426301731632813721053565602584006669361647374979609110217141189985003840188917225460523033372774136910715202237293584755733438042644216567563619222830113994770478752731026047788940326851901106228403003791587412047281254828416828440015032377802784094192537349093802163873170946231944133598834305362895374385296761312303210357770337974518322216075020141406284393245858603171127132598059695314335254116026015774750512204391768305611864388814440227199472085129010007050779807702538570904612612122122847785419873396835706080930837253267935078019519211144578774018539048762001166387821026612932318929275803074350763474165501151280679078295332194496653441124229917186133498390385848583459652478449111569885999320523456201264267679259698720411336081351073950683043254735712136269994989309863706475332749837817261225049835498965355121540199305600229891991390510311055201955511468648559641359346704552142776951630226650403613301783272418687520682865498961457101231849971934701035810266428273180224460545667047710066882075490868792719554023302422227138639763477450829668914441462253552608668450539166122272582169168528449566069750834510145777716497105357731601670282160142370975965269122162174709982890639939697291295471375228904389027402411105044523636299668899643497982676129894656886199644067190755704030319868386555632587398706953567999535303366271193580226657709089128550820229960260308416882836933526107327691587377547393623399330972953186821903572956890554426109892273792564476202658436982877368699363818383275571024464363253812234180181845792793023972929077048238111853410599802473730305668745780193472599637933612198999296364156279204713221276235283626829300200451729914183662584990767716790116755181810897379761267141975556520098577517615993755933880010336737582711048879991235186003896048879899162949205114351008743341082127133389810507308121724837235451061437827004583403918348794339350154038680926960868293782380474574008317208128031509436820749435677094987154671496719118040920820327150492558224268040877430396924324120417026199184321955826747197141431901476919177226217254346878767913878186347548688475492861195199281214858632047468560892609809310070198107640181730048890480497038978225910741413590570194370730003130749115464114916752595454345179936989255654870699603878866851161060795816701826411977795842165668569682457231330897409400718411292835088304936921993405033675641624187976521955004228244446698613066761411895449256872619586749956979445320224074487142401596207606341255478171157456141643714529525192876130991832916167579006407604270637756249843598869942784507887866618071296055662579691353500596369231888076374989486711621685836546185684963816358568833994505343826575562928865320538659751383972324151413647111903975144894129117141805490967234404614221912580710940662206145626801079012202740018155685922225388275607540319658217999924635859832247416785707795551860289164337197533334627825322143591076566299281852734139726398669060061427364012356206613131503747296575722224156532072756663977254150994742520621211710778895787557618218045482303060084379852358420811572817908657866670662190057861789952594451993466314364564069574684318969912777124781202527695198352359650880522887287387857757529027345970933903944473796531236930783099862375583336669555310505017811196561744578460511099439194021928186602693674359654671860317368146204110188075505252534149731812843980812547940624237843567262814283133285253930937897653100352635098717337120679226155807284748689466939956086079838110595885746613130139916205829094881298762046410938598558360125357344837946534244473840262413102128627114747968081804038270251900940965902513335390775825459105250898084371186363993871627863779925624062409301573893743068806439822744963563409079707218011171435281888565141700512698927981091846612727089877477778669289377012823124044415685345400839252784571809880579795013560422356485010963851337763312501852501309427073651842308840248721973181483285511329436724091764344874079035917982318362766292014864455202259710428424962128291813457354443795044725006153825224988609483911290917501321288252755169139113455787128689530310396891731445879174526142116320701587384574453948814035868148777367732658119774520345545849268033230248989719149723761585910729634786155492311066757412830423023217592388062762745987642551424244427273008032191956315037481291383911824942155585676496663649535850771252992699542649990490186944287473876370453000719814960648189584336387763161191340543646852608305482060694141531544009142394810789781372931168495134751777657321372292000319857647062232950656586230486886673920397794654056427228072515983426476061214304016056409168500037933108071859272519610880496790986258132266920553567366823015354488132245750701301764239392908240718371911953411492918421959129168069681436456933542324207908230546137678301833250332722752626888810140970289006477916589089543503379524601786472693487828915557196136174808810436338042378013699929852474991648407409023374169932791608084380344618735388170499897366302870465777915502098068872427872701112871075142132061242765365959925292298133381485131903408244348395101397470117677019829408610610171922941022718491779316103530497271343378039993641953787488345885112366150321408525910564079828514467058948171170356064046650092845398781480281916012072102331682413145542558482690406144983512143999906107991649126067879722887402169931955258589579638431191350838187907311860265207466608152372372686324975757176416566521640855616739172551780443241678599962342067083012790109016012557789708920368378665933606100592122866743706144656047744655504267531616892269283054115607340410319057763718556272034592657372161537684407044952851812770726615042876762960137471279787360582749788498318832487768624612393216735309107112174704997005917590506244997998484327440677599357701276620235625780027104715006458567121003924223943088598353054932602200538597908754897845417994248083861573010416290341708845316596312979430086700544475899733062567150954231823006774675784823663024300157467058615387461459584070650039355124760620620390835707206850418361441537476539111268591498489615133246551645202820903037831152063261123407680250171817323138137812181664243064610002800108244873766945365586262768271874384921780034466563639283920231853530274307280001379556387399286732464703148731202136358150075120770023425694988787417652771802108489789810295232294997367360696492315675071639130710793798755877030974532111823800049417367136357141799015726719642554174229839015284017755798832786173259586069836941404268220322258730591564817581230950070790272596989841957907031728443483956100812243968637073374397757615739553278508439590127601302123404854672654781328216788199144435601902806379348513628540817232365137238783884976806276656505352419377163767451181016485754124027864607527800888156555250523029566799443125885864101138225750570875035055230791052731355986623829344317099935988663215127843632923637509019945862723260037163763711758654934910027449834486899599704935284151804439825549707410184780069334913722693489475217978950343701008890423109631019446762801453427963033819204196016708224448110489892683975887818006071133016156204196230137144565735732627971448050002915228449970607017194915670936024070615451400858450340124834051896279154304233433399185526574106886162021602451566847606132244441829206601320244646951235636462556058511008158120562847617034399977433836554182812028983174615503556972524501626583043505526033040018204311335146256597289419055643438051722053077835209719369549795660762385560993254170876822358669533625145287503690415348418381258825644543407229190875698384908769334263504847497511095481888644836410530485021720161391301010494065372344208460777036406497525142813195828864349924050214576231802418572986682609588250501371457123447121021520167979626678883394284099255894431202158911556725161944809165555857492203486580468601431587495286434228923376855121487084939326309450268557365089173699752430489893898662385489250265455511220504498909272818152342504748405354594773985411073512586245029415937411508563697264901667841610736177613964045304417052598507762458560141472118059594453400614670799390380457850336769285069013762709299827624317895195392205084179575761814272248901581426836448816408345286493938630461130199287182091992175901271419463658156059897613116232352344615930679227026805733163636226860911569149927129575635688070885630503861218683566424095254861289021651900181379848635536499979380325867886712531123383268402905017112936324294590630632726149686444783548783464832804820259414304101857646550755288386977584758321913103895323544792245725854568887427421517632337140967111574191495525993879337401130692171554751659027957848494551494728291479587113405605656213093078075724510421856398851392665808777758866365553958287771740614526422853397161756204153702200474053334460985391821456501251 ``` # Notes: * I use `test.expect` to make tests secret. If I use `test.assert_equals`, the output will be unreadable because the numbers are huge.
reference
from math import factorial def sum_fib(n): a, b, s = 0, 1, 0 while n: s += factorial(a) a, b = b, a + b n -= 1 return s
Fib Factorials
589926bf7a2a3992050014f1
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/589926bf7a2a3992050014f1
6 kyu
Implement a function, `multiples(m, n)`, which returns an array of the first `m` multiples of the real number `n`. Assume that `m` is a positive integer. Ex. ``` multiples(3, 5.0) ``` should return ``` [5.0, 10.0, 15.0] ```
reference
def multiples(m, n): return [i * n for i in range(1, m + 1)]
Return the first M multiples of N
593c9175933500f33400003e
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/593c9175933500f33400003e
7 kyu
It's the most hotly anticipated game of the school year - Gryffindor vs Slytherin! Write a function which returns the winning team. You will be given two arrays with two values. The first given value is the number of points scored by the team's Chasers and the second a string with a 'yes' or 'no' value if the team caught the golden snitch! The team who catches the snitch wins their team an extra 150 points - but doesn't always win them the game. ```javascript gameWinners([150, 'yes'],[200, 'no']) //'Gryffindor wins!' gameWinners([400, 'no'],[350, 'yes']) //'Slytherin wins!' ``` If the score is a tie return "It's a draw!"" ** The game only ends when someone catches the golden snitch, so one array will always include 'yes' or 'no.' Points scored by Chasers can be any positive integer.
reference
def game_winners(gryffindor, slytherin): g, s = (team[0] + 150 * (team[1] == 'yes') for team in [gryffindor, slytherin]) return 'Gryffindor wins!' if g > s else 'Slytherin wins!' if s > g else "It's a draw!"
Gryffindor vs Slytherin Quidditch Game
5840946ea3d4c78e90000068
[ "Fundamentals" ]
https://www.codewars.com/kata/5840946ea3d4c78e90000068
7 kyu
*This is my first Kata in the Ciphers series. This series is meant to test our coding knowledge.* ## Ciphers #1 - The 01 Cipher This cipher doesn't exist, I just created it by myself. It can't actually be used, as there isn't a way to decode it. It's a hash. Multiple sentences may also have the same result. ## How this cipher works It looks at the letter, and sees it's index in the alphabet, the alphabet being `a-z`, if you didn't know. If it is odd, it is replaced with `1`, if it's even, its replaced with `0`. Note that the index should start from 0. Also, if the character isn't a letter, it remains the same. ## Example ```javascript encode("Hello World!"); // => "10110 00111!" ``` This is because `H`'s index is `7`, which is odd, so it is replaced by `1`, and so on. Have fun (en)coding!
reference
def encode(s): return '' . join(str(1 - ord(c) % 2) if c . isalpha() else c for c in s)
Ciphers #1 - The 01 Cipher
593f50f343030bd35e0000c6
[ "Fundamentals" ]
https://www.codewars.com/kata/593f50f343030bd35e0000c6
7 kyu
For a given large number (num), write a function which returns the number with the second half of digits changed to 0. In cases where the number has an odd number of digits, the middle digit onwards should be changed to 0. <b>Example</b>: 192827764920 --> 192827000000 938473 --> 938000 2837743 --> 2830000
reference
def manipulate(n): n = str(n) middle = len(n) / / 2 return int(n[: middle] + '0' * len(n[middle:]))
Number Manipulation I (Easy)
5890579a34a7d44f3b00009e
[ "Fundamentals" ]
https://www.codewars.com/kata/5890579a34a7d44f3b00009e
7 kyu
You have to create a function named`one_two` (`oneTwo` for Java or `Preloaded.OneTwo` for C#) that returns 1 or 2 with equal probabilities. `one_two` is already defined in a global scope and can be called everywhere. Your goal is to create a function named `one_two_three` (`oneTwoThree` for Java or `OneTwoThree` for C#) that returns 1, 2 or 3 with equal probabilities using only the `one_two` function. Do not try to cheat returning repeating non-random sequences. There is a randomness test especially for this case.
games
def one_two_three(): res = one_two(), one_two() return (1 if res == (1, 1) else 2 if res == (1, 2) else 3 if res == (2, 1) else one_two_three())
Return 1, 2, 3 randomly
593e84f16e836ca9a9000054
[ "Probability", "Puzzles" ]
https://www.codewars.com/kata/593e84f16e836ca9a9000054
6 kyu
Given a matrix represented as a list of string, such as ``` ###..... ..###... ....###. .....### .....### ....###. ..###... ###..... ``` write a function ```if:javascript `rotateClockwise(matrix)` ``` ```if:ruby,python `rotate_clockwise(matrix)` ``` that return its 90° clockwise rotation, for our example: ``` #......# #......# ##....## .#....#. .##..##. ..####.. ..####.. ...##... ``` > <strong style="color:red;"> /!\ </strong> You must return a **rotated copy** of `matrix`! (`matrix` must be the same before and after calling your function) > Note that the matrix isn't necessarily a square, though it's always a rectangle! > Please also note that the equality `m == rotateClockwise(rotateClockwise(rotateClockwise(rotateClockwise(m))));` (360° clockwise rotation), is not always true because `rotateClockwise([''])` => `[]` and `rotateClockwise(['','',''])` => `[]` (empty lines information is lost)
reference
def rotate_clockwise(m): return ['' . join(l[:: - 1]) for l in zip(* m)]
Matrix Rotation
593e978a3bb47a8308000b8f
[ "Matrix", "Fundamentals" ]
https://www.codewars.com/kata/593e978a3bb47a8308000b8f
6 kyu
# Introduction There is a war and nobody knows - the alphabet war! The letters called airstrikes to help them in war - dashes and dots are spread everywhere on the battlefield. # Task Write a function that accepts `reinforces` array of strings and `airstrikes` array of strings. The `reinforces` strings consist of only small letters. The size of each string in `reinforces` array is the same. The `airstrikes` strings consists of `*` and white spaces. The size of each airstrike may vary. There may be also no airstrikes at all. The first row in `reinforces` array is the current battlefield. Whenever some letter is killed by bomb, it's replaced by a letter from next string in `reinforces` array on the same position. The airstrike always starts from the beginning of the battlefield. The `*` means a bomb drop place. The each `*` bomb kills letter only on the battelfield. The bomb kills letter on the same index on battlefield plus the adjacent letters. The letters on the battlefield are replaced after airstrike is finished. Return string of letters left on the battlefield after the last airstrike. In case there is no any letter left in `reinforces` on specific position, return `_`. ``` reinforces = [ "abcdefg", "hijklmn"]; airstrikes = [ " * ", "* * "]; The battlefield is : "abcedfg". The first airstrike : " * " After first airstrike : "ab___fg" Reinforces are comming : "abjklfg" The second airstrike : "* * " After second airstrike : "_____fg" Reinforces are coming : "hi___fg" No more airstrikes => return "hi___fg" ``` # Other example ``` reinforces = ["g964xxxxxxxx", "myjinxin2015", "steffenvogel", "smile67xxxxx", "giacomosorbi", "freywarxxxxx", "bkaesxxxxxxx", "vadimbxxxxxx", "zozofouchtra", "colbydauphxx" ]; airstrikes = ["* *** ** ***", " ** * * * **", " * *** * ***", " ** * * ** ", "* ** * ***", "*** ", "**", "*", "*" ] ``` That should lead to: ```javascript alphabetWar(reinforces, airstrikes); // => codewarsxxxx ``` ```python alphabet_war(reinforces, airstrikes); # => codewarsxxxx ``` ```csharp alphabetWar(reinforces, airstrikes); // => codewarsxxxx ``` ```java AlphabetWars.reinforcesMassacre(reinforces, airstrikes); // => codewarsxxxx ``` ```c alphabet_war(reinforces, airstrikes, 10, 9); /* => codewarsxxxx */ ``` ```nasm mov rdi, reinforces mov rsi, airstrikes mov rdx, 10 mov rcx, 9 call alphabet_war ; RAX <- "codewarsxxxx" ``` # Alphabet war Collection <table border="0" cellpadding="0" cellspacing="0"> <tr> <td ><a href="https://www.codewars.com/kata/59377c53e66267c8f6000027" target="_blank">Alphavet war </a></td> </tr> <tr> <td ><a href="https://www.codewars.com/kata/5938f5b606c3033f4700015a" target="_blank">Alphabet war - airstrike - letters massacre</a></td> </tr> <tr> <td ><a href="https://www.codewars.com/kata/alphabet-wars-reinforces-massacre" target="_blank">Alphabet wars - reinforces massacre</a></td> </tr> <tr> <td ><a href="https://www.codewars.com/kata/59437bd7d8c9438fb5000004" target="_blank">Alphabet wars - nuclear strike</a></td> </tr> <tr> <td ><a href="https://www.codewars.com/kata/59473c0a952ac9b463000064" target="_blank">Alphabet war - Wo lo loooooo priests join the war</a></td> </tr> </table>
reference
def alphabet_war(r, airstrikes): rIdx = [0] * (len(r[0]) + 2) for a in airstrikes: massacre = {i + d for i, c in enumerate(a, 1) for d in range(- 1, 2) if c == '*'} for i in massacre: rIdx[i] += 1 return '' . join(r[row][i] if row < len(r) else "_" for i, row in enumerate(rIdx[1: - 1]))
Alphabet wars - reinforces massacre
593e2077edf0d3e2d500002d
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/593e2077edf0d3e2d500002d
6 kyu
You are very very happy and very very very excited to solve this Kata. Show it to us by creating a function `iam` such as: ```javascript iam('happy') // returns the string "I am happy" iam('excited') // returns the string "I am excited" iam()('scared') // returns the string "I am very scared" iam()()('interested') // returns the string "I am very very interested" ``` and so on... As you understood, the function `iam` accept 1 optional parameter. If provided, the function returns a `string`. If NOT provided, it must returns a `function` allowing to continue the sentence. I am very very very curious to see you approach the problem. Enjoy!
reference
def iam(* s, n=0): return f'I am { " very" * n } { s [ 0 ] } ' if s else lambda * s: iam(* s, n=n + 1)
I am very very very....
58402cdc5225619d0c0000cb
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/58402cdc5225619d0c0000cb
6 kyu
A faro shuffle of a deck of playing cards is a shuffle in which the deck is split exactly in half and then the cards in the two halves are perfectly interwoven, such that the original bottom card is still on the bottom and the original top card is still on top. For example, faro shuffling the list ```python ['ace', 'two', 'three', 'four', 'five', 'six'] ``` gives ```python ['ace', 'four', 'two', 'five', 'three', 'six' ] ``` If `8` perfect faro shuffles are performed on a deck of `52` playing cards, the deck is restored to its original order. Write a function that takes an integer `n` and returns an integer representing the number of faro shuffles it takes to restore a deck of `n` cards to its original order. Assume `n` is an even number between `2` and `2000`.
reference
def faro_cycles(n): x, cnt = 2, 1 while x != 1 and n > 3: cnt += 1 x = x * 2 % (n - 1) return cnt
Faro Shuffle Count
57bc802c615f0ba1e3000029
[ "Lists", "Iterators", "Fundamentals" ]
https://www.codewars.com/kata/57bc802c615f0ba1e3000029
6 kyu
You need to cook pancakes, but you are very hungry. As known, one needs to fry a pancake one minute on each side. What is the minimum time you need to cook `n` pancakes, if you can put on the frying pan only `m` pancakes at a time? `n` and `m` are positive integers between 1 and 1000.
reference
from math import ceil def cook_pancakes(n, m): if m > n: return 2 else: return ceil((n / m) * 2)
Fast cooking pancakes
58552bdb68b034a1a80001fb
[ "Logic", "Fundamentals" ]
https://www.codewars.com/kata/58552bdb68b034a1a80001fb
7 kyu
# Task Smartphones software security has become a growing concern related to mobile telephony. It is particularly important as it relates to the security of available personal information. For this reason, Ahmed decided to encrypt phone numbers of contacts in such a way that nobody can decrypt them. At first he tried encryption algorithms very complex, but the decryption process is tedious, especially when he needed to dial a speed dial. He eventually found the algorithm following: instead of writing the number itself, Ahmed multiplied by 10, then adds the result to the original number. For example, if the phone number is `123`, after the transformation, it becomes `1353`. Ahmed truncates the result (from the left), so it has as many digits as the original phone number. In this example Ahmed wrote `353` instead of `123` in his smart phone. Ahmed needs a program to recover the original phone number from number stored on his phone. The program return "impossible" if the initial number can not be calculated. Note: There is no left leading zero in either the input or the output; Input `s` is given by string format, because it may be very huge ;-) # Example For `s="353"`, the result should be `"123"` ``` 1230 + 123 ....... = 1353 truncates the result to 3 digit -->"353" So the initial number is "123" ``` For `s="123456"`, the result should be `"738496"` ``` 7384960 + 738496 ......... = 8123456 truncates the result to 6 digit -->"123456" So the initial number is "738496" ``` For `s="4334"`, the result should be `"impossible"` Because no such a number can be encrypted to `"4334"`. # Input/Output - `[input]` string `s` string presentation of n with `1 <= n <= 10^100` - `[output]` a string The original phone number before encryption, or `"impossible"` if the initial number can not be calculated.
games
def decrypt(s): for n in range(1, 11): res, mod = divmod(int(str(n) + s), 11) if mod == 0: return str(res) return 'impossible'
Simple Fun #126: Decrypt Number
58a3cb34623e8c119d0000d5
[ "Puzzles" ]
https://www.codewars.com/kata/58a3cb34623e8c119d0000d5
6 kyu
Find the longest substring within a string that contains at most 2 unique characters. ``` substring("a") => "a" substring("aaa") => "aaa" substring("abacd") => "aba" substring("abacddcd") => "cddcd" substring("cefageaacceaccacca") => "accacca" ``` This function will take alphanumeric characters as input. In cases where there could be more than one correct answer, the first string occurrence should be used. For example, substring('abc') should return 'ab' instead of 'bc'. Although there are O(N^2) solutions to this problem, you should try to solve this problem in O(N) time. Tests may pass for O(N^2) solutions but, this is not guaranteed. This question is much harder than some of the other substring questions. It's easy to think that you have a solution and then get hung up on the implementation.
algorithms
def substring(s): r, rm = [], [] for i, x in enumerate(s): if x in r or len(set(r)) < 2: r += x else: if len(r) > len(rm): rm = r[:] r = [y for y in r[- 1:: - 1] if y == r[- 1]] + [x] if len(r) > len(rm): rm = r[:] return '' . join(rm)
Longest 2-character substring
55bc0c54147a98798f00003e
[ "Algorithms" ]
https://www.codewars.com/kata/55bc0c54147a98798f00003e
6 kyu
Your task is to create a new implementation of `modpow` so that it computes `(x^y)%n` for large `y`. The problem with the current implementation is that the output of `Math.pow` is so large on our inputs that it won't fit in a 64-bit float. You're also going to need to be efficient, because we'll be testing some pretty big numbers. ```if:python A lot of things have been forbidden. Amidst others, don't: - ...import things - ...use eval, exec, compile, ... and a lot of things you'd use to cheat your way through the kata - ...use the `int.__pow__` method Due to these limitations, you cannot use any property or method (like, even `lst.append` is forbidden). But don't worry, you don't need this to solve the kata... ;) ``` ```if:haskell Some obscure imports have been forbidden. ``` ~~~if:lambdacalc ## Encodings Numbers: [`BinaryScott`](https://github.com/codewars/lambda-calculus/wiki/encodings-guide#scott-binary-encoded-numerals)</br> Purity: [`LetRec`](https://github.com/codewars/lambda-calculus/wiki/Introduction-to-Lambda-Calculus#define-named-terms) ~~~ ## Random tests ~~~if:cobol `$15$` random tests with `$2 \le x \le 40001$`, `$3000000 \le y \le 2000000000$`, `$1000 \le n \le 10000000$`. ~~~ ~~~if:haskell `$2 \le x \le 40000$`, `$3000000 \le y \le 2000000000$`, `$1000 \le n \le 10000000$`. ~~~ ~~~if:javascript,coffeescript,c `$150$` random tests with `$2 \le x \le 40000$`, `$3000000 \le y \le 2000000000$`, `$1000 \le n \le 10000000$`. ~~~ ~~~if:lambdacalc `$10$` random tests with `$2 \le x \le 4000$`, `$30000 \le y \le 2000000$`, `$100 \le n \le 1000$`. ~~~ ~~~if:python `$150$` random tests with `$2 \le x \le 40000$`, `$3000000 \le y \le 4000000000$`, `$1000 \le n \le 10000000$`. ~~~
algorithms
def power_mod(b, e, m): res, b = 1, b % m while e > 0: if e & 1: res = res * b % m e >>= 1 b = b * b % m return res
Efficient Power Modulo n
52fe629e48970ad2bd0007e6
[ "Mathematics", "Algorithms", "Performance" ]
https://www.codewars.com/kata/52fe629e48970ad2bd0007e6
5 kyu
For a given list `[x1, x2, x3, ..., xn]` compute the last (decimal) digit of `x1 ^ (x2 ^ (x3 ^ (... ^ xn)))`. E. g., with the input `[3, 4, 2]`, your code should return `1` because `3 ^ (4 ^ 2) = 3 ^ 16 = 43046721`. _Beware:_ powers grow incredibly fast. For example, `9 ^ (9 ^ 9)` has more than 369 millions of digits. `lastDigit` has to deal with such numbers efficiently. _Corner cases:_ we assume that `0 ^ 0 = 1` and that `lastDigit` of an empty list equals to 1. This kata generalizes [Last digit of a large number](http://www.codewars.com/kata/last-digit-of-a-large-number/haskell); you may find useful to solve it beforehand.
algorithms
def last_digit(lst): n = 1 for x in reversed(lst): n = x * * (n if n < 4 else n % 4 + 4) return n % 10
Last digit of a huge number
5518a860a73e708c0a000027
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/5518a860a73e708c0a000027
3 kyu
In this country soldiers are poor but they need a certain level of secrecy for their communications so, though they do not know Caesar cypher, they reinvent it in the following way. The action of a Caesar cipher is to replace each plaintext letter (plaintext letters are from 'a' to 'z' or from 'A' to 'Z') with a different one a fixed number of places up or down the alphabet. This displacement of a number of places is called the "shift" or the "rotate" of the message. For example, if the shift is `1` letter `a` becomes `b` and `A` becomes `B`; the shift is cyclic so, with a shift of `1`, `z` becomes `a` and `Z` becomes`A`. They use ASCII, without really knowing it, but code only letters a-z and A-Z. Other characters are kept such as. They change the "rotate" each new message. This "rotate" is a prefix for their message once the message is coded. The prefix is built of 2 letters, the second one being shifted from the first one by the "rotate", the first one is the first letter, after being downcased, of the uncoded message. For example if the "rotate" is 2, if the first letter of the uncoded message is 'J' the prefix should be 'jl'. To lessen risk they cut the coded message and the prefix in five pieces since they have only five runners and each runner has only one piece. If possible the message will be evenly split between the five runners; if not possible, parts 1, 2, 3, 4 will be longer and part 5 shorter. The fifth part can have length equal to the other ones or shorter. If there are many options of how to split, choose the option where the fifth part has the longest length, provided that the previous conditions are fulfilled. *If the last part is the empty string don't put this empty string in the resulting array.* For example, if the coded message has a length of 17 the five parts will have lengths of 4, 4, 4, 4, 1. The parts 1, 2, 3, 4 are evenly split and the last part of length 1 is shorter. If the length is 16 the parts will be of lengths 4, 4, 4, 4, 0. Parts 1, 2, 3, 4 are evenly split and the fifth runner will stay at home since his part is the empty string and is not kept. Could you ease them in programming their coding? Example with shift = 1 : message : "I should have known that you would have a perfect answer for me!!!" code : => ["ijJ tipvme ibw", "f lopxo uibu z", "pv xpvme ibwf ", "b qfsgfdu botx", "fs gps nf!!!"] By the way, maybe could you give them a hand to decode? Caesar cipher : see Wikipedia
reference
def shift_char(c, i): r = c if ord('a') <= ord(c) <= ord('z'): o = (ord(c) - ord('a') + i) % 26 r = chr(o + ord('a')) elif ord('A') <= ord(c) <= ord('Z'): o = (ord(c) - ord('A') + i) % 26 r = chr(o + ord('A')) return r def encode_str(strng, shift): encoded = "" c = str(strng[0]). lower() encoded = c + shift_char(c, shift) for s in strng: encoded += shift_char(s, shift) chunk = len(encoded) / / 5 if len(encoded) % 5 != 0: chunk += 1 r = [encoded[i * chunk:(i + 1) * chunk] for i in range(5)] if (r[4] == ""): return r[0: - 1] else: return r def decode(arr): encoded = "" . join(arr) result = "" shift = - (ord(encoded[1]) - ord(encoded[0]) % 26) for s in encoded[2:]: result += shift_char(s, shift) return result
Second Variation on Caesar Cipher
55084d3898b323f0aa000546
[ "Fundamentals", "Ciphers", "Cryptography" ]
https://www.codewars.com/kata/55084d3898b323f0aa000546
5 kyu
## Task You are given a car odometer which displays the miles traveled as an integer. The odometer has a defect, however: it proceeds from digit `3` to digit `5` always skipping the digit `4`. This defect shows up in all positions (ones, tens, hundreds, etc). For example, if the odometer displays `15339` and the car travels another mile, the odometer changes to `15350` (instead of `15340`). Your task is to calculate the real distance, according The number the odometer shows. ## Example For `n = 13` the output should be `12`(4 skipped). For `n = 15` the output should be `13`(4 and 14 skipped). For `n = 2003` the output should be `1461`. ## Input/Output - `[input]` integer `n` The number the odometer shows. `1 <= n <= 999999999` - `[output]` an integer The real distance.
algorithms
tr = str . maketrans('56789', '45678') def faulty_odometer(n): return int(str(n). translate(tr), 9)
Simple Fun #178: Faulty Odometer
58b8d22560873d9068000085
[ "Algorithms" ]
https://www.codewars.com/kata/58b8d22560873d9068000085
5 kyu
A common problem in number theory is to find x given a such that: a * x = 1 mod [n] Then x is called the inverse of a modulo n. Your goal is to code a function inverseMod wich take a and n as parameters and return x. You may be interested by these pages: http://en.wikipedia.org/wiki/Modular_multiplicative_inverse http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm a and n should be co-prime to have a solution, if it is not the case, you should return None (Python), nil (Ruby), null (Javascript) or 0 (COBOL). a and n will be positive integers. The problem can easily be generalised to negative integer with some sign changes so we won't deal with them.
algorithms
from math import gcd def inverseMod(a, m): if gcd(a, m) == 1: return pow(a, - 1, m)
Modular Multiplicative Inverse
53c945d750fe7094ee00016b
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/53c945d750fe7094ee00016b
6 kyu
This Kata is a continuation of [Part 1](http://www.codewars.com/kata/the-fusc-function-part-1). The `fusc` function is defined recursively as follows: fusc(0) = 0 fusc(1) = 1 fusc(2n) = fusc(n) fusc(2n + 1) = fusc(n) + fusc(n + 1) Your job is to produce the code for the `fusc` function. In this kata, your function will be tested with large values of `n` more than 1000 bits ( in LC and PHP: at most 52 bits, in OCaml: at most 64 bits ), so you should be concerned about stack overflow and timeouts. Method suggestion: Imagine that instead of `fusc(n)`, you were to implement `fib(n)`, which returns the n'th Fibonacci number. The function is recursively defined by: ``` 1. fib(0) = 1 2. fib(1) = 1 3. fib(n + 2) = fib(n) + fib(n + 1), if n + 2 > 1 ``` If one translates the above definition directly into a recursive function, the result is not very efficient. One can try memoization, but that requires lots of space and is not necessary. So, first step is to try and find a _tail recursive_ definition. In order to do that we try to write both sides of equation 3) on the same form. Currently, the left side of the equation contains a single term, whereas the right side is the sum of two terms. A first attempt is to add `fib(n + 1)` to both sides of the equation: ``` 3. fib(n + 1) + fib(n + 2) = fib(n) + 2 * fib(n + 1) ``` The two sides of the equation look much more alike, but there is still an essential difference, which is the coefficient of the second term of each side. On the left side of the equation, it is `1` and, on the right, it is `2`. To remedy this, we can introduce a variable `b`: ``` 3. fib(n + 1) + b * fib(n + 2) = b * fib(n) + (b + 1) * fib(n + 1) ``` We notice that the coefficients of the first term are not the same (`1` on the left and `b` on the right), so we introduce a variable `a`: ``` 3. a * fib(n + 1) + b * fib(n + 2) = b * fib(n) + (a + b) * fib(n + 1) ``` Now the two sides have the same form (call it `F`), which we can define as: ```F(a, b, n) = a * fib(n) + b * fib(n + 1)``` In fact, we can write equation 3) as: ``` 3. F(a, b, n + 1) = F(b, a + b, n) ``` We also have, by definition of `F` and `fib`: ``` 4. F(a, b, 0) = a * fib(0) + b * fib(1) = a + b ``` Also, by definition of `F`: ``` 5. fib(n) = F(1, 0, n) ``` The next step is to translate the above into code: ``` def fib(n): def F(a, b, n): if n == 0: return a + b # see 4. above return F(b, a + b, n - 1) # see 3. above return F(1, 0, n) # see 5. above ``` The final step (optional for languages that support tail call optimization) is to replace the tail recursive function `F` with a loop: ``` def fib(n): a, b = 1, 0 # see 5. above while n > 0: a, b, n = b, a + b, n - 1 # see 3. above return a + b . # see 4. above ``` Voila! Now, go do the same with `fusc`. ~~~if:lambdacalc ### Encodings purity: `LetRec` numEncoding: `BinaryScott` ~~~
algorithms
def fusc(n): a, b = 1, 0 for i in bin(n)[2:]: if i == '1': b += a else: a += b return b
The fusc function -- Part 2
57040e445a726387a1001cf7
[ "Algorithms", "Recursion" ]
https://www.codewars.com/kata/57040e445a726387a1001cf7
4 kyu
Every natural number, ```n```, may have a prime factorization like: <a href="http://imgur.com/M5n0WCg"><img src="http://i.imgur.com/M5n0WCg.png?1" title="source: imgur.com" /></a> We define the arithmetic derivative of ```n```, ```n'``` the value of the expression: <a href="http://imgur.com/D9Ckb8P"><img src="http://i.imgur.com/D9Ckb8P.png?1" title="source: imgur.com" /></a> Let's do the calculation for ```n = 231525```. ``` 231525 = 3³5²7³ n' = (3*3²)*5²7³ + 3³*(2*5)*7³ + 3³*5²*(3*7²) = 231525 + 92610 + 99225 = 423360 ``` We may make a chain of arithmetic derivatives, starting from a number we apply to the result the transformation and so on until we get the result ```1```. ``` n ---> n' ---> (n')' ---> ((n')')' ---> ..... ---> ((...(n')...)')' ``` Let's do it starting with our number, ```n = 231525``` and making a chain of 5 terms: ``` 231525 ---> 423360 ---> 1899072 ---> 7879680 ---> 51895296 ``` We need a function ```chain_arith_deriv()``` that receives two arguments: ```start``` and ```k```, amount of terms of the chain. The function should output the chain in an array format: ``` chain_arith_deriv(start, k) ---> [start, term1, term2, .....term(k-1)] # a total of k-terms ``` For the case presented above: ```python chain_arith_deriv(231525, 5) == [231525, 423360, 1899072, 7879680, 51895296] ``` The function has to reject prime numbers giving an alerting message ```python chain_arith_deriv(997, 5) == "997 is a prime number" ``` Features of the tests: ``` Number of Random Tests: 50 1000 ≤ start ≤ 99000000 3 ≤ k ≤ 15 ``` Enjoy it and do your best!
reference
from collections import Counter def factorization(n): res, cur = Counter(), 2 while n > 1 and n >= cur * * 2: if n % cur == 0: res[cur] += 1 n / /= cur else: cur += (1 if cur == 2 else 2) if n > 1: res[n] += 1 return res def arithm_deriv(n): return sum(pw * n / / pr for pr, pw in factorization(n). items()) if n > 1 else 1 def chain_arith_deriv(start, k): if arithm_deriv(start) == 1: return '{} is a prime number' . format(start) res = [start] for _ in range(k - 1): res . append(arithm_deriv(res[- 1])) return res
Building Chains Using the Arithmetic Derivative of a Number
572ced1822719279fa0005ea
[ "Fundamentals", "Mathematics", "Recursion" ]
https://www.codewars.com/kata/572ced1822719279fa0005ea
6 kyu
Ever since you started work at the grocer, you have been faithfully logging down each item and its category that passes through. One day, your boss walks in and asks, "Why are we just randomly placing the items everywhere? It's too difficult to find anything in this place!" Now's your chance to improve the system, impress your boss, and get that raise! The input is a comma-separated list with category as the prefix in the form `"fruit_banana"`. Your task is to group each item into the 4 categories `Fruit, Meat, Other, Vegetable` and output a string with a category on each line followed by a sorted comma-separated list of items. For example, given: ``` "fruit_banana,vegetable_carrot,fruit_apple,canned_sardines,drink_juice,fruit_orange" ``` output: ``` "fruit:apple,banana,orange\nmeat:\nother:juice,sardines\nvegetable:carrot" ``` Assume that: 1. Only strings of the format `category_item` will be passed in 2. Strings will always be in lower case 3. Input will not be empty 4. Category and/or item will not be empty 5. There will be no duplicate items 6. All categories may not have items
reference
def group_groceries(groceries): categories = {"fruit": [], "meat": [], "other": [], "vegetable": []} for entry in groceries . split(","): category, item = entry . split("_") categories[category if category in categories else "other"]. append(item) return "\n" . join([f" { category } : { ',' . join ( sorted ( items ))} " for category, items in categories . items()])
Grocer Grouping
593c0ebf8b90525a62000221
[ "Fundamentals" ]
https://www.codewars.com/kata/593c0ebf8b90525a62000221
6 kyu
Create a combat function that takes the player's current health and the amount of damage recieved, and returns the player's new health. Health can't be less than <b>0<b>.
reference
def combat(health, damage): return max(0, health - damage)
Grasshopper - Terminal game combat function
586c1cf4b98de0399300001d
[ "Fundamentals" ]
https://www.codewars.com/kata/586c1cf4b98de0399300001d
8 kyu
<div style="border:1px solid;position:relative;padding:1ex 1ex 1ex 11.1em;"><div style="position:absolute; left:0;top:0;bottom:0; width:10em; padding:1ex;text-align:center;border:1px solid;margin:0 1ex 0 0;color:#000;background-color:#eee;font-variant:small-caps">Part of Series 3/3</div><div>This kata is part of a series on the Morse code. Make sure you solve the [first part](/kata/decode-the-morse-code) and the [second part](/kata/decode-the-morse-code-advanced) and then reuse and advance your code to solve this one.</div></div><br>In this kata you have to deal with "real-life" scenarios, when Morse code transmission speed slightly varies throughout the message as it is sent by a non-perfect human operator. Also the sampling frequency may not be a multiple of the length of a typical "dot". For example, the message <code>HEY JUDE</code>, that is <code>···· · −·−− &nbsp; ·−−− ··− −·· ·</code> may actually be received as follows: <code>0000000011011010011100000110000001111110100111110011111100000000000111011111111011111011111000000101100011111100000111110011101100000100000</code> As you may see, this transmission is generally accurate according to the standard, but some dots and dashes and pauses are a bit shorter or a bit longer than the others. Note also, that, in contrast to the previous kata, the estimated average rate (bits per dot) may not be a whole number &ndash; as the hypotetical transmitter is a human and doesn't know anything about the receiving side sampling rate. For example, you may sample line 10 times per second (100ms per sample), while the operator transmits so that his dots and short pauses are 110-170ms long. Clearly 10 samples per second is enough resolution for this speed (meaning, each dot and pause is reflected in the output, nothing is missed), and dots would be reflected as 1 or 11, but if you try to estimate rate (bits per dot), it would not be 1 or 2, it would be about (110 + 170) / 2 / 100 = 1.4. Your algorithm should deal with situations like this well. Also, remember that each separate message is supposed to be possibly sent by a different operator, so its rate and other characteristics would be different. So you have to analyze each message (i. e. test) independently, without relying on previous messages. On the other hand, we assume the transmission charactestics remain consistent throghout the message, so you have to analyze the message as a whole to make decoding right. Consistency means that if in the beginning of a message '11111' is a dot and '111111' is a dash, then the same is true everywhere in that message. Moreover, it also means '00000' is definitely a short (in-character) pause, and '000000' is a long (between-characters) pause. That said, your task is to implement two functions: 1.&nbsp;Function <code>decodeBitsAdvanced(bits)</code>, that should find an estimate for the transmission rate of the message, take care about slight speed variations that may occur in the message, correctly decode the message to dots <code>.</code>, dashes <code>-</code> and spaces (one between characters, three between words) and return those as a string. Note that some extra <code>0</code>'s may naturally occur at the beginning and the end of a message, make sure to ignore them. If message is empty or only contains <code>0</code>'s, return empty string. Also if you have trouble discerning if the particular sequence of <code>1</code>'s is a dot or a dash, assume it's a dot. If stuck, check <a href="https://en.wikipedia.org/wiki/K-means_clustering">this</a> for ideas. 2.&nbsp;Function <code>decodeMorse(morseCode)</code>, that would take the output of the previous function and return a human-readable string. If the input is empty string or only contains spaces, return empty string. **NOTE:** For coding purposes you have to use ASCII characters `.` and `-`, not Unicode characters. The Morse code table is preloaded for you as <code>MORSE_CODE</code> dictionary, feel free to use it. For C, the function `morse_code` acts like the dictionary. For C++, Scala and Go, a map is used. For C#, it's called <code>Preloaded.MORSE_CODE</code>. For Racket, a hash called MORSE-CODE is used. ```racket (hash-ref MORSE-CODE "".-.") ; returns "C" ``` ```c const char *morse_code (const char *dotsdashes); ``` ```cpp extern map <string, string> morse_code; ``` ```scala val MorseCodes.MORSE_CODE: Map[string, string]; ``` ```go var MORSE_CODE map[string]string ``` Of course, not all messages may be fully automatically decoded. But you may be sure that all the test strings would be valid to the point that they could be reliably decoded as described above, so you may skip checking for errors and exceptions, just do your best in figuring out what the message is! Good luck!
algorithms
import re def decodeBitsAdvanced(bits): out, bits = '', bits . strip('0') if bits == "": return bits len1, len0 = map(len, re . findall(r'1+', bits) ), map(len, re . findall(r'0+', bits)) mlen1 = min(len1) mlen0 = min(len0) if len0 else mlen1 lenbit = max(len1) if max(len1) == min( mlen1, mlen0) else float(max(len1)) / 2 b = re . findall(r'1+|0+', bits) for i in b: if len(i) >= lenbit * 2.3 and len(i) > 4 and i[0] == '0': out += ' ' elif len(i) > lenbit and i[0] == '1': out += '-' elif len(i) > lenbit and i[0] == '0': out += ' ' elif len(i) <= lenbit and i[0] == '1': out += '.' return out def decodeMorse(morseCode): return ' ' . join('' . join(MORSE_CODE[l] for l in w . split()) for w in morseCode . split(' '))
Decode the Morse code, for real
54acd76f7207c6a2880012bb
[ "Algorithms" ]
https://www.codewars.com/kata/54acd76f7207c6a2880012bb
2 kyu
Mrs Jefferson is a great teacher. One of her strategies that helped her to reach astonishing results in the learning process is to have some fun with her students. At school, she wants to make an arrangement of her class to play a certain game with her pupils. For that, she needs to create the arrangement with **the minimum amount of groups that have consecutive sizes**. Let's see. She has ```14``` students. After trying a bit she could do the needed arrangement: ```[5, 4, 3, 2]``` - one group of ```5``` students - another group of ```4``` students - then, another one of ```3``` - and finally, the smallest group of ```2``` students. As the game was a success, she was asked to help to the other classes to teach and show the game. That's why she desperately needs some help to make this required arrangements that make her spend a lot of time. To make things worse, she found out that there are some classes with some special number of students that is impossible to get that arrangement. Please, help this teacher! Your code will receive the number of students of the class. It should output the arrangement as an array with the consecutive sizes of the groups in decreasing order. For the special case that no arrangement of the required feature is possible the code should output ```[-1] ``` The value of n is unknown and may be pretty high because some classes joined to to have fun with the game. You may see more example tests in the Example Tests Cases Box.
reference
def shortest_arrang(n): # For odd n, we can always construct n with 2 consecutive integers. if n % 2 == 1: return [n / / 2 + 1, n / / 2] # For even n, n is the sum of either an odd number or even number of # consecutive positive integers. Moreover, this property is exclusive. for i in range(3, n / / 2): if i % 2 == 1 and n % i == 0: # For odd i, if n / i is an integer, then the sequence, which has # odd length, is centered around n / i. return list(range(n / / i + i / / 2, n / / i - i / / 2 - 1, - 1)) elif i % 2 == 0 and n % i == i / / 2: # For even i, if the remainder of n / i is 1/2, then the sequence # (even length) is centered around n / i. return list(range(n / / i + i / / 2, n / / i - i / / 2, - 1)) # If none of the above are satisfied, then n is a power of 2 and we cannot # write it as the sum of two consecutive integers. return [- 1]
Help Mrs Jefferson
59321f29a010d5aa80000066
[ "Fundamentals", "Data Structures", "Arrays", "Mathematics" ]
https://www.codewars.com/kata/59321f29a010d5aa80000066
6 kyu
You will be given a certain array of length ```n```, such that ```n > 4```, having positive and negative integers but there will be no zeroes and all the elements will occur once in it. We may obtain an amount of ```n``` sub-arrays of length ```n - 1```, removing one element at a time (from left to right). For each subarray, let's calculate the product and sum of its elements with the corresponding absolute value of the quotient, ```q = SubProduct/SubSum``` (if it is possible, SubSum cannot be 0). Then we select the array with the lowest value of ```|q|```(absolute value) e.g.: we have the array, ```arr = [1, 23, 2, -8, 5]``` ``` Sub Arrays SubSum SubProduct |q| [23, 2, -8, 5] 22 -1840 83.636363 [1, 2, -8, 5] 0 -80 No value [1, 23, -8, 5] 21 -920 43.809524 [1, 23, 2, 5] 31 230 7.419355 <--- selected array [1, 23, 2, -8] 18 368 20.444444 ``` Let's compare the given array with the selected subarray: ``` [1, 23, 2, -8, 5] [1, 23, 2, 5] ``` The difference between them is at the index ```3``` for the given array, with element ```-8```, so we put both things for a result ```[3, -8]```. That means that to obtain the selected subarray we have to take out the value -8 at index 3. We need a function that receives an array as an argument and outputs the pair ```[index, arr[index]]``` that generates the subarray with the lowest value of ```|q|```. ```python select_subarray([1, 23, 2, -8, 5]) == [3, -8] ``` Another case: ```python select_subarray([1, 3, 23, 4, 2, -8, 5, 18]) == [2, 23] ``` In Javascript the function will be ```selectSubarray()```. We may have some special arrays that may have more than one solution as the one that follows below. ```python select_subarray([10, 20, -30, 100, 200]) == [[3, 100], [4, 200]] ``` If there is more than one result the function should output a 2Darray sorted by the index of the element removed from the array. Thanks to Unnamed for detecting the special cases when we have multiple solutions. Features of the random tests: ``` Number of tests = 200 length of the array, l, such that 20 <= l <= 100 ``` Enjoy it!!
reference
from functools import reduce from operator import mul def select_subarray(arr): total = sum(arr) m = reduce(mul, arr) qs = [ (abs((m / / x) / (total - x)) if total - x else float("inf"), i) for i, x in enumerate(arr) ] q = min(qs) result = [[i, arr[i]] for x, i in qs if x == q[0]] return result[0] if len(result) == 1 else result
Remove a Specific Element of an Array
581bb3c1c221fb8e790001ef
[ "Fundamentals", "Data Structures", "Algorithms", "Mathematics", "Logic" ]
https://www.codewars.com/kata/581bb3c1c221fb8e790001ef
6 kyu
# Task Your task is to create a `Funnel` data structure. It consists of three basic methods: `fill()`, `drip()` and `toString()/to_s/__str__`. Its maximum capacity is 15 data. Data should be arranged in an inverted triangle, like this: ``` \1 2 3 4 5/ \7 8 9 0/ \4 5 6/ \2 3/ \1/ ``` The string method should return a multi-line string to display current funnel data arrangement: ```javascript var funnel = new Funnel() console.log(funnel.toString()) \ / \ / \ / \ / \ / ``` ```ruby funnel = Funnel.new print funnel.to_s \ / \ / \ / \ / \ / ``` ```python funnel = Funnel() print(funnel) \ / \ / \ / \ / \ / ``` ```java Funnel funnel = new Funnel(); System.out.println(funnel); \ / \ / \ / \ / \ / ``` The method `fill()` should accept one or more arguments to fill in the funnel: ```ruby funnel = Funnel.new funnel.fill(1) print funnel.to_s \ / \ / \ / \ / \1/ funnel.fill(2) print funnel.to_s \ / \ / \ / \2 / \1/ funnel.fill(3) print funnel.to_s \ / \ / \ / \2 3/ \1/ funnel.fill(4,5) print funnel.to_s \ / \ / \4 5 / \2 3/ \1/ funnel.fill(6,7,8,9) print funnel.to_s \ / \7 8 9 / \4 5 6/ \2 3/ \1/ ``` ```javascript var funnel = new Funnel() funnel.fill(1) console.log(funnel.toString()) \ / \ / \ / \ / \1/ funnel.fill(2) console.log(funnel.toString()) \ / \ / \ / \2 / \1/ funnel.fill(3) console.log(funnel.toString()) \ / \ / \ / \2 3/ \1/ funnel.fill(4,5) console.log(funnel.toString()) \ / \ / \4 5 / \2 3/ \1/ funnel.fill(6,7,8,9) console.log(funnel.toString()) \ / \7 8 9 / \4 5 6/ \2 3/ \1/ ``` ```python funnel = Funnel() funnel.fill(1) print (funnel) \ / \ / \ / \ / \1/ funnel.fill(2) print (funnel) \ / \ / \ / \2 / \1/ funnel.fill(3) print (funnel) \ / \ / \ / \2 3/ \1/ funnel.fill(4,5) print (funnel) \ / \ / \4 5 / \2 3/ \1/ funnel.fill(6,7,8,9) print(funnel) \ / \7 8 9 / \4 5 6/ \2 3/ \1/ ``` ```java Funnel funnel = new Funnel(); funnel.fill(1); System.out.println(funnel); \ / \ / \ / \ / \1/ funnel.fill(2); System.out.println(funnel); \ / \ / \ / \2 / \1/ funnel.fill(3); System.out.println(funnel); \ / \ / \ / \2 3/ \1/ funnel.fill(4,5); System.out.println(funnel); \ / \ / \4 5 / \2 3/ \1/ funnel.fill(6,7,8,9); System.out.println(funnel); \ / \7 8 9 / \4 5 6/ \2 3/ \1/ ``` In each row, `fill()` always fill data from left to right. The method `drip()` should drip the bottom value out of funnel and returns this value: ```javascript (continue the example above) var v = funnel.drip() console.log(v) 1 console.log(funnel.toString()) \ / \ 8 9 / \7 5 6/ \4 3/ \2/ ``` ```ruby (continue the example above) v = funnel.drip() puts v 1 print funnel.to_s \ / \ 8 9 / \7 5 6/ \4 3/ \2/ ``` ```python (continue the example above) v = funnel.drip() print(v) 1 print(funnel) \ / \ 8 9 / \7 5 6/ \4 3/ \2/ ``` ```java // (continue the example above) Character v = funnel.drip(); System.out.println(v); 1 System.out.println(funnel); \ / \ 8 9 / \7 5 6/ \4 3/ \2/ ``` As you can see, the bottom 1 was dripping out. The number above it will fill it's place. The rules to fill are: Select one of the two numbers above it, which bear the "weight" of relatively large. In other words, there are more numbers on this number. Is this a bit hard to understand? Please see the following: ``` In the example above, before the execution of drip(), funnel is: \ / \7 8 9 / \4 5 6/ \2 3/ \1/ ``` * After drip(), 1 will be dripped out. * We should choose a number between 2 and 3 to fill the place of 1. * 2 has 5 numbers on it(4,5,7,8,9). 3 has 4 numbers on it(5,6,8,9) * So we choose 2 to fill the place of 1 * And now, the place of 2 is empty. * We also need choose a number between 4 and 5 to fill the place of 2. * 4 has 2 numbers on it(7,8). 5 has 2 numbers on it too(8,9) * There are same "weight" on 4 and 5, * In this case, we choose the number on the left * So we choose 4 to fill the place of 2 * And then choose 7 to fill the place of 4 Let us continue to `drip()`: ```javascript funnel.drip() console.log(funnel.toString()) \ / \ 9 / \7 8 6/ \5 3/ \4/ funnel.drip() console.log(funnel.toString()) \ / \ / \7 9 6/ \8 3/ \5/ funnel.drip() console.log(funnel.toString()) \ / \ / \ 9 6/ \7 3/ \8/ funnel.drip() console.log(funnel.toString()) \ / \ / \ 6/ \7 9/ \3/ funnel.drip() console.log(funnel.toString()) \ / \ / \ / \7 6/ \9/ funnel.drip() console.log(funnel.toString()) \ / \ / \ / \ 6/ \7/ funnel.drip() console.log(funnel.toString()) \ / \ / \ / \ / \6/ funnel.drip() console.log(funnel.toString()) \ / \ / \ / \ / \ / ``` ```ruby funnel.drip print funnel.to_s \ / \ 9 / \7 8 6/ \5 3/ \4/ funnel.drip print funnel.to_s \ / \ / \7 9 6/ \8 3/ \5/ funnel.drip print funnel.to_s \ / \ / \ 9 6/ \7 3/ \8/ funnel.drip print funnel.to_s \ / \ / \ 6/ \7 9/ \3/ funnel.drip print funnel.to_s \ / \ / \ / \7 6/ \9/ funnel.drip print funnel.to_s \ / \ / \ / \ 6/ \7/ funnel.drip print funnel.to_s \ / \ / \ / \ / \6/ funnel.drip print funnel.to_s \ / \ / \ / \ / \ / ``` ```python funnel.drip() print(funnel) \ / \ 9 / \7 8 6/ \5 3/ \4/ funnel.drip() print(funnel) \ / \ / \7 9 6/ \8 3/ \5/ funnel.drip() print(funnel) \ / \ / \ 9 6/ \7 3/ \8/ funnel.drip() print(funnel) \ / \ / \ 6/ \7 9/ \3/ funnel.drip() print(funnel) \ / \ / \ / \7 6/ \9/ funnel.drip() print(funnel) \ / \ / \ / \ 6/ \7/ funnel.drip() print(funnel) \ / \ / \ / \ / \6/ funnel.drip() print(funnel) \ / \ / \ / \ / \ / ``` ```java funnel.drip(); System.out.println(funnel); \ / \ 9 / \7 8 6/ \5 3/ \4/ funnel.drip(); System.out.println(funnel); \ / \ / \7 9 6/ \8 3/ \5/ funnel.drip(); System.out.println(funnel); \ / \ / \ 9 6/ \7 3/ \8/ funnel.drip(); System.out.println(funnel); \ / \ / \ 6/ \7 9/ \3/ funnel.drip(); System.out.println(funnel); \ / \ / \ / \7 6/ \9/ funnel.drip(); System.out.println(funnel); \ / \ / \ / \ 6/ \7/ funnel.drip(); System.out.println(funnel); \ / \ / \ / \ / \6/ funnel.drip(); System.out.println(funnel); \ / \ / \ / \ / \ / ``` When the funnel is empty, drip() will return `null/nil/None` ```javascript var v= funnel.drip() console.log(v) null console.log(funnel.toString()) \ / \ / \ / \ / \ / ``` ```ruby v= funnel.drip puts v nil print funnel.to_s \ / \ / \ / \ / \ / ``` ```ruby v= funnel.drip() print(v) None print(funnel) \ / \ / \ / \ / \ / ``` ```java System.out.println(funnel.drip()); null System.out.println(funnel); \ / \ / \ / \ / \ / ``` Another edge case is: When funnel is full, fill() will not change the funnel. A bit complex...
algorithms
class Funnel (object): SIZE = 5 def __init__(self): self . fun = [[None] * (x + 1) for x in range(self . SIZE)] def fill(self, * args): genBlanks = ((x, y) for x, r in enumerate(self . fun) for y, v in enumerate(r) if v is None) for v, (x, y) in zip(args, genBlanks): self . fun[x][y] = v def drip(self): y, cnt = 0, sum(v is not None for row in self . fun for v in row) drop = self . fun[0][0] for x in range(self . SIZE - 1): left = cnt - sum(self . fun[xx][y + xx - x] is not None for xx in range(x, self . SIZE)) right = cnt - sum(self . fun[xx][y] is not None for xx in range(x, self . SIZE)) ySwp, cnt = (y, left) if left >= right else (y + 1, right) self . fun[x][y] = self . fun[x + 1][ySwp] y = ySwp if not cnt: break self . fun[x + 1][y] = None return drop def __str__(self): return '\n' . join(f' { " " * x } \\ { " " . join ( " " if v is None else str ( v ) for v in r )} /' for x, r in enumerate(reversed(self . fun)))
Create a funnel
585b373ce08bae41b800006e
[ "Algorithms" ]
https://www.codewars.com/kata/585b373ce08bae41b800006e
4 kyu
## Getting the Minimum Absolute Difference ### Task Given an array of integers with at least 2 elements: `a1, a2, a3, a4, ... aN` The absolute difference between two array elements `ai` and `aj`, where `i != j`, is the absolute value of `ai - aj`. Return the minimum absolute difference (MAD) between any two elements in the array. ### Example For `[-10, 0, -3, 1]` the MAD is `1`. Explanation: ``` | -10 - 0 | = 10 | -10 - (-3) | = 7 | -10 - 1 | = 11 | 0 - (-10) | = 10 | 0 - (-3) | = 3 | 0 - 1 | = 1 | -3 - (-10) | = 7 | -3 - 0 | = 3 | -3 - 1 | = 4 | 1 - (-10) | = 11 | 1 - 0 | = 1 | 1 - (-3) | = 4 ``` The minimum value is `1` ( both `| 0 - 1 |` and `| 1 - 0 |` ). ### Note Note that the same value can appear more than once in the array. In that case, the MAD will be `0`. ```if:lambdacalc ### Encodings purity: `LetRec` numEncoding: `Church` export constructors `cons, nil` for your `List` encoding ```
algorithms
def getting_mad(arr): xs = sorted(arr) return min(b - a for a, b in zip(xs, xs[1:]))
Getting MAD
593a061b942a27ac940000a7
[ "Fundamentals", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/593a061b942a27ac940000a7
6 kyu
Given a hash of letters and the number of times they occur, recreate all of the possible anagram combinations that could be created using all of the letters, sorted alphabetically. The inputs will never include numbers, spaces or any special characters, only lowercase letters a-z. E.g. get_words({2=>["a"], 1=>["b", "c"]}) => ["aabc", "aacb", "abac", "abca", "acab", "acba", "baac", "baca", "bcaa", "caab", "caba", "cbaa"]
games
from itertools import permutations def get_words(letters): word = "" . join( qty * char for qty in letters for chars in letters[qty] for char in chars) return sorted({"" . join(permutation) for permutation in permutations(word)})
Get All Possible Anagrams from a Hash
543e926d38603441590021dd
[ "Puzzles" ]
https://www.codewars.com/kata/543e926d38603441590021dd
6 kyu
The Binomial Form of a polynomial has many uses, just as the standard form does. For comparison, if p(x) is in Binomial Form and q(x) is in standard form, we might write p(x) := a<sub>0</sub> \* xC0 + a<sub>1</sub> \* xC1 + a<sub>2</sub> \* xC2 + ... + a<sub>N</sub> \* xCN q(x) := b<sub>0</sub> + b<sub>1</sub> \* x + b<sub>2</sub> \* x<sup>2</sup> + ... + b<sub>N</sub> \* x<sup>N</sup> Both forms have tricks for evaluating them, but tricks should not be necessary. The most important thing to keep in mind is that aCb can be defined for non-integer values of a; in particular, ``` aCb := a * (a-1) * (a-2) * ... * (a-b+1) / b! // for any value a and integer values b := a! / ((a-b)!b!) // for integer values a,b ``` The inputs to your function are an array which specifies a polynomial in Binomial Form, ordered by highest-degree-first, and also a number to evaluate the polynomial at. An example call might be ```javascript valueAt([1, 2, 7], 3); ``` ```python value_at([1, 2, 7], 3) ``` ```ruby value_at([1, 2, 7], 3) ``` and the return value would be 16, since 3C2 + 2 * 3C1 + 7 = 16. In more detail, this calculation looks like ``` 1 * xC2 + 2 * xC1 + 7 * xC0 :: x = 3 3C2 + 2 * 3C1 + 7 3 * (3-1) / 2! + 2 * 3 / 1! + 7 3 + 6 + 7 = 16 ``` More information can be found by reading about [Binomial Coefficients](https://en.wikipedia.org/wiki/Binomial_coefficient) or about [Finite Differences](https://en.wikipedia.org/wiki/Finite_difference). Note that while a solution should be able to handle non-integer inputs and get a correct result, any solution should make use of rounding to two significant digits (as the official solution does) since high precision for non-integers is not the point here.
reference
from math import prod, factorial def comb(x, y): return prod(x - i for i in range(y)) / factorial(y) def value_at(poly_spec, x): return round(sum(v * comb(x, i) for i, v in enumerate(reversed(poly_spec))), 2)
Polynomial Evaluation - Binomial Form
56782b25c05cad45f700000f
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/56782b25c05cad45f700000f
6 kyu
Given a string of space separated words, return the longest word. If there are multiple longest words, return the rightmost longest word. #### Examples "red white blue" => "white" "red blue gold" => "gold"
reference
def longest_word(string_of_words): return max(reversed(string_of_words . split()), key=len)
Inspiring Strings
5939ab6eed348a945f0007b2
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5939ab6eed348a945f0007b2
7 kyu
In this kata, you should determine the values in an unknown array of numbers. You'll be given a function `f`, which you can call like this: ```haskell f a b -- returns an Integral ``` ```csharp f(a, b); ``` ```python f(a, b) ``` ```rust f(a, b) ``` where `a` and `b` are indexes of two different elements in the unknown array, 1 or 2 indexes apart. `f` will return the sum of those two elements. The absolute difference between `a` and `b` must not be 0 nor greater than 2 (that is: the chosen indexes must be exactly 1 or 2 apart). Your goal is to figure out the correct array. The whole procedure is: 1. You are given `f` and the length of the array `n`. 0. Ask `f` for any element sums you want. 0. Create and return the correct array according to the answers. The array will always have at least 3 elements. ## Don't forget to give upvotes and feedbacks!
games
from itertools import accumulate def guess(f, n): return [* accumulate(range(n - 1), lambda x, i: f(i, i + 1) - x, initial=f(0, 1) + f(0, 2) - f(1, 2) >> 1)]
Guess the array
59392ff00203d9686a0000c6
[ "Puzzles", "Algorithms", "Arrays" ]
https://www.codewars.com/kata/59392ff00203d9686a0000c6
6 kyu
<img src="https://i.imgur.com/ta6gv1i.png?1" title="source: imgur.com" /> # Story A freak power outage at the zoo has caused all of the electric cage doors to malfunction and swing open... All the animals are out and some of them are eating each other! # <span style='color:red'>It's a Zoo Disaster!</span> Here is a list of zoo animals, and what they can eat * antelope eats grass * big-fish eats little-fish * bug eats leaves * bear eats big-fish * bear eats bug * bear eats chicken * bear eats cow * bear eats leaves * bear eats sheep * chicken eats bug * cow eats grass * fox eats chicken * fox eats sheep * giraffe eats leaves * lion eats antelope * lion eats cow * panda eats leaves * sheep eats grass # Kata Task ### INPUT A comma-separated string representing all the things at the zoo ### TASK Figure out who eats whom until no more eating is possible. ### OUTPUT A list of strings (refer to the example below) where: * The first element is the initial zoo (same as INPUT) * The last element is a comma-separated string of what the zoo looks like when all the eating has finished * All other elements (2nd to last-1) are of the form ```X eats Y``` describing what happened # Notes * Animals can only eat things beside them * Animals always eat to their **LEFT** before eating to their **RIGHT** * Always the **LEFTMOST** animal capable of eating will eat before any others * Any other things you may find at the zoo (which are not listed above) do not eat anything and are not edible # Example *Input* ```"fox,bug,chicken,grass,sheep"``` *Working* <table> <tr><td>1<td>fox can't eat bug<td><pre>"fox,bug,chicken,grass,sheep"</pre></tr> <tr><td>2<td>bug can't eat anything<td><pre>"fox,bug,chicken,grass,sheep"</pre></tr> <tr><td>3<td><span style='color:red'>chicken eats bug</span><td><pre>"fox,chicken,grass,sheep"</pre></tr> <tr><td>4<td><span style='color:red'>fox eats chicken</span><td><pre>"fox,grass,sheep"</pre></tr> <tr><td>5<td>fox can't eat grass<td><pre>"fox,grass,sheep"</pre></tr> <tr><td>6<td>grass can't eat anything<td><pre>"fox,grass,sheep"</pre></tr> <tr><td>7<td><span style='color:red'>sheep eats grass</span><td><pre>"fox,sheep"</pre></tr> <tr><td>8<td><span style='color:red'>fox eats sheep</span><td><pre>"fox"</pre></tr> </table> *Output* ```["fox,bug,chicken,grass,sheep", "chicken eats bug", "fox eats chicken", "sheep eats grass", "fox eats sheep", "fox"]```
reference
EATERS = {"antelope": {"grass"}, "big-fish": {"little-fish"}, "bug": {"leaves"}, "bear": {"big-fish", "bug", "chicken", "cow", "leaves", "sheep"}, "chicken": {"bug"}, "cow": {"grass"}, "fox": {"chicken", "sheep"}, "giraffe": {"leaves"}, "lion": {"antelope", "cow"}, "panda": {"leaves"}, "sheep": {"grass"}} def who_eats_who(zoo): ansLst, zooLst, n = [zoo], zoo . split(","), 0 while n < len(zooLst): # Eats on its left while n > 0 and zooLst[n - 1] in EATERS . get(zooLst[n], set()): ansLst . append("{} eats {}" . format(zooLst[n], zooLst . pop(n - 1))) n -= 2 # Eats on its right while n >= 0 and n != len(zooLst) - 1 and zooLst[n + 1] in EATERS . get(zooLst[n], set()): ansLst . append("{} eats {}" . format(zooLst[n], zooLst . pop(n + 1))) n += 1 # Nothing to eat, step forward return ansLst + [',' . join(zooLst)]
The Hunger Games - Zoo Disaster!
5902bc7aba39542b4a00003d
[ "Fundamentals" ]
https://www.codewars.com/kata/5902bc7aba39542b4a00003d
5 kyu
Our cells go through a process called protein synthesis to translate the instructions in DNA into an amino acid chain, or polypeptide. Your job is to replicate this! --- **Step 1: Transcription** Your input will be a string of DNA that looks like this: `"TACAGCTCGCTATGAATC"` You then must transcribe it to mRNA. Each letter, or base, gets transcribed. ```T -> A A -> U G -> C C -> G``` Also, you will split it into groups of three, or _codons_. The above example would become: `"AUG UCG AGC GAU ACU UAG"` --- **Step 2: Translation** After you have the mRNA strand, you will turn it into an amino acid chain. Each codon corresponds to an amino acid: ``` Ala GCU, GCC, GCA, GCG Leu UUA, UUG, CUU, CUC, CUA, CUG Arg CGU, CGC, CGA, CGG, AGA, AGG Lys AAA, AAG Asn AAU, AAC Met AUG Asp GAU, GAC Phe UUU, UUC Cys UGU, UGC Pro CCU, CCC, CCA, CCG Gln CAA, CAG Ser UCU, UCC, UCA, UCG, AGU, AGC Glu GAA, GAG Thr ACU, ACC, ACA, ACG Gly GGU, GGC, GGA, GGG Trp UGG His CAU, CAC Tyr UAU, UAC Ile AUU, AUC, AUA Val GUU, GUC, GUA, GUG Stop UAG, UGA, UAA``` Phew, that's a long list! The above example would become: `"Met Ser Ser Thr Asp Stop"` Any additional sets of bases that aren't in a group of three aren't included. For example: `"AUG C"` would become `"Met"` --- Anyway, your final output will be the mRNA sequence and the polypeptide. Here are some examples: *In:* `"TACAGCTCGCTATGAATC"` *Out:* `["AUG UCG AGC GAU ACU UAG","Met Ser Ser Asp Thr Stop"]` --- *In:* `"ACGTG"` *Out:* `["UGC AC","Cys"]`
reference
import re TABLE = str . maketrans('ACGT', 'UGCA') def protein_synthesis(dna): rna = re . findall(r'.{1,3}', dna . translate(TABLE)) return ' ' . join(rna), ' ' . join(x for x in map(CODON_DICT . get, rna) if x)
Protein Synthesis: From DNA to Polypeptide
58df2d65808fbcdfc800004a
[ "Fundamentals" ]
https://www.codewars.com/kata/58df2d65808fbcdfc800004a
6 kyu
# Introduction There is a war...between alphabets! There are two groups of hostile letters. The tension between left side letters and right side letters was too high and the war began. The letters called airstrike to help them in war - dashes and dots are spread throughout the battlefield. Who will win? # Task Write a function that accepts a `fight` string which consists of only small letters and `*` which represents a bomb drop place. Return who wins the fight after bombs are exploded. When the left side wins return `Left side wins!`, and when the right side wins return `Right side wins!`. In other cases, return `Let's fight again!`. The left side letters and their power: ``` w - 4 p - 3 b - 2 s - 1 ``` The right side letters and their power: ``` m - 4 q - 3 d - 2 z - 1 ``` The other letters don't have power and are only victims. The `*` bombs kill the adjacent letters ( i.e. `aa*aa` => `a___a`, `**aa**` => `______` ); # Example ```csharp AlphabetWar("s*zz"); //=> Right side wins! AlphabetWar("*zd*qm*wp*bs*"); //=> Let's fight again! AlphabetWar("zzzz*s*"); //=> Right side wins! AlphabetWar("www*www****z"); //=> Left side wins! ``` ```javascript alphabetWar("s*zz"); //=> Right side wins! alphabetWar("*zd*qm*wp*bs*"); //=> Let's fight again! alphabetWar("zzzz*s*"); //=> Right side wins! alphabetWar("www*www****z"); //=> Left side wins! ``` ```c alphabet_war("s*zz"); /* => Right side wins! */ alphabet_war("*zd*qm*wp*bs*"); /* => Let's fight again! */ alphabet_war("zzzz*s*"); /* => Right side wins! */ alphabet_war("www*www****z"); /* => Left side wins! */ ``` ```nasm global main: extern alphabet_war section .data strz: db "s*zz", 0h0 strzd: db "*zd*qm*wp*bs*", 0h0 strzzz: db "zzzz*s*", 0h0 strwww: db "www*www****z", 0h0 section .text main: mov rdi, strz call alphabet_war ; RAX <- Right side wins! mov rdi, strzd call alphabet_war ; RAX <- Let's fight again! mov rdi, strzzz call alphabet_war ; RAX <- Right side wins! mov rdi, strwww call alphabet_war ; RAX <- Left side wins! ret ``` # Alphabet war Collection <table border="0" cellpadding="0" cellspacing="0"> <tr> <td ><a href="https://www.codewars.com/kata/59377c53e66267c8f6000027" target="_blank">Alphavet war </a></td> </tr> <tr> <td ><a href="https://www.codewars.com/kata/5938f5b606c3033f4700015a" target="_blank">Alphabet war - airstrike - letters massacre</a></td> </tr> <tr> <td ><a href="https://www.codewars.com/kata/alphabet-wars-reinforces-massacre" target="_blank">Alphabet wars - reinforces massacre</a></td> </tr> <tr> <td ><a href="https://www.codewars.com/kata/59437bd7d8c9438fb5000004" target="_blank">Alphabet wars - nuclear strike</a></td> </tr> <tr> <td ><a href="https://www.codewars.com/kata/59473c0a952ac9b463000064" target="_blank">Alphabet war - Wo lo loooooo priests join the war</a></td> </tr> </table>
reference
import re powers = { 'w': - 4, 'p': - 3, 'b': - 2, 's': - 1, 'm': + 4, 'q': + 3, 'd': + 2, 'z': + 1, } def alphabet_war(fight): fight = re . sub('.(?=\*)|(?<=\*).', '', fight) result = sum(powers . get(c, 0) for c in fight) if result < 0: return 'Left side wins!' elif result > 0: return 'Right side wins!' else: return "Let's fight again!"
Alphabet war - airstrike - letters massacre
5938f5b606c3033f4700015a
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/5938f5b606c3033f4700015a
6 kyu
# Church Numbers Church Numbers are representations of natural numbers (non-negative integers) as functions. Not only as functions, but as functions that can perform a task upon a value a set number of times. This is an important concept of Lambda Calculus, so naturally we'll have to talk about Lambda Calculus. # Lambda Calculus Lambda Calculus is a syntax for functional computing/mathematics. In Lambda Calculus, a function has one input, and one output. However, the input function can be another lambda function (which accepts another input), and this can somewhat simulate multiple inputs with some important differences; this is called "currying". Some languages (e.g., Haskell) naturally use curried functions. Other languages (e.g., Javascript) must have currying forced upon them. The solution starts with the functions properly curried, and will need to remain that way. # Church Functions Back to Church Numbers. With a Church Number, we want to accept "two inputs" (a function ```f``` and a value ```x```; remember they're curried, so it's ```c(f)(x)``` not ```c(f, x)```), and we want to successively perform ```f``` on ```x```. So, if we have Church Number 2, that should mean ```f(f(x))```. If you're working in Haskell, ignore this bit; you're already curried. To define this, we'll start at zero: ```javascript var zero = (f) => (x) => x; ``` ```python zero = lambda f: lambda x: x ``` ```haskell type Lambda a = (a -> a) type Cnum a = Lambda a -> Lambda a zero :: Cnum a zero f = id ``` As you can see, zero accepts a function, and returns a function. The returned function performs ```f``` zero times and returns the result (also known as an identify function). One goes a step further: ```javascript var one = (f) => (x) => f(x); ``` ```python one = lambda f: lambda x: f(x) ``` ```haskell one :: Cnum a one f = f ``` Of course, it would get tedious to have to declare every natural number you need. So let's write a successor function: ```javascript var succ = (c) => (f) => (x) => f(c(f)(x)); ``` ```python succ = lambda c: lambda f: lambda x: f(c(f)(x)) ``` ```haskell churchSucc :: Cnum a -> Cnum a churchSucc c = (\h -> h . c h) ``` The successor function takes a Church Number (including zero), and returns a function that performs one more application of ```f``` than the previous Church Number. So, ```succ(zero)``` is equivalent to ```one```, ```succ(succ(zero))``` is ```two```, etc.. And how you use a Church Number ```c``` is to: ```javascript var result = c(f)(x); ``` ```python result = c(f)(x) ``` ```haskell let result = c f x ``` ```result``` will be ```f``` performed on ```x``` ```c``` times. So if ```c``` is 3 (```succ(succ(succ(zero)))```), result will be ```f(f(f(x)))```. # Your Goal Implement some basic arithmetic for Church Numbers, namely adding, multiplying, and exponentiation. Performance is part of this kata; if you're timing out (and Codewars isn't under load), you'll need to come up with more efficient functions. ## General Tips Since the functions are curried, you can call a function with only one "input" and receive a function back. Think of this like the classic ```adder``` function: ```javascript var addX = (x) => (y) => x + y; var addOne = addX(1); addOne(5);// == 6 ``` ```python add_x = lambda x: lambda y: x + y add_one = add_x(1) add_one(5) # == 6 ``` ```haskell addX x y = x + y addOne y = addX 1 let six = addOne 5 ``` With Church Numbers, this means that ```c(f)``` is a function that takes one input (x) and returns ```f``` performed on ```x``` ```c``` times. The ability to pass this function around is useful, to give an example, for multiplying. ## Adding Tips What you want to do is perform ```f``` on ```x``` through an entire one of your Church inputs, then feed that value into your next Church input as if it were ```x```. Lambda Calculus definition for adding: ```c1 f (c2 f x)``` ## Multiplying Tips You can use repeated adding to multiply, but there's a much cleaner solution. Remember ```c(f)``` is a function of its own. Lambda Calculus definition for multiplying: ```c1 (c2 f) x``` ## Exponentiation Tips Similar to multiplying, you _could_ use repeated multiplication, but it's better not to. In fact, exponentiation is syntactically simpler than adding with Church Numbers (even if it takes some brain gymnastics to figure out why). Lambda Calculus definition: ```(ce cb) f x``` While it isn't a hard requirement for this kata, try to implement multiplying without adding, and exponentiation without multiplying or adding. It's actually simpler this way (really). ## Testing Tips The following functions are preloaded; feel free to use them for testing purposes. They can't be used when you Submit, only when you run your own test cases. ```javascript var zero = (f) => (x) => x; var succ = (c) => (f) => (x) => f(c(f)(x)); var numerify = (c) => c((i) => i + 1)(0); //Turns a Church Number into an integer var churchify = (n) => (f) => (x) => { //Turns an integer into a Church Number. for(var i = 0; i < n; i++) x = f(x); return x; }; //For churchify, why don't we use succ(churchify(n - 1))? The stack size gets out of hand. ``` ```python zero = lambda f: lambda x: x succ = lambda c: lambda f: lambda x: f(c(f)(x)) numerify = lambda c: c(lambda i: i + 1)(0) def churchify(n): def _f(f): def _x(x): for i in range(n): x = f(x) return x return _x return _f # For churchify, why don't we use succ(churchify(n - 1))? The stack size gets out of hand. ``` ```haskell module Haskell.Codewars.Church.Preloaded where type Lambda a = (a -> a) type Cnum a = Lambda a -> Lambda a zero :: Cnum a zero f = id churchSucc :: Cnum a -> Cnum a churchSucc c = (\h -> h . c h) churchify 0 = zero churchify n = churchSucc (churchify (n-1)) numerify :: Cnum Int -> Int numerify c = c (+1) 0 ``` You won't need to sanitize your inputs; you will always receive valid Church Numbers into churchAdd, churchMul, and churchPow. ## Beta Notes A C# version is forthcoming. If someone else translates into other languages, I'll add them as well. It's improbable that a satisfactory Java solution can be made since generics and lambdas don't play well. After you finish, please mark as Ready (or add why it isn't to the discussion) and give a kyu rating.
algorithms
def church_add(c1): return lambda c2: lambda f: lambda x: c1(f)(c2(f)(x)) def church_mul(c1): return lambda c2: lambda f: c1(c2(f)) def church_pow(cb): return lambda ce: ce(cb)
Church Numbers - Add, Multiply, Exponents
55c0c452de0056d7d800004d
[ "Algorithms" ]
https://www.codewars.com/kata/55c0c452de0056d7d800004d
3 kyu
<h2>Task:</h2> <p>Complete the function <code>piecesValue</code>/<code>pieces_value</code> that accepts two arguments, an 8x8 array (arr),representing a chess board and a string (s). Depending on the value of the string <code>s</code> (which can be either <code>"white"</code> or <code>"black"</code>) calculate the value of the pieces on the table for the corresponding player(white or black). <br> Empty fields will be marked as a space <code>" "</code> while the fields with pieces look like this:</p> ```javascript "w-king" //meaning white king "b-bishop" //a black bishop "w-pawn" //white pawn ``` ...and so on. Preloaded for you there is an object called `hash` (`values` in python): ```javascript const hash = Object.freeze({ queen: 9, rook: 5, bishop: 3, knight: 3, pawn: 1 }); ``` ```python values = { 'queen': 9, 'rook': 5, 'bishop': 3, 'knight': 3, 'pawn': 1, } ``` <p>Having the estimated value of each piece. This is a rough estimation and the real piece value depends on other factors in game as well ,such as the game being a closed or open one, which can favor either knights or bishops. (If you are interested more about that here: <a href="https://www.chess.com/chessopedia/view/open-closed">open vs closed game</a>.) But for our purposes we will use the mentioned values. <br> <b>Note:</b> the value of a king cannot be estimated because without it the game would be over, so <strong>DO NOT</strong> take into consideration the value of the king.You will not be tested for invalid input.<br> </p> <strong>Example case:</strong> ```javascript piecesValue([[' ',' ',' ',' ',' ',' ',' ',' '], [' ',' ','b-queen',' ',' ',' ',' ','w-queen'], [' ','b-king',' ',' ','w-rook',' ',' ',' '], [' ',' ',' ',' ',' ',' ',' ',' '], [' ',' ',' ',' ',' ',' ',' ',' '], ['w-king',' ',' ',' ',' ',' ',' ',' '], [' ',' ',' ',' ',' ',' ',' ',' '], [' ',' ',' ',' ',' ',' ',' ',' ']], 'white'); //should be 14 since white has a queen and a rook //while the same table would return 9 for 'black' piecesValue([[' ',' ',' ',' ',' ',' ',' ',' '], [' ',' ','b-queen',' ',' ',' ',' ','w-queen'], [' ','b-king',' ','b-pawn','w-rook',' ',' ',' '], [' ',' ',' ',' ','w-pawn',' ',' ',' '], [' ',' ',' ',' ',' ','w-bishop',' ',' '], ['w-king',' ',' ',' ',' ',' ',' ',' '], [' ',' ',' ','b-pawn',' ',' ',' ',' '], [' ',' ',' ',' ',' ',' ',' ',' ']], 'white'); //should return 18 for 'white' (queen, rook, pawn, bishop) //and 11 in case s is 'black'(queen, pawn, pawn) ``` ## Happy coding warrior!
reference
values = { 'queen': 9, 'rook': 5, 'bishop': 3, 'knight': 3, 'pawn': 1, } def pieces_value(arr, s): return sum(values . get(x[2:], 0) for x in sum(arr, []) if x[0] == s[0])
Chess piece values
5832514f64a4cecd1c000013
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5832514f64a4cecd1c000013
6 kyu
As a part of this Kata, you need to create a function that when provided with a triplet, returns the index of the numerical element that lies between the other two elements. The input to the function will be an array of three distinct numbers (Haskell: a tuple). For example: gimme([2, 3, 1]) => 0 *2* is the number that fits between *1* and *3* and the index of *2* in the input array is *0*. Another example (just to make sure it is clear): gimme([5, 10, 14]) => 1 *10* is the number that fits between *5* and *14* and the index of *10* in the input array is *1*.
reference
def gimme(inputArray): # Implement this function return inputArray . index(sorted(inputArray)[1])
Find the middle element
545a4c5a61aa4c6916000755
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/545a4c5a61aa4c6916000755
7 kyu
This is the simple version of Shortest Code series. If you need some challenges, please try the [challenge version](http://www.codewars.com/kata/56fc7a29fca8b900eb001fac) ## Task: Give you an number array ```arr```, and a number ```n```(n>=0), In accordance with the rules of kata, returns the array after ```n``` times changes . Rules: In every time of change, when the element of array is an odd number, it changed by ```x*3+1```(element is x), and merge with next element ```arr[i]+arr[i+1]```(i is index of element, if it's the last element of array, do not merge with other element);when the element is a even number, changed by ```x=x/2```,and split to two element. Example: ``` arr=[3,4,5] n=0: [3,4,5] n=1: [14,16] element1=>3*3+1==10, then merge element2, 10+4=14; element2 merged by element1, so element2 disappeared; element3=>5*3+1==16, no element merge n=2: [7,7,8,8] element1 split into 7,7; element1 split into 8,8; n=3: [29,4,4,4,4] n=4: [92,2,2,2,2,2,2] n=5: [46,46,1,1,1,1,1,1,1,1,1,1,1,1] n=6: [23,23,23,23,5,5,5,5,5,5] n=... [...] ``` ### Series: - [Bug in Apple](http://www.codewars.com/kata/56fe97b3cc08ca00e4000dc9) - [Father and Son](http://www.codewars.com/kata/56fe9a0c11086cd842000008) - [Jumping Dutch act](http://www.codewars.com/kata/570bcd9715944a2c8e000009) - [Planting Trees](http://www.codewars.com/kata/5710443187a36a9cee0005a1) - [Give me the equation](http://www.codewars.com/kata/56fe9b65cc08cafbc5000de3) - [Find the murderer](http://www.codewars.com/kata/570f3fc5b29c702c5500043e) - [Reading a Book](http://www.codewars.com/kata/570ca6a520c69f39dd0016d4) - [Eat watermelon](http://www.codewars.com/kata/570df12ce6e9282a7d000947) - [Special factor](http://www.codewars.com/kata/570e5d0b93214b1a950015b1) - [Guess the Hat](http://www.codewars.com/kata/570ef7a834e61306da00035b) - [Symmetric Sort](http://www.codewars.com/kata/5705aeb041e5befba20010ba) - [Are they symmetrical?](http://www.codewars.com/kata/5705cc3161944b10fd0004ba) - [Max Value](http://www.codewars.com/kata/570771871df89cf59b000742) - [Trypophobia](http://www.codewars.com/kata/56fe9ffbc25bf33fff000f7c) - [Virus in Apple](http://www.codewars.com/kata/5700af83d1acef83fd000048) - [Balance Attraction](http://www.codewars.com/kata/57033601e55d30d3e0000633) - [Remove screws I](http://www.codewars.com/kata/5710a50d336aed828100055a) - [Remove screws II](http://www.codewars.com/kata/5710a8fd336aed00d9000594) - [Regular expression compression](http://www.codewars.com/kata/570bae4b0237999e940016e9) - [Collatz Array(Split or merge)](http://www.codewars.com/kata/56fe9d579b7bb6b027000001) - [Tidy up the room](http://www.codewars.com/kata/5703ace6e55d30d3e0001029) - [Waiting for a Bus](http://www.codewars.com/kata/57070eff924f343280000015)
games
def sc(arr, n): for _ in range(n): out, vs = [], iter(arr) for v in vs: if v & 1: out . append(3 * v + 1 + next(vs, 0)) else: out . extend((v / / 2, v / / 2)) arr = out return arr
Coding 3min: Collatz Array(Split or merge)
56fe9d579b7bb6b027000001
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/56fe9d579b7bb6b027000001
6 kyu
## Problem There are `n` apples that need to be divided into four piles. We need two mysterious number `x` and `y`. Let The number of first pile equals to `x+y`, the number of second pile equals to `x-y`, the number of third pile equals to `x*y`, the number of fourth pile equals to `x/y`. We need to calculate how many apples are there in each pile. Of course, there won't be so many unknowns. We know the total number of apples(`n`) and the second mysterious number(`y`). For example: there are 48 apples need to divided into four piles. y=3. that is, 1st pile should be x+3, 2nd pile should be x-3, 3rd pile should be x*3, 4th pile should be x/3. Do you know how much `x` is? `x` should be 9, because: ``` (9 + 3) + (9 - 3) + (9 * 3) + (9 / 3) = 12 + 6 + 27 + 3 = 48 ``` So, 48 apples should be divided into `12, 6, 27, 3`. ## Task Implement a function that accepts two argument, `n` and `y`, and returns the number of apples in each pile as described above. Each resulting number should be a positive integer. If there's no way to divide the apples, return an empty array/empty value (refer to the function declaration and test cases in your language of choice to see which option is relevant for you). ## Examples ``` n = 48 y = 3 result = [12, 6, 27, 3] n = 100 y = 4 result = [20, 12, 64, 4] n = 24 y = 4 result = [] (no way to divide the apples) n = 25 y = 4 result = [] ([8,0,16,1] is not a correct answer since you can't have empty piles) ```
games
def four_piles(n, y): x, r = divmod(n * y, (y + 1) * * 2) return [] if r or x == y else [x + y, x - y, x * y, x / / y]
T.T.T.27: Four piles of apples
57aae4facf1fa57b3300005d
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/57aae4facf1fa57b3300005d
7 kyu
Let's define `increasing` numbers as the numbers whose digits, read from left to right, are never less than the previous ones: 234559 is an example of increasing number. Conversely, `decreasing` numbers have all the digits read from left to right so that no digits is bigger than the previous one: 97732 is an example of decreasing number. You do not need to be the next Gauss to figure that all numbers with 1 or 2 digits are either increasing or decreasing: 00, 01, 02, ..., 98, 99 are all belonging to one of this categories (if not both, like 22 or 55): 101 is indeed the first number which does NOT fall into either of the categories. Same goes for all the numbers up to 109, while 110 is again a decreasing number. Now your task is rather easy to declare (a bit less to perform): you have to build a function to return the total occurrences of all the increasing or decreasing numbers *below* 10 raised to the xth power (x will always be >= 0). To give you a starting point, there are a grand total of increasing and decreasing numbers as shown in the table: |Total | Below| | --- | --- | | 1 | 1 | | 10 | 10 | | 100 | 100 | | 475 | 1000 | | 1675 | 10000| | 4954 | 100000| | 12952 | 1000000| This means that your function will have to behave like this: ```python total_inc_dec(0)==1 total_inc_dec(1)==10 total_inc_dec(2)==100 total_inc_dec(3)==475 total_inc_dec(4)==1675 total_inc_dec(5)==4954 total_inc_dec(6)==12952 ``` ```javascript totalIncDec(0)==1 totalIncDec(1)==10 totalIncDec(2)==100 totalIncDec(3)==475 totalIncDec(4)==1675 totalIncDec(5)==4954 totalIncDec(6)==12952 ``` ```ruby total_inc_dec(0)==1 total_inc_dec(1)==10 total_inc_dec(2)==100 total_inc_dec(3)==475 total_inc_dec(4)==1675 total_inc_dec(5)==4954 total_inc_dec(6)==12952 ``` ```haskell totalIncDec 0 `shouldBe` 1 totalIncDec 1 `shouldBe` 10 totalIncDec 2 `shouldBe` 100 totalIncDec 3 `shouldBe` 475 totalIncDec 4 `shouldBe` 1675 totalIncDec 5 `shouldBe` 4954 totalIncDec 6 `shouldBe` 12952 ``` ```clojure total-inc-dec 0 => 1 total-inc-dec 1 => 10 total-inc-dec 2 => 100 total-inc-dec 3 => 475 total-inc-dec 4 => 1675 total-inc-dec 5 => 4954 total-inc-dec 6 => 12952 ``` ```csharp TotalIncDec(0) == 1 TotalIncDec(1) == 10 TotalIncDec(2) == 100 TotalIncDec(3) == 475 TotalIncDec(4) == 1675 TotalIncDec(5) == 4954 TotalIncDec(6) == 12952 ``` ```coffeescript totalIncDec(0)==1 totalIncDec(1)==10 totalIncDec(2)==100 totalIncDec(3)==475 totalIncDec(4)==1675 totalIncDec(5)==4954 totalIncDec(6)==12952 ``` ```java totalIncDec(0)==1 totalIncDec(1)==10 totalIncDec(2)==100 totalIncDec(3)==475 totalIncDec(4)==1675 totalIncDec(5)==4954 totalIncDec(6)==12952 ``` ```scala totalIncDec(0) should be (1) totalIncDec(1) should be (10) totalIncDec(2) should be (100) totalIncDec(3) should be (475) totalIncDec(4) should be (1675) totalIncDec(5) should be (4954) totalIncDec(6) should be (12952) ``` ```racket (equal? (total-inc-dec 0) 1) (equal? (total-inc-dec 1) 10) (equal? (total-inc-dec 2) 100) (equal? (total-inc-dec 3) 475) (equal? (total-inc-dec 4) 1675) (equal? (total-inc-dec 5) 4954) (equal? (total-inc-dec 6) 12952) ``` ```cobol TOTAL-INC-DEC 0 -> 1 TOTAL-INC-DEC 1 -> 10 TOTAL-INC-DEC 2 -> 100 TOTAL-INC-DEC 3 -> 475 TOTAL-INC-DEC 4 -> 1675 TOTAL-INC-DEC 5 -> 4954 TOTAL-INC-DEC 6 -> 12952 ``` **Tips:** efficiency and trying to figure out how it works are essential: with a brute force approach, some tests with larger numbers may take more than the total computing power currently on Earth to be finished in the short allotted time. To make it even clearer, the increasing or decreasing numbers between in the range 101-200 are: [110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 122, 123, 124, 125, 126, 127, 128, 129, 133, 134, 135, 136, 137, 138, 139, 144, 145, 146, 147, 148, 149, 155, 156, 157, 158, 159, 166, 167, 168, 169, 177, 178, 179, 188, 189, 199, 200], that is 47 of them. In the following range, 201-300, there are 41 of them and so on, getting rarer and rarer. **Trivia:** just for the sake of your own curiosity, a number which is neither decreasing of increasing is called a `bouncy` number, like, say, 3848 or 37294; also, usually 0 is not considered being increasing, decreasing or bouncy, but it will be for the purpose of this kata
games
from math import factorial as fac def xCy(x, y): return fac(x) / / fac(y) / / fac(x - y) def total_inc_dec(x): return 1 + sum([xCy(8 + i, i) + xCy(9 + i, i) - 10 for i in range(1, x + 1)])
Total increasing or decreasing numbers up to a power of 10
55b195a69a6cc409ba000053
[ "Number Theory", "Combinatorics", "Puzzles" ]
https://www.codewars.com/kata/55b195a69a6cc409ba000053
4 kyu
Function receive a two-dimensional square array of random integers. On the main diagonal, all the negative integers must be changed to `0`, while the others must be changed to 1 (Note: `0` is considered non-negative, here). (_You can mutate the input if you want, but it is a better practice to not mutate the input_) Example: Input array ``` [ [-1, 4, -5, -9, 3 ], [ 6, -4, -7, 4, -5 ], [ 3, 5, 0, -9, -1 ], [ 1, 5, -7, -8, -9 ], [-3, 2, 1, -5, 6 ] ] ``` Output array ``` [ [ 0, 4, -5, -9, 3 ], [ 6, 0, -7, 4, -5 ], [ 3, 5, 1, -9, -1 ], [ 1, 5, -7, 0, -9 ], [-3, 2, 1, -5, 1 ] ] ```
reference
def matrix(arr): for z in range(len(arr)): if arr[z][z] < 0: arr[z][z] = 0 else: arr[z][z] = 1 return arr
Change two-dimensional array
581214d54624a8232100005f
[ "Arrays", "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/581214d54624a8232100005f
7 kyu
# Introduction There is a war and nobody knows - the alphabet war! There are two groups of hostile letters. The tension between left side letters and right side letters was too high and the war began. # Task Write a function that accepts `fight` string consists of only small letters and return who wins the fight. When the left side wins return `Left side wins!`, when the right side wins return `Right side wins!`, in other case return `Let's fight again!`. The left side letters and their power: ``` w - 4 p - 3 b - 2 s - 1 ``` The right side letters and their power: ``` m - 4 q - 3 d - 2 z - 1 ``` The other letters don't have power and are only victims. # Example ```csharp AlphabetWar("z"); //=> Right side wins! AlphabetWar("zdqmwpbs"); //=> Let's fight again! AlphabetWar("zzzzs"); //=> Right side wins! AlphabetWar("wwwwwwz"); //=> Left side wins! ``` ```javascript alphabetWar("z"); //=> Right side wins! alphabetWar("zdqmwpbs"); //=> Let's fight again! alphabetWar("zzzzs"); //=> Right side wins! alphabetWar("wwwwwwz"); //=> Left side wins! ``` ```coffeescript alphabetWar("z"); # => Right side wins! alphabetWar("zdqmwpbs"); # => Let's fight again! alphabetWar("zzzzs"); # => Right side wins! alphabetWar("wwwwwwz"); # => Left side wins! ``` # Alphabet war Collection <table border="0" cellpadding="0" cellspacing="0"> <tr> <td ><a href="https://www.codewars.com/kata/59377c53e66267c8f6000027" target="_blank">Alphavet war </a></td> </tr> <tr> <td ><a href="https://www.codewars.com/kata/5938f5b606c3033f4700015a" target="_blank">Alphabet war - airstrike - letters massacre</a></td> </tr> <tr> <td ><a href="https://www.codewars.com/kata/alphabet-wars-reinforces-massacre" target="_blank">Alphabet wars - reinforces massacre</a></td> </tr> <tr> <td ><a href="https://www.codewars.com/kata/59437bd7d8c9438fb5000004" target="_blank">Alphabet wars - nuclear strike</a></td> </tr> <tr> <td ><a href="https://www.codewars.com/kata/59473c0a952ac9b463000064" target="_blank">Alphabet war - Wo lo loooooo priests join the war</a></td> </tr> </table>
reference
def alphabet_war(fight): d = {'w': 4, 'p': 3, 'b': 2, 's': 1, 'm': - 4, 'q': - 3, 'd': - 2, 'z': - 1} r = sum(d[c] for c in fight if c in d) return {r == 0: "Let's fight again!", r > 0: "Left side wins!", r < 0: "Right side wins!" }[True]
Alphabet war
59377c53e66267c8f6000027
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/59377c53e66267c8f6000027
7 kyu
# Introduction Ka ka ka cypher is a cypher used by small children in some country. When a girl wants to pass something to the other girls and there are some boys nearby, she can use Ka cypher. So only the other girls are able to understand her. <br/> She speaks using KA, ie.: <br> `ka thi ka s ka bo ka y ka i ka s ka u ka gly` what simply means `this boy is ugly`. <br/> # Task Write a function that accepts a string word and returns encoded message using ka cypher. <br/><br/> Our rules:<br> - The encoded word should start from `ka`. - The `ka` goes after vowel (a,e,i,o,u) - When there is multiple vowels together, the `ka` goes only after the last `vowel` - When the word is finished by a vowel, do not add the `ka` after # Input/Output The `word` string consists of only lowercase and uppercase characters. There is only 1 word to convert - no white spaces. # Example ``` "a" => "kaa" "ka" => "kaka" "aa" => "kaaa" "Abbaa" => "kaAkabbaa" "maintenance" => "kamaikantekanakance" "Woodie" => "kaWookadie" "Incomprehensibilities" => "kaIkancokamprekahekansikabikalikatiekas" ``` # Remark Ka cypher's country residents, please don't hate me for simplifying the way how we divide the words into "syllables" in the Kata. I don't want to make it too hard for other nations ;-P
reference
import re KA_PATTERN = re . compile(r'(?![aeiou]+$)([aeiou]+)', re . I) def ka_co_ka_de_ka_me(word): return 'ka' + KA_PATTERN . sub(r'\1ka', word)
Ka Ka Ka cypher - words only vol 1
5934d648d95386bc8200010b
[ "Fundamentals" ]
https://www.codewars.com/kata/5934d648d95386bc8200010b
6 kyu
A local birthing center is interested in names! They have arrays of all the baby names they see each year, but the lists are sooo long! They don’t know how to calculate how many times one name is used. Given an array of names and a specific name string, return the number of times that specific name appears in the array. ``` javascript countName( ["Tom","Bob","Harry","Bob"] , "Bob") //should return 2, since "Bob" shows up 2 times in the array ``` ```python count_name( ["Tom","Bob","Harry","Bob"] , "Bob") # should return 2, since "Bob" shows up 2 times in the array ```
reference
def count_name(arr, name): return arr . count(name)
ScholarStem: Unit 6- Baby count!
5702f077e55d30a7af000115
[ "Fundamentals" ]
https://www.codewars.com/kata/5702f077e55d30a7af000115
7 kyu
Raj was to move up through a pattern of stairs of a given number **(n)**. Help him to get to the top using the function **stairs**. ##Keep in mind : * If **n<1** then return ' ' . * There are a lot of spaces before the stair starts except for **pattern(1)** ##Examples : pattern(1) 1 1 pattern(6) 1 1 1 2 2 1 1 2 3 3 2 1 1 2 3 4 4 3 2 1 1 2 3 4 5 5 4 3 2 1 1 2 3 4 5 6 6 5 4 3 2 1 pattern(12) 1 1 1 2 2 1 1 2 3 3 2 1 1 2 3 4 4 3 2 1 1 2 3 4 5 5 4 3 2 1 1 2 3 4 5 6 6 5 4 3 2 1 1 2 3 4 5 6 7 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8 8 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8 9 9 8 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8 9 0 0 9 8 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8 9 0 1 1 0 9 8 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8 9 0 1 2 2 1 0 9 8 7 6 5 4 3 2 1
reference
def stairs(n): return "\n" . join(step(i). rjust(4 * n - 1) for i in range(1, n + 1)) def step(n): h = " " . join(str(i % 10) for i in range(1, n + 1)) return f" { h } { h [:: - 1 ]} "
Walk-up Stairs
566c3f5b9de85fdd0e000026
[ "ASCII Art", "Fundamentals" ]
https://www.codewars.com/kata/566c3f5b9de85fdd0e000026
6 kyu
From a sentence, deduce the total number of animals. For example : "I see 3 zebras, 5 lions and 6 giraffes." The answer must be 14 "Mom, 3 rhinoceros and 6 snakes come to us!" The answer must be 9
reference
def CountAnimals(s): return sum(int(e) for e in s . split() if e . isdigit())
How many animals are there?
593406b8f3d071d83c00005d
[ "Fundamentals" ]
https://www.codewars.com/kata/593406b8f3d071d83c00005d
7 kyu
# Task An IP address contains four numbers(0-255) and separated by dots. It can be converted to a number by this way: Given a string `s` represents a number or an IP address. Your task is to convert it to another representation(`number to IP address` or `IP address to number`). You can assume that all inputs are valid. # Example Example IP address: `10.0.3.193` Convert each number to a 8-bit binary string (may needs to pad leading zeros to the left side): ``` 10 --> 00001010 0 --> 00000000 3 --> 00000011 193 --> 11000001 ``` Combine these four strings: `00001010 00000000 00000011 11000001` and then convert them to a decimal number: `167773121` # Input/Output `[input]` string `s` A number or IP address in string format. `[output]` a string A converted number or IP address in string format. # Example For `s = "10.0.3.193"`, the output should be `"167773121"`. For `s = "167969729"`, the output should be `"10.3.3.193"`.
algorithms
from ipaddress import IPv4Address def numberAndIPaddress(s): return str(int(IPv4Address(s))) if '.' in s else str(IPv4Address(int(s)))
Simple Fun #319: Number And IP Address
5936371109ca68fe6900000c
[ "Algorithms" ]
https://www.codewars.com/kata/5936371109ca68fe6900000c
6 kyu
# Task Your task is to sort the characters in a string according to the following rules: ``` - Rule1: English alphabets are arranged from A to Z, case insensitive. ie. "Type" --> "epTy" - Rule2: If the uppercase and lowercase of an English alphabet exist at the same time, they are arranged in the order of oringal input. ie. "BabA" --> "aABb" - Rule3: non English alphabet remain in their original position. ie. "By?e" --> "Be?y" ``` # Input/Output `[input]` string `s` A non empty string contains any characters(English alphabets or non English alphabets). `[output]` a string A sorted string according to the rules above. # Example For `s = "cba"`, the output should be `"abc"`. For `s = "Cba"`, the output should be `"abC"`. For `s = "cCBbAa"`, the output should be `"AaBbcC"`. For `s = "c b a"`, the output should be `"a b c"`. For `s = "-c--b--a-"`, the output should be `"-a--b--c-"`. For `s = "Codewars"`, the output should be `"aCdeorsw"`.
algorithms
def sort_string(s): a = iter(sorted((c for c in s if c . isalpha()), key=str . lower)) return '' . join(next(a) if c . isalpha() else c for c in s)
Simple Fun #318: Sort String
5936256f2e2a27edc9000047
[ "Algorithms", "Strings", "Sorting" ]
https://www.codewars.com/kata/5936256f2e2a27edc9000047
6 kyu
# Task: Based on the received dimensions, `a` and `b`, of an ellipse, calculare its area and perimeter. ## Example: ```javascript Input: elipse(5,2) Output: "Area: 31.4, perimeter: 23.1" ``` ```python Input: ellipse(5,2) Output: "Area: 31.4, perimeter: 23.1" ``` **Note:** The perimeter approximation formula you should use: `π * (3/2(a+b) - sqrt(ab))` ___ ## Have fun :)
reference
from math import pi def ellipse(a, b): return f"Area: { pi * a * b : .1 f } , perimeter: { pi * ( 1.5 * ( a + b ) - ( a * b ) * * .5 ): .1 f } "
Area and perimeter of the ellipse
5830e7feff1a3ce8d4000062
[ "Fundamentals" ]
https://www.codewars.com/kata/5830e7feff1a3ce8d4000062
6 kyu
What is the most asked question on CodeWars? > [Can](https://www.google.com/search?q=site%3Acodewars.com+"can+someone+explain") [someone](https://www.google.com/search?q=site%3Acodewars.com+"can+you+explain") [explain](https://www.google.com/search?q=site%3Acodewars.com+"can+anyone+explain") `/*...*/`? You need to write a function `detect` that will check if a string starts with `Can someone explain`, case sensitive. Return `true` if so, `false` otherwise. Let's hope you don't write a solution that makes people ask that question at you!
reference
def detect(comment): return comment . startswith('Can someone explain')
The most asked question on CodeWars
5935ecef7705f9614500002d
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5935ecef7705f9614500002d
null
**This Kata is intended as a small challenge for my students** All Star Code Challenge #19 You work for an ad agency and your boss, Bob, loves a catchy slogan. He's always jumbling together "buzz" words until he gets one he likes. You're looking to impress Boss Bob with a function that can do his job for him. Create a function called sloganMaker() that accepts an array of string "buzz" words. The function returns an array of all possible UNIQUE string permutations of the buzz words (concatonated and separated by spaces). Your boss is not very bright, so anticipate him using the same "buzz" word more than once, by accident. The function should ignore these duplicate string inputs. ``` sloganMaker(["super", "hot", "guacamole"]); //[ 'super hot guacamole', // 'super guacamole hot', // 'hot super guacamole', // 'hot guacamole super', // 'guacamole super hot', // 'guacamole hot super' ] sloganMaker(["cool", "pizza", "cool"]); // => [ 'cool pizza', 'pizza cool' ] ``` Note: There should be NO duplicate strings in the output array The input array MAY contain duplicate strings, which should STILL result in an output array with all unique strings An empty string is valid input ```if-not:python,crystal The order of the permutations in the output array does not matter ``` ```if:python,crystal The order of the output array must match those rules: 1. Generate the permutations in lexicographic order of the original array. 2. keep only the first occurence of a permutation, when duplicates are found. ```
reference
def slogan_maker(array): print(array) from itertools import permutations array = remove_duplicate(array) return [' ' . join(element) for element in list(permutations(array, len(array)))] def remove_duplicate(old_list): final_list = [] for num in old_list: if num not in final_list: final_list . append(num) return final_list
All Star Code Challenge #19
5865a407b359c45982000036
[ "Strings", "Combinatorics", "Permutations", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5865a407b359c45982000036
5 kyu
**This Kata is intended as a small challenge for my students** Create a function that takes a string argument and returns that same string with all vowels removed (vowels are "a", "e", "i", "o", "u"). Example (**Input** --> **Output**) ``` "drake" --> "drk" "aeiou" --> "" ``` ```cpp remove_vowels("drake") // => "drk" remove_vowels("aeiou") // => "" ```
reference
def remove_vowels(strng): return '' . join([i for i in strng if i not in 'aeiou'])
All Star Code Challenge #3
58640340b3a675d9a70000b9
[ "Fundamentals" ]
https://www.codewars.com/kata/58640340b3a675d9a70000b9
7 kyu
**This Kata is intended as a small challenge for my students** All Star Code Challenge #16 Create a function called noRepeat() that takes a string argument and returns a single letter string of the **first** not repeated character in the entire string. ```javascript noRepeat("aabbccdde") // => "e" noRepeat("wxyz") // => "w" noRepeat("testing") // => "e" ``` ``` haskell noRepeat "aabbccdde" `shouldBe` 'e' noRepeat "wxyz" `shouldBe` 'w' noRepeat "testing" `shouldBe` 'e' ``` Note: ONLY letters from the english alphabet will be used as input There will ALWAYS be at least one non-repeating letter in the input string
reference
def no_repeat(s): return next(c for c in s if s . count(c) == 1)
All Star Code Challenge #16
586566b773bd9cbe2b000013
[ "Fundamentals" ]
https://www.codewars.com/kata/586566b773bd9cbe2b000013
7 kyu
Reverse every other word in a given string, then return the string. Throw away any leading or trailing whitespace, while ensuring there is exactly one space between each word. Punctuation marks should be treated as if they are a part of the word in this kata.
reference
def reverse_alternate(string): return " " . join(y[:: - 1] if x % 2 else y for x, y in enumerate(string . split()))
Reverse every other word in the string
58d76854024c72c3e20000de
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/58d76854024c72c3e20000de
6 kyu
# Task Since the weather was good, some students decided to go for a walk in the park after the first lectures of the new academic year. There they saw a squirrel, which climbed a tree in a spiral at a constant angle to the ground. They calculated that in one loop the squirrel climbes `h` meters (vertical height), the height of the tree is equal to `H` (`v` in Ruby), and the length of its circumference equals `S`. These calculations were exhausting, so now the students need your help to figure out how many meters the path length of squirrel climbed when it reached the tree top. The result should be rounded to 4 decimal places. # Code Limit Less than `52` characters (JavaScript & Python) Less than `48` characters (Ruby) # Example For `h = 4, H = 16, S = 3`, the output should be `20`. For `h = 8, H = 9, S = 37`, the output should be `42.5869`.
games
def squirrel(h, H, S): return round(H / h * (h * * 2 + S * * 2) * * 0.5, 4)
One Line Task: Squirrel And Tree
59016379ee5456d8cc00000f
[ "Puzzles", "Restricted" ]
https://www.codewars.com/kata/59016379ee5456d8cc00000f
4 kyu
Zalgo text is text that leaks into our plane of existence from a corrupted dimension of Unicode. For example: ``` H̗̪͇͓̙͎̣̄ͬa͚̯̦͉̖̥v͆ͩ̃͆̓̐ͥe̟͎͖͕͍̎ ̰͚̩̟͕̰͊̽̍ͯ̌͊ā̖̪͉͍̥͙̿ͩ̃ͅ ̬̥͎͑̿ͧg̰̳̺͔̦͉ͫ̀̐̓̐r̝̫̱̘̰͐͋ͯͭͭͭ͆e͙͕̖̗͙̰͌ͭä͓͚̝͓́̌͑ͪ͊ṱͥ ̱ͣd͎͔͎͇̫̪̘̃͐̇à͕̮̈͋ͪy̼̳̱ͮ!̳̥̰̭͇̔ͮ̽̓ ``` Complete the function that converts a string of Zalgo text into a string interpretable by our mortal eyes. For example, the string above would be converted into: ``` Have a great day! ``` The converted string should only feature ASCII characters. --- _Some [hints](http://stackoverflow.com/questions/6579844/how-does-zalgo-text-work) if you're stuck..._
reference
def read_zalgo(zalgotext): return "" . join([c for c in zalgotext if c . isascii()])
Zalgo text reader
588fe9eaadbbfb44b70001fc
[ "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/588fe9eaadbbfb44b70001fc
7 kyu
Given an array representing the height of towers on a 2d plane, with each tower being of width 1, Whats's the maximum amount of units of water that can be captured between the towers when it rains? Each tower is immediately next to the tower next to it in the array, except in instances where a height of 0 is shown, then no tower would be present. A single unit can be thought of as a 2d square with a width 1. ### Examples ``` [5,2,10] should return 3 [1,0,5,2,6,3,10] should return 7 [15,0,6,10,11,2,5] should return 20 [1,5,1] should return 0 [6,5] should return 0 [] should return 0 ``` ### Performances: Watch out for performances: you'll need a solution linear with the number of towers.
games
from itertools import accumulate def rain_volume(towers): a = accumulate(towers, max) b = accumulate(towers[:: - 1], max) a = [max(0, i - j) for i, j in zip(a, towers)] b = [max(0, i - j) for i, j in zip(b, towers[:: - 1])] return sum(min(i, j) for i, j in zip(a, b[:: - 1]))
City Swim - 2D (TowerFlood And PlainFlood)
58e77c88fd2d893a77000102
[ "Puzzles", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/58e77c88fd2d893a77000102
5 kyu
Format any integer provided into a string with "," (commas) in the correct places. **Example:** ``` For n = 100000 the function should return '100,000'; For n = 5678545 the function should return '5,678,545'; for n = -420902 the function should return '-420,902'. ```
reference
def number_format(n): return f' { n :,} '
Number Format
565c4e1303a0a006d7000127
[ "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/565c4e1303a0a006d7000127
6 kyu
#Rotate a square matrix like a vortex Your task is to rotate a square matrix of numbers like a vortex. ``` In most vortices, the fluid flow velocity is greatest next to its axis and decreases in inverse proportion to the distance from the axis. ``` So the rotation speed increases with every ring nearer to the middle. For this kata this means, that the outer "ring" of the matrix rotates one step. The next ring rotates two steps. The next ring rotates three steps. And so on... The rotation is always "to the left", so against clockwise!<br> An example: ``` The given matrix: 5 3 6 1 5 8 7 4 1 2 4 3 3 1 2 2 First step: The outer ring is rotated once to the left. 5 3 6 1 -> 1 4 3 2 5 8 7 4 -> 6 8 7 2 1 2 4 3 -> 3 2 4 1 3 1 2 2 -> 5 5 1 3 Second step: The second ring is rotated twice to the left. 8 7 -> 7 4 -> 4 2 2 4 -> 8 2 -> 7 8 In the whole square the second step looks like this: 1 4 3 2 -> 1 4 3 2 6 8 7 2 -> 6 4 2 2 3 2 4 1 -> 3 7 8 1 5 5 1 3 -> 5 5 1 3 No more rings. So the result is clear. ``` #Task Create the method for rotating like a vortex. The method has one input parameter:<br> The sqaure matrix as an array of arrays <br> Your method have to return the rotated matrix. You must not change the input array! Create a new array for the output. The square matrix will always be at least 1x1 and at most 20x20 and of course the array will never be null. <br><br><br> Have fun coding it and please don't forget to vote and rank this kata! :-) I have also created other katas. Take a look if you enjoyed this kata!
algorithms
import numpy as np def rotate_like_a_vortex(matrix): fuck = np . array(matrix) for num in range(len(matrix) / / 2): fuck[num: len(matrix) - num, num: len(matrix) - num] = np . rot90( fuck[num: len(matrix) - num, num: len(matrix) - num], k=1, axes=(0, 1)) return fuck . tolist()
Rotate a square matrix like a vortex
58d3cf477a4ea9bb2f000103
[ "Logic", "Arrays", "Algorithms", "Matrix" ]
https://www.codewars.com/kata/58d3cf477a4ea9bb2f000103
5 kyu
# Hooray - It's "Spaghetti Night" again ! Spaghetti is my favourite meal, so I always like to save the longest piece for last... But since my <a href="https://www.codewars.com/kata/57d7805cec167081a50014ac">last "Spaghetti Night"</a> the price of my special ID spaghetti has really gone through the roof and so I have changed to a cheaper brand. Unfortunately, this cheaper spaghetti only has a SINGLE ID somewhere on each piece of spaghetti. Oh well, at least it tastes the same. # Task Write some spaghetti code to help me know which piece of spaghetti is the longest. Try NOT to write spaghetti code that looks like <a href="https://en.wikipedia.org/wiki/Spaghetti_code">spaghetti code</a> ! NOTES * Spaghetti pieces all look the same ("S") except for a single uppercase letter unique ID *somewhere* on the piece (which may also be "S") * Spaghetti pieces do not touch each other, or themselves * Spaghetti pieces twist only up, down, left, right (not diagonally) * If multiple spaghetti pieces are longest, just return any one of them (all spaghetti tastes the same) * If the plate has no spaghetti then return empty string * All of my plates are rectangular * Plates can have any (non alphabetic) background pattern on them # Examples Ex1 ``` SSSSSASS____ ____________ SSSSSSBSSSS_ ____________ SSSSSC______ ``` *Answer:* ```B``` <hr> Ex2 ``` SSSSSSSSS______ ________S__SSS_ S S A S _S___S__S____S_ B S S _S___SSSSSCSSS_ ``` *Answer:* ```C```
algorithms
def spaghetti_code(plate): def is_noodle(c): return 'A' <= c <= 'Z' def is_inside(a, b): return 0 <= a < X and 0 <= b < Y def flood(i, j): typ_s . add(board[i][j]) board[i][j] = '_' return 1 + sum(flood(x, y) for x, y in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)] if is_inside(x, y) and is_noodle(board[x][y])) board = [* map(list, plate)] X, Y = len(board), board and len(board[0]) top, typ = 0, "" for i, r in enumerate(board): for j, c in enumerate(r): if not is_noodle(c): continue typ_s = set() n = flood(i, j) if n > top: top, typ = n, (typ_s - {'S'} or {'S'}). pop() return typ
Spaghetti Code - #2 Hard
586dd5f4a44cfc48bb000011
[ "Algorithms" ]
https://www.codewars.com/kata/586dd5f4a44cfc48bb000011
4 kyu
Define a regular expression which tests if a given string representing a binary number is divisible by 5. ### Examples: ```csharp // 5 divisable by 5 Regex.IsMatch('101', DivisibleByFive) == true // 135 divisable by 5 Regex.IsMatch('10000111', DivisibleByFive) == true // 666 not divisable by 5 Regex.IsMatch('0000001010011010', DivisibleByFive) == false ``` ```javascript // 5 divisable by 5 divisibleByFive.test('101') === true // 135 divisable by 5 divisibleByFive.test('10000111') === true // 666 not divisable by 5 divisibleByFive.test('0000001010011010') === false ``` ```php // 5 is divisible by 5 preg_match($pattern, '101'); // => 1 // 135 is divisible by 5 preg_match($pattern, '10000111'); // => 1 // 666 is not divisible by 5 preg_match($pattern, '0000001010011010'); // => 0 ``` ```python # 5 divisible by 5 PATTERN.match('101') == true # 135 divisible by 5 PATTERN.match('10000111') == true # 666 not divisible by 5 PATTERN.match('0000001010011010') == false ``` ```java // 5 divisible by 5 DivisibleByFive.pattern().matcher('101').matches() == true // 135 divisible by 5 DivisibleByFive.pattern().matcher('10000111').matches() == true // 666 not divisible by 5 DivisibleByFive.pattern().matcher('0000001010011010').matches() == false ``` ### Note: This can be solved by creating a Finite State Machine that evaluates if a string representing a number in binary base is divisible by given number. The detailed explanation for dividing by 3 is [here](http://math.stackexchange.com/questions/140283/why-does-this-fsm-accept-binary-numbers-divisible-by-three) The FSM diagram for dividing by 5 is [here](http://aswitalski.github.io/img/FSM-binary-divisible-by-five.png "Finite State machine - string representing a binary number divisible by 5")
algorithms
# build a DFA (Deterministic Finite Automaton) # then use steps from # https://stackoverflow.com/questions/34476333/regular-expression-for-binary-numbers-divisible-by-5 # to reduce the DFA graph to the final regular expression. # At the end, the + character has been used, instead of *, to reject empty strings PATTERN = r"^(0|1(10)*(0|11)(01*01|01*00(10)*(0|11))*1)+$"
Regular expression for binary numbers divisible by 5
5647c3858d4acbbe550000ad
[ "Binary", "Algorithms", "Regular Expressions" ]
https://www.codewars.com/kata/5647c3858d4acbbe550000ad
4 kyu
Your task is to convert a given number into a string with commas added for easier readability. The number should be rounded to 3 decimal places and the commas should be added at intervals of three digits before the decimal point. There does not need to be a comma at the end of the number. You will receive both positive and negative numbers. ## Examples ```python commas(1) == "1" commas(1000) == "1,000" commas(100.2346) == "100.235" commas(1000000000.23) == "1,000,000,000.23" commas(-1) == "-1" commas(-1000000.123) == "-1,000,000.123" ```
reference
def commas(num): return "{:,.3f}" . format(num). rstrip("0"). rstrip(".")
Add commas to a number
56a115cadb39a2faa000001e
[ "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/56a115cadb39a2faa000001e
6 kyu
# Task Find the integer from `a` to `b` (included) with the greatest number of divisors. For example: ``` divNum(15, 30) ==> 24 divNum(1, 2) ==> 2 divNum(0, 0) ==> 0 divNum(52, 156) ==> 120 ``` If there are several numbers that have the same (maximum) number of divisors, the smallest among them should be returned. Return the string `"Error"` if `a > b`.
reference
import numpy as np s = np . ones(100000) for i in range(2, 100000): s[i:: i] += 1 def div_num(a, b): return max(range(a, b + 1), key=lambda i: (s[i], - i), default='Error')
Find Number With Maximum Number Of Divisors
588c0a38b7cd14085300003f
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/588c0a38b7cd14085300003f
6 kyu
Given an array of integers, return the smallest common factors of all integers in the array. When i say **Smallest Common Factor** i mean the smallest number above 1 that can divide all numbers in the array without a remainder. ```javascript scf([200, 30, 18, 8, 64, 34]) //=> 2 scf([21, 45, 51, 27, 33]) //=> 3 scf([133, 147, 427, 266]) //=> 7 ``` If there are no common factors above 1, return 1 (technically 1 is always a common factor).
algorithms
def scf(arr): for i in range(2, (min(arr) if arr else 1) + 1): if all(x % i == 0 for x in arr): return i return 1
Get Smallest Common Factor
5933af2db328fbc731000010
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/5933af2db328fbc731000010
7 kyu
## Explanation Write a function that shortens a string to a given length. Instead of cutting the string from the end, your function will shorten it from the middle like shrinking. For example: ``` sentence = "The quick brown fox jumps over the lazy dog" res = shorten(sentence, 27) res === "The quick br...the lazy dog" ``` Your function should also accept an optional argument `glue` to get the parts together. ``` sentence = "The quick brown fox jumps over the lazy dog" res = shorten(sentence, 27, '---') res === "The quick br---the lazy dog" ``` ## Rules are simple: - Result must always be equal to the given `length` - Only exception to above rule is, when string is already shorter than given length. In that case string should be returned untouched. - If no `glue` is sent `...` should be used by default - If `glue` cannot go exactly in the middle, **second part** should be longer - If glue cannot fit in the shortened string, string should be shortened without shrinking. - meaning; `shorten('hello world', 5, '....')` should return `hello` because 4 char glue cannot fit in the shortened string. - glue must have at least 1 char on both ends. Example minimum `h...d`, results `....d` or `h....` are not excepted. - You can assume you'll always receive a `string` as the sentence and the glue. And `integer number` for the length. - Think about other possible edge cases, there are some surprises.
reference
def shorten(string, length, glue="..."): if len(string) < length: return string if length < len(glue) + 2: return string[: length] l1, l2 = (length - len(glue)) / / 2, (length - len(glue) + 1) / / 2 return string[: l1] + glue + string[- l2:]
String Shortener (shrink)
557d18803802e873170000a0
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/557d18803802e873170000a0
6 kyu
Your friend invites you out to a cool floating pontoon around 1km off the beach. Among other things, the pontoon has a huge slide that drops you out right into the ocean, a small way from a set of stairs used to climb out. As you plunge out of the slide into the water, you see a shark hovering in the darkness under the pontoon... Crap! You need to work out if the shark will get to you before you can get to the pontoon. To make it easier... as you do the mental calculations in the water you either freeze when you realise you are dead, or swim when you realise you can make it! You are given 5 variables; * sharkDistance = distance from the shark to the pontoon. The shark will eat you if it reaches you before you escape to the pontoon. * sharkSpeed = how fast it can move in metres/second. * pontoonDistance = how far you need to swim to safety in metres. * youSpeed = how fast you can swim in metres/second. * dolphin = a boolean, if true, you can half the swimming speed of the shark as the dolphin will attack it. * The pontoon, you, and the shark are all aligned in one dimension. If you make it, return "Alive!", if not, return "Shark Bait!".
reference
def shark(pontoon_distance, shark_distance, you_speed, shark_speed, dolphin): if dolphin: shark_speed = shark_speed / 2 shark_eat_time = shark_distance / shark_speed you_safe_time = pontoon_distance / you_speed return "Shark Bait!" if you_safe_time > shark_eat_time else "Alive!"
Holiday VI - Shark Pontoon
57e921d8b36340f1fd000059
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/57e921d8b36340f1fd000059
8 kyu
You are given an array of positive and negative integers and a number ```n``` and ```n > 1```. The array may have elements that occurs more than once. Find all the combinations of n elements of the array that their sum are 0. ```python arr = [1, -1, 2, 3, -2] n = 3 find_zero_sum_groups(arr, n) == [-2, -1, 3] # -2 - 1 + 3 = 0 ``` The function should ouput every combination or group in increasing order. We may have more than one group: ```python arr = [1, -1, 2, 3, -2, 4, 5, -3 ] n = 3 find_zero_sum_groups(arr, n) == [[-3, -2, 5], [-3, -1, 4], [-3, 1, 2], [-2, -1, 3]] ``` In the case above the function should output a sorted 2D array. The function will not give a group twice, or more, only once. ```python arr = [1, -1, 2, 3, -2, 4, 5, -3, -3, -1, 2, 1, 4, 5, -3 ] n = 3 find_zero_sum_groups(arr, n) == [[-3, -2, 5], [-3, -1, 4], [-3, 1, 2], [-2, -1, 3]] ``` If there are no combinations with sum equals to 0, the function will output an alerting message. ```python arr = [1, 1, 2, 3] n = 2 find_zero_sum_groups(arr, n) == "No combinations" ``` If the function receives an empty array will output an specific alert: ```python arr = [] n = 2 find_zero_sum_groups(arr, n) == "No elements to combine" ``` As you have seen the solutions may have a value occurring only once. Enjoy it!
reference
from itertools import combinations def find_zero_sum_groups(arr, n): combos = sorted(sorted(c) for c in combinations(set(arr), n) if sum(c) == 0) return combos if len(combos) > 1 else combos[0] if combos else "No combinations" if arr else "No elements to combine"
Search The 0 Sums Combinations in an Array
5711fc7c159cde6ac70003e2
[ "Fundamentals", "Data Structures", "Algorithms", "Mathematics", "Logic" ]
https://www.codewars.com/kata/5711fc7c159cde6ac70003e2
6 kyu
Create a function that takes in the sum and age difference of two people, calculates their individual ages, and returns a pair of values (oldest age first) if those exist or `null/None` or `{-1, -1} in C` if: * `sum < 0` * `difference < 0` * Either of the calculated ages come out to be negative
reference
def get_ages(a, b): x = (a + b) / 2 y = (a - b) / 2 return None if a < 0 or b < 0 or x < 0 or y < 0 else (x, y)
Calculate Two People's Individual Ages
58e0bd6a79716b7fcf0013b1
[ "Fundamentals", "Algorithms", "Arrays" ]
https://www.codewars.com/kata/58e0bd6a79716b7fcf0013b1
7 kyu
Given an array of integers. Return a number that is the sum of 1. The product of all the non-negative numbers 2. The sum of all the negative numbers # Edge cases - If there are no non-negative numbers, assume the product of them to be 1. - Similarly, if there are no negative numbers, assume the sum of them to be 0. - If the array is null, result should be 0. # For example: ```javascript mathEngine([1, 2, 3, -4, -5]) // should return -3 ``` ```ruby math_engine([1, 2, 3, -4, -5]) # should return -3 ``` ```python math_engine([1, 2, 3, -4, -5]) # should return -3 ```
reference
from math import prod def math_engine(arr): return 0 if arr is None else prod(a for a in arr if a >= 0) + sum(a for a in arr if a < 0)
Math engine
587854330594a6fb7e000057
[ "Fundamentals" ]
https://www.codewars.com/kata/587854330594a6fb7e000057
7 kyu
You are developing an image hosting website. You have to create a function for generating random and unique image filenames. Create a function for generating a random 6 character string which will be used to access the photo URL. To make sure the name is not already in use, you are given access to an PhotoManager object. You can call it like so to make sure the name is unique ```javascript // at this point, the website has only one photo, hosted on the 'ABCDEF' url photoManager.nameExists('ABCDEF'); // returns true photoManager.nameExists('BBCDEF'); // returns false ``` ```java // at this point, the website has only one photo, hosted on the 'ABCDEF' url photoManager.nameExists("ABCDEF"); // returns true photoManager.nameExists("BBCDEF"); // returns false ``` ```cpp // at this point, the website has only one photo, hosted on the 'ABCDEF' url photoManager.nameExists("ABCDEF"); // returns true photoManager.nameExists("BBCDEF"); // returns false ``` <strong>Note:</strong> We consider two names with same letters but different cases to be unique.
reference
import uuid def generateName(): return str(uuid . uuid4())[: 6]
Image host filename generator
586a933fc66d187b6e00031a
[ "Logic", "Object-oriented Programming", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/586a933fc66d187b6e00031a
6 kyu
In Dark Souls, players level up trading souls for stats. 8 stats are upgradable this way: vitality, attunement, endurance, strength, dexterity, resistance, intelligence, and faith. Each level corresponds to adding one point to a stat of the player's choice. Also, there are 10 possible classes each having their own starting level and stats: ``` Warrior (Level 4): 11, 8, 12, 13, 13, 11, 9, 9 Knight (Level 5): 14, 10, 10, 11, 11, 10, 9, 11 Wanderer (Level 3): 10, 11, 10, 10, 14, 12, 11, 8 Thief (Level 5): 9, 11, 9, 9, 15, 10, 12, 11 Bandit (Level 4): 12, 8, 14, 14, 9, 11, 8, 10 Hunter (Level 4): 11, 9, 11, 12, 14, 11, 9, 9 Sorcerer (Level 3): 8, 15, 8, 9, 11, 8, 15, 8 Pyromancer (Level 1): 10, 12, 11, 12, 9, 12, 10, 8 Cleric (Level 2): 11, 11, 9, 12, 8, 11, 8, 14 Deprived (Level 6): 11, 11, 11, 11, 11, 11, 11, 11 ``` From level 1, the necessary souls to level up each time up to 11 are `673`, `690`, `707`, `724`, `741`, `758`, `775`, `793`, `811`, and `829`. Then from 11 to 12 and onwards the amount is defined by the expression `round(pow(x, 3) * 0.02 + pow(x, 2) * 3.06 + 105.6 * x - 895)` where `x` is the number corresponding to the next level. Your function will receive a string with the character class and a list of stats. It should calculate which level is required to get the desired character build and the amount of souls needed to do so. The result should be a string in the format: `'Starting as a [CLASS], level [N] will require [M] souls.'` where `[CLASS]` is your starting class, `[N]` is the required level, and `[M]` is the amount of souls needed respectively.
games
D = {"warrior": (4, 86), "knight": (5, 86), "wanderer": (3, 86), "thief": (5, 86), "bandit": (4, 86), "hunter": (4, 86), "sorcerer": (3, 82), "pyromancer": (1, 84), "cleric": (2, 84), "deprived": (6, 88)} def count(x): return round(pow(x, 3) * 0.02 + pow(x, 2) * 3.06 + 105.6 * x - 895) memo = [0, 0, 673, 1363, 2070, 2794, 3535, 4293, 5068, 5861, 6672, 7501] def need(level): while len(memo) <= level: memo . append(memo[- 1] + count(len(memo))) return memo[level] def souls(character, build): level, stats = D[character] goal = level + sum(build) - stats return f"Starting as a { character } , level { goal } will require { need ( goal ) - need ( level )} souls."
Dark Souls: Prepare To Die - Soul Level
592a5f9fa3df0a28730000e7
[ "Puzzles" ]
https://www.codewars.com/kata/592a5f9fa3df0a28730000e7
6 kyu
## Story Your friend Bob is working as a taxi driver. After working for a month he is frustrated in the city's traffic lights. He asks you to write a program for a new type of traffic light. It is made so it turns green for the road with the most congestion. ## Task Given 2 pairs of values each representing a road (the number of cars on it and its name), construct an object whose `turngreen` method returns the name of the road with the most traffic at the moment of the method call, and clears that road from cars. After both roads are clear of traffic, or if the number of cars on both roads is the same from the beginning, return an empty value instead. ### Example ``` t = SmartTrafficLight([42, "27th ave"], [72, "3rd st"]) t.turngreen() == "3rd st" t.turngreen() == "27th ave" t.turngreen() == null t = SmartTrafficLight([10, "27th ave"], [10, "3rd st"]) t.turngreen() == null ```
reference
class SmartTrafficLight: def __init__(self, a, b): self . a = [] if a[0] == b[0] else sorted((a, b)) def turngreen(self): if self . a: return self . a . pop()[1]
Smart Traffic Lights
58587905ed1b4dad6e0000c6
[ "Fundamentals", "Object-oriented Programming" ]
https://www.codewars.com/kata/58587905ed1b4dad6e0000c6
6 kyu
## Graphics Series #3: Repair the LED display ### Story There is a huge LED monitor, because it's too old, Its digital display module is faulty. Can you fix it? ### Rules Normal display data is stored in an array, its name is `nums`. It has been preload, you can use it directly. Fault types are: | 1. Flip up and down | 2. Flip left and right | 3. Flip both 1 and 2 | |:-------------------:|:----------------------:|:--------------------:| | <svg width=131 height=69><rect x="0" y="0" width=51 height=69 style="fill:rgb(64,64,80);stroke-width:0" /><circle cx="7" cy="7" r="3.5" fill="#332" /><circle cx="16" cy="7" r="3.5" fill="#332" /><circle cx="25" cy="7" r="3.5" fill="#8f0" /><circle cx="34" cy="7" r="3.5" fill="#332" /><circle cx="43" cy="7" r="3.5" fill="#332" /><circle cx="7" cy="16" r="3.5" fill="#332" /><circle cx="16" cy="16" r="3.5" fill="#8f0" /><circle cx="25" cy="16" r="3.5" fill="#8f0" /><circle cx="34" cy="16" r="3.5" fill="#332" /><circle cx="43" cy="16" r="3.5" fill="#332" /><circle cx="7" cy="25" r="3.5" fill="#332" /><circle cx="16" cy="25" r="3.5" fill="#332" /><circle cx="25" cy="25" r="3.5" fill="#8f0" /><circle cx="34" cy="25" r="3.5" fill="#332" /><circle cx="43" cy="25" r="3.5" fill="#332" /><circle cx="7" cy="34" r="3.5" fill="#332" /><circle cx="16" cy="34" r="3.5" fill="#332" /><circle cx="25" cy="34" r="3.5" fill="#8f0" /><circle cx="34" cy="34" r="3.5" fill="#332" /><circle cx="43" cy="34" r="3.5" fill="#332" /><circle cx="7" cy="43" r="3.5" fill="#332" /><circle cx="16" cy="43" r="3.5" fill="#332" /><circle cx="25" cy="43" r="3.5" fill="#8f0" /><circle cx="34" cy="43" r="3.5" fill="#332" /><circle cx="43" cy="43" r="3.5" fill="#332" /><circle cx="7" cy="52" r="3.5" fill="#332" /><circle cx="16" cy="52" r="3.5" fill="#332" /><circle cx="25" cy="52" r="3.5" fill="#8f0" /><circle cx="34" cy="52" r="3.5" fill="#332" /><circle cx="43" cy="52" r="3.5" fill="#332" /><circle cx="7" cy="61" r="3.5" fill="#332" /><circle cx="16" cy="61" r="3.5" fill="#8f0" /><circle cx="25" cy="61" r="3.5" fill="#8f0" /><circle cx="34" cy="61" r="3.5" fill="#8f0" /><circle cx="43" cy="61" r="3.5" fill="#332" /><rect x="80" y="0" width=51 height=69 style="fill:rgb(64,64,80);stroke-width:0" /><circle cx="87" cy="7" r="3.5" fill="#332" /><circle cx="96" cy="7" r="3.5" fill="#fc0" /><circle cx="105" cy="7" r="3.5" fill="#fc0" /><circle cx="114" cy="7" r="3.5" fill="#fc0" /><circle cx="123" cy="7" r="3.5" fill="#332" /><circle cx="87" cy="16" r="3.5" fill="#332" /><circle cx="96" cy="16" r="3.5" fill="#332" /><circle cx="105" cy="16" r="3.5" fill="#fc0" /><circle cx="114" cy="16" r="3.5" fill="#332" /><circle cx="123" cy="16" r="3.5" fill="#332" /><circle cx="87" cy="25" r="3.5" fill="#332" /><circle cx="96" cy="25" r="3.5" fill="#332" /><circle cx="105" cy="25" r="3.5" fill="#fc0" /><circle cx="114" cy="25" r="3.5" fill="#332" /><circle cx="123" cy="25" r="3.5" fill="#332" /><circle cx="87" cy="34" r="3.5" fill="#332" /><circle cx="96" cy="34" r="3.5" fill="#332" /><circle cx="105" cy="34" r="3.5" fill="#fc0" /><circle cx="114" cy="34" r="3.5" fill="#332" /><circle cx="123" cy="34" r="3.5" fill="#332" /><circle cx="87" cy="43" r="3.5" fill="#332" /><circle cx="96" cy="43" r="3.5" fill="#332" /><circle cx="105" cy="43" r="3.5" fill="#fc0" /><circle cx="114" cy="43" r="3.5" fill="#332" /><circle cx="123" cy="43" r="3.5" fill="#332" /><circle cx="87" cy="52" r="3.5" fill="#332" /><circle cx="96" cy="52" r="3.5" fill="#fc0" /><circle cx="105" cy="52" r="3.5" fill="#fc0" /><circle cx="114" cy="52" r="3.5" fill="#332" /><circle cx="123" cy="52" r="3.5" fill="#332" /><circle cx="87" cy="61" r="3.5" fill="#332" /><circle cx="96" cy="61" r="3.5" fill="#332" /><circle cx="105" cy="61" r="3.5" fill="#fc0" /><circle cx="114" cy="61" r="3.5" fill="#332" /><circle cx="123" cy="61" r="3.5" fill="#332" /></svg> | <svg width=131 height=69><rect x="0" y="0" width=51 height=69 style="fill:rgb(64,64,80);stroke-width:0" /><circle cx="7" cy="7" r="3.5" fill="#332" /><circle cx="16" cy="7" r="3.5" fill="#8f0" /><circle cx="25" cy="7" r="3.5" fill="#8f0" /><circle cx="34" cy="7" r="3.5" fill="#8f0" /><circle cx="43" cy="7" r="3.5" fill="#332" /><circle cx="7" cy="16" r="3.5" fill="#8f0" /><circle cx="16" cy="16" r="3.5" fill="#332" /><circle cx="25" cy="16" r="3.5" fill="#332" /><circle cx="34" cy="16" r="3.5" fill="#332" /><circle cx="43" cy="16" r="3.5" fill="#8f0" /><circle cx="7" cy="25" r="3.5" fill="#332" /><circle cx="16" cy="25" r="3.5" fill="#332" /><circle cx="25" cy="25" r="3.5" fill="#332" /><circle cx="34" cy="25" r="3.5" fill="#332" /><circle cx="43" cy="25" r="3.5" fill="#8f0" /><circle cx="7" cy="34" r="3.5" fill="#332" /><circle cx="16" cy="34" r="3.5" fill="#332" /><circle cx="25" cy="34" r="3.5" fill="#332" /><circle cx="34" cy="34" r="3.5" fill="#8f0" /><circle cx="43" cy="34" r="3.5" fill="#332" /><circle cx="7" cy="43" r="3.5" fill="#332" /><circle cx="16" cy="43" r="3.5" fill="#332" /><circle cx="25" cy="43" r="3.5" fill="#8f0" /><circle cx="34" cy="43" r="3.5" fill="#332" /><circle cx="43" cy="43" r="3.5" fill="#332" /><circle cx="7" cy="52" r="3.5" fill="#332" /><circle cx="16" cy="52" r="3.5" fill="#8f0" /><circle cx="25" cy="52" r="3.5" fill="#332" /><circle cx="34" cy="52" r="3.5" fill="#332" /><circle cx="43" cy="52" r="3.5" fill="#332" /><circle cx="7" cy="61" r="3.5" fill="#8f0" /><circle cx="16" cy="61" r="3.5" fill="#8f0" /><circle cx="25" cy="61" r="3.5" fill="#8f0" /><circle cx="34" cy="61" r="3.5" fill="#8f0" /><circle cx="43" cy="61" r="3.5" fill="#8f0" /><rect x="80" y="0" width=51 height=69 style="fill:rgb(64,64,80);stroke-width:0" /><circle cx="87" cy="7" r="3.5" fill="#332" /><circle cx="96" cy="7" r="3.5" fill="#fc0" /><circle cx="105" cy="7" r="3.5" fill="#fc0" /><circle cx="114" cy="7" r="3.5" fill="#fc0" /><circle cx="123" cy="7" r="3.5" fill="#332" /><circle cx="87" cy="16" r="3.5" fill="#fc0" /><circle cx="96" cy="16" r="3.5" fill="#332" /><circle cx="105" cy="16" r="3.5" fill="#332" /><circle cx="114" cy="16" r="3.5" fill="#332" /><circle cx="123" cy="16" r="3.5" fill="#fc0" /><circle cx="87" cy="25" r="3.5" fill="#fc0" /><circle cx="96" cy="25" r="3.5" fill="#332" /><circle cx="105" cy="25" r="3.5" fill="#332" /><circle cx="114" cy="25" r="3.5" fill="#332" /><circle cx="123" cy="25" r="3.5" fill="#332" /><circle cx="87" cy="34" r="3.5" fill="#332" /><circle cx="96" cy="34" r="3.5" fill="#fc0" /><circle cx="105" cy="34" r="3.5" fill="#332" /><circle cx="114" cy="34" r="3.5" fill="#332" /><circle cx="123" cy="34" r="3.5" fill="#332" /><circle cx="87" cy="43" r="3.5" fill="#332" /><circle cx="96" cy="43" r="3.5" fill="#332" /><circle cx="105" cy="43" r="3.5" fill="#fc0" /><circle cx="114" cy="43" r="3.5" fill="#332" /><circle cx="123" cy="43" r="3.5" fill="#332" /><circle cx="87" cy="52" r="3.5" fill="#332" /><circle cx="96" cy="52" r="3.5" fill="#332" /><circle cx="105" cy="52" r="3.5" fill="#332" /><circle cx="114" cy="52" r="3.5" fill="#fc0" /><circle cx="123" cy="52" r="3.5" fill="#332" /><circle cx="87" cy="61" r="3.5" fill="#fc0" /><circle cx="96" cy="61" r="3.5" fill="#fc0" /><circle cx="105" cy="61" r="3.5" fill="#fc0" /><circle cx="114" cy="61" r="3.5" fill="#fc0" /><circle cx="123" cy="61" r="3.5" fill="#fc0" /></svg> | <svg width=131 height=69><rect x="0" y="0" width=51 height=69 style="fill:rgb(64,64,80);stroke-width:0" /><circle cx="7" cy="7" r="3.5" fill="#332" /><circle cx="16" cy="7" r="3.5" fill="#332" /><circle cx="25" cy="7" r="3.5" fill="#332" /><circle cx="34" cy="7" r="3.5" fill="#8f0" /><circle cx="43" cy="7" r="3.5" fill="#332" /><circle cx="7" cy="16" r="3.5" fill="#332" /><circle cx="16" cy="16" r="3.5" fill="#332" /><circle cx="25" cy="16" r="3.5" fill="#8f0" /><circle cx="34" cy="16" r="3.5" fill="#8f0" /><circle cx="43" cy="16" r="3.5" fill="#332" /><circle cx="7" cy="25" r="3.5" fill="#332" /><circle cx="16" cy="25" r="3.5" fill="#8f0" /><circle cx="25" cy="25" r="3.5" fill="#332" /><circle cx="34" cy="25" r="3.5" fill="#8f0" /><circle cx="43" cy="25" r="3.5" fill="#332" /><circle cx="7" cy="34" r="3.5" fill="#8f0" /><circle cx="16" cy="34" r="3.5" fill="#332" /><circle cx="25" cy="34" r="3.5" fill="#332" /><circle cx="34" cy="34" r="3.5" fill="#8f0" /><circle cx="43" cy="34" r="3.5" fill="#332" /><circle cx="7" cy="43" r="3.5" fill="#8f0" /><circle cx="16" cy="43" r="3.5" fill="#8f0" /><circle cx="25" cy="43" r="3.5" fill="#8f0" /><circle cx="34" cy="43" r="3.5" fill="#8f0" /><circle cx="43" cy="43" r="3.5" fill="#8f0" /><circle cx="7" cy="52" r="3.5" fill="#332" /><circle cx="16" cy="52" r="3.5" fill="#332" /><circle cx="25" cy="52" r="3.5" fill="#332" /><circle cx="34" cy="52" r="3.5" fill="#8f0" /><circle cx="43" cy="52" r="3.5" fill="#332" /><circle cx="7" cy="61" r="3.5" fill="#332" /><circle cx="16" cy="61" r="3.5" fill="#332" /><circle cx="25" cy="61" r="3.5" fill="#332" /><circle cx="34" cy="61" r="3.5" fill="#8f0" /><circle cx="43" cy="61" r="3.5" fill="#332" /><rect x="80" y="0" width=51 height=69 style="fill:rgb(64,64,80);stroke-width:0" /><circle cx="87" cy="7" r="3.5" fill="#332" /><circle cx="96" cy="7" r="3.5" fill="#fc0" /><circle cx="105" cy="7" r="3.5" fill="#332" /><circle cx="114" cy="7" r="3.5" fill="#332" /><circle cx="123" cy="7" r="3.5" fill="#332" /><circle cx="87" cy="16" r="3.5" fill="#332" /><circle cx="96" cy="16" r="3.5" fill="#fc0" /><circle cx="105" cy="16" r="3.5" fill="#332" /><circle cx="114" cy="16" r="3.5" fill="#332" /><circle cx="123" cy="16" r="3.5" fill="#332" /><circle cx="87" cy="25" r="3.5" fill="#fc0" /><circle cx="96" cy="25" r="3.5" fill="#fc0" /><circle cx="105" cy="25" r="3.5" fill="#fc0" /><circle cx="114" cy="25" r="3.5" fill="#fc0" /><circle cx="123" cy="25" r="3.5" fill="#fc0" /><circle cx="87" cy="34" r="3.5" fill="#332" /><circle cx="96" cy="34" r="3.5" fill="#fc0" /><circle cx="105" cy="34" r="3.5" fill="#332" /><circle cx="114" cy="34" r="3.5" fill="#332" /><circle cx="123" cy="34" r="3.5" fill="#fc0" /><circle cx="87" cy="43" r="3.5" fill="#332" /><circle cx="96" cy="43" r="3.5" fill="#fc0" /><circle cx="105" cy="43" r="3.5" fill="#332" /><circle cx="114" cy="43" r="3.5" fill="#fc0" /><circle cx="123" cy="43" r="3.5" fill="#332" /><circle cx="87" cy="52" r="3.5" fill="#332" /><circle cx="96" cy="52" r="3.5" fill="#fc0" /><circle cx="105" cy="52" r="3.5" fill="#fc0" /><circle cx="114" cy="52" r="3.5" fill="#332" /><circle cx="123" cy="52" r="3.5" fill="#332" /><circle cx="87" cy="61" r="3.5" fill="#332" /><circle cx="96" cy="61" r="3.5" fill="#fc0" /><circle cx="105" cy="61" r="3.5" fill="#332" /><circle cx="114" cy="61" r="3.5" fill="#332" /><circle cx="123" cy="61" r="3.5" fill="#332" /></svg> | Your task is write code in function `checkLED`/`check_led`. Check the argument `led` (2D array contains 0 and 1, 1 is the dots, 0 is the blank, looks like the example above), find the errors and correct them, and return the modified array. ## Graphics Series: - [#1: barcode EAN-13 part1](https://www.codewars.com/kata/576260cc784ead319a00052d) - [#2: barcode EAN-13 part2](https://www.codewars.com/kata/57636ce99aa148b6a3000d1c) - [#3: Repair the LED display](https://www.codewars.com/kata/5763a557f716cad8fb00039d)
games
from preloaded import nums import numpy as np def check_led(a): a = np . array(a) for i in range(0, len(a[0]), 5): digit = a[:, i: i + 5] for x in (digit[:: - 1], digit[:, :: - 1], digit[:: - 1, :: - 1]): if x . tolist() in nums: a[:, i: i + 5] = x return a . tolist()
Graphics Series #3: Repair the LED display
5763a557f716cad8fb00039d
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/5763a557f716cad8fb00039d
5 kyu
>When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said # Description: In kindergarten, the teacher gave the children some candies. The number of candies each child gets is not always the same. Here is an array `candies`(all elements are positive integer). It's the number of candy for each child: ``` candies = [10,2,8,22,16,4,10,6,14,20] ``` The teacher asked the children to form a circle and play a game: Each child gives half of his candies to the child on his right(at the same time). If the number of children's candy is an odd number, the teacher will give him an extra candy, so that he can evenly distribute his candy. Repeat such distribute process, until all the children's candies are equal in number. You should return two numbers: 1.How many times of distribution; 2. After the game, the number of each child's candy. Returns the result using an array that contains two elements. # Some examples: ``` candies = [ 1,2,3,4,5 ] Distribution 1: [ 4,2,3,4,5 ] Distribution 2: [ 5,3,3,4,5 ] Distribution 3: [ 6,5,4,4,5 ] Distribution 4: [ 6,6,5,4,5 ] Distribution 5: [ 6,6,6,5,5 ] Distribution 6: [ 6,6,6,6,6 ] So, we need return: [6,6] distributionOfCandy([1,2,3,4,5]) === [6,6] candies = [ 10, 2, 8, 22, 16, 4, 10, 6, 14, 20 ] distribution 1: [ 15, 6, 5, 15, 19, 10, 7, 8, 10, 17 ] distribution 2: [ 17, 11, 6, 11, 18, 15, 9, 8, 9, 14 ] distribution 3: [ 16, 15, 9, 9, 15, 17, 13, 9, 9, 12 ] distribution 4: [ 14, 16, 13, 10, 13, 17, 16, 12, 10, 11 ] distribution 5: [ 13, 15, 15, 12, 12, 16, 17, 14, 11, 11 ] distribution 6: [ 13, 15, 16, 14, 12, 14, 17, 16, 13, 12 ] distribution 7: [ 13, 15, 16, 15, 13, 13, 16, 17, 15, 13 ] distribution 8: [ 14, 15, 16, 16, 15, 14, 15, 17, 17, 15 ] distribution 9: [ 15, 15, 16, 16, 16, 15, 15, 17, 18, 17 ] distribution 10: [ 17, 16, 16, 16, 16, 16, 16, 17, 18, 18 ] distribution 11: [ 18, 17, 16, 16, 16, 16, 16, 17, 18, 18 ] distribution 12: [ 18, 18, 17, 16, 16, 16, 16, 17, 18, 18 ] distribution 13: [ 18, 18, 18, 17, 16, 16, 16, 17, 18, 18 ] distribution 14: [ 18, 18, 18, 18, 17, 16, 16, 17, 18, 18 ] distribution 15: [ 18, 18, 18, 18, 18, 17, 16, 17, 18, 18 ] distribution 16: [ 18, 18, 18, 18, 18, 18, 17, 17, 18, 18 ] distribution 17: [ 18, 18, 18, 18, 18, 18, 18, 18, 18, 18 ] So, we need return: [17,18] distributionOfCandy([10,2,8,22,16,4,10,6,14,20]) === [17,18] ```
reference
def distribution_of_candy(candies): steps = 0 while len(set(candies)) > 1: candies = [(a + 1) / / 2 + (b + 1) / / 2 for a, b in zip(candies, candies[- 1:] + candies)] steps += 1 return [steps, candies . pop()]
Children and candies
582933a3c983ca0cef0003de
[ "Puzzles", "Fundamentals" ]
https://www.codewars.com/kata/582933a3c983ca0cef0003de
6 kyu
**This Kata is intended as a small challenge for my students** Create a function, called insurance(), that computes the cost of renting a car. The function takes 3 arguments: the age of the renter, the size of the car, and the number days for the rental. The function should return an integer number of the calculated total cost of the rental. Age (integer) : There is a daily charge of $10 if the driver is under 25 Car Size (string) : There may be an additional daily charge based on the car size: car size surcharge "economy" $0 "medium" $10 "full-size" $15 Rental Days (integer) : There is a base daily charge of $50 for renting a car. Simply multiply the one day cost by the number of days the car is rented in order to get the full cost. Note: Negative rental days should return 0 cost. Any other car size NOT listed should come with a same surcharge as the "full-size", $15. ```javascript insurance(18, "medium", 7); // => 490 insurance(30,"full-size",30); // => 1950 insurance(21,"economy",-10); // => 0 insurance(42,"my custom car",7); // => 455 ```
reference
def insurance(age, size, num_of_days): if num_of_days <= 0: return 0 cost = 0 one_day_cost = 50 if size == "medium": one_day_cost += 10 elif size != 'economy': one_day_cost += 15 if age < 25: one_day_cost += 10 cost = one_day_cost * num_of_days return cost
Cost of my ride
586430a5b3a675296a000395
[ "Fundamentals" ]
https://www.codewars.com/kata/586430a5b3a675296a000395
7 kyu