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
Fortunately last weekend, I met an utterly drunk old man. He was too drunk to be aggressive towards me. He was letting everything what he held out, from both his mind and his stomach. Although i was a bit uncomfortable, the old man's broken wisdom words caught my attention. However, his talk was not continuous as it was frequently interrupted by an involuntary contractions ``` 'puke' and 'hiccup'``` . Now i am hiring you to clean up his ``` 'puke' ``` and ```'hiccup' ``` and tell me the old man's wisdom words. Because drunk man also needs to take a pause and take a deep breath, you have to remove those pauses (redundant/unnecessary spaces).
reference
def wdm(talk): return ' ' . join(talk . replace('puke', ''). replace('hiccup', ''). split())
Wise drunk man
58e953ace87e856a97000046
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/58e953ace87e856a97000046
7 kyu
Compute the [complex logarithm](https://en.wikipedia.org/wiki/Complex_logarithm) at any given **complex number**, accurate to at least `1 in 10^-12`. The imaginary part should be inside the interval `(βˆ’Ο€, Ο€]` (i.e if the imaginary part is exactly `Ο€`, keep it as is). Note: You shouldn't try to compute the value of this function at the poles. Please return `null`/`NULL`/`nil`/`None` (C#: throw an `ArgumentException`, Java: throw an `ArithmeticException`) if this happens. ~~~if:csharp `System.Numerics` is disallowed in this Kata. ~~~
algorithms
from cmath import log as clog def log(real, imag): try: lg = clog(complex(real, imag)) return lg . real, lg . imag except ValueError: pass
Computing the complex logarithm function
590ba2baf06c49595f0000a0
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/590ba2baf06c49595f0000a0
6 kyu
In this Kata you must convert integers numbers from and to a negative-base binary system. Negative-base systems can accommodate all the same numbers as standard place-value systems, but both positive and negative numbers are represented without the use of a minus sign (or, in computer representation, a sign bit); this advantage is countered by an increased complexity of arithmetic operations. To help understand, the first eight digits (in decimal) of the Base(-2) system is: `[1, -2, 4, -8, 16, -32, 64, -128]` Example conversions: `Decimal, negabinary` ``` 6, '11010' -6, '1110' 4, '100' 18, '10110' -11, '110101' ```
algorithms
def int_to_negabinary(i): ds = [] while i != 0: ds . append(i & 1) i = - (i >> 1) return '' . join(str(d) for d in reversed(ds)) if ds else '0' def negabinary_to_int(s): i = 0 for c in s: i = - (i << 1) + int(c) return i
Base -2
54c14c1b86b33df1ff000026
[ "Algorithms", "Binary" ]
https://www.codewars.com/kata/54c14c1b86b33df1ff000026
5 kyu
Given a set of elements (integers or string characters, characters only in RISC-V), where any element may occur more than once, return the number of subsets that do not contain a repeated element. Let's see with an example: ``` set numbers = {1, 2, 3, 4} ``` The subsets are: ``` {{1}, {2}, {3}, {4}, {1,2}, {1,3}, {1,4}, {2,3}, {2,4}, {3,4}, {1,2,3}, {1,2,4}, {1,3,4}, {2,3,4}, {1,2,3,4}} ``` There are 15 subsets. As you can see, the empty set, {}, is not counted. Let's see an example with repetitions of an element: ``` set letters = {a, b, c, d, d} ``` The subsets for this case (including only those that have no repeated elements inside) will be: ``` {{a}, {b}, {c}, {d}, {a,b}, {a,c}, {a,d}, {b,c}, {b,d}, {c,d}, {a,b,c}, {a,b,d}, {a,c,d}, {b,c,d}, {a,b,c,d}} ``` There are 15 subsets. The function `est_subsets()` (javascript: `estSubsets()`) will calculate the number of these subsets. It will receive the array as an argument and according to its features will output the amount of subsets that do not contain a repeated element. ```python est_subsets([1, 2, 3, 4]) == 15 est_subsets(['a', 'b', 'c', 'd', 'd']) == 15 ``` Features of the random tests: ``` Low Performance Tests: 40 Length of the arrays between 6 and 15 High Performance Tests: 80 Length of the arrays between 15 and 100 (Python and Ruby) between 15 and 63 (C++) and between 15 and 50 in javascript and Lua ``` Just do it!
reference
def est_subsets(arr): return 2 * * len(set(arr)) - 1
Estimating Amounts of Subsets
584703d76f6cf6ffc6000275
[ "Fundamentals", "Data Structures", "Algorithms", "Mathematics", "Logic", "Strings" ]
https://www.codewars.com/kata/584703d76f6cf6ffc6000275
6 kyu
**This Kata is intended as a small challenge for my students** Your family runs a shop and have just brought a Scrolling Text Machine (http://3.imimg.com/data3/RP/IP/MY-2369478/l-e-d-multicolour-text-board-250x250.jpg) to help get some more business. The scroller works by replacing the current text string with a similar text string, but with the first letter shifted to the end; this simulates movement. Your father is far too busy with the business to worry about such details, so, naturally, he's making you come up with the text strings. Create a function named rotate() that accepts a string argument and returns an array of strings with each letter from the input string being rotated to the end. ```javascript rotate("Hello") // => ["elloH", "lloHe", "loHel", "oHell", "Hello"] ``` ```java new ScrollingTextMachine().rotate("Hello") // => ["elloH", "lloHe", "loHel", "oHell", "Hello"] ``` ```cpp rotate("Hello") // => {"elloH", "lloHe", "loHel", "oHell", "Hello"} ``` Note: The original string should be included in the output array. The order matters. Each element of the output array should be the rotated version of the previous element. The output array SHOULD be the same length as the input string. The function should return an empty array with a 0 length string, '', as input.
reference
def rotate(str_): return [str_[i + 1:] + str_[: i + 1] for i in range(len(str_))]
All Star Code Challenge #15
586560a639c5ab3a260000f3
[ "Fundamentals" ]
https://www.codewars.com/kata/586560a639c5ab3a260000f3
6 kyu
# Task You have found a machine which, when fed with two numbers `s` and `e`, produces a strange code consisting of the letters `"a"` and `"b"`. The machine seems to be using the following algorithm: ``` step1: Check if s is less than e - 1. If so, continue to step 2. If not, exit. step2: Increment s by 1, Decrement e by 1 step3: If this is the first letter you're producing, produce `"a"`. Otherwise produce a letter different from the one you last produced (only `"a"` and `"b"` may be produced). go to step 1.``` Your task is to write a function that simulates the workings of the machine. # Input/Output `[input]` integer `s` `4 ≀ s ≀ 20.` `[input]` integer `e` `4 ≀ e ≀ 20.` [output] string A string of the letters the machine produced. # Example For `s = 4 and e = 8`, the output should be `"ab"`. ``` s e string 4 8 "a" 5 7 "ab" 6 6 exit ```
games
def strange_code(s, e): if s >= e - 1: return '' n = (e - s) / / 2 return 'ab' * (n / / 2) + 'a' * (n % 2)
Simple Fun #241: Strange Code
590a7f2be8e86e1240000068
[ "Puzzles" ]
https://www.codewars.com/kata/590a7f2be8e86e1240000068
7 kyu
Lot of junior developer can be stuck when they need to change the access permission to a file or a directory in an Unix-like operating systems. To do that they can use the `chmod` command and with some magic trick they can change the permissionof a file or a directory. For more information about the `chmod` command you can take a look at the [wikipedia page](https://en.wikipedia.org/wiki/Chmod). `chmod` provides two types of syntax that can be used for changing permissions. An absolute form using octal to denote which permissions bits are set e.g: 766. Your goal in this kata is to define the octal you need to use in order to set yout permission correctly. Here is the list of the permission you can set with the octal representation of this one. - User - read (4) - write (2) - execute (1) - Group - read (4) - write (2) - execute (1) - Other - read (4) - write (2) - execute (1) The method take a hash in argument this one can have a maximum of 3 keys (`owner`,`group`,`other`). Each key will have a 3 chars string to represent the permission, for example the string `rw-` say that the user want the permission `read`, `write` without the `execute`. If a key is missing set the permission to `---` **Note**: `chmod` allow you to set some special flags too (`setuid`, `setgid`, `sticky bit`) but to keep some simplicity for this kata we will ignore this one.
reference
def chmod_calculator(perm): perms = {"r": 4, "w": 2, "x": 1} value = "" for permission in ["user", "group", "other"]: value += str(sum(perms . get(x, 0) for x in perm . get(permission, ""))) return value
chmod calculator in octal.
57f4ccf0ab9a91c3d5000054
[ "Fundamentals" ]
https://www.codewars.com/kata/57f4ccf0ab9a91c3d5000054
6 kyu
### Corner circle A circle with radius `r` is placed in a right angled corner, where `r` is an integer and `β‰₯ 1`. <center><img src="https://i.imgur.com/9HWl86o.png" alt="circles" style="max-height:20em"></center> What is the radius of the smaller circle, rounded to two decimal places?
games
def corner_circle(r): return round(r * 0.171572875, 2)
Corner circle
5898761a9c700939ee000011
[ "Mathematics", "Puzzles" ]
https://www.codewars.com/kata/5898761a9c700939ee000011
6 kyu
You are given a certain integer, ```n, n > 0```. You have to search the partition or partitions, of n, with maximum product value. Let'see the case for ```n = 8```. ``` Partition Product [8] 8 [7, 1] 7 [6, 2] 12 [6, 1, 1] 6 [5, 3] 15 [5, 2, 1] 10 [5, 1, 1, 1] 5 [4, 4] 16 [4, 3, 1] 12 [4, 2, 2] 16 [4, 2, 1, 1] 8 [4, 1, 1, 1, 1] 4 [3, 3, 2] 18 <---- partition with maximum product value [3, 3, 1, 1] 9 [3, 2, 2, 1] 12 [3, 2, 1, 1, 1] 6 [3, 1, 1, 1, 1, 1] 3 [2, 2, 2, 2] 16 [2, 2, 2, 1, 1] 8 [2, 2, 1, 1, 1, 1] 4 [2, 1, 1, 1, 1, 1, 1] 2 [1, 1, 1, 1, 1, 1, 1, 1] 1 ``` ~~~if:python,javascript,ruby So our needed function will work in that way: If there is only one partition with maximum product value, it will return a list of two elements, the unique partition and the product value. ### Example (input -> output) ``` 8 -> [[3, 3, 2], 18] ``` If there are more than one partition with maximum product value, the function should output the partitions in a length sorted way. ### Example (input -> output) ``` 10 --> [[4, 3, 3], [3, 3, 2, 2], 36] ``` ~~~ ~~~if-not:python,javascript,ruby So our needed function will return a tuple of two elements, the first being a list of all the partitions, sorted by increasing length, and the second being the maximum product value. ### Examples (input -> output) ``` 8 -> ([[3, 3, 2]], 18) 10 --> ([[4, 3, 3], [3, 3, 2, 2]], 36) ``` ~~~ Enjoy it!
reference
def find_part_max_prod(n): if n == 1: return [[1], 1] q, r = divmod(n, 3) if r == 0: return [[3] * q, 3 * * q] if r == 1: return [[4] + [3] * (q - 1), [3] * (q - 1) + [2, 2], 3 * * (q - 1) * 2 * * 2] return [[3] * q + [2], 3 * * q * 2]
Find the Partition with Maximum Product Value
5716a4c2794d305f4900156b
[ "Fundamentals", "Data Structures", "Algorithms", "Mathematics", "Logic" ]
https://www.codewars.com/kata/5716a4c2794d305f4900156b
5 kyu
In this kata, your goal is to write a function which will reverse the vowels in a string. Any characters which are not vowels should remain in their original position. Here are some examples: ``` "Hello!" => "Holle!" "Tomatoes" => "Temotaos" "Reverse Vowels In A String" => "RivArsI Vewols en e Streng" ``` For simplicity, you can treat the letter y as a consonant, not a vowel. Good luck!
reference
def reverse_vowels(s): v = [c for c in s if c . lower() in 'aeiou'] return '' . join(v . pop(- 1) if c . lower() in 'aeiou' else c for c in s)
Reverse Vowels In A String
585db3e8eec141ce9a00008f
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/585db3e8eec141ce9a00008f
6 kyu
The sports centre needs repair. Vandals have been kicking balls so hard into the roof that some of the tiles have started sticking up. The roof is represented by r. As a quick fix, the committee have decided to place another old roof over the top, if they can find one that fits. This is your job. A 'new' roof (f) will fit if it currently has a hole in it at the location where the old roof has a tile sticking up. Sticking up tiles are represented by either '\\' or '/'. Holes in the 'new' roof are represented by spaces (' '). Any other character can not go over a sticking up tile. Return true if the new roof fits, false if it does not.
reference
def roof_fix(new, old): return all(patch == ' ' for patch, tile in zip(new, old) if tile in '\/')
Roof Replacement
57d15a03264276aaf000007f
[ "Fundamentals", "Strings", "Arrays" ]
https://www.codewars.com/kata/57d15a03264276aaf000007f
6 kyu
Given a string, return a new string that has transformed based on the input: * Change case of every character, ie. lower case to upper case, upper case to lower case. * Reverse the order of words from the input. **Note:** You will have to handle multiple spaces, and leading/trailing spaces. For example: ``` "Example Input" ==> "iNPUT eXAMPLE" ``` You may assume the input only contain English alphabet and spaces.
reference
def string_transformer(s): return ' ' . join(s . swapcase(). split(' ')[:: - 1])
String transformer
5878520d52628a092f0002d0
[ "Fundamentals" ]
https://www.codewars.com/kata/5878520d52628a092f0002d0
6 kyu
No Story No Description Only by Thinking and Testing Look at result of testcase, guess the code! # #Series:<br> <a href="http://www.codewars.com/kata/56d904db9963e9cf5000037d">01:A and B?</a><br> <a href="http://www.codewars.com/kata/56d9292cc11bcc3629000533">02:Incomplete string</a><br> <a href="http://www.codewars.com/kata/56d931ecc443d475d5000003">03:True or False</a><br> <a href="http://www.codewars.com/kata/56d93f249c844788bc000002">04:Something capitalized</a><br> <a href="http://www.codewars.com/kata/56d949281b5fdc7666000004">05:Uniq or not Uniq</a> <br> <a href="http://www.codewars.com/kata/56d98b555492513acf00077d">06:Spatiotemporal index</a><br> <a href="http://www.codewars.com/kata/56d9b46113f38864b8000c5a">07:Math of Primary School</a><br> <a href="http://www.codewars.com/kata/56d9c274c550b4a5c2000d92">08:Math of Middle school</a><br> <a href="http://www.codewars.com/kata/56d9cfd3f3928b4edd000021">09:From nothingness To nothingness</a><br> <a href="http://www.codewars.com/kata/56dae2913cb6f5d428000f77">10:Not perfect? Throw away!</a> <br> <a href="http://www.codewars.com/kata/56db19703cb6f5ec3e001393">11:Welcome to take the bus</a><br> <a href="http://www.codewars.com/kata/56dc41173e5dd65179001167">12:A happy day will come</a><br> <a href="http://www.codewars.com/kata/56dc5a773e5dd6dcf7001356">13:Sum of 15(Hetu Luosliu)</a><br> <a href="http://www.codewars.com/kata/56dd3dd94c9055a413000b22">14:Nebula or Vortex</a><br> <a href="http://www.codewars.com/kata/56dd927e4c9055f8470013a5">15:Sport Star</a><br> <a href="http://www.codewars.com/kata/56de38c1c54a9248dd0006e4">16:Falsetto Rap Concert</a><br> <a href="http://www.codewars.com/kata/56de4d58301c1156170008ff">17:Wind whispers</a><br> <a href="http://www.codewars.com/kata/56de82fb9905a1c3e6000b52">18:Mobile phone simulator</a><br> <a href="http://www.codewars.com/kata/56dfce76b832927775000027">19:Join but not join</a><br> <a href="http://www.codewars.com/kata/56dfd5dfd28ffd52c6000bb7">20:I hate big and small</a><br> <a href="http://www.codewars.com/kata/56e0e065ef93568edb000731">21:I want to become diabetic ;-)</a><br> <a href="http://www.codewars.com/kata/56e0f1dc09eb083b07000028">22:How many blocks?</a><br> <a href="http://www.codewars.com/kata/56e1161fef93568228000aad">23:Operator hidden in a string</a><br> <a href="http://www.codewars.com/kata/56e127d4ef93568228000be2">24:Substring Magic</a><br> <a href="http://www.codewars.com/kata/56eccc08b9d9274c300019b9">25:Report about something</a><br> <a href="http://www.codewars.com/kata/56ee0448588cbb60740013b9">26:Retention and discard I</a><br> <a href="http://www.codewars.com/kata/56eee006ff32e1b5b0000c32">27:Retention and discard II</a><br> <a href="http://www.codewars.com/kata/56eff1e64794404a720002d2">28:How many "word"?</a><br> <a href="http://www.codewars.com/kata/56f167455b913928a8000c49">29:Hail and Waterfall</a><br> <a href="http://www.codewars.com/kata/56f214580cd8bc66a5001a0f">30:Love Forever</a><br> <a href="http://www.codewars.com/kata/56f25b17e40b7014170002bd">31:Digital swimming pool</a><br> <a href="http://www.codewars.com/kata/56f4202199b3861b880013e0">32:Archery contest</a><br> <a href="http://www.codewars.com/kata/56f606236b88de2103000267">33:The repair of parchment</a><br> <a href="http://www.codewars.com/kata/56f6b4369400f51c8e000d64">34:Who are you?</a><br> <a href="http://www.codewars.com/kata/56f7eb14f749ba513b0009c3">35:Safe position</a><br> <br> # #Special recommendation Another series, innovative and interesting, medium difficulty. People who like to challenge, can try these kata: <a href="http://www.codewars.com/kata/56c85eebfd8fc02551000281">Play Tetris : Shape anastomosis</a><br> <a href="http://www.codewars.com/kata/56cd5d09aa4ac772e3000323">Play FlappyBird : Advance Bravely</a><br>
games
class Phone (object): def __init__(self): self . ring = "" self . screen = "" self . microphone = "" def incomingcall(self, number): self . name, self . ring = next( ((c["name"], c["ring"]) for c in contacts if c["number"] == number), ("stranger", "Di Da Di")) self . screen = f"Call: { self . name } \nNumber: { number } " def connect(self): self . __init__() self . microphone = "Hello, who is speaking, please?" if self . name == "stranger" else f"Hello, { self . name } !" def hangup(self): self . __init__()
Thinking & Testing : Mobile phone simulator
56de82fb9905a1c3e6000b52
[ "Puzzles", "Games", "Object-oriented Programming" ]
https://www.codewars.com/kata/56de82fb9905a1c3e6000b52
6 kyu
~~~if-not:factor A nested list (or *array* in JavaScript) is a list that appears as a value inside another list, ```python [item, item, [item, item], item] ``` in the above list, [item, item] is a nested list. Your goal is to write a function that determines the depth of the deepest nested list within a given list. return 1 if there are no nested lists. The list passed to your function can contain any data types. ~~~ ~~~if:factor A nested list in factor is a sequence that appears inside another sequence. ```factor { item item { item item } item } ``` in the above list, `{ item item }` is a nested list. Your goal is to write a word that determines the depth of the deepest nested list within a given list. return 1 if there are no nested lists. The list passed to your function can contain any data types. ~~~ A few examples: ```python list_depth([True]) return 1 list_depth([]) return 1 list_depth([2, "yes", [True, False]]) return 2 list_depth([1, [2, [3, [4, [5, [6], 5], 4], 3], 2], 1]) return 6 list_depth([2.0, [2, 0], 3.7, [3, 7], 6.7, [6, 7]]) return 2 ``` ```javascript arrayDepth([true]) // returns 1 arrayDepth([]) // returns 1 arrayDepth([2, "yes", [true, false]]) // returns 2 arrayDepth([1, [2, [3, [4, [5, [6], 5], 4], 3], 2], 1]) // returns 6 arrayDepth([2.0, [2, 0], 3.7, [3, 7], 6.7, [6, 7]]) // returns 2 ``` ```factor { t } depth -> 1 { } depth -> 1 { 2 "yes" { t 0 } } depth -> 2 { 1 { 2 { 3 { 4 { 5 { 6 } 5 } 4 } 3 } 2 } 1 } depth -> 6 { 2.0 { 2 0 } 3.7 { 3 7 } 6.7 { 6 7 } } depth -> 2 ```
algorithms
def list_depth(l): depths = [1] for x in l: if isinstance(x, list): depths . append(list_depth(x) + 1) return max(depths)
Nested List Depth
56b3b9c7a6df24cf8c00000e
[ "Lists", "Algorithms" ]
https://www.codewars.com/kata/56b3b9c7a6df24cf8c00000e
6 kyu
You're playing to scrabble. But counting points is hard. You decide to create a little script to calculate the best possible value. The function takes two arguments :<br/> <ol> <li>`points` : an array of integer representing for each letters from A to Z the points that it pays</li> <li>`words` : an array of strings, uppercase </li> </ol> <br/> You must return the index of the shortest word which realize the highest score. If the length and the score are the same for two elements, return the index of the first one.
algorithms
from string import ascii_uppercase as uppercase def get_best_word(points, words): points = dict(zip(uppercase, points)) def score(word): return sum(points[c] for c in word) return words . index(sorted(sorted(words, key=len), key=score, reverse=True)[0])
Scrabble best word
563f960e3c73813942000015
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/563f960e3c73813942000015
6 kyu
### Background: At work I need to keep a timesheet, by noting which project I was working on every 15 minutes. I have an timer that beeps every 15 minutes to prompt me to note down what I was working on at that point, but sometimes when I'm away from my desk or working continuously on one project, I don't note anything down and these get recorded as `null`. ### Task: Help me populate my timesheet by replacing any `null` values in the array with the correct project name which is given by surrounding matching values. ### Examples: ```ruby fill_gaps([1,nil,1]) -> [1,1,1] # Replace nill values surrounded by matching values fill_gaps([1,nil,nil,nil,1]) -> [1,1,1,1,1] # There may be multiple nils fill_gaps([1,nil,1,2,nil,2]) -> [1,1,1,2,2,2] # There may be multiple replacements required fill_gaps([1,nil,2,nil,2,nil,1]) -> [1,nil,2,2,2,nil,1] # No nesting. fill_gaps([1,nil,2]) -> [1,nil,2] # No replacement if ends don't match fill_gaps([nil,1,nil]) -> [nil,1,nil] # No replacement if ends don't match off the ends of the array fill_gaps(['codewars', nil, nil, 'codewars', 'real work', nil, nil, 'real work']) -> ["codewars", "codewars", "codewars", "codewars", "real work", "real work", "real work", "real work"] # Works with strings too ``` ```javascript fill_gaps([1,null,1]) -> [1,1,1] # Replace nulll values surrounded by matching values fill_gaps([1,null,null,null,1]) -> [1,1,1,1,1] # There may be multiple nulls fill_gaps([1,null,1,2,null,2]) -> [1,1,1,2,2,2] # There may be multiple replacements required fill_gaps([1,null,2,null,2,null,1]) -> [1,null,2,2,2,null,1] # No nesting. fill_gaps([1,null,2]) -> [1,null,2] # No replacement if ends don't match fill_gaps([null,1,null]) -> [null,1,null] # No replacement if ends don't match off the ends of the array fill_gaps(['codewars', null, null, 'codewars', 'real work', null, null, 'real work']) -> ["codewars", "codewars", "codewars", "codewars", "real work", "real work", "real work", "real work"] # Works with strings too ``` ```haskell -- Replace null values surrounded by matching values fillGaps [Just 1, Nothing, Just 1] -> [Just 1, Just 1, Just 1] -- There may be multiple nulls fillGaps [Just 1, Nothing, Nothing, Nothing, Just 1] -> [Just 1, Just 1, Just 1, Just 1, Just 1] -- There may be multiple replacements required fillGaps [Just 1, Nothing, Just 1, Just 2, Nothing, Just 2] -> [Just 1, Just 1, Just 1, Just 2, Just 2, Just 2] -- No nesting fillGaps [Just 1, Nothing, Just 2, Nothing, Just 2, Nothing, Just 1] -> [Just 1, Nothing, Just 2, Just 2, Just 2, Nothing, Just 1] -- No replacement if ends don't match fillGaps [Just 1, Nothing, Just 2] -> [Just 1, Nothing, Just 2] -- No replacement if ends don't match off the ends of the array fillGaps [Nothing, Just 1, Nothing] -> [Nothing, Just 1, Nothing] ``` ```python fill_gaps([1,None,1]) -> [1,1,1] # Replace None values surrounded by matching values fill_gaps([1,None,None,None,1]) -> [1,1,1,1,1] # There may be multiple Nones fill_gaps([1,None,1,2,None,2]) -> [1,1,1,2,2,2] # There may be multiple replacements required fill_gaps([1,None,2,None,2,None,1]) -> [1,None,2,2,2,None,1] # No nesting. fill_gaps([1,None,2]) -> [1,None,2] # No replacement if ends don't match fill_gaps([None,1,None]) -> [None,1,None] # No replacement if ends don't match off the ends of the array fill_gaps(['codewars', None, None, 'codewars', 'real work', None, None, 'real work']) -> ["codewars", "codewars", "codewars", "codewars", "real work", "real work", "real work", "real work"] # Works with strings too ``` ### Input: An array of values some of which will be `null` ### Output: An array with any consecutive `null` elements surrounded by equal values replaced by that value. ### Note: `null` is language specific, for Ruby it will be `nil`, for Python `None` Input will always be a valid array. The original array should not be modified. The output array might still contain `null` values. The values in the array can be of different data types, but as long as they are `==` they can be considered the same. In Haskell `Maybe Int` is used, hence numbers only and `Nothing` as an empty value Sometimes I forget to note when I stopped working on a project and started on a new one. In this case there will still be `null`s in the resulting array. In this case I'll need to manually resolve the problem by checking my git logs or message timestamps for clues as to when I changed task. But that's not something you need to worry about in this kata.
algorithms
def fill_gaps(timesheet): result = timesheet[:] v, i = None, None for j, w in enumerate(timesheet): if w is not None: if w == v: for k in range(i + 1, j): result[k] = v else: v = w i = j return result
Fill in the gaps in my timesheet.
564871e795df155582000013
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/564871e795df155582000013
6 kyu
*This kata is based on [Project Euler Problem 539](https://projecteuler.net/problem=539)* ## Object Find the last number between 1 and `n` (inclusive) that survives the elimination process #### How It Works Start with the first number on the left then remove every other number moving right until you reach the the end, then from the numbers remaining start with the first number on the right and remove every other number moving left, repeat the process alternating between left and right until only one number remains which you return as the "last man standing" ## Example given an input of `9` our set of numbers is `1 2 3 4 5 6 7 8 9` start by removing from the left 2 4 6 8 1 3 5 7 9 then from the right 2 6 4 8 then the left again 6 2 until we end with `6` as the last man standing **Note:** due to the randomness of the tests it is possible that you will get unlucky and a few of the tests will be really large, so try submitting 2 or 3 times. As always any feedback would be much appreciated
algorithms
def last_man_standing(n): a = list(range(1, n + 1)) while len(a) > 1: a = a[1:: 2][:: - 1] return a[0]
Last man standing
567c26df18e9b1083a000049
[ "Lists", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/567c26df18e9b1083a000049
7 kyu
For a given two numbers your mission is to derive a function that evaluates whether two given numbers are **abundant**, **deficient** or **perfect** and whether together they are **amicable**. ### Abundant Numbers An abundant number or excessive number is a number for which the sum of its proper divisors is greater than the number itself. The integer 12 is the first abundant number. Its proper divisors are 1, 2, 3, 4 and 6 for a total of 16 (> 12). ### Deficient Numbers A deficient number is a number for which the sum of its proper divisors is less than the number itself. The first few deficient numbers are: 1, 2, 3, 4, 5, 7, 8, 9. ### Perfect Numbers A perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself. The first perfect number is 6, because 1, 2, and 3 are its proper positive divisors, and 1 + 2 + 3 = 6. ### Amicable Numbers Amicable numbers are two different numbers so related that the sum of the proper divisors of each is equal to the other number. (A proper divisor of a number is a positive factor of that number other than the number itself. For example, the proper divisors of 6 are 1, 2, and 3.) For example, the smallest pair of amicable numbers is (220, 284); for the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110, of which the sum is 284; and the proper divisors of 284 are 1, 2, 4, 71 and 142, of which the sum is 220. ### The Function For a given two numbers, derive function `deficientlyAbundantAmicableNumbers(num1, num2)` which returns a string with first and second word either abundant or deficient depending on whether `num1` or `num2` are abundant, deficient or perfect. The string should finish with either amicable or not amicable depending on the relationship between `num1` and `num2`. e.g. `deficientlyAbundantAmicableNumbers(220, 284)` returns `"abundant deficient amicable"` as 220 is an abundant number, 284 is a deficient number and amicable because 220 and 284 are an amicable number pair. See Part 1 - [Excessively Abundant Numbers](http://www.codewars.com/kata/56a75b91688b49ad94000015) See Part 2 - [The Most Amicable of Numbers](http://www.codewars.com/kata/56b5ebaa26fd54188b000018)
reference
def deficiently_abundant_amicable_numbers(a, b): c, d = map(sumOfDivs, (a, b)) return f' { kind ( a , c )} { kind ( b , d ) } { "not " * ( a != d or b != c or a == b ) } amicable' def kind( n, sD): return 'abundant' if sD > n else 'perfect' if sD == n else 'deficient' def sumOfDivs(n): return sum( d for d in range(1, int(n / 2 + 1)) if not n % d)
Deficiently Abundant Perfect Amicable Numbers
56bc7687e8936faed5000c09
[ "Fundamentals", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/56bc7687e8936faed5000c09
6 kyu
You're fed up about changing the version of your software manually. Instead, you will create a little script that will make it for you. ## Exercice Create a function `nextVersion`, that will take a string in parameter, and will return a string containing the next version number. For example: ``` Current -> Next version "1.2.3" -> "1.2.4" "0.9.9" -> "1.0.0" "1" -> "2" "1.2.3.4.5.6.7.8" -> "1.2.3.4.5.6.7.9" "9.9" -> "10.0" ``` ## Rules All numbers, except the first one, must be lower than 10: if there are, you have to set them to 0 and increment the next number in sequence. You can assume all tests inputs to be valid.
algorithms
def next_version(version): ns = version . split('.') i = len(ns) - 1 while i > 0 and ns[i] == '9': ns[i] = '0' i -= 1 ns[i] = str(int(ns[i]) + 1) return '.' . join(ns)
Next Version
56c0ca8c6d88fdb61b000f06
[ "Arrays", "Strings", "Algorithms" ]
https://www.codewars.com/kata/56c0ca8c6d88fdb61b000f06
6 kyu
Hi there! You have to implement the `String get_column_title(int num) // syntax depends on programming language` function that takes an integer number (index of the Excel column) and returns the string represents the title of this column. # Intro In the MS Excel lines are numbered by decimals, columns - by sets of letters. For example, the first column has the title "A", second column - "B", 26th - "Z", 27th - "AA". "BA"(53) comes after "AZ"(52), "AAA" comes after "ZZ". <img src="http://i.imgur.com/mSus9fj.png" align=center></img> <img src="http://i.imgur.com/6iDaoef.png" align=center></img> Excel? Columns? More details [here](https://en.wikipedia.org/wiki/Microsoft_Excel) # Input It takes only one argument - column decimal index number. Argument `num` is a natural number. # Output Output is the upper-case string represents the title of column. It contains the English letters: A..Z # Errors For cases `num < 1` your function should throw/raise `IndexError`. In case of non-integer argument you should throw/raise `TypeError`. In Java, you should throw `Exceptions`. Nothing should be returned in Haskell. # Examples ## Python, Ruby: ``` >>> get_column_title(52) "AZ" >>> get_column_title(1337) "AYK" >>> get_column_title(432778) "XPEH" >>> get_column_title() TypeError: >>> get_column_title("123") TypeError: >>> get_column_title(0) IndexError: ``` ## JS, Java: ``` >>> getColumnTitle(52) "AZ" >>> getColumnTitle(1337) "AYK" >>> getColumnTitle(432778) "XPEH" >>> getColumnTitle() TypeError: >>> getColumnTitle("123") TypeError: >>> getColumnTitle(0) IndexError: ``` # Hint The difference between the 26-digits notation and Excel columns numeration that in the first system, after "Z" there are "BA", "BB", ..., while in the Excel columns scale there is a range of 26 elements: AA, AB, ... , AZ between Z and BA. It is as if in the decimal notation was the following order: 0, 1, 2, .., 9, 00, 01, 02, .., 09, 10, 11, .., 19, 20..29..99, 000, 001 and so on. # Also The task is really sapid and hard. If you're stuck - write to the discussion board, there are many smart people willing to help.
algorithms
from string import ascii_uppercase as u def get_column_title(n): assert isinstance(n, int) and n > 0 col = [] while n: n, r = divmod(n - 1, 26) col . append(u[r]) return '' . join(reversed(col))
Get the Excel column title!
56d082c24f60457198000e77
[ "Algorithms" ]
https://www.codewars.com/kata/56d082c24f60457198000e77
6 kyu
What is your favourite day of the week? Check if it's the most frequent day of the week in the year. You are given a year as integer (e. g. 2001). You should return the most frequent day(s) of the week in that year. The result has to be a list of days sorted by the order of days in week (e. g. `['Monday', 'Tuesday']`, `['Saturday', 'Sunday']`, `['Monday', 'Sunday']`). Week starts with Monday. __Input:__ Year as an __int__. __Output:__ The list of most frequent days sorted by the order of days in week (from Monday to Sunday). __Preconditions:__ * Week starts on Monday. * Year is between 1583 and 4000. * Calendar is Gregorian. ### Examples (input -> output): ``` * 2427 -> ['Friday'] * 2185 -> ['Saturday'] * 2860 -> ['Thursday', 'Friday'] ```
reference
from calendar import weekday week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] def most_frequent_days(year): beg = weekday(year, 1, 1) end = weekday(year, 12, 31) if beg == end: return [week[beg]] else: if beg < end: return [week[beg], week[end]] else: return [week[end], week[beg]]
Most Frequent Weekdays
56eb16655250549e4b0013f4
[ "Fundamentals" ]
https://www.codewars.com/kata/56eb16655250549e4b0013f4
6 kyu
# Intro Hi there! You have to implement the `get_reversed_color(hex_color)` (Python, Ruby, Haskell) or `getReversedColor(hexColor)` (JavaScript, Java) <img src="http://www.w3schools.com/colors/img_colormap.gif" align=right></img> function that takes a hex-color string and returns the string represents the complementary color. What is the hex-color? You can find the answer on [w3schools](http://www.w3schools.com/colors/colors_picker.asp) and [Wikipedia](https://en.wikipedia.org/wiki/Web_colors) # Input It takes only one argument - string with hex value (case-ignored with chars 0..9 or A..F) without hash-char "#". Argument `hex_color` is not necessarily with 6-digits length - rest of digits are filled by zeros: ``` "a23" <=> "000a23" "" <=> "0" <=> "000000" ``` # Output Output is the upper-cased string contains of the hash character (#) and complementary color. Complementary color is some color which gives completely white color in sum with entered one: `#000A23` + `#FFF5DC` = `#FFFFFF` # Errors If the entered string is incorrect: length is 7+, has non-hexadecimal characters or non-string type, then the Error(IllegalArgumentException - Java) should be raised/thrown or Nothing should be returned in Haskell. ``` >>> getReversedColor("00fffff") Uncaught Error: Incorrect string length >>> getReversedColor("00ffZZ") Uncaught Error: Non-hex chars >>> getReversedColor(112233) Uncaught Error: Incorrect string type ``` # Examples ```python >>> get_reversed_color("01fD08") "#FE02F7" >>> get_reversed_color("") "#FFFFFF" >>> get_reversed_color("a23") "#FFF5DC" ``` ```ruby >>> get_reversed_color("01fD08") "#FE02F7" >>> get_reversed_color("") "#FFFFFF" >>> get_reversed_color("a23") "#FFF5DC" ``` ```javascript >>> getReversedColor("01fD08") "#FE02F7" >>> getReversedColor("") "#FFFFFF" >>> getReversedColor("a23") "#FFF5DC" ```
reference
def get_reversed_color(hex_color): if hex_color . startswith('#') or len(hex_color) > 6: raise ValueError return "#%06X" % (16777215 - int('0' + hex_color, 16))
HTML Complementary Color
56be4affc5dc03b84b001d2d
[ "Fundamentals" ]
https://www.codewars.com/kata/56be4affc5dc03b84b001d2d
6 kyu
You have a grid with `$m$` rows and `$n$` columns. Return the number of unique ways that start from the top-left corner and go to the bottom-right corner. You are only allowed to move right and down. For example, in the below grid of `$2$` rows and `$3$` columns, there are `$10$` unique paths: ``` o----o----o----o | | | | o----o----o----o | | | | o----o----o----o ``` **Note:** there are random tests for grids up to 1000 x 1000 in most languages, so a naive solution will not work. --- *Hint: use mathematical permutation and combination*
reference
from scipy . misc import comb def number_of_routes(m, n): return comb(m + n, min(m, n), exact=True)
Paths in the Grid
56a127b14d9687bba200004d
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/56a127b14d9687bba200004d
6 kyu
Vicky is quite the small wonder. Most people don't even realize she's not a real girl, but a robot living amongst us. Sure, if you stick around her home for a while you might see her creator open up her back and make a few tweaks and even see her recharge in the closet instead of sleeping in a bed. In this kata, we're going to help Vicky keep track of the words she's learning. Write a function, learnWord(word) ( LearnWord(word) in C# ) which is a method of the Robot object. The function should report back whether the word is now stored, or if she already knew the word. Example: ````javascript var vicky = new Robot(); vicky.learnWord('hello') -> 'Thank you for teaching me hello' vicky.learnWord('abc') -> 'Thank you for teaching me abc' vicky.learnWord('hello') -> 'I already know the word hello' vicky.learnWord('wow!') -> 'I do not understand the input' ```` ````java Robot vicky = new Robot(); vicky.learnWord("hello") -> "Thank you for teaching me hello" vicky.learnWord("abc") -> "Thank you for teaching me abc" vicky.learnWord("hello") -> "I already know the word hello" vicky.learnWord("wow!") -> "I do not understand the input" ```` ````csharp Robot vicky = new Robot(); vicky.LearnWord("hello"); // "Thank you for teaching me hello" vicky.LearnWord("abc"); // "Thank you for teaching me abc" vicky.LearnWord("hello"); // "I already know the word hello" vicky.LearnWord("wow!"); // "I do not understand the input" ```` Case shouldn't matter. Only alpha characters are valid. There's also a little trick here. Enjoy! <div style="width: 320px; text-align: center; color: white; border: white 1px solid;"> Check out my other 80's Kids Katas: </div> <div> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-1-how-many-licks-does-it-take'><span style='color:#00C5CD'>80's Kids #1:</span> How Many Licks Does It Take</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-2-help-alf-find-his-spaceship'><span style='color:#00C5CD'>80's Kids #2:</span> Help Alf Find His Spaceship</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-3-punky-brewsters-socks'><span style='color:#00C5CD'>80's Kids #3:</span> Punky Brewster's Socks</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-4-legends-of-the-hidden-temple'><span style='color:#00C5CD'>80's Kids #4:</span> Legends of the Hidden Temple</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-5-you-cant-do-that-on-television'><span style='color:#00C5CD'>80's Kids #5:</span> You Can't Do That on Television</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-6-rock-em-sock-em-robots'><span style='color:#00C5CD'>80's Kids #6:</span> Rock 'Em, Sock 'Em Robots</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-7-shes-a-small-wonder'><span style='color:#00C5CD'>80's Kids #7:</span> She's a Small Wonder</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-8-the-secret-world-of-alex-mack'><span style='color:#00C5CD'>80's Kids #8:</span> The Secret World of Alex Mack</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-9-down-in-fraggle-rock'><span style='color:#00C5CD'>80's Kids #9:</span> Down in Fraggle Rock </a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-10-captain-planet'><span style='color:#00C5CD'>80's Kids #10:</span> Captain Planet </a><br /> </div>
reference
BAD_INPUT = 'I do not understand the input' KNOWN_WORD = 'I already know the word %s' NEW_WORD = 'Thank you for teaching me %s' class Robot (object): def __init__(self): self . vocabulary = set( word . lower() for message in (BAD_INPUT, KNOWN_WORD, NEW_WORD) for word in message . split() if word != '%s') def learn_word(self, word): if not word . isalpha(): return BAD_INPUT lc_word = word . lower() if lc_word in self . vocabulary: return KNOWN_WORD % word self . vocabulary . add(lc_word) return NEW_WORD % word
80's Kids #7: She's a Small Wonder
56743fd3a12043ffbb000049
[ "Fundamentals", "Object-oriented Programming" ]
https://www.codewars.com/kata/56743fd3a12043ffbb000049
6 kyu
You've made it through the moat and up the steps of knowledge. You've won the temples games and now you're hunting for treasure in the final temple run. There's good news and bad news. You've found the treasure but you've triggered a nasty trap. You'll surely perish in the temple chamber. With your last movements, you've decided to draw an "X" marks the spot for the next archaeologist. Given an odd number, n, draw an X for the next crew. Follow the example below. ````javascript markSpot(5) -> X X X X X X X X X For a clearer understanding of the output, let '.' represent a space and \n the newline. X.......X\n ..X...X\n ....X\n ..X...X\n X.......X\n markSpot(3) -> X X X X X ```` ````coffeescript markSpot(5) # X X X X X X X X X For a clearer understanding of the output, let '.' represent a space and \n the newline. X.......X\n ..X...X\n ....X\n ..X...X\n X.......X\n markSpot(3) # X X X X X ```` If n = 1 return 'X\n' and if you're given an even number or invalid input, return '?'. The output should be a string with no spaces after the final X on each line, but a \n to indicate a new line. <div style="width: 320px; text-align: center; color: white; border: white 1px solid;"> Check out my other 80's Kids Katas: </div> <div> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-1-how-many-licks-does-it-take'><span style='color:#00C5CD'>80's Kids #1:</span> How Many Licks Does It Take</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-2-help-alf-find-his-spaceship'><span style='color:#00C5CD'>80's Kids #2:</span> Help Alf Find His Spaceship</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-3-punky-brewsters-socks'><span style='color:#00C5CD'>80's Kids #3:</span> Punky Brewster's Socks</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-4-legends-of-the-hidden-temple'><span style='color:#00C5CD'>80's Kids #4:</span> Legends of the Hidden Temple</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-5-you-cant-do-that-on-television'><span style='color:#00C5CD'>80's Kids #5:</span> You Can't Do That on Television</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-6-rock-em-sock-em-robots'><span style='color:#00C5CD'>80's Kids #6:</span> Rock 'Em, Sock 'Em Robots</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-7-shes-a-small-wonder'><span style='color:#00C5CD'>80's Kids #7:</span> She's a Small Wonder</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-8-the-secret-world-of-alex-mack'><span style='color:#00C5CD'>80's Kids #8:</span> The Secret World of Alex Mack</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-9-down-in-fraggle-rock'><span style='color:#00C5CD'>80's Kids #9:</span> Down in Fraggle Rock </a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-10-captain-planet'><span style='color:#00C5CD'>80's Kids #10:</span> Captain Planet </a><br /> </div>
algorithms
def mark_spot(n): if isinstance(n, int) and n % 2 != 0 and n > 0: top = [' ' * i * 2 + 'X' + ' ' * (n * 2 - 3 - 4 * i) + 'X' for i in range(n / 2)] middle = [' ' * (n - 1) + 'X'] bottom = top[:: - 1] return '\n' . join(top + middle + bottom) + '\n' else: return '?'
80's Kids #4: Legends of the Hidden Temple
56648a2e2c464b8c030000bf
[ "Games", "Algorithms" ]
https://www.codewars.com/kata/56648a2e2c464b8c030000bf
6 kyu
Well, those numbers were right and we're going to feed their ego. Write a function, isNarcissistic, that takes in any amount of numbers and returns true if all the numbers are narcissistic. Return false for invalid arguments (numbers passed in as strings are ok). For more information about narcissistic numbers (and believe me, they love it when you read about them) follow this link: https://en.wikipedia.org/wiki/Narcissistic_number
algorithms
def is_narcissistic(* l): try: return all(sum(int(i) * * len(str(n)) for i in str(n)) == n for n in map(int, l)) except: return False
Numbers so vain, they probably think this Kata is about them.
565225029bcf176687000022
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/565225029bcf176687000022
6 kyu
<div style="border:1pt solid; background-color:#030; padding:1ex;margin:0 0 1ex;"> <span style="border:1px solid;display:inline-block;padding:0 1ex; margin-right:1em; background-color:#ccc;color:#000;">Stuck?</span> [Try this one](http://www.codewars.com/kata/remove-the-minimum).</div> # A Storm at Sea Jill the adventurer has seen everything, from the highest mountains, to the most dangerous animals. But today she sailed through a hideous storm and shipwrecked. Left with only a damaged life boat and some supplies, she has carefully balanced out the weight not to capsize. But the weight is too much for the small life boat, she has to get rid of some items. Beginning from one side of the boat, she starts to remove the `n` smallest items and hopes for the best… # Task Given an array of integers, remove the `n` smallest. If there are multiple elements with the same value, remove the ones with a lower index first. If `n` is greater than the length of the array/list, return an empty list/array. If `n` is zero or less, return the original array/list. Don't change the order of the elements that are left. ### Examples ```javascript removeSmallest (-10) [1,2,3,4,5] = [1,2,3,4,5] removeSmallest 0 [1,2,3,4,5] = [1,2,3,4,5] removeSmallest 2 [5,3,2,1,4] = [5,3,4] removeSmallest 3 [5,3,2,1,4] = [5,4] removeSmallest 3 [1,2,3,4,5] = [4,5] removeSmallest 5 [1,2,3,4,5] = [] removeSmallest 9 [1,2,3,4,5] = [] removeSmallest 2 [1,2,1,2,1] = [2,2,1] ``` ```coffeescript removeSmallest (-10) [1,2,3,4,5] = [1,2,3,4,5] removeSmallest 0 [1,2,3,4,5] = [1,2,3,4,5] removeSmallest 2 [5,3,2,1,4] = [5,3,4] removeSmallest 3 [5,3,2,1,4] = [5,4] removeSmallest 3 [1,2,3,4,5] = [4,5] removeSmallest 5 [1,2,3,4,5] = [] removeSmallest 9 [1,2,3,4,5] = [] removeSmallest 2 [1,2,1,2,1] = [2,2,1] ``` ```haskell removeSmallest (-10) [1,2,3,4,5] = [1,2,3,4,5] removeSmallest 0 [1,2,3,4,5] = [1,2,3,4,5] removeSmallest 2 [5,3,2,1,4] = [5,3,4] removeSmallest 3 [5,3,2,1,4] = [5,4] removeSmallest 3 [1,2,3,4,5] = [4,5] removeSmallest 5 [1,2,3,4,5] = [] removeSmallest 9 [1,2,3,4,5] = [] removeSmallest 2 [1,2,1,2,1] = [2,2,1] ``` ```python remove_smallest ((-10), [1,2,3,4,5]) = [1,2,3,4,5] remove_smallest (0, [1,2,3,4,5]) = [1,2,3,4,5] remove_smallest (2, [5,3,2,1,4]) = [5,3,4] remove_smallest (3, [5,3,2,1,4]) = [5,4] remove_smallest (3, [1,2,3,4,5]) = [4,5] remove_smallest (5, [1,2,3,4,5]) = [] remove_smallest (9, [1,2,3,4,5]) = [] remove_smallest (2, [1,2,1,2,1]) = [2,2,1] ``` ```ruby remove_smallest((-10), [1,2,3,4,5]) = [1,2,3,4,5] remove_smallest(0, [1,2,3,4,5]) = [1,2,3,4,5] remove_smallest(2, [5,3,2,1,4]) = [5,3,4] remove_smallest(3, [5,3,2,1,4]) = [5,4] remove_smallest(3, [1,2,3,4,5]) = [4,5] remove_smallest(5, [1,2,3,4,5]) = [] remove_smallest(9, [1,2,3,4,5]) = [] remove_smallest(2, [1,2,1,2,1]) = [2,2,1] ```
reference
from heapq import nsmallest def remove_smallest(n, arr): if n <= 0: return arr a = arr[:] for i in nsmallest(n, a): a . remove(i) return a
Another one downβ€”the Survival of the Fittest!
563ce9b8b91d25a5750000b6
[ "Lists", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/563ce9b8b91d25a5750000b6
6 kyu
Every positive integer number, that is not prime, may be decomposed in prime factors. For example the prime factors of 20, are: ``` 2, 2, and 5, because: 20 = 2 . 2 . 5 ``` The first prime factor (the smallest one) of ```20``` is ```2``` and the last one (the largest one) is ```5```. The sum of the first and the last prime factors, ```sflpf``` of 20 is: ```sflpf = 2 + 5 = 7``` The number ```998 ```is the only integer in the range ```[4, 1000]``` that has a value of ```501``` , so its ```sflpf``` equals to 501, but in the range ```[4, 5000]``` we will have more integers with ```sflpf = 501``` and are: ```998, 1996, 2994, 3992, 4990```. We need a function ```sflpf_data()``` (javascript: ```sflpfData()```that receives two arguments, ```val``` as the value of sflpf and ```nMax``` as a limit, and the function will output a sorted list of the numbers between ```4``` to ```nMax```(included) that have the same value of sflpf equals to ```val```. Let's see some cases: ```python sflpf_data(10, 100) == [21, 25, 63] /// the prime factorization of these numbers are: Number Prime Factorization Sum First and Last Prime Factor 21 = 3 . 7 ----> 3 + 7 = 10 25 = 5 . 5 ----> 5 + 5 = 10 63 = 3 . 3 . 7 ----> 3 + 7 = 10 ``` ```python sflpf_data(10, 200) == [21, 25, 63, 105, 125, 147, 189] sflpf_data(15, 150) == [26, 52, 78, 104, 130] ``` (Advice:Try to discard primes in a fast way to have a more agile code) Enjoy it!
reference
def sflpf_data(val, nMax): r = [] for i in range(2, nMax): fac = primef(i) if len(fac) > 1 and fac[0] + fac . pop() == val: r . append(i) return r def primef(n): i = 2 f = [] while i * i <= n: if n % i: i += 1 else: n / /= i f . append(i) if n > 1: f . append(n) return f
The Sum of The First and The Last Prime Factor Make Chains of Numbers
5629b94e34e04f8fb200008e
[ "Mathematics", "Data Structures", "Algorithms" ]
https://www.codewars.com/kata/5629b94e34e04f8fb200008e
6 kyu
Your function ```given_nth_value()``` (Javascript: ```givenNthValue()```)will receive an array or list of integers, positive or negative, then, it will receive an integer k, to search a certain term and finally the mode string ```"min"``` or ```"max"```. We may understand better graphically ```python given_nth_value(arr, k, "max") or given_nth_value(arr, k, "min") ``` The function will work differently depending on the receiving last entry, that string define the mode of the function: - if it is ```"max"```, the function will build internally an array of received values in descending order and will output the k-th term in the list. - if it is ```"min"```, the function will build internally an array of received values in ascending order and will output the k-th term in the list. Let's see clearer all these explanations with some cases. ```python arr = [3, 3, -1, 10, 6, 8, -5, 4, 22, 31, 34, - 16, -16, 8 , 8] # (15 elements) k = 5 str_ = "min" given_nth_value(arr, k, str_) -------> 4 /// The ascending list of values of this array is: k-th value Value (we received 15 elements but there are only 11 values) 1 -16 2 -5 3 -1 4 3 5 -------> 4 (As k = 5, the value to output is 4) 6 6 7 8 8 10 9 22 10 31 11 34 ``` Let's see the inverse case: ```python the same arr in the above case k = 6 str_ = "max" given_nth_value(arr, k, str_) -------> 6 /// The desending list of values of this array is: k-th value Value 1 34 2 31 3 22 4 10 5 8 6 -------> 6 (As k = 6, the value to output is 6) 7 4 8 3 9 -1 10 -5 11 -16 ``` If the value of k is higher than the number of values, the asked function will return the string ```"No way"``` ```python the same array above k = 13 str_ = "max" given_nth_value(arr, k, str_) -------> No way ``` If we have a "corrupted array", an array that has one element that is not an integer, the function will output ```"Invalid entry list"``` ```python arr = [3, 3, -1, 10, 6, 8, -5, 'Yes', 4, 22, 31] k= 4 str_ = "max" given_nth_value(arr, k, str_) -------> Invalid entry list ``` On the other hand, if our array is an empty list, the function should output: ```"No values in the array"``` ```python arr = [] k= 4 str_ = "max" given_nth_value(arr, k, str_) -------> No values in the array ``` If there is a typing mistake in the third entry, the function will return: ```"Valid entries: 'max' or 'min'"``` ```python arr = [3, 3, -1, 10, 6, 8, -5, 4, 22, 31] k = 2 str_ = 'mix' given_nth_value(arr, k, str_) -------> Valid entries: 'max' or 'min' ``` But if the last string has uppercases letters of the words ```max``` or ```min```, the function should work without problems. For example: ```python arr = [3, 3, -1, 10, 6, 8, -5, 4, 22, 31] k = 2 str_ = 'MaX' given_nth_value(arr, k, str_) -------> 22 ``` If the second entry is not a positive integer (k < 0), the function should output "Incorrect value for k". The code should detect if k is a string , too, with the same result. ```python arr = [3, 3, -1, 10, 6, 8, -5, 4, 22, 31] k = "Second" str_ = 'MaX' given_nth_value(arr, k, str_) -------> "Incorrect value for k" ``` If we have more than one "irregularity" simultaneously the code should not output all the mistakes or invalid entries. It will output only one, checking in the following order: 1) The value of k. 2) The mode strings: "max" or "min". 3) The array with the values. Let's see some cases with more than one invalid entry following the priority described above: ```python arr = [] k = "Second" str_ = 'MaX' given_nth_value(arr, k, str_) -------> "Incorrect value for k" arr = [] k = - 10 str_ = 'asdasd' given_nth_value(arr, k, str_) -------> "Incorrect value for k" arr = [1,2,3,2,4,-5, 'Four'] k = 29 str_ = 'kljklj' given_nth_value(arr, k, str_) -------> "Valid entries: 'max' or 'min'" arr = [1,2,3,2,4,-5, 'Four'] k = 29 str_ = 'MiN' given_nth_value(arr, k, str_) -------> "Invalid entry list" ``` For all the cases the function will receive three arguments. Enjoy it!!
reference
def given_nth_value(lst, k, mode): s = set(lst) if not isinstance(k, int) or k < 0: return "Incorrect value for k" if not isinstance(mode, str) or mode . lower() not in ("max", "min"): return "Valid entries: 'max' or 'min'" if not s or any(not isinstance(e, int) for e in s): return "Invalid entry list" if s else "No values in the array" if k >= len(s): return "No way" lst = sorted(s) return lst[k - 1] if mode == "min" else lst[- k]
Required Data II (Easy One)
560985a07add63e1a1000019
[ "Fundamentals", "Algorithms", "Data Structures", "Sorting" ]
https://www.codewars.com/kata/560985a07add63e1a1000019
6 kyu
We want to find the numbers higher or equal than 1000 that the sum of every four consecutives digits cannot be higher than a certain given value. If the number is ``` num = d1d2d3d4d5d6 ```, and the maximum sum of 4 contiguous digits is ```maxSum```, then: ```python d1 + d2 + d3 + d4 <= maxSum d2 + d3 + d4 + d5 <= maxSum d3 + d4 + d5 + d6 <= maxSum ``` For that purpose, we need to create a function, ```max_sumDig()```, that receives ```nMax```, as the max value of the interval to study (the range (1000, nMax) ), and a certain value, ```maxSum```, the maximum sum that every four consecutive digits should be less or equal to. The function should output the following list with the data detailed bellow: ```[(1), (2), (3)]``` (1) - the amount of numbers that satisfy the constraint presented above (2) - the closest number to the mean of the results, if there are more than one, the smallest number should be chosen. (3) - the total sum of all the found numbers Let's see a case with all the details: ``` max_sumDig(2000, 3) -------> [11, 1110, 12555] (1) -There are 11 found numbers: 1000, 1001, 1002, 1010, 1011, 1020, 1100, 1101, 1110, 1200 and 2000 (2) - The mean of all the found numbers is: (1000 + 1001 + 1002 + 1010 + 1011 + 1020 + 1100 + 1101 + 1110 + 1200 + 2000) /11 = 1141.36363, so 1110 is the number that is closest to that mean value. (3) - 12555 is the sum of all the found numbers 1000 + 1001 + 1002 + 1010 + 1011 + 1020 + 1100 + 1101 + 1110 + 1200 + 2000 = 12555 Finally, let's see another cases ``` max_sumDig(2000, 4) -----> [21, 1120, 23665] max_sumDig(2000, 7) -----> [85, 1200, 99986] max_sumDig(3000, 7) -----> [141, 1600, 220756] ``` Happy coding!!
reference
def check(num, max_sum): l = [int(i) for i in str(num)] for i in range(0, len(l) - 3): if sum(l[i: i + 4]) > max_sum: return False return True def max_sumDig(nMax, maxSum): found = [i for i in range(1000, nMax + 1) if check(i, maxSum)] mean = sum(found) / float(len(found)) for i in range(len(found) - 1): if abs(mean - found[i]) < abs(mean - found[i + 1]): mean = found[i] break return [len(found), mean, sum(found)]
How Many Numbers? II
55f5efd21ad2b48895000040
[ "Algorithms", "Data Structures", "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/55f5efd21ad2b48895000040
5 kyu
We have the first value of a certain sequence, we will name it ```init_val```. We define pattern list, ```pattern_l```, an array that has the differences between contiguous terms of the sequence. ``` E.g: pattern_l = [k1, k2, k3, k4]``` The terms of the sequence will be such values that: ```python term1 = init_val term2 - term1 = k1 term3 - term2 = k2 term4 - term3 = k3 term5 - term4 = k4 term6 - term5 = k1 term7 - term6 = k2 term8 - term7 = k3 term9 - term8 = k4 .... - ..... = ... .... - ..... = ... ``` So the values of the differences between contiguous terms are cyclical and are repeated as the differences values of the pattern list stablishes. Let's see an example with numbers: ```python init_val = 10 pattern_l = [2, 1, 3] term1 = 10 term2 = 12 term3 = 13 term4 = 16 term5 = 18 term6 = 19 term7 = 22 # and so on... ``` We can easily obtain the next terms of the sequence following the values in the pattern list. We see that the sixth term of the sequence, ```19```, has the sum of its digits ```10```. Make a function ```sum_dig_nth_term()```, that receives three arguments in this order ```sum_dig_nth_term(init_val, pattern_l, nth_term(ordinal number of the term in the sequence)) ``` This function will output the sum of the digits of the n-th term of the sequence. Let's see some cases for this function: ```python sum_dig_nth_term(10, [2, 1, 3], 6) -----> 10 # because the sixth term is 19 sum of Dig = 1 + 9 = 10. # The sequence up to the sixth-Term is: 10, 12, 13, 16, 18, 19 sum_dig_nth_term(10, [1, 2, 3], 15) ----> 10 # 37 is the 15-th term, and 3 + 7 = 10 ``` Enjoy it and happy coding!!
reference
def sumDig_nthTerm(initVal, patternL, nthTerm): cycles, position = divmod(nthTerm - 1, len(patternL)) result = initVal + sum(patternL) * cycles + sum(patternL[: position]) return sum(map(int, str(result)))
Reach Me and Sum my Digits
55ffb44050558fdb200000a4
[ "Fundamentals", "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/55ffb44050558fdb200000a4
6 kyu
Every number may be factored in prime factors. For example, the number 18 may be factored by its prime factors ``` 2 ``` and ```3``` ``` 18 = 2 . 3 . 3 = 2 . 3Β² ``` The sum of the prime factors of 18 is ```2 + 3 + 3 = 8``` But some numbers like 70 are divisible by the sum of its prime factors: ``` 70 = 2 . 5 . 7 # sum of prime factors = 2 + 5 + 7 = 14 and 70 is a multiple of 14 ``` Of course that primes would fulfill this property, but is obvious, because the prime decomposition of a number, is the number itself and every number is divisible by iself. That is why we will discard every prime number in the results We are interested in collect the integer positive numbers (non primes) that have this property in a certain range ```[a, b]``` (inclusive). Make the function ```mult_primefactor_sum()```, that receives the values ```a```, ```b``` as limits of the range ```[a, b]``` and ```a < b``` and outputs the sorted list of these numbers. Let's see some cases: ```python mult_primefactor_sum(10, 100) == [16, 27, 30, 60, 70, 72, 84] mult_primefactor_sum(1, 60) == [1, 4, 16, 27, 30, 60] ```
algorithms
def mult_primefactor_sum(a, b): s = [] for i in range(a, b + 1): r = factorize_add(i) if r != i and i % r == 0: s . append(i) return s def factorize_add(num): if num < 4: return num d = 2 p = 0 while d < num * * .5 + 1: while not num % d: p += d num /= d d += 1 if d == 2 else 2 return p if num == 1 else p + num
The Sum Of The Prime Factors Of a Number... What For?
5626ec066d35051d4500009e
[ "Algorithms" ]
https://www.codewars.com/kata/5626ec066d35051d4500009e
6 kyu
<h1>Most Improvd - Puzzles #4</h1> <p> When being graded in a subject or a course high marks are focused on the most but what about most improved? As a computer science teacher you would like to create a function which calculates the most improved students and rank them in a list. </p> <h2>Task</h2> <p> Your task is to compelete the function calculateImproved to return an array sorted by most improved as percentages. </p> <h2>Input</h2> <p> The input you will receive will be an array of students, students will be an object containing a name and array of marks (in order of acheived) the marks will be out of 100, a student can however have a mark of null if the test was not attempted (treat this as 0) <br><strong> Example of student Object:</strong> ```{name:'Henry, Johns',marks:[25,50]}``` </p> <h2>Output</h2> <p> The output expected will be an array of objects similar to the student object, containing the name and total improvement percentage out of the first and last mark given to calculate the overall improvement percentage. The output array must be sorted by most improved (Round the calculated improvement) If there is a tie in improvements then order by name (capitals before lowercase).<br><strong> Example of return Object:</strong> ```{name:'Henry, Johns',improvement:100}``` </p> <h2>Preloaded</h2> <p> The Student class has been preloaded with the constructor accepting two parameters a name and marks which should be an array of numbers. </p>
games
def calculate_improved(students): students = ({ "name": s["name"], "improvement": round( 100.0 * (s["marks"][- 1] or 0) / (s["marks"][0] or 0) - 100.0) if s["marks"][0] else 0 } for s in students) return sorted(students, key=lambda s: (- s["improvement"], s["name"]))
Most improved - Puzzles #4
55da2a419f8361df45000025
[ "Arrays", "Puzzles" ]
https://www.codewars.com/kata/55da2a419f8361df45000025
6 kyu
Decompose a number into an array *(tuple in Haskell, array of arrays `long[][]` in C# or Java)* in the form `[ [k1, k2, k3, ...], r ]` such that: ### num = 2<sup>k1</sup> + 3<sup>k2</sup> + 4<sup>k3</sup> + ... + n<sup>kn-1</sup> + r Where every k<sub>i</sub> > 1 and every k<sub>i</sub> is maximized (first maximizing for 2, then 3, and so on) ### Examples ```python 0 --> [ [], 0 ] 3 --> [ [], 3 ] # because there is no `k` more than 1 26 --> [ [4, 2], 1 ] # 26 = 2^4 + 3^2 + 1 8330475 --> [ [22, 13, 10, 8, 7, 6, 6, 5, 5, 5, 4, 4, 4, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2], 0 ] # 8330475 = 2^22 + 3^13 + 4^10 + ... + 22^2 + 23^2 + 24^2 + 0 ```
algorithms
from math import log def decompose(n): i = 2 result = [] while n >= i * i: k = int(log(n, i)) result . append(k) n -= i * * k i += 1 return [result, n]
Decompose a number
55ec80d40d5de30631000025
[ "Algorithms" ]
https://www.codewars.com/kata/55ec80d40d5de30631000025
6 kyu
Spin-off of <a href="http://www.codewars.com/kata/558dd9a1b3f79dc88e000001" target="_blank" title="Duplicated Number in a Consecutive Unsorted List">this kata</a>, here you will have to figure out an efficient strategy to solve the problem of finding the sole duplicate number among an unsorted array/list of numbers starting from 1 up to n. Hints: a solution in linear time can be found; using the most intuitive ones to search for duplicates that can run in O(nΒ²) time won't work.
algorithms
def find_dup(arr): seen = set() for a in arr: if a in seen: return a seen . add(a)
Find The Duplicated Number in a Consecutive Unsorted List - Tougher Version
558f0553803bc3c4720000af
[ "Lists", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/558f0553803bc3c4720000af
6 kyu
Some numbers have the property to be divisible by 2 and 3. Other smaller subset of numbers have the property to be divisible by 2, 3 and 5. Another subset with less abundant numbers may be divisible by 2, 3, 5 and 7. These numbers have something in common: their prime factors are contiguous primes. Implement a function that finds the amount of numbers that have the first `N` primes as factors below a given limit. Let's see some cases: ``` count_specMult(3, 200) => 6 The first 3 primes are: 2, 3 and 5. And the found numbers below 200 are: 30, 60, 90, 120, 150, 180. ``` Happy coding!!
reference
from gmpy2 import next_prime as np from math import prod def count_specMult(n, t): a, b = 2, [] while n > 0: b, a, n = b + [a], np(a), n - 1 return t / / prod(b)
Special Multiples
55e785dfcb59864f200000d9
[ "Mathematics", "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/55e785dfcb59864f200000d9
6 kyu
The integers 14 and 15, are contiguous (1 the difference between them, obvious) and have the same number of divisors. ```python 14 ----> 1, 2, 7, 14 (4 divisors) 15 ----> 1, 3, 5, 15 (4 divisors) ``` ```javascript 14 ----> 1, 2, 7, 14 (4 divisors) 15 ----> 1, 3, 5, 15 (4 divisors) ``` ```coffeescript 14 ----> 1, 2, 7, 14 (4 divisors) 15 ----> 1, 3, 5, 15 (4 divisors) ``` ```java 14 ----> 1, 2, 7, 14 (4 divisors) 15 ----> 1, 3, 5, 15 (4 divisors) ``` ```csharp 14 ----> 1, 2, 7, 14 (4 divisors) 15 ----> 1, 3, 5, 15 (4 divisors) ``` ```ruby 14 ----> 1, 2, 7, 14 (4 divisors) 15 ----> 1, 3, 5, 15 (4 divisors) ``` ```clojure 14 ----> 1, 2, 7, 14 (4 divisors) 15 ----> 1, 3, 5, 15 (4 divisors) ``` ```haskell 14 ----> 1, 2, 7, 14 (4 divisors) 15 ----> 1, 3, 5, 15 (4 divisors) ``` The next pair of contiguous integers with this property is 21 and 22. ```python 21 -----> 1, 3, 7, 21 (4 divisors) 22 -----> 1, 2, 11, 22 (4 divisors) ``` ```ruby 21 -----> 1, 3, 7, 21 (4 divisors) 22 -----> 1, 2, 11, 22 (4 divisors) ``` ```javascript 21 -----> 1, 3, 7, 21 (4 divisors) 22 -----> 1, 2, 11, 22 (4 divisors) ``` ```coffeescript 21 -----> 1, 3, 7, 21 (4 divisors) 22 -----> 1, 2, 11, 22 (4 divisors) ``` ```java 21 -----> 1, 3, 7, 21 (4 divisors) 22 -----> 1, 2, 11, 22 (4 divisors) ``` ```csharp 21 -----> 1, 3, 7, 21 (4 divisors) 22 -----> 1, 2, 11, 22 (4 divisors) ``` ```clojure 21 -----> 1, 3, 7, 21 (4 divisors) 22 -----> 1, 2, 11, 22 (4 divisors) ``` ```haskell 21 -----> 1, 3, 7, 21 (4 divisors) 22 -----> 1, 2, 11, 22 (4 divisors) ``` We have 8 pairs of integers below 50 having this property, they are: ```python [[2, 3], [14, 15], [21, 22], [26, 27], [33, 34], [34, 35], [38, 39], [44, 45]] ``` ```ruby [[2, 3], [14, 15], [21, 22], [26, 27], [33, 34], [34, 35], [38, 39], [44, 45]] ``` ```javascript [[2, 3], [14, 15], [21, 22], [26, 27], [33, 34], [34, 35], [38, 39], [44, 45]] ``` ```coffeescript [[2, 3], [14, 15], [21, 22], [26, 27], [33, 34], [34, 35], [38, 39], [44, 45]] ``` ```java "[[2, 3], [14, 15], [21, 22], [26, 27], [33, 34], [34, 35], [38, 39], [44, 45]]" ``` ```csharp "[[2, 3], [14, 15], [21, 22], [26, 27], [33, 34], [34, 35], [38, 39], [44, 45]]" ``` ```clojure [[2, 3], [14, 15], [21, 22], [26, 27], [33, 34], [34, 35], [38, 39], [44, 45]] ``` ```haskell [[2, 3], [14, 15], [21, 22], [26, 27], [33, 34], [34, 35], [38, 39], [44, 45]] ``` Let's see now the integers that have a difference of 3 between them. There are seven pairs below 100: ```python [[2, 5], [35, 38], [55, 58], [62, 65], [74, 77], [82, 85], [91, 94]] ``` ```ruby [[2, 5], [35, 38], [55, 58], [62, 65], [74, 77], [82, 85], [91, 94]] ``` ```javascript [[2, 5], [35, 38], [55, 58], [62, 65], [74, 77], [82, 85], [91, 94]] ``` ```coffeescript [[2, 5], [35, 38], [55, 58], [62, 65], [74, 77], [82, 85], [91, 94]] ``` ```java "[[2, 5], [35, 38], [55, 58], [62, 65], [74, 77], [82, 85], [91, 94]]" ``` ```csharp "[[2, 5], [35, 38], [55, 58], [62, 65], [74, 77], [82, 85], [91, 94]]" ``` ```clojure [[2, 5], [35, 38], [55, 58], [62, 65], [74, 77], [82, 85], [91, 94]] ``` ```haskell [[2, 5], [35, 38], [55, 58], [62, 65], [74, 77], [82, 85], [91, 94]] ``` Let's name, diff, the difference between two integers, next and prev, (diff = next - prev) and nMax, an upper bound of the range. We need a special function, count_pairsInt(), that receives two arguments, diff and nMax and outputs the amount of pairs of integers that fulfill this property, all of them being smaller (not smaller or equal) than nMax. Let's see it more clearly with examples. ```python count_pairsInt(1, 50) -----> 8 (See case above) count_pairsInt(3, 100) -----> 7 (See case above) ``` ```ruby count_pairs_int(1, 50) -----> 8 (See case above) count_pairs_int(3, 100) -----> 7 (See case above) ``` ```javascript count_pairsInt(1, 50) -----> 8 (See case above) count_pairsInt(3, 100) -----> 7 (See case above) ``` ```coffeescript count_pairsInt(1, 50) -----> 8 (See case above) count_pairsInt(3, 100) -----> 7 (See case above) ``` ```java count_pairsInt(1, 50) -----> 8 (See case above) count_pairsInt(3, 100) -----> 7 (See case above) ``` ```csharp count_pairsInt(1, 50) -----> 8 (See case above) count_pairsInt(3, 100) -----> 7 (See case above) ``` ```clojure count_pairsInt(1, 50) -----> 8 (See case above) count_pairsInt(3, 100) -----> 7 (See case above) ``` ```haskell count_pairsInt(1, 50) -----> 8 (See case above) count_pairsInt(3, 100) -----> 7 (See case above) ``` Happy coding!!!
reference
def count_pairs_int(d, m): return sum(1 for i in range(1, m - d) if divisors(i) == divisors(i + d)) def divisors(n): return sum(1 + (n / / k != k) for k in range(1, int(n * * 0.5) + 1) if n % k == 0)
Find Numbers with Same Amount of Divisors
55f1614853ddee8bd4000014
[ "Algorithms", "Mathematics", "Data Structures", "Fundamentals" ]
https://www.codewars.com/kata/55f1614853ddee8bd4000014
6 kyu
Create a function ```javascript hasTwoCubeSums(n) ``` ```java boolean hasTwoCubeSums(int n) ``` ```python has_two_cube_sums(n) ``` ```ruby has_two_cube_sums(n) ``` ```csharp bool HasTwoCubeSums(int n) ``` ```haskell hasTwoCubeSums :: Integer -> Bool ``` which checks if a given number `n` can be written as the sum of two cubes in two different ways: `n = aΒ³+bΒ³ = cΒ³+dΒ³`. All the numbers `a`, `b`, `c` and `d` should be different and greater than `0`. E.g. 1729 = 9Β³+10Β³ = 1Β³+12Β³. ```javascript hasTwoCubeSums(1729); // true hasTwoCubeSums(42); // false ``` ```java hasTwoCubeSums(1729); // true hasTwoCubeSums(42); // false ``` ```python has_two_cube_sums(1729); // true has_two_cube_sums(42); // false ``` ```ruby has_two_cube_sums(1729); // true has_two_cube_sums(42); // false ``` ```csharp HasTwoCubeSums(1729); // true HasTwoCubeSums(42); // false ``` ```haskell hasTwoCubeSums 1729 -- True hasTwoCubeSums 42 -- False ```
reference
def has_two_cube_sums(n): sum = [] power = int(n * * (1 / 3.0)) + 1 for i in xrange(1, power): for x in xrange(1, power): if i == x: continue tmp = i * * 3 + x * * 3 if tmp > n: break if tmp == n: if len(sum) == 2: return True sum . append([i, x]) return False
Two cube sums
55fd4919ce2a1d7c0d0000f3
[ "Fundamentals" ]
https://www.codewars.com/kata/55fd4919ce2a1d7c0d0000f3
6 kyu
We need a function that receives an array or list of integers (positive and negative) and may give us the following information in the order and structure presented below: `[(1), (2), (3), [[(4)], 5]]` (1) - Total amount of received integers. (2) - Total amount of different values the array has. (3) - Total amount of values that occur only once. (4) and (5) both in a list (4) - It is (or they are) the element(s) that has (or have) the maximum occurrence. If there are more than one, the elements should be sorted (by their value obviously) (5) - Maximum occurrence of the integer(s) _____ Let's see some cases: ``` for list [-3, -2, -1, 3, 4, -5, -5, 5, -1, -5] ----> [10, 7, 5, [[-5], 3]] (1) - The list has ten elements (10 numbers) (2) - We have seven different values: -5, -3, -2, -1, 3, 4, 5 (7 values) (3) - The numbers that occur only once: -3, -2, 3, 4, 5 (5 values) (4) and (5) - The number -5 occurs three times (3 occurrences) for list [4, 4, 2, -3, 1, 4, 3, 2, 0, -5, 2, -2, -2, -5] ----> [14, 8, 4, [[2, 4], 3]] ``` Enjoy it and happy coding!!
reference
from collections import defaultdict, Counter def count_sel(nums): cnt = Counter(nums) d = defaultdict(list) total = 0 unique = 0 for k, v in cnt . iteritems(): d[v]. append(k) total += v unique += 1 maximum = max(d) return [total, unique, len(d[1]), [sorted(d[maximum]), maximum]]
Required Data I
55f95dbb350b7b1239000030
[ "Algorithms", "Data Structures", "Sorting", "Fundamentals" ]
https://www.codewars.com/kata/55f95dbb350b7b1239000030
6 kyu
Create a function ```sel_number()```, that will select numbers that fulfill the following constraints: 1) The numbers should have 2 digits at least. 2) They should have their respective digits in increasing order from left to right. Examples: 789, 479, 12678, have these feature. But 617, 89927 are not of this type. In general, if ```d1, d2, d3....``` are the digits of a certain number ```i``` Example: ```( i = d1d2d3d4d5) so, d1 < d2 < d3 < d4 < d5``` 3) They cannot have digits that occurs twice or more. Example: 8991 should be discarded. 4) The difference between neighbouring pairs of digits cannot exceed certain value. Example: If the difference between contiguous digits cannot exceed 2, so 1345, 23568 and 234578 pass this test. Other numbers like 1456, 389, 157 don't belong to that group because in the first number(1456), the difference between second and first digit 4 - 1 > 2; in the next one(389), we have 8 - 3 > 2; and see by yourself why 157 should be discarded. In general, taking the example above of ```i = d1d2d3d4d5```: ``` d2 - d1 <= d; d3 - d2 <= d; d4 - d3 <= d; d5 - d4 <= d; ``` The function should accept two arguments n and d; n is the upper limit of the range to work with(all the numbers should be less or equal than n), and d is maximum difference between every pair of its contiguous digits. It's clear that 1 <= d <= 8. Here we have some cases: ``` sel_number(0,1) = 0 # n = 0, empty range sel_number(3, 1) = 0 # n = 3, numbers should be higher or equal than 12 sel_number(13, 1) = 1 # only 12 fulfill the requirements sel_number(20, 2) = 2 # 12 and 13 are the numbers sel_number(30, 2) = 4 # 12, 13, 23 and 24 are the selected ones sel_number(44, 2) = 6 # 12, 13, 23, 24, 34 and 35 are valid ones sel_number(50, 3) = 12 # 12, 13, 14, 23, 24, 25, 34, 35, 36, 45, 46 and 47 are valid ``` Compare the last example with this one: ``` sel_number(47, 3) = 12 # 12, 13, 14, 23, 24, 25, 34, 35, 36, 45, 46 and 47 are valid ``` (because the instructions says the value of may be included if it fulfills the above constraints of course) Happy coding!!
reference
from itertools import pairwise def sel_number(n: int, d: int) - > int: return sum(all(0 < b - a <= d for a, b in pairwise(map(int, str(i)))) for i in range(12, n + 1))
How Many Numbers?
55d8aa568dec9fb9e200004a
[ "Fundamentals", "Algorithms", "Mathematics", "Data Structures" ]
https://www.codewars.com/kata/55d8aa568dec9fb9e200004a
6 kyu
- Input: Integer `n` - Output: String Example: `a(4)` prints as ``` A A A A A A A A ``` `a(8)` prints as ``` A A A A A A A A A A A A A A A A A A ``` `a(12)` prints as ``` A A A A A A A A A A A A A A A A A A A A A A A A A A A A ``` Note: - Each line's length is `2n - 1` - Each line should be concatenate by line break `"\n"` - If `n` is less than `4`, it should return `""` - If `n` is odd, `a(n) = a(n - 1)`, eg `a(5) == a(4); a(9) == a(8)`
reference
def a(n): """ """ if n % 2 != 0: n = n - 1 if n < 4: return '' side = " " * (n - 1) li = [side + "A" + side] for i in range(1, n): side = side[1:] middle = "A " * (i - 1) if i == (n / 2) else " " * (i - 1) li . append(side + "A " + middle + "A" + side) return "\n" . join(li)
A for Apple
55de3f83e92c3e521a00002a
[ "ASCII Art", "Fundamentals" ]
https://www.codewars.com/kata/55de3f83e92c3e521a00002a
6 kyu
Let's say take 2 strings, A and B, and define the similarity of the strings to be the length of the longest prefix common to both strings. For example, the similarity of strings `abc` and `abd` is 2, while the similarity of strings `aaa` and `aaab` is 3. write a function that calculates the sum of similarities of a string S with each of it's **suffixes**. ### Examples (input -> output): ``` 'ababaa' -> 11 'abc' -> 3 ``` Explanation: In the first case, the suffixes of the string are `ababaa`, `babaa`, `abaa`, `baa`, `aa` and `a`. The similarities of each of these strings with the string `ababaa` are 6,0,3,0,1,1 respectively. Thus the answer is 6 + 0 + 3 + 0 + 1 + 1 = 11. For the second case, the answer is simply 3 + 0 + 0 = 3. Note : Each string will have at least one character - no need to check for empty strings :)
algorithms
from os . path import commonprefix def string_suffix(s): return sum(len(commonprefix([s, s[i:]])) for i in range(len(s)))
String Suffixes
559d34cb2e65e765b90000f0
[ "Strings", "Logic", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/559d34cb2e65e765b90000f0
6 kyu
Find the closest prime number under a certain integer ```n``` that has the maximum possible amount of even digits. For ```n = 1000```, the highest prime under ```1000``` is ```887```, having two even digits (8 twice) Naming ```f()```, the function that gives that prime, the above case and others will be like the following below. ``` f(1000) ---> 887 (even digits: 8, 8) f(1210) ---> 1201 (even digits: 2, 0) f(10000) ---> 8887 f(500) ---> 487 f(487) ---> 467 ``` Features of the random tests: ``` Number of tests = 28 1000 <= n <= 5000000 ``` Enjoy it!!
reference
from gmpy2 import next_prime def f(n): first = 2 result = count = 1 while first < n: temp = sum(i in '02468' for i in str(first)) if temp >= count: count = temp result = first first = next_prime(first) return result
Primes with Even Digits
582dcda401f9ccb4f0000025
[ "Strings", "Data Structures", "Algorithms", "Mathematics", "Number Theory" ]
https://www.codewars.com/kata/582dcda401f9ccb4f0000025
5 kyu
We have the following sequence: ```python f(0) = 0 f(1) = 1 f(2) = 1 f(3) = 2 f(4) = 4; f(n) = f(n-1) + f(n-2) + f(n-3) + f(n-4) + f(n-5); ``` Your task is to give the number of total values for the odd terms of the sequence up to the n-th term (included). (The number n (of n-th term) will be given as a positive integer) The values 1 (one) is the only that is duplicated in the sequence and should be counted only once. E.g. ``` count_odd_pentaFib(5) -----> 1 # because the terms up to 5 are: 0, 1, 1, 2, 4, 8 (only 1 is odd and counted once) ``` Other examples: ``` count_odd_pentaFib(10) ------> 3 #because the odds terms are: [1, 1, 31, 61] (three different values) count_odd_pentaFib(15) ------> 5 # beacause the odd terms are: [1, 1, 31, 61, 1793, 3525] (five different values) ``` Good luck !! (Your code should be fast. Many moderate high values will be waiting to test it.)
reference
def count_odd_pentaFib(n): return 2 * (n / / 6) + [0, 1, 2, 2, 2, 2][n % 6] - (n >= 2)
Pentabonacci
55c9172ee4bb15af9000005d
[ "Fundamentals", "Mathematics", "Algorithms", "Performance", "Dynamic Programming" ]
https://www.codewars.com/kata/55c9172ee4bb15af9000005d
6 kyu
Define two functions: `hex_to_bin` and `bin_to_hex` (or `hexToBin` and `binToHex`) # hex_to_bin Takes a hexadecimal string as an argument . **Note:** This string can contain upper or lower case characters and start with any amount of zeros. Returns the binary representation (without leading zeros) of the numerical value of the hexadecimal string. Examples: ``` "00F" --> "1111" "5" --> "101" "00000" --> "0" "04D2" --> "10011010010" ``` # bin_to_hex Takes a binary string (with or without leading zeros) as an argument . Returns the hexadecimal representation of the numerical value of the binary string. **Note:** Any non-numerical characters should be lower case Examples: ``` "1111" --> "f" "000101" --> "5" "10011010010" --> "4d2" ``` **Note:** You can assume all arguments are valid so there is no need for error checking. Oh, and I've disabled a few things. Any feedback would be much appreciated
games
bin2hex = {"0000": "0", "0001": "1", "0010": "2", "0011": "3", "0100": "4", "0101": "5", "0110": "6", "0111": "7", "1000": "8", "1001": "9", "1010": "a", "1011": "b", "1100": "c", "1101": "d", "1110": "e", "1111": "f"} hex2bin = {v: k for k, v in bin2hex . items()} def bin_to_hex(s, res=""): s = "0" * (4 - len(s) % 4) + s while s: res += bin2hex[s[: 4]] s = s[4:] return res . lstrip("0") or "0" def hex_to_bin(s, res=""): while s: res += hex2bin[s[0]. lower()] s = s[1:] return res . lstrip("0") or "0"
Bin to Hex and back
55d1b0782aa1152115000037
[ "Puzzles", "Binary", "Strings", "Data Types" ]
https://www.codewars.com/kata/55d1b0782aa1152115000037
6 kyu
##Task: You have to write a function `add` which takes two binary numbers as strings and returns their sum as a string. ##Note: * You are `not allowed to convert binary to decimal & vice versa`. * The sum should contain `No leading zeroes`. ##Examples: ``` add('111','10'); => '1001' add('1101','101'); => '10010' add('1101','10111') => '100100' ```
reference
def binary_string_to_int(string): return sum((d == '1') * 2 * * i for i, d in enumerate(string[:: - 1])) def add(a, b): return '{:b}' . format(binary_string_to_int(a) + binary_string_to_int(b))
Adding Binary Numbers
55c11989e13716e35f000013
[ "Binary", "Bits", "Fundamentals" ]
https://www.codewars.com/kata/55c11989e13716e35f000013
6 kyu
**Ore Numbers** (also called Harmonic Divisor Numbers) are numbers for which the [harmonic mean](https://en.wikipedia.org/wiki/Harmonic_mean) of all their divisors (including the number itself) equals an integer. For example, 6 is an Ore Number because its harmonic mean is exactly 2: ``` H(6) = 4 / (1/1 + 1/2 + 1/3 + 1/6) = 2 ``` Your task is to complete the function returns ```true``` if the given number is an Ore Number and ```false``` otherwise. You can assume all inputs will be valid positive integers. **Hint:** The harmonic mean is the total number of divisors divided by the sum of their reciprocals.
algorithms
# Harmonic mean = count/sum(1/divisors) # can be simplified to # Harmonic Mean = count*n/sum(divisors) # this avoids the many division operations in the sum def is_ore(n): sum = 0 count = 0 for divisor in range(1, n + 1): if n % divisor == 0: count += 1 sum += divisor if n * count % sum == 0: return True return False
Ore Numbers
55ba95a17970ff3e80000064
[ "Mathematics", "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/55ba95a17970ff3e80000064
6 kyu
Backwards Read Primes are primes that when read backwards in base 10 (from right to left) are a different prime. (This rules out primes which are palindromes.) ``` Examples: 13 17 31 37 71 73 are Backwards Read Primes ``` 13 is such because it's prime and read from right to left writes 31 which is prime too. Same for the others. #### Task Find all Backwards Read Primes between two positive given numbers (both inclusive), the second one always being greater than or equal to the first one. The resulting array or the resulting string will be ordered following the natural order of the prime numbers. #### Examples (in general form): backwardsPrime(2, 100) => [13, 17, 31, 37, 71, 73, 79, 97] backwardsPrime(9900, 10000) => [9923, 9931, 9941, 9967] backwardsPrime(501, 599) => [] See "Sample Tests" for your language. #### Notes - Forth Return only the first backwards-read prime between start and end or 0 if you don't find any - Ruby Don't use Ruby Prime class, it's disabled.
algorithms
def backwardsPrime(start, stop): primes = [] for n in range(start, stop + 1): if n not in primes and is_prime(n) and is_prime(reverse(n)) and n != reverse(n): primes . append(n) if start <= reverse(n) <= stop: primes . append(reverse(n)) return sorted(primes) def is_prime(n): for i in range(2, int(n * * (0.5)) + 1): if n % i == 0: return False return True def reverse(n): return int('' . join(str(n)[:: - 1]))
Backwards Read Primes
5539fecef69c483c5a000015
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5539fecef69c483c5a000015
6 kyu
Scheduling is how the processor decides which jobs (processes) get to use the processor and for how long. This can cause a lot of problems. Like a really long process taking the entire CPU and freezing all the other processes. One solution is Round-Robin, which today you will be implementing. Round-Robin works by queuing jobs in a First In First Out fashion, but the processes are only given a short slice of time. If a processes is not finished in that time slice, it yields the proccessor and goes to the back of the queue. For this Kata you will be implementing the ```javascript function roundRobin(jobs, slice, index) ``` ```python def round_robin(jobs, time_slice, index): ``` ```ruby def roundRobin(jobs, slice, index) ``` It takes in: 1. "jobs" a non-empty positive integer array. It represents the queue and clock-cycles(cc) remaining till the job[i] is finished. 2. "slice" a positive integer. It is the amount of clock-cycles that each job is given till the job yields to the next job in the queue. 3. "index" a positive integer. Which is the index of the job we're interested in. roundRobin returns: 1. the number of cc till the job at index is finished. Here's an example: ``` roundRobin([10,20,1], 5, 0) at 0cc [10,20,1] jobs[0] starts after 5cc [5,20,1] jobs[0] yields, jobs[1] starts after 10cc [5,15,1] jobs[1] yields, jobs[2] starts after 11cc [5,15,0] jobs[2] finishes, jobs[0] starts after 16cc [0,15,0] jobs[0] finishes ``` so: ``` roundRobin([10,20,1], 5, 0) == 16 ``` **You can assume that the processor can switch jobs between cc so it does not add to the total time.
algorithms
def roundRobin(jobs, slice, index): total_cc = 0 while True: for idx in range(len(jobs)): cc = min(jobs[idx], slice) jobs[idx] -= cc total_cc += cc if idx == index and jobs[idx] == 0: return total_cc
Scheduling (Round-Robin)
550cb646b9e7b565d600048a
[ "Algorithms" ]
https://www.codewars.com/kata/550cb646b9e7b565d600048a
6 kyu
<h3>Introduction to Disjunctions</h3> <p>In logic and mathematics, a disjunction is an operation on 2 or more propositions. A disjunction is true if and only if 1 or more of its operands is true. In programming, we typically denote a disjunction using "||", but in logic we typically use "v".</p> <p>Example of disjunction:</p> <pre><code>p = 1 > 2 = false q = 2 < 3 = true therefore p v q is true</code></pre> <p>In a programming language, we might write this as:</p> <pre><code>var p = 1 &gt; 2; // false var q = 2 &lt; 3; // true var result = p || q; // true</code></pre> <p>The above example demonstrates an inclusive disjunction (meaning it includes cases where both operands are true). Disjunctions can also be exlusive. An exclusive disjunction is typically represented by "⊻" and is true if and only if both operands have opposite values.</p> <pre><code>p = 1 < 2 = true q = 2 < 3 = true therefore p ⊻ q is false</code></pre> <p>This can become confusing when dealing with more than 2 operands.</p> <pre><code>r = 3 < 4 = true p ⊻ q ⊻ r = ???</code></pre> <p>We handle these situations by evaluating the expression from left to right.</p> <pre><code>p ⊻ q = false (p ⊻ q) ⊻ r = true</code></pre> <h3>Directions:</h3> <p>For this kata, your task is to implement a function that performs a disjunction operation on 2 or more propositions.</p> <ul> <li>Should take a boolean array as its first parameter and a single boolean as its second parameter, which, if true, should indicate that the disjunction should be exclusive as opposed to inclusive.</li> <li>Should return true or false.</li> </ul>
algorithms
from operator import or_, xor from functools import reduce def disjunction(operands, is_exclusive): return reduce([or_, xor][is_exclusive], operands)
Logical Disjunctions
55b019265ff4eeef8c000039
[ "Logic", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/55b019265ff4eeef8c000039
6 kyu
You certainly can tell which is the larger number between 2<sup>10</sup> and 2<sup>15</sup>. But what about, say, 2<sup>10</sup> and 3<sup>10</sup>? You know this one too. Things tend to get a bit more complicated with **both** different bases and exponents: which is larger between 3<sup>9</sup> and 5<sup>6</sup>? Well, by now you have surely guessed that you have to build a function to compare powers, returning -1 if the first member is larger, 0 if they are equal, 1 otherwise; powers to compare will be provided in the `[base, exponent]` format: ```ruby compare_powers([2,10],[2,15])==1 compare_powers([2,10],[3,10])==1 compare_powers([2,10],[2,10])==0 compare_powers([3,9],[5,6])==-1 compare_powers([7,7],[5,8])==-1 ``` ```javascript comparePowers([2,10],[2,15])===1 comparePowers([2,10],[3,10])===1 comparePowers([2,10],[2,10])===0 comparePowers([3,9],[5,6])===-1 comparePowers([7,7],[5,8])===-1 ``` ```coffeescript comparePowers([2,10],[2,15])==1 comparePowers([2,10],[3,10])==1 comparePowers([2,10],[2,10])==0 comparePowers([3,9],[5,6])==-1 comparePowers([7,7],[5,8])==-1 ``` ```python compare_powers([2,10],[2,15])==1 compare_powers([2,10],[3,10])==1 compare_powers([2,10],[2,10])==0 compare_powers([3,9],[5,6])==-1 compare_powers([7,7],[5,8])==-1 ``` ```haskell -- Haskell results should reflect your usual `compare` -- result, e.g. 1 `compare` 2 == LT. (2, 10) `comparePowers` (2, 15) `shouldBe` LT (1, 10) `comparePowers` (2, 10) `shouldBe` LT (2, 10) `comparePowers` (2, 10) `shouldBe` EQ (3, 9) `comparePowers` (1, 6) `shouldBe` GT (1, 7) `comparePowers` (1, 8) `shouldBe` EQ ``` ```c compare_powers((int[]){2, 10}, (int[]){2, 15}) == 1; compare_powers((int[]){2, 10}, (int[]){3, 10}) == 1; compare_powers((int[]){2, 10}, (int[]){2, 10}) == 0; compare_powers((int[]){3, 9}, (int[]){5, 6}) == -1; compare_powers((int[]){7, 7}, (int[]){5, 8}) == -1; ``` ```if:nasm <code>int compare_powers(const int n1[2], const int n2[2])</code> ``` ```nasm compare_powers((int[]){2, 10}, (int[]){2, 15}) == 1; compare_powers((int[]){2, 10}, (int[]){3, 10}) == 1; compare_powers((int[]){2, 10}, (int[]){2, 10}) == 0; compare_powers((int[]){3, 9}, (int[]){5, 6}) == -1; compare_powers((int[]){7, 7}, (int[]){5, 8}) == -1; ``` ```java comparePowers(new int[]{2, 10}, new int[]{2, 15}) == 1; comparePowers(new int[]{2, 10}, new int[]{3, 10}) == 1; comparePowers(new int[]{2, 10}, new int[]{2, 10}) == 0; comparePowers(new int[]{3, 9}, new int[]{5, 6}) == -1; comparePowers(new int[]{7, 7}, new int[]{5, 8}) == -1; ``` Only positive integers will be tested, including bigger numbers - you are warned now, so be diligent try to implement an efficient solution not to drain too much on CW resources ;)!
algorithms
from math import log def compare_powers(* numbers): a, b = map(lambda n: n[1] * log(n[0]), numbers) return (a < b) - (a > b)
Compare powers
55b2549a781b5336c0000103
[ "Algorithms" ]
https://www.codewars.com/kata/55b2549a781b5336c0000103
6 kyu
You may be familiar with the concept of combinations: for example, if you take 5 cards from a 52 cards deck as you would playing poker, you can have a certain number (2,598,960, would you say?) of different combinations. In mathematics the number of *k* combinations you can have taking from a set of *n* elements is called the [binomial coefficient](https://en.wikipedia.org/wiki/Binomial_coefficient) of n and k, more popularly called **n choose k**. The formula to compute it is relatively simple: `n choose k`==`n!/(k!*(n-k)!)`, where `!` of course denotes the factorial operator. You are now to create a choose function that computes the binomial coefficient, like this: ``` choose(1,1)==1 choose(5,4)==5 choose(10,5)==252 choose(10,20)==0 choose(52,5)==2598960 ``` Be warned: a certain degree of optimization is expected, both to deal with larger numbers precision and computing time.
algorithms
from math import comb as choose
Quick (n choose k) calculator
55b22ef242ad87345c0000b2
[ "Combinatorics", "Algorithms" ]
https://www.codewars.com/kata/55b22ef242ad87345c0000b2
6 kyu
Lucas numbers are numbers in a sequence defined like this: ``` L(0) = 2 L(1) = 1 L(n) = L(n-1) + L(n-2) ``` Your mission is to complete the function that returns the `n`th term of this sequence. **Note:** It should work for negative numbers as well; how you do this is you flip the equation around, so for negative numbers: `L(n) = L(n+2) - L(n+1)` ## Examples ``` L(-10) = 123 L(-5) = -11 L(-1) = -1 L(0) = 2 L(1) = 1 L(5) = 11 L(10) = 123 ```
algorithms
def lucasnum(n): a = 2 b = 1 flip = n < 0 and n % 2 != 0 for _ in range(abs(n)): a, b = b, a + b return - a if flip else a
Lucas numbers
55a7de09273f6652b200002e
[ "Algorithms" ]
https://www.codewars.com/kata/55a7de09273f6652b200002e
6 kyu
Create an English to Enigeliisohe Translator, which after each consonant or semivowel inserts in lower case form the last vowel which precedes it in the alphabet. Trivia: Enigeliisohe is a language based on written English, and Esper' phonetics, in which each letter in written English is converted to the Esperanto name of that letter. Most of the Esper' consonants are pronounced the same as in English, but since there are exceptions, here are some key examples how certain Esper' letter names are pronounced... "a" is named "a", and it's name is pronounced like the "a" in "father". <br> <br> "c" is named "ca", and it's name is pronounced like the "sha" in "shaman". <br> <br> "e" is named "e", and it's name is pronounced like the "e" in "egg". <br> <br> "g" is named "ge", and it's name is pronounced like the "ge" in "get". <br> <br> "h" is named "he", and it's name is pronounced like the "he" in "help". <br> <br> "i" is named "i", and it's name is pronounced like the "i" in "it". <br> <br> "j" is named "ji", and it's name is pronounced as some people pronounce the "si" in "vision". In other words, like the "zh'i" in "vizh'in". <br> <br> "o" is named "o", and it's name is pronounced like the "o" in "both". <br> <br> "q" is named "qo", and it's name is pronounced like the "ch" in the Scottish word "loche", followed by the sound of "o" in "both". In English, one might spell such a name "kho", or "qho", to give a better idea of how it's pronounced. <br> <br> "u" is named "u", and it's name is pronounced like the "oo" in "hook" or "book" or "took". <br> <br> "x" is named "xu", and it's name is pronounced like the "thoo" in "thook". <br> Accented letters are unsupported, and therefore letters with diacritic marks, if encountered, should remain unchanged and not get a vowel attached to them. Extra challenge: Try reading some Enigeliisohe out loud, once you have finished programming your translator. :)
algorithms
def toexuto(text): output = '' for char in text: output += char for item in 'abcd efgh ijklmn opqrst uvwxyz' . split(): if char . lower() in item[1:]: output += item[0] return output
Enigeliisohe too Eniigeeliiisoohee Toroanisoliatooro
55a5d97d81a010881800004a
[ "Regular Expressions", "Strings", "Algorithms" ]
https://www.codewars.com/kata/55a5d97d81a010881800004a
6 kyu
Write a function that takes an `array / list` of numbers and returns a number. See the examples and try to guess the pattern: ```python (1, 2, 6, 1, 6, 3, 1, 9, 6) => 393 (1, 2, 3) => 5 (0, 2, 3) => 3 (1, 0, 3) => 3 (3, 2) => 6 ```
games
from functools import reduce from operator import add, mul from itertools import cycle def even_odd(arr): ops = cycle((mul, add)) return reduce(lambda x, y: next(ops)(x, y), arr)
Even Odd Pattern #1
559e708e72d342b0c900007b
[ "Logic", "Arrays", "Mathematics", "Puzzles" ]
https://www.codewars.com/kata/559e708e72d342b0c900007b
6 kyu
You're hanging out with your friends in a bar, when suddenly one of them is so drunk, that he can't speak, and when he wants to say something, he writes it down on a paper. However, none of the words he writes make sense to you. He wants to help you, so he points at a beer and writes "yvvi". You start to understand what he's trying to say, and you write a script, that decodes his words. Keep in mind that numbers, as well as other characters, can be part of the input, and you should keep them like they are. You should also test if the input is a string. If it is not, return "Input is not a string".
games
def parse_character(char): if 65 <= ord(char) <= 90: return chr(155 - ord(char)) elif 97 <= ord(char) <= 122: return chr(219 - ord(char)) else: return char def decode(string_): if not isinstance(string_, str): return "Input is not a string" return "" . join(map(parse_character, string_))
Drunk friend
558ffec0f0584f24250000a0
[ "Strings", "Algorithms", "Puzzles" ]
https://www.codewars.com/kata/558ffec0f0584f24250000a0
6 kyu
Given a side length `n`, traveling only right and down how many ways are there to get from the top left corner to the bottom right corner of an `n by n` grid? Your mission is to write a program to do just that! Add code to `route(n)` that returns the number of routes for a grid `n by n` (if n is less than 1 return 0). Examples: -100 -> 0 1 -> 2 2 -> 6 20 -> 137846528820 Note: you're traveling on the edges of the squares in the grid not the squares themselves. PS.If anyone has any suggestions of how to improve this kata please let me know.
games
from math import factorial def routes(n): return n > 0 and factorial(2 * n) / / factorial(n) * * 2
Routes in a square grid
559aa1295f5c38fd7b0000ac
[ "Fundamentals", "Puzzles" ]
https://www.codewars.com/kata/559aa1295f5c38fd7b0000ac
6 kyu
**Getting Familiar:** <a href="http://simple.wikipedia.org/wiki/Leet" title="example">LEET:</a> (sometimes written as "1337" or "l33t"), also known as eleet or leetspeak, is another alphabet for the English language that is used mostly on the internet. It uses various combinations of ASCII characters to replace Latinate letters. For example, leet spellings of the word leet include 1337 and l33t; eleet may be spelled 31337 or 3l33t. <a href="http://en.wikipedia.org/wiki/Greek_alphabet" title="example">GREEK:</a> The Greek alphabet has been used to write the Greek language since the 8th century BC. It was derived from the earlier Phoenician alphabet, and was the first alphabetic script to have distinct letters for vowels as well as consonants. It is the ancestor of the Latin and Cyrillic scripts.Apart from its use in writing the Greek language, both in its ancient and its modern forms, the Greek alphabet today also serves as a source of technical symbols and labels in many domains of mathematics, science and other fields. **Your Task :** You have to create a function which takes a string as input and returns it in the form of (L33T+GrΡΡκ)Case. Note: The letters which are not being converted in (L33T+GrΡΡκ)Case should be returned in the lowercase. **(L33T+GrΡΡκ)Case:** A=Ξ± (Alpha) B=Ξ² (Beta) D=Ξ΄ (Delta) E=Ξ΅ (Epsilon) I=ΞΉ (Iota) K=ΞΊ (Kappa) N=Ξ· (Eta) O=ΞΈ (Theta) P=ρ (Rho) R=Ο€ (Pi) T=Ο„ (Tau) U=ΞΌ (Mu) V=Ο… (Upsilon) W=Ο‰ (Omega) X=Ο‡ (Chi) Y=Ξ³ (Gamma) **Examples:** CodeWars => cθδΡωαπs Kata => κατα
reference
trans = str . maketrans("abdeiknoprtuvwxy", "αβδΡικηθρπτμυωχγ") def gr33k_l33t(string): return string . lower(). translate(trans)
(L33T + GrΡΡκ) Case
556025c8710009fc2d000011
[ "Strings", "Algorithms", "Unicode" ]
https://www.codewars.com/kata/556025c8710009fc2d000011
6 kyu
In this kata you have to correctly return who is the "survivor", ie: the last element of a <a href="http://www.codewars.com/kata/josephus-permutation/" target="_blank" title="Josephus sequence">Josephus permutation</a>. Basically you have to assume that n people are put into a circle and that they are eliminated in steps of k elements, like this: ``` n=7, k=3 => means 7 people in a circle one every 3 is eliminated until one remains [1,2,3,4,5,6,7] - initial sequence [1,2,4,5,6,7] => 3 is counted out [1,2,4,5,7] => 6 is counted out [1,4,5,7] => 2 is counted out [1,4,5] => 7 is counted out [1,4] => 5 is counted out [4] => 1 counted out, 4 is the last element - the survivor! ``` The above link about the "base" kata description will give you a more thorough insight about the origin of this kind of permutation, but basically that's all that there is to know to solve this kata. **Notes and tips:** using the solution to the other kata to check your function may be helpful, but as much larger numbers will be used, using an array/list to compute the number of the survivor may be too slow; you may assume that both n and k will always be >=1.
algorithms
def josephus_survivor(n, k): v = 0 for i in range(1, n + 1): v = (v + k) % i return v + 1
Josephus Survivor
555624b601231dc7a400017a
[ "Mathematics", "Combinatorics", "Algorithms", "Lists", "Arrays" ]
https://www.codewars.com/kata/555624b601231dc7a400017a
5 kyu
This problem takes its name by arguably the most important event in the life of the ancient historian Josephus: according to his tale, he and his 40 soldiers were trapped in a cave by the Romans during a siege. Refusing to surrender to the enemy, they instead opted for mass suicide, with a twist: **they formed a circle and proceeded to kill one man every three, until one last man was left (and that it was supposed to kill himself to end the act)**. Well, Josephus and another man were the last two and, as we now know every detail of the story, you may have correctly guessed that they didn't exactly follow through the original idea. You are now to create a function that returns a Josephus permutation, taking as parameters the initial *array/list of items* to be permuted as if they were in a circle and counted out every *k* places until none remained. **Tips and notes:** it helps to start counting from 1 up to n, instead of the usual range 0 to n-1; k will always be >=1. For example, with an array=`[1,2,3,4,5,6,7]` and k=3, the function should act this way. ``` [1,2,3,4,5,6,7] - initial sequence [1,2,4,5,6,7] => 3 is counted out and goes into the result [3] [1,2,4,5,7] => 6 is counted out and goes into the result [3,6] [1,4,5,7] => 2 is counted out and goes into the result [3,6,2] [1,4,5] => 7 is counted out and goes into the result [3,6,2,7] [1,4] => 5 is counted out and goes into the result [3,6,2,7,5] [4] => 1 is counted out and goes into the result [3,6,2,7,5,1] [] => 4 is counted out and goes into the result [3,6,2,7,5,1,4] ``` So our final result is: ``` [3,6,2,7,5,1,4] ``` For more info, browse the <a href="http://en.wikipedia.org/wiki/Josephus_problem" target="_blank">Josephus Permutation</a> page on wikipedia; related kata: <a href="http://www.codewars.com/kata/josephus-survivor" target="_blank" title="Josephus sequence - last element">Josephus Survivor</a>. Also, [live game demo](https://iguacel.github.io/josephus/) by [OmniZoetrope](https://www.codewars.com/users/OmniZoetrope).
algorithms
def josephus(xs, k): i, ys = 0, [] while len(xs) > 0: i = (i + k - 1) % len(xs) ys . append(xs . pop(i)) return ys
Josephus Permutation
5550d638a99ddb113e0000a2
[ "Mathematics", "Permutations", "Algorithms", "Combinatorics" ]
https://www.codewars.com/kata/5550d638a99ddb113e0000a2
5 kyu
# Introduction <pre style="white-space: pre-wrap;white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;">Hungry Hungry Hippos is a tabletop game made for 2–4 players, produced by Hasbro, under the brand of its subsidiary, Milton Bradley. The idea for the game was published in 1967 by toy inventor Fred Kroll and it was introduced in 1978. The objective of the game is for each player to collect as many marbles as possible with their 'hippo' (a toy hippo model). (Source <a href="https://en.wikipedia.org/wiki/Hungry_Hungry_Hippos">Wikipedia</a>) </pre> <center><img src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/hippo.jpg" alt="Squares"></center> # Task <pre style="white-space: pre-wrap;white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;"> Your task is to write a simple class called <font color="#A1A85E">Game</font> that checks how many times a hippo has to leap into the centre of the arena to collect some food. You will be given an integer array called <font color="#A1A85E">board</font> that defines where all the food can be found. You have to return an integer for the amount of leaps a hippo has to do to eat all of the food. </pre> # Rules <pre style="white-space: pre-wrap;white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;"> 1.&nbsp; The <font color="#A1A85E">board</font> array contains 0’s for spaces and 1’s for food 2.&nbsp; The <font color="#A1A85E">board</font> is n x n in size, where n is between 5 and 50. 3.&nbsp; One leap consists of food items that are either <font color="#A1A85E">horizontally</font> or <font color="#A1A85E">vertically</font> connected to each other. If they are not connected, then another leap is needed. </pre> # Returns <pre style="white-space: pre-wrap;white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;"> Return an integer for the amount of leaps needed to collect all of the food. </pre> # Example ## Initialise ```ruby board = [[1,1,0,0,0], [1,1,0,0,0], [0,0,0,0,0], [0,0,0,1,1], [0,0,0,1,1]] game = Game.new(board) game.play() ``` ```python board = [[1,1,0,0,0], [1,1,0,0,0], [0,0,0,0,0], [0,0,0,1,1], [0,0,0,1,1]] game = Game(board) game.play() ``` ```javascript board = [[1,1,0,0,0], [1,1,0,0,0], [0,0,0,0,0], [0,0,0,1,1], [0,0,0,1,1]] game = new Game(board) game.play() ``` ```csharp int[,] board = { { 1, 1, 0, 0, 0 }, { 1, 1, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 1, 1 }, { 0, 0, 0, 1, 1 } }; Game game = new Game(board); game.play(); ``` ## Result There are 2 blocks of food connected horizontally or vertically so you must return 2.<br> <img src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/hippo.png"><br> Good luck and enjoy! # Kata Series If you enjoyed this, then please try one of my other Katas. Any feedback, translations and grading of beta Katas are greatly appreciated. Thank you. <span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/>&nbsp;<a href="https://www.codewars.com/kata/58663693b359c4a6560001d6" target="_blank">Maze Runner</a></span> <span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/>&nbsp;<a href="https://www.codewars.com/kata/58693bbfd7da144164000d05" target="_blank">Scooby Doo Puzzle</a></span> <span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/7KYU.png" alt="Rank"/>&nbsp;<a href="https://www.codewars.com/kata/586a1af1c66d18ad81000134" target="_blank">Driving License</a></span> <span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/>&nbsp;<a href="https://www.codewars.com/kata/586c0909c1923fdb89002031" target="_blank">Connect 4</a></span> <span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/>&nbsp;<a href="https://www.codewars.com/kata/586e6d4cb98de09e3800014f" target="_blank">Vending Machine</a></span> <span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/>&nbsp;<a href="https://www.codewars.com/kata/587136ba2eefcb92a9000027" target="_blank">Snakes and Ladders</a></span> <span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/>&nbsp;<a href="https://www.codewars.com/kata/58a848258a6909dd35000003" target="_blank">Mastermind</a></span> <span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/>&nbsp;<a href="https://www.codewars.com/kata/58b2c5de4cf8b90723000051" target="_blank">Guess Who?</a></span> <span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/>&nbsp;<a href="https://www.codewars.com/kata/58f5c63f1e26ecda7e000029" target="_blank">Am I safe to drive?</a></span> <span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/>&nbsp;<a href="https://www.codewars.com/kata/58f5c63f1e26ecda7e000029" target="_blank">Mexican Wave</a></span> <span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/>&nbsp;<a href="https://www.codewars.com/kata/58fdcc51b4f81a0b1e00003e" target="_blank">Pigs in a Pen</a></span> <span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/>&nbsp;<a href="https://www.codewars.com/kata/590300eb378a9282ba000095" target="_blank">Hungry Hippos</a></span> <span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/>&nbsp;<a href="https://www.codewars.com/kata/5904be220881cb68be00007d" target="_blank">Plenty of Fish in the Pond</a></span> <span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/>&nbsp;<a href="https://www.codewars.com/kata/590adadea658017d90000039" target="_blank">Fruit Machine</a></span> <span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/>&nbsp;<a href="https://www.codewars.com/kata/591eab1d192fe0435e000014" target="_blank">Car Park Escape</a></span>
reference
class Game (): AROUND = {(- 1, 0), (1, 0), (0, - 1), (0, 1)} def __init__(self, board): self . toCheck = {(x, y) for x in range(len(board)) for y in range(len(board)) if board[x][y] == 1} def play(self): c = 0 while self . toCheck: newInLeap = {self . toCheck . pop()} while newInLeap: newInLeap = {(x + dx, y + dy) for x, y in newInLeap for dx, dy in self . AROUND if (x + dx, y + dy) in self . toCheck} self . toCheck -= newInLeap c += 1 return c
Hungry Hippos
590300eb378a9282ba000095
[ "Games", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/590300eb378a9282ba000095
5 kyu
## Task Given a `matrix`, find its submatrix obtained by deleting the specified rows and emptying the specified columns. ## Input/Output `[input]` 2D integer array `matrix` 2-dimensional array of integers. `1 ≀ matrix.length ≀ 10,` `1 ≀ matrix[0].length ≀ 10,` `0 ≀ matrix[i][j] ≀ 9.` `[input]` integer array `rowsToDelete` Array of indices (0-based) of rows to be deleted. `0 ≀ rowsToDelete.length ≀ 5,` `0 ≀ rowsToDelete[i] < matrix.length.` `[input]` integer array `columnsToDelete` Array of indices (0-based) of columns to be deleted. `0 ≀ columnsToDelete.length ≀ 5,` `0 ≀ columnsToDelete[i] < matrix[0].length.` `[output]` 2D integer array # Example For ``` matrix = [ [1, 0, 0, 2] , [0, 5, 0, 1] , [0, 0, 3, 5] ] rowsToDelete = [1] columnsToDelete = [0, 2] ``` the output should be ``` [ [0, 2] , [0, 5] ] ```
reference
import numpy as np def construct_submatrix(m, rs, cs): return np . delete(np . delete(m, rs, 0), cs, 1). tolist()
Simple Fun #235: Construct Submatrix
590818ddffa0da26ad00009b
[ "Fundamentals", "Matrix" ]
https://www.codewars.com/kata/590818ddffa0da26ad00009b
7 kyu
You will get an odd integer `n` (`n >= 3`) and your task is to draw an X. The lines are separated by newlines (`\n`). Use the following characters: `'β– '` and `'β–‘'` (Ruby, Crystal and PHP: `'o'` and `' '`). ## Examples ``` β– β–‘β–‘β–‘β–  β– β–‘β–  β–‘β– β–‘β– β–‘ x(3) => β–‘β– β–‘ x(5) => β–‘β–‘β– β–‘β–‘ β– β–‘β–  β–‘β– β–‘β– β–‘ β– β–‘β–‘β–‘β–  ``` --- #### Series: 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 x(n): ret = [['β–‘' for _ in range(n)] for _ in range(n)] for i in range(len(ret)): ret[i][i] = 'β– ' ret[i][- 1 - i] = 'β– ' return '\n' . join('' . join(row) for row in ret)
ASCII Fun #1: X- Shape
5906436806d25f846400009b
[ "ASCII Art" ]
https://www.codewars.com/kata/5906436806d25f846400009b
6 kyu
See the "contour" of a matrix in the following example: ``` M = [[ 1, 3, -4, 5, -2, 5, 1], [2, 0, -7, 6, 8, 8, 15], [4, 4, -2,-10, 7, -1, 7], [-1, 3, 1, 0, 11, 4, 21], [-7, 6, -4, 10, 5, 7, 6], [-5, 4, 3, -5, 7, 8, 17], [-11,3, 4, -8, 6, 16, 4]] ``` It's made of: - the elements of the first row: ```1,3,-4,5,-2,5,1``` - the ones of the last column (excepting the first one, ```1```): ```15, 7,21,6,17,4``` - the elements of the last row (excepting the last one, ```4```):```16,6,-8,4,3,-11``` - and finally, the ones of the first column(excepting the first one, ```1```, and the last one, ```-11```): ```-5,-7,-1,4,2``` The instructions for this kata are as it follows: Input: We receive a matrix, ```M```, of ```m``` rows and ```n``` columns with two integers ```a```, and ```b```, such that ```a < b``` always. Task: We have to select the elements of the countour of the matrix ```M``` that are in the range ```[a, b]``` (values of ```a``` and ```b``` are inclusive) **in order to find the element or elements of them with the highest occurrence frequency**. Output: We have to give an array with the maximum amount of occurrences followed by the wanted value or in the case of having two or more encountered values, in increasing order. See the case with matrix M given above with ```a = -1``` and ```b = 7```. The contour of M is: ``` [1,3,-4,5,-2,5,1,15,7,21,6,17,4,16,6,-8,4,3,-11,-5,-7,-1,4,2] ``` The elements that are in the range ```[-1, 7]``` are: ``` [1,3,5,5,1,7,6,4,6,4,3,-1,4,2] ``` The number ```4``` has the highest occurrence frequency and it is ```3```. So the output will be ```[3, [4]]```. See this another example with the same values for a and b: ``` M1 = [[ 1, 3, -4, 5, 1, 5, 1], [ 2, 0, -7, 6, 8, 8, 15], [ 4, 4, -2, -10, 7, -1, 7] [ -1, 3, 1, 0, 11, 4, 21], [ 7, 6, -4, 10, 5, 7, 6], [ 5, 4, 3, -5, 7, 8, 17], [-11, 3, 4, -8, 7, 16, 4]] ``` The output will be: ``` [3, [1, 4, 5, 7]] // see the array of encountered numbers sorted ``` That means that the numbers ```1, 4, 5, 7``` have the same occurrence frequency, ```3```. In the case that all the values have the same frequency, the output will be the empty array. ``` M2 = [[2,1,1,6], [1,3,2,2], [2,1,2,6]] and a = 0, b = 5 ``` ```contour = [2,1,1,6,2,6,2,1,2,1]``` Then, ```[2,1,1,2,2,1,2,1]``` are in the range ```[0,5]``` ```2``` with ```4``` occurrences and ```1``` with ```4``` occurrences There is no maximum frequency value so the output will be ```[]```. Features of the Random Tests ``` Number of tests = 200 10 <= m <= 200 // m is the number of rows 10 <= n <= 200 // n is the amount of columns -50 <= a < b <= 50 -50 <= m[i][j] <= 50 ``` Try to avoid using nested loops (unless a very smart one). Probably a O(nΒ²) algorithm will not pass the tests. This kata is tagged with OPTIMIZATION. :) Enjoy it!
reference
from collections import Counter def countour_mode(m, a, b): v = m[0] + [r[- 1] for r in m[1:]] + m[- 1][: - 1] + [r[0] for r in m[1: - 1]] c = Counter([e for e in v if a <= e <= b]) mx = max(c . values()) return [mx, sorted([k for k in c if c[k] == mx])] if len(set(c . values())) > 1 else []
#7 Matrices: Focused on the Contour
590572de63bfadf5d4000027
[ "Matrix", "Algorithms", "Searching", "Fundamentals" ]
https://www.codewars.com/kata/590572de63bfadf5d4000027
6 kyu
*Note: to get straight to the kata you may skip the first two paragraphs* ## Introduction - JoJo's World You may have heard about one of the most popular and influencial Japanese franchises, hailing from the 80s and still running with very good sale figures: <a href="http://en.wikipedia.org/wiki/JoJo's_Bizarre_Adventure" target="_blank">JoJo no Kimyō na Bōken</a> AKA JoJo's Bizarre Adventure. And if the notion of "bizarre" somehow eludes you, you could think of something like facing a basically immortal ancient superhuman being, worshipped and feared by both Aztecs and Romans who just got upgraded to demigod status and his showing off his new powers against you and your allies, which happen to include the largest American foundation, a nazi supercyborg and his loyal elite troopers. ## Instructions But I digress: point is that to date the author creates 8 sagas around 8 different JoJos: the one you could recognize in the video is <b>Jo</b>seph <b>Jo</b>estar, grand-son of the fist JoJo, <b>Jo</b>nathan <b>Jo</b>estar. And you could see a pattern already here: you are a JoJo if both your name and surname start with "Jo-". One more complication comes with the third JoJo: Jotaro Kujo (or, following Japanese use of putting the family name first: Ku<b>Jo</b> <b>Jo</b>taro). One last variant comes with the fifth JoJo: as it is of Italian descent (well, sorta of) and the traditional Italian alphabet has only 21 letters (lacking J, K, W, Y and X), the name that you would pronounce <b>Jo</b>rno <b>Jo</b>vanna has to be spelled "Giorno Giovanna". Now, the drill in this kata is rather easy: either create a regex expression or a function to find if a given name is a proper JoJo or not in boolean terms (true/True if it is valid, false/False otherwise). To recap, you have a valid JoJo if: - both your firstname and your surname start with "Jo-" - your firstname starts with "Jo-" and your surname ends with "-Jo" - both your firstname and your surname start with "Gio-" Notes: - don't expect the to have a string formed by only two words joined by a space: strings may be of 1 word, 2 words, 3 words or more - lower- and uppercase will not matter here - consider the first word as the firstname and the last word as the surname ## Examples ```python "Joseph Joestar" --> valid JoJo name "Dio Brando" --> invalid JoJo name "George Joestar II" --> invalid JoJo name (still cool, though) "Giorno Giovanna" --> valid JoJo name "Josuke Joestar" --> valid JoJo name (not his actual surname, but ok) "Kars" --> invalid JoJo name "Caesar Zeppeli" --> invalid JoJo name ``` ## Final Notes This kata is designed to give regex beginners a chance, so in your solutions try to be as **creative, elegant, extravagant** and **glamorous** as possible, in full homage of Hiroiko Araki, JoJo's creator and sole mangaka to work with institutions like the Louvre Museum of the famous luxury brand Gucci, not to mention <a href="http://jojo.wikia.com/wiki/List_of_cultural_influences_of_JoJo%27s_Bizarre_Adventure" target="_blank">how influential it has been on the Japanese pop culture</a> (the video above alone containes inspirations fort least 4 major beatem ups characters, including Guile of SFII fame). *All the characters named in this kata are copyright of their rightful owners and are mentioned only for educational purposes, a fair use according to the Berne convention. Also: buy the products if you like it!*
reference
regex = "^(jo[a-zA-Z]* (jo[a-zA-Z]*|[a-zA-Z]*jo))|(gio[a-zA-Z]* gio[a-zA-Z]*)" def is_jojo(name): spl = name . split() return len(spl) > 1 and (spl[0][0: 2] == 'Jo' and (spl[1][- 2:] == 'jo' or spl[1][0: 2] == 'Jo')) or (spl[0][0: 3] == 'Gio' and spl[1][0: 3] == 'Gio')
JoJo's Bizarre Kata
55327e12f5363713200000e4
[ "Fundamentals", "Regular Expressions", "Strings" ]
https://www.codewars.com/kata/55327e12f5363713200000e4
6 kyu
You're a support engineer and you have to write a regex that captures the following information from our log files: - the date - the log level (ERROR, INFO or DEBUG), - the user - the main function - the sub function - the logged message You asked your supervisor about the rules defining all the logs. He told you that: the sub function may or may not be here, if no sub-function return ```undefined```, the log level can only be one of the 3 presented, the logged message contains any kind of character, all fields are separated by arbitrary spaces (but at least one). For the date format, just standard ISO but don't worry about validation (see PS). Username cannot contains spaces. The regex should not match if the log doesn't follow above rules. ### Examples #### Matching logs ``` <DATE> <LOG LEVEL> [<USER>:<FUNCTION>(:<SUBFUNCTION>)] <MESSAGE> 2003-07-08 16:49:45,896 ERROR [user1:mainfunction:subfunction] We have a problem 2003-07-08 16:49:46,896 INFO [user1:mainfunction] We don't have a problem ``` #### Wrong logs Invalid log level ``` 2003-07-08 16:49:45,896 CRITICAL [user1:mainfunction:subfunction] We have a problem ``` Invalid timestamp (no seconds/minutes) ``` 2003-07-08 16:45,896 ERROR [user1:mainfunction:subfunction] We have a problem ``` Invalid username (contains spaces) ``` 2003-07-08 16:45:13,896 ERROR [best user ever:mainfunction:subfunction] We have a problem ``` PS: for simplicity of this kata dates don't need to be valid, e.g. ```2223-13-41 26:65:13,896``` is accepted, I suggest you to look here if you want to train for that: http://www.codewars.com/kata/548db0bd1df5bbf29b0000b7
reference
# Date parsing logparser = ("(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2},\d{3})\s+" # Error level "(ERROR|INFO|DEBUG)\s+" # User, Function, Subfunction "\[(\w+):(\w+)(?::(\w+))?\]\s+" # Error message "(.+)")
Parse the log
558ecd6398ae4ed3350000c2
[ "Regular Expressions", "Parsing", "Fundamentals" ]
https://www.codewars.com/kata/558ecd6398ae4ed3350000c2
6 kyu
Given an integer `n` return `"odd"` if the number of its divisors is odd. Otherwise return `"even"`. **Note**: big inputs will be tested. ## Examples: All prime numbers have exactly two divisors (hence `"even"`). For `n = 12` the divisors are `[1, 2, 3, 4, 6, 12]` – `"even"`. For `n = 4` the divisors are `[1, 2, 4]` – `"odd"`.
algorithms
def oddity(n): # your code here return 'odd' if n * * 0.5 == int(n * * 0.5) else 'even'
Odd/Even number of divisors
55830eec3e6b6c44ff000040
[ "Mathematics", "Performance", "Algorithms" ]
https://www.codewars.com/kata/55830eec3e6b6c44ff000040
6 kyu
Description: ------------ A [triangle number](https://en.wikipedia.org/wiki/Triangular_number) is a number where *n* objects form an equilateral triangle (it's a bit hard to explain). For example, 6 is a triangle number because you can arrange 6 objects into an equilateral triangle: ``` 1 2 3 4 5 6 ``` 8 is not a triangle number because 8 objects do not form an equilateral triangle: ``` 1 2 3 4 5 6 7 8 ``` In other words, the *n*th triangle number is equal to the sum of the *n* natural numbers from 1 to *n*. Your task: ---------- Check if a given input is a valid triangle number. Return true if it is, false if it is not (note that any non-integers, including non-number types, are not triangle numbers). You are encouraged to develop an effective algorithm: test cases include really big numbers. Assumptions: ------------ You may assume that the given input, if it is a number, is always positive. Notes: ------ 0 and 1 are triangle numbers.
algorithms
# solution based on the fact that triangle numbers are defined by forumla n(n+1)/2 # so if we have integer n which can fit into formula for our number, then number is triangle # We simply need to solve equation like ax^2+bx+c = 0 and check if answer is integer # 25 ms for 34 tests from math import sqrt def is_triangle_number(number): if type(number) is not int: return False n = (- 1 + sqrt(1 + 8 * number)) / 2.0 if n . is_integer(): return True return False
Triangle number check
557e8a141ca1f4caa70000a6
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/557e8a141ca1f4caa70000a6
6 kyu
### Background We **all** know about "balancing parentheses" (plus brackets, braces and chevrons) and even balancing characters that are identical. Read that last sentence again, I balanced different characters and identical characters twice and you didn't even notice... :) ### Kata Your challenge in this kata is to write a piece of code to validate that a supplied string is balanced. You must determine if all that is open is then closed, and nothing is closed which is not already open! You will be given a string to validate, and a second string, where each pair of characters defines an opening and closing sequence that needs balancing. You may assume that the second string always has an even number of characters. ### Example ```python # In this case '(' opens a section, and ')' closes a section is_balanced("(Sensei says yes!)", "()") # => True is_balanced("(Sensei says no!", "()") # => False # In this case '(' and '[' open a section, while ')' and ']' close a section is_balanced("(Sensei [says] yes!)", "()[]") # => True is_balanced("(Sensei [says) no!]", "()[]") # => False # In this case a single quote (') both opens and closes a section is_balanced("Sensei says 'yes'!", "''") # => True is_balanced("Sensei say's no!", "''") # => False ``` ```javascript // In this case '(' opens a section, and ')' closes a section isBalanced("(Sensei says yes!)", "()") // => True isBalanced("(Sensei says no!", "()") // => False // In this case '(' and '[' open a section, while ')' and ']' close a section isBalanced("(Sensei [says] yes!)", "()[]") // => True isBalanced("(Sensei [says) no!]", "()[]") // => False // In this case a single quote (') both opens and closes a section isBalanced("Sensei says 'yes'!", "''") // => True isBalanced("Sensei say's no!", "''") // => False ``` ```csharp // In this case '(' opens a section, and ')' closes a section Kata.IsBalanced("(Sensei says yes!)", "()"); // => True Kata.IsBalanced("(Sensei says no!", "()"); // => False // In this case '(' and '[' open a section, while ')' and ']' close a section Kata.IsBalanced("(Sensei [says] yes!)", "()[]"); // => True Kata.IsBalanced("(Sensei [says) no!]", "()[]"); // => False // In this case a single quote (') both opens and closes a section Kata.IsBalanced("Sensei says 'yes'!", "''"); // => True Kata.IsBalanced("Sensei say's no!", "''"); // => False ``` ```coffeescript # In this case '(' opens a section, and ')' closes a section isBalanced("(Sensei says yes!)", "()") # => True isBalanced("(Sensei says no!", "()") # => False # In this case '(' and '[' open a section, while ')' and ']' close a section isBalanced("(Sensei [says] yes!)", "()[]") # => True isBalanced("(Sensei [says) no!]", "()[]") # => False # In this case a single quote (') both opens and closes a section isBalanced("Sensei says 'yes'!", "''") # => True isBalanced("Sensei say's no!", "''") # => False ```
algorithms
def is_balanced(source, caps): source = filter(lambda x: x in caps, source) caps = dict(zip(caps[:: 2], caps[1:: 2])) stack = [] for cap in source: if stack and cap == caps . get(stack[- 1], ''): stack . pop() else: stack . append(cap) return not stack
All that is open must be closed...
55679d644c58e2df2a00009c
[ "Stacks", "Parsing", "Algorithms" ]
https://www.codewars.com/kata/55679d644c58e2df2a00009c
5 kyu
Removed due to copyright infringement. <!--- Vasya isn't really good at math. However, he wants to get a good mark for the class. So he made a deal with his teacher. "I wil study very hard and will be able to solve any given problem!" - Vasya said. Finally, today is the time to show what Vasya achieved. He solved the given task immediately. Can you? ### Task: You are given a system of equations: ```math a^2 + b = n \\ a + b^2=m ``` In JS, C# and Java the parameters of the system: `1 ≀ n, m ≀ 1000` You should count, how many there are pairs of integers (a, b) (0 ≀ a, b) which satisfy the system. ### Examples ```csharp SystemOfEq.Solution(9,3) // => 1 SystemOfEq.Solution(14,28) // => 1 SystemOfEq.Solution(4,20) // => 0 ``` ```java SystemOfEq.Solution(9,3) // => 1 SystemOfEq.Solution(14,28) // => 1 SystemOfEq.Solution(4,20) // => 0 ``` ```javascript solution(9,3) // => 1 solution(14,28) // => 1 solution(4,20) // => 0 ``` ```ruby solution(9,3) # => 1 solution(14,28) # => 1 solution(4,20) # => 0 ``` ```python solution(9,3) # => 1 solution(14,28) # => 1 solution(4,20) # => 0 ``` ```haskell solution 9 3 # => 1 solution 14 28 # => 1 solution 4 20 # => 0 ``` ```clojure (solution 9 3) # => 1 (solution 14 28) # => 1 (solution 4 20) # => 0 ``` --->
reference
def solution(n, m): return sum(a + max(n - a * a, 0) * * 2 == m for a in range(0, m))
Vasya and System of Equations
556eed2836b302917b0000a3
[ "Fundamentals", "Mathematics", "Algorithms", "Logic", "Numbers", "Algebra", "Puzzles", "Games" ]
https://www.codewars.com/kata/556eed2836b302917b0000a3
6 kyu
### Preface You are currently working together with a local community to build a school teaching children how to code. First plans have been made and the community wants to decide on the best location for the coding school. In order to make this decision data about the location of students and potential locations is collected. ### Problem In order to be able to attract and teach as many students as possible we want to minimize the total traveling distance for potential students. The streets system is organized in a traditional grid system and students can only travel horizontally or vertically (not diagonal). The locations of interested students is given as an array with the first value of each entry presenting the x coordinate and the second value presenting the y coordinate: ```javascript var students = [[3,7],[2,2],[14,1], ...]; ``` ```ruby students = [[3,7],[2,2],[14,1], ...]; ``` ```python students = [[3,7],[2,2],[14,1], ...]; ``` Potential locations are passed as an array of objects with an unique id, a x and y coordinate: ```javascript var locations = [{id: 1, x: 3, y: 4}, {id: 2, x: 8, y: 2}, ...]; ``` ```ruby locations = [{"id"=> 1, "x"=> 3, "y"=> 4}, {"id"=> 2, "x"=> 8, "y"=> 2}, ...]; ``` ```python locations = [{"id": 1, "x": 3, "y": 4}, {"id": 2, "x": 8, "y": 2}, ...]; ``` Your task is now to evaluate which of the school locations would be best to minimize the distance for all potential students to the school. The desired output should consist of a string indicating the ID of the best suitable location and the x and y coordinates in the following form: ``` "The best location is number 1 with the coordinates x = 3 and y = 4" ```
algorithms
def optimum_location(students, locations): m = min(locations, key=lambda loc: sum( abs(loc['x'] - s[0]) + abs(loc['y'] - s[1]) for s in students)) return "The best location is number %d with the coordinates x = %d and y = %d" % (m['id'], m['x'], m['y'])
Optimum coding school location
55738b0cffd95756c3000056
[ "Algorithms" ]
https://www.codewars.com/kata/55738b0cffd95756c3000056
6 kyu
# Problem Statement Write a function that takes two string parameters, an IP (v4) address and a subnet mask, and returns two strings: the network block, and the host identifier. The function does not need to support CIDR notation. # Description A single IP address with subnet mask actually specifies several addresses: a network block, and a host identifier, and a broadcast address. These addresses can be calculated using a bitwise AND operation on each bit. (The broadcast address is not used in this kata.) ## Example A computer on a simple home network might have the following IP and subnet mask: ``` IP: 192.168.2.1 Subnet: 255.255.255.0 (CIDR Notation: 192.168.2.1 /24) ``` In this example, the network block is: **192.168.2.0**. And the host identifier is: **0.0.0.1**. ## bitwise AND To calculate the network block and host identifier the bits in each octet are ANDed together. When the result of the AND operation is '1', the bit specifies a network address (instead of a host address). To compare the first octet in our example above, convert both the numbers to binary and perform an AND operation on each bit: ``` 11000000 (192 in binary) 11111111 (255 in binary) --------------------------- (AND each bit) 11000000 (192 in binary) ``` So in the first octet, '**192**' is part of the network address. The host identifier is simply '**0**'. For more information see the [Subnetwork](http://en.wikipedia.org/wiki/Subnetwork) article on Wikipedia.
algorithms
def ipv4__parser(addr, mask): return tuple("." . join(str(n) for n in a) for a in zip(* (((a & m), (a & ~ m)) for a, m in zip((int(n) for n in addr . split(".")), (int(n) for n in mask . split("."))))))
IPv4 Parser
556d120c7c58dacb9100008b
[ "Networks", "Binary", "Bits", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/556d120c7c58dacb9100008b
6 kyu
It is a well-known fact that behind every good comet is a UFO. These UFOs often come to collect loyal supporters from here on Earth. Unfortunately, they only have room to pick up one group of followers on each trip. They do, however, let the groups know ahead of time which will be picked up for each comet by a clever scheme: they pick a name for the comet which, along with the name of the group, can be used to determine if it is a particular group's turn to go (who do you think names the comets?). The details of the matching scheme are given below; your job is to write a program which takes the names of a group and a comet and then determines whether the group should go with the UFO behind that comet. Both the name of the group and the name of the comet are converted into a number in the following manner: the final number is just the product of all the letters in the name, where "A" is 1 and "Z" is 26. For instance, the group "USACO" would be `21 * 19 * 1 * 3 * 15` = 17955. If the group's number mod 47 is the same as the comet's number mod 47, then you need to tell the group to get ready! (Remember that "a mod b" is the remainder left over after dividing a by b; 34 mod 10 is 4.) Write a program which reads in the name of the comet and the name of the group and figures out whether according to the above scheme the names are a match, printing "GO" if they match and "STAY" if not. The names of the groups and the comets will be a string of capital letters with no spaces or punctuation, up to 6 characters long. Example: ```javascript group = "COMETQ" comet = "HVNGAT" ride(group,comet) == "GO" ``` ```coffeescript group = 'COMETQ' comet = 'HVNGAT' ride(group,comet) == 'GO' ``` ```haskell group = "COMETQ" comet = "HVNGAT" ride group comet == Go ``` ```clojure (def group "COMETQ") (def comet "HVNGAT") (ride group comet) ; returns "GO" ``` ```ruby group = "COMETQ" comet = "HVNGAT" ride(group,comet) == "GO" ``` Converting the letters to numbers: ``` C O M E T Q 3 15 13 5 20 17 H V N G A T 8 22 14 7 1 20 ``` then calculate the product mod 47: ``` 3 * 15 * 13 * 5 * 20 * 17 = 994500 mod 47 = 27 8 * 22 * 14 * 7 * 1 * 20 = 344960 mod 47 = 27 ``` Because both products evaluate to 27 (when modded by 47), the mission is 'GO'.
algorithms
def ride(group, comet): n1 = 1 n2 = 1 for x in group: n1 *= ord(x . lower()) - 96 for x in comet: n2 *= ord(x . lower()) - 96 if n1 % 47 == n2 % 47: return "GO" else: return "STAY"
Your Ride Is Here
55491e9e50f2fc92f3000074
[ "Algorithms" ]
https://www.codewars.com/kata/55491e9e50f2fc92f3000074
6 kyu
Removed due to copyright infringement. <!--- Vasya wants to climb up a stair of certain amount of steps (Input parameter 1). There are 2 simple rules that he has to stick to. 1. Vasya can climb 1 or 2 steps at each move. 2. Vasya wants the number of moves to be a multiple of a certain integer. (Input parameter 2). ### Task: What is the `MINIMAL` number of moves making him climb to the top of the stairs that satisfies his conditions? ### Input 1. Number of stairs: `0 < N ≀ 10000` ; 2. Integer to be multiplied : `1 < M ≀ 10 `; ### Output 1. Return a single integer - the minimal number of moves being a multiple of M; 2. If there is no way he can climb satisfying condition return - 1 instead. (`Nothing` in Haskell) ### Examples ```csharp Stairs.NumberOfSteps(10, 2) => 6 // Sequence of steps : {2, 2, 2, 2, 1, 1} Stairs.NumberOfSteps(3, 5) => -1 // !Possible sequences of steps : {2, 1}, {1, 2}, {1, 1, 1} ``` ```java Stairs.NumberOfSteps(10, 2) => 6 // Sequence of steps : {2, 2, 2, 2, 1, 1} Stairs.NumberOfSteps(3, 5) => -1 // !Possible sequences of steps : {2, 1}, {1, 2}, {1, 1, 1} ``` ```ruby numberOfSteps(10, 2) => 6 # Sequence of steps : {2, 2, 2, 2, 1, 1} numberOfSteps(3, 5) => -1 # !Possible sequences of steps : {2, 1}, {1, 2}, {1, 1, 1} ``` ```python numberOfSteps(10, 2) => 6 # Sequence of steps : {2, 2, 2, 2, 1, 1} numberOfSteps(3, 5) => -1 # !Possible sequences of steps : {2, 1}, {1, 2}, {1, 1, 1} ``` ```clojure numberOfSteps(10, 2) => 6 # Sequence of steps : {2, 2, 2, 2, 1, 1} numberOfSteps(3, 5) => -1 # !Possible sequences of steps : {2, 1}, {1, 2}, {1, 1, 1} ``` ```javascript numberOfSteps(10, 2) => 6 // Sequence of steps : {2, 2, 2, 2, 1, 1} numberOfSteps(3, 5) => -1 // !Possible sequences of steps : {2, 1}, {1, 2}, {1, 1, 1} ``` ``` haskell numberOfSteps 10 2 == Just 6 -- Sequence of steps : {2, 2, 2, 2, 1, 1} numberOfSteps 3 5 == Nothing -- Not possible, since the sequences of steps would be {2, 1}, {1, 2} or {1, 1, 1} ``` --->
algorithms
def numberOfSteps(steps, m): if (steps < m): return - 1 if (steps % 2 == 0 and (steps / 2) % m == 0): return (steps / 2) return (steps / 2) + m - ((steps / 2) % m)
Vasya and Stairs
55251c0d2142d7b4ab000aef
[ "Algorithms", "Mathematics", "Logic", "Numbers", "Fundamentals" ]
https://www.codewars.com/kata/55251c0d2142d7b4ab000aef
6 kyu
# Feynman's squares Richard Phillips Feynman was a well-known American physicist and a recipient of the Nobel Prize in Physics. He worked in theoretical physics and pioneered the field of quantum computing. Recently, an old farmer found some papers and notes that are believed to have belonged to Feynman. Among notes about mesons and electromagnetism, there was a napkin where he wrote a simple puzzle: "how many different squares are there in a grid of NxN squares?". For example, when N=2, the answer is 5: the 2x2 square itself, plus the four 1x1 squares in its corners: <img src=http://www.spoj.com/content/disatoba:feynman.gif> # Task Complete the function that solves Feynman's question in general. The input to your function will always be a positive integer. # Examples ```python 1 --> 1 2 --> 5 3 --> 14 ``` *(Adapted from the Sphere Online Judge problem SAMER08F by Diego Satoba)*
games
def count_squares(n): return n * (n + 1) * (2 * n + 1) / / 6
Feynman's square question
551186edce486caa61000f5c
[ "Puzzles" ]
https://www.codewars.com/kata/551186edce486caa61000f5c
6 kyu
This kata is part one of precise fractions series (see pt. 2: http://www.codewars.com/kata/precise-fractions-pt-2-conversion). When dealing with fractional values, there's always a problem with the precision of arithmetical operations. So lets fix it! Your task is to implement class ```Fraction``` that takes care of simple fraction arithmetics. Requirements: * class must have two-parameter constructor `Fraction(numerator, denominator)`; passed values will be non-zero integers, and may be positive or negative. * two conversion methods must be supported: * `toDecimal()` returns decimal representation of fraction * `toString()` returns string with fractional representation of stored value in format: [ SIGN ] [ WHOLES ] [ NUMERATOR / DENOMINATOR ] * **Note**: each part is returned only if it is available and non-zero, with the only possible space character going between WHOLES and fraction. Examples: '-1/2', '3', '-5 3/4' * The fractional part must always be normalized (ie. the numerator and denominators must not have any common divisors). * Four operations need to be implemented: `add`, `subtract`, `multiply` and `divide`. Each of them may take integers as well as another `Fraction` instance as an argument, and must return a new `Fraction` instance. * Instances must be immutable, hence none of the operations may modify either of the objects it is called upon, nor the passed argument. #### Python Notes * If one integer is passed into the initialiser, then the fraction should be assumed to represent an integer not a fraction. * You must implement the standard operator overrides `__add__`, `__sub__`, `__mul__`, `__div__`, in each case you should support `other` being an `int` or another instance of `Fraction`. * Implement `__str__` and `to_decimal` in place of `toString` and `toDecimal` as described above.
games
from fractions import Fraction Fraction . to_decimal = lambda f: float(f . numerator) / f . denominator simple_fraction = Fraction . __str__ def mixed_fraction(f): n, d, s = abs(f . numerator), f . denominator, simple_fraction(f) return s . replace(str(n), '%d %d' % divmod(n, d), 1) if 1 < d < n else s Fraction . __str__ = mixed_fraction
Precise fractions pt. 1 - basics
54cf4fc26b85dc27bf000a6b
[ "Algorithms", "Mathematics", "Puzzles" ]
https://www.codewars.com/kata/54cf4fc26b85dc27bf000a6b
5 kyu
## Mastermind *Mastermind* is a two-player game where one player creates a four-color code from a possible six colors. The other player has ten turns to guess this code. After each guess, the "codemaker" places pegs corresponding to correct guesses and the "codebreaker" then guesses again, based on these pegs. Black pegs are given for every color in the guess that is correctly placed, and white pegs are given for other colors in the guess that are in the code, but were not guessed in the correct position. More info: [Mastermind](http://en.wikipedia.org/wiki/Mastermind_(board_game)). ## Task Your task is to implement a function that will compare the player's guess to the secret code and return an appropriate number of colored hints - one **black** peg for each correctly guessed color in a correct position, one **white** peg for each correct color in an incorrect position. ### Specifics for this kata: * The number of colors in the code is random instead of always being 4 * The number of possible colors has been increased * The same color may appear multiple times in different positions ## Examples: ``` No elements match: code = [1, 2, 3] guess = [4, 5, 6] result = {black: 0, white: 0} 2 elements match, both in wrong positions: code = [1, 2, 3] guess = [2, 1, 4] result = {black: 0, white: 2} 3 elements match, one in correct position and two in wrong positions: code = [1, 2, 3] guess = [2, 1, 3] result = {black: 1, white: 2} 3 elements match, one in correct position and two in wrong positions: code = [0, 0, 0, 1, 1] guess = [2, 2, 0, 0, 0] result = {black: 1, white: 2} ```
algorithms
def get_hints(answer, guess): black = 0 white = 0 for number in set(guess): white += min(answer . count(number), guess . count(number)) for i, number in enumerate(guess): if number == answer[i]: white -= 1 black += 1 return {"black": black, "white": white}
Mastermind Hint Pegs
54f0d905d49112f3a300055a
[ "Arrays", "Games", "Algorithms" ]
https://www.codewars.com/kata/54f0d905d49112f3a300055a
6 kyu
Calculus class...is awesome! But you are a programmer with no time for mindless repetition. Your teacher spent a whole day covering differentiation of polynomials, and by the time the bell rang, you had already conjured up a program to automate the process. You realize that a polynomial of degree n a<sub>n</sub>x<sup>n</sup> + a<sub>n-1</sub>x<sup>n-1</sup> + ... + a<sub>0</sub> can be represented as an array of coefficients [a<sub>n</sub>, a<sub>n-1</sub>, ..., a<sub>0</sub>] For example, we would represent 5x<sup>2</sup> + 2x + 1 as [5,2,1] 3x<sup>2</sup> + 1 as [3,0,1] x<sup>4</sup> as [1,0,0,0,0] x as [1, 0] 1 as [1] Your function will take a coefficient array as an argument and return a **new array** representing the coefficients of the derivative. ```javascript var poly1 = [1, 1] // x + 1 diff(poly1) === [1] // 1 var poly2 = [1, 1, 1] // x^2 + x + 1 diff(poly2) === [2, 1] // 2x + 1 diff(diff(poly2)) === [2] // 2 var poly3 = [2, 1, 0, 0] // 2x^3 + x^2 diff(poly3) === [6, 2, 0] // 6x^2 + 2x ``` ```python poly1 = [1, 1] # x + 1 diff(poly1) == [1] # 1 poly2 = [1, 1, 1] # x^2 + x + 1 diff(poly2) == [2, 1] # 2x + 1 diff(diff(poly2)) == [2] # 2 poly3 = [2, 1, 0, 0] # 2x^3 + x^2 diff(poly3) == [6, 2, 0] # 6x^2 + 2x ``` Note: your function will always return a new array which has one less element than the argument (unless the argument is [], in which case [] is returned).
algorithms
def diff(poly): return [poly[i] * (len(poly) - 1 - i) for i in range(len(poly) - 1)]
Diff That Poly!
54f4b6e7576d7af70900092b
[ "Mathematics", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/54f4b6e7576d7af70900092b
6 kyu
> **Note**: This kata is a translation of this (Java) one: http://www.codewars.com/kata/rotate-array. I have not translated this first one as usual because I did not solved it, and I fear not being able to solve it (Java is **not** my cup of... tea). @cjmcgraw, if you want to use my translation on your kata feel free to use it. Create a function named "rotate" that takes an array and returns a new one with the elements inside rotated n spaces. If n is greater than 0 it should rotate the array to the right. If n is less than 0 it should rotate the array to the left. If n is 0, then it should return the array unchanged. Example: ```javascript var data = [1, 2, 3, 4, 5]; rotate(data, 1) // => [5, 1, 2, 3, 4] rotate(data, 2) // => [4, 5, 1, 2, 3] rotate(data, 3) // => [3, 4, 5, 1, 2] rotate(data, 4) // => [2, 3, 4, 5, 1] rotate(data, 5) // => [1, 2, 3, 4, 5] rotate(data, 0) // => [1, 2, 3, 4, 5] rotate(data, -1) // => [2, 3, 4, 5, 1] rotate(data, -2) // => [3, 4, 5, 1, 2] rotate(data, -3) // => [4, 5, 1, 2, 3] rotate(data, -4) // => [5, 1, 2, 3, 4] rotate(data, -5) // => [1, 2, 3, 4, 5] ``` ```csharp var data = new object[] { 1, 2, 3, 4, 5 }; Kata.Rotate(data, 1); // => [5, 1, 2, 3, 4] Kata.Rotate(data, 2); // => [4, 5, 1, 2, 3] Kata.Rotate(data, 3); // => [3, 4, 5, 1, 2] Kata.Rotate(data, 4); // => [2, 3, 4, 5, 1] Kata.Rotate(data, 5); // => [1, 2, 3, 4, 5] Kata.Rotate(data, 0); // => [1, 2, 3, 4, 5] Kata.Rotate(data, -1); // => [2, 3, 4, 5, 1] Kata.Rotate(data, -2); // => [3, 4, 5, 1, 2] Kata.Rotate(data, -3); // => [4, 5, 1, 2, 3] Kata.Rotate(data, -4); // => [5, 1, 2, 3, 4] Kata.Rotate(data, -5); // => [1, 2, 3, 4, 5] ``` ```coffeescript data = [1, 2, 3, 4, 5] rotate(data, 1) # => [5, 1, 2, 3, 4] rotate(data, 2) # => [4, 5, 1, 2, 3] rotate(data, 3) # => [3, 4, 5, 1, 2] rotate(data, 4) # => [2, 3, 4, 5, 1] rotate(data, 5) # => [1, 2, 3, 4, 5] rotate(data, 0) # => [1, 2, 3, 4, 5] rotate(data, -1) # => [2, 3, 4, 5, 1] rotate(data, -2) # => [3, 4, 5, 1, 2] rotate(data, -3) # => [4, 5, 1, 2, 3] rotate(data, -4) # => [5, 1, 2, 3, 4] rotate(data, -5) # => [1, 2, 3, 4, 5] ``` ```python data = [1, 2, 3, 4, 5]; rotate(data, 1) # => [5, 1, 2, 3, 4] rotate(data, 2) # => [4, 5, 1, 2, 3] rotate(data, 3) # => [3, 4, 5, 1, 2] rotate(data, 4) # => [2, 3, 4, 5, 1] rotate(data, 5) # => [1, 2, 3, 4, 5] rotate(data, 0) # => [1, 2, 3, 4, 5] rotate(data, -1) # => [2, 3, 4, 5, 1] rotate(data, -2) # => [3, 4, 5, 1, 2] rotate(data, -3) # => [4, 5, 1, 2, 3] rotate(data, -4) # => [5, 1, 2, 3, 4] rotate(data, -5) # => [1, 2, 3, 4, 5] ``` ```haskell data = [1, 2, 3, 4, 5] rotate 1 data -- => [5, 1, 2, 3, 4] rotate 2 data -- => [4, 5, 1, 2, 3] rotate 3 data -- => [3, 4, 5, 1, 2] rotate 4 data -- => [2, 3, 4, 5, 1] rotate 5 data -- => [1, 2, 3, 4, 5] rotate 0 data -- => [1, 2, 3, 4, 5] rotate -1 data -- => [2, 3, 4, 5, 1] rotate -2 data -- => [3, 4, 5, 1, 2] rotate -3 data -- => [4, 5, 1, 2, 3] rotate -4 data -- => [5, 1, 2, 3, 4] rotate -5 data -- => [1, 2, 3, 4, 5] ``` Furthermore the method should take ANY array of objects and perform this operation on them: ```javascript rotate(['a', 'b', 'c'], 1) // => ['c', 'a', 'b'] rotate([1.0, 2.0, 3.0], 1) // => [3.0, 1.0, 2.0] rotate([true, true, false], 1) // => [false, true, true] ``` ```csharp Kata.Rotate(new object[] { 'a', 'b', 'c' }, 1); // => ['c', 'a', 'b'] Kata.Rotate(new object[] { 1.0, 2.0, 3.0 }, 1); // => [3.0, 1.0, 2.0] Kata.Rotate(new object[] { true, true, false }, 1); // => [false, true, true] ``` ```coffeescript rotate(['a', 'b', 'c'], 1) # => ['c', 'a', 'b'] rotate([1.0, 2.0, 3.0], 1) # => [3.0, 1.0, 2.0] rotate([true, true, false], 1) # => [false, true, true] ``` ```python rotate(['a', 'b', 'c'], 1) # => ['c', 'a', 'b'] rotate([1.0, 2.0, 3.0], 1) # => [3.0, 1.0, 2.0] rotate([True, True, False], 1) # => [False, True, True] ``` ```haskell rotate 1 ['a', 'b', 'c'] -- => ['c', 'a', 'b'] rotate 1 [1.0, 2.0, 3.0] 1 -- => [3.0, 1.0, 2.0] rotate 1 [True, True, False] -- => [False, True, True] rotate 1 ["one", "two", "three"] -- => ["three", "one", "two"] ``` Finally the rotation shouldn't be limited by the indices available in the array. Meaning that if we exceed the indices of the array it keeps rotating. Example: ```javascript var data = [1, 2, 3, 4, 5] rotate(data, 7) // => [4, 5, 1, 2, 3] rotate(data, 11) // => [5, 1, 2, 3, 4] rotate(data, 12478) // => [3, 4, 5, 1, 2] ``` ```csharp var data = new object[] { 1, 2, 3, 4, 5 }; Kata.Rotate(data, 7); // => [4, 5, 1, 2, 3] Kata.Rotate(data, 11); // => [5, 1, 2, 3, 4] Kata.Rotate(data, 12478); // => [3, 4, 5, 1, 2] ``` ```coffeescript data = [1, 2, 3, 4, 5] rotate(data, 7) # => [4, 5, 1, 2, 3] rotate(data, 11) # => [5, 1, 2, 3, 4] rotate(data, 12478) # => [3, 4, 5, 1, 2] ``` ```python data = [1, 2, 3, 4, 5] rotate(data, 7) # => [4, 5, 1, 2, 3] rotate(data, 11) # => [5, 1, 2, 3, 4] rotate(data, 12478) # => [3, 4, 5, 1, 2] ``` ```haskell data = [1, 2, 3, 4, 5] rotate 7 data -- => [4, 5, 1, 2, 3] rotate 11 data -- => [5, 1, 2, 3, 4] rotate 12478 data -- => [3, 4, 5, 1, 2] ```
algorithms
def rotate(arr, n): # ... n = n % len(arr) return arr[- n:] + arr[: - n]
Rotate Array (JS)
54f8b0c7a58bce9db6000dc4
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/54f8b0c7a58bce9db6000dc4
6 kyu
Build Tower Advanced --- Build Tower by the following given arguments:<br> * __number of floors__ (integer and always greater than 0)<br> * __block size__ (width, height) (integer pair and always greater than (0, 0)) *** Tower block unit is represented as `*`. Tower blocks of block size (2, 1) and (2, 3) would look like respectively: ``` ** ``` ``` ** ** ** ``` *** for example, a tower of 3 floors with block size = (2, 3) looks like below ``` [ ' ** ', ' ** ', ' ** ', ' ****** ', ' ****** ', ' ****** ', '**********', '**********', '**********' ] ``` and a tower of 6 floors with block size = (2, 1) looks like below ``` [ ' ** ', ' ****** ', ' ********** ', ' ************** ', ' ****************** ', '**********************' ] ``` *** Don't return a whole string containing line-endings but a list/array/vector of strings instead! This kata might looks like a __5.5kyu__ one. So challenge yourself! Go take a look at [Build Tower](https://www.codewars.com/kata/576757b1df89ecf5bd00073b) which is a more basic version :)
reference
def tower_builder(n_floors, block_size): w, h = block_size filled_block = '*' * w empty_block = ' ' * w tower = [] for n in range(1, n_floors + 1): for _ in range(h): tower . append(empty_block * (n_floors - n) + filled_block * (2 * n - 1) + empty_block * (n_floors - n)) return tower
Build Tower Advanced
57675f3dedc6f728ee000256
[ "Strings", "ASCII Art", "Fundamentals" ]
https://www.codewars.com/kata/57675f3dedc6f728ee000256
6 kyu
## Do you know how to make a spiral? Let's test it! --- *Classic definition: A spiral is a curve which emanates from a central point, getting progressively farther away as it revolves around the point.* --- Your objective is to complete a function `createSpiral(N)` that receives an integer `N` and returns an `NxN` two-dimensional array with numbers `1` through `NxN` represented as a clockwise spiral. Return an empty array if `N < 1` or `N` is not int / number Examples: `N = 3` `Output: [[1,2,3],[8,9,4],[7,6,5]]` ``` 1 2 3 8 9 4 7 6 5 ``` `N = 4` `Output: [[1,2,3,4],[12,13,14,5],[11,16,15,6],[10,9,8,7]]` ``` 1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7 ``` `N = 5` `Output: [[1,2,3,4,5],[16,17,18,19,6],[15,24,25,20,7],[14,23,22,21,8],[13,12,11,10,9]]` ``` 1 2 3 4 5 16 17 18 19 6 15 24 25 20 7 14 23 22 21 8 13 12 11 10 9 ```
games
def createSpiral(n): if not isinstance(n, int): return [] d = iter(range(n * * 2)) a = r = [[[x, y] for y in range(n)] for x in range(n)] while a: for x, y in a[0]: r[x][y] = next(d) + 1 a = list(zip(* a[1:]))[:: - 1] return r
The Clockwise Spiral
536a155256eb459b8700077e
[ "Arrays", "Puzzles" ]
https://www.codewars.com/kata/536a155256eb459b8700077e
5 kyu
# Write this function ![](http://i.imgur.com/mlbRlEm.png) `for i from 1 to n`, do `i % m` and return the `sum` f(n=10, m=5) // returns 20 (1+2+3+4+0 + 1+2+3+4+0) *You'll need to get a little clever with performance, since n can be a very large number*
algorithms
def f(n, m): re, c = divmod(n, m) return m * (m - 1) / 2 * re + (c + 1) * c / 2
Sum of many ints
54c2fc0552791928c9000517
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/54c2fc0552791928c9000517
6 kyu
## The galactic games have begun! It's the galactic games! Beings of all worlds come together to compete in several interesting sports, like nroogring, fredling and buzzing (the beefolks love the last one). However, there's also the traditional marathon run. Unfortunately, there have been cheaters in the last years, and the committee decided to place sensors on the track. Committees being committees, they've come up with the following rule: > A sensor should be placed every 3 and 5 meters from the start, e.g. > at 3m, 5m, 6m, 9m, 10m, 12m, 15m, 18m…. Since you're responsible for the track, you need to buy those sensors. Even worse, you don't know how long the track will be! And since there might be more than a single track, and you can't be bothered to do all of this by hand, you decide to write a program instead. ## Task Return the sum of the multiples of 3 and 5 __below__ a number. Being the _galactic_ games, the tracks can get rather large, so your solution should work for _really_ large numbers (greater than 1,000,000). ### Examples ```haskell solution 10 `shouldBe` 23 = 3 + 5 + 6 + 9 solution 20 `shouldBe` 78 = 3 + 5 + 6 + 9 + 10 + 12 + 15 + 18 ``` ```javascript solution (10) // => 23 = 3 + 5 + 6 + 9 solution (20) // => 78 = 3 + 5 + 6 + 9 + 10 + 12 + 15 + 18 ``` ```python solution (10) # => 23 = 3 + 5 + 6 + 9 solution (20) # => 78 = 3 + 5 + 6 + 9 + 10 + 12 + 15 + 18 ``` ```ruby solution(10) # => 23 = 3 + 5 + 6 + 9 solution(20) # => 78 = 3 + 5 + 6 + 9 + 10 + 12 + 15 + 18 ```
algorithms
def summ(number, d): n = (number - 1) / / d return n * (n + 1) * d / / 2 def solution(number): return summ(number, 3) + summ(number, 5) - summ(number, 15)
Multiples of 3 and 5 redux
54bb6ee72c4715684d0008f9
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/54bb6ee72c4715684d0008f9
6 kyu
For a given nonempty string `s` find a minimum substring `t` and the maximum number `k`, such that the entire string `s` is equal to `t` repeated `k` times. The input string consists of lowercase latin letters. Your function should return : * a tuple `(t, k)` (in Python) * an array `[t, k]` (in Ruby and JavaScript) * in C, return `k` and write to the string `t` passed in parameter ## Examples: ``` "ababab" ---> (t = "ab", k = 3) "abcde" ---> (t = "abcde", k = 1) because for this string, the minimum substring 't' such that 's' is 'k' times 't', is 's' itself. ```
algorithms
def f(s): m = __import__('re'). match(r'^(.+?)\1*$', s) return (m . group(1), len(s) / len(m . group(1)))
Repeated Substring
5491689aff74b9b292000334
[ "Algorithms" ]
https://www.codewars.com/kata/5491689aff74b9b292000334
6 kyu
#Source This kata is an application of a magic trick. This magic trick is based on a mathematic algorithm: the Zeckendorf theorem: ``` Every positive integer can be expressed uniquely as a sum of distinct non-consecutive Fibonacci numbers. ``` **Don't be afraid, you don't need to understand the theorem to solve this kata.** ------------------------- #Magic Trick Description Here is how the magic trick work: 1. Ask the spectator to choose a number between 0 and 100 (included) 2. Give a *special* set of card to the spectator, these cards contains a list of numbers. Here is what the cards look like: [https://blogdemaths.files.wordpress.com/2013/01/cartes-magiques.pdf](CLICK) 3. Ask the spectator to give you back only the cards where his number is written on it. 4. You can guess the number of your spectator ------------------------- #Magic Trick Explanation You just need to sum the first number on each card and TADAM. In practice you could ask numbers much higher (with 10 cards it can go up to 231) but that would make really long cards. ------------------------- #Objective We will consider that each presented card has an "index" on it to recognize it. Those cards are already given to you. Write a class magicZ with 2 functions ```gueZZ([indexes of card])``` and ```getMagicZindex(n)```. - ```gueZZ(indexes)``` takes an array being the index of each card and return the guessed number - ```getMagicZindex(n)``` takes a number and return the list of indexes for this value (the number can be higher than 100) ##Example: I chose number 70: - ```gueZZ([1,5,8]) === 70``` - ```getMagicZindex(70) = [1,5,8]``` ##Note The spectator is always going to try to trick. Be prepared to receive duplicated cards (ignore the duplicates) or fewer cards than expected (respond with 0). ##Next If you think this kata was too simple, you can try to generate the cards used in this kata, here: http://www.codewars.com/kata/zeckendorf-cards-generator . Good Luck, Don't forget to up vote if you like, thanks *IVBakker*
games
class magicZ (): def __init__(self): self . fib = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89] def gueZZ(self, indexes=[]): return sum(self . fib[i] for i in set(indexes)) def get_magicZ_index(self, n): indexes = [] for i, f in list(enumerate(self . fib))[:: - 1]: if n >= f: n -= f indexes . append(i) return indexes[:: - 1]
Magic Zeckendorf
549013f6f71e7786aa0002a8
[ "Mathematics", "Puzzles" ]
https://www.codewars.com/kata/549013f6f71e7786aa0002a8
6 kyu
> [Run-length encoding](https://en.wikipedia.org/w/index.php?title=Run-length_encoding) (RLE) is a very simple form of data compression in which runs of data (that is, sequences in which the same data value occurs in many consecutive data elements) are stored as a single data value and count, rather than as the original run. <cite>Wikipedia</cite> ## Task Your task is to write such a run-length encoding. For a given string, return a list (or array) of pairs (or arrays) [ (i<sub>1</sub>, s<sub>1</sub>), (i<sub>2</sub>, s<sub>2</sub>), …, (i<sub>n</sub>, s<sub>n</sub>) ], such that one can reconstruct the original string by replicating the character s<sub>x</sub> i<sub>x</sub> times and concatening all those strings. Your run-length encoding should be minimal, ie. for all i the values s<sub>i</sub> and s<sub>i+1</sub> should differ. ## Examples As the article states, RLE is a _very_ simple form of data compression. It's only suitable for runs of data, as one can see in the following example: ```haskell runLengthEncoding "hello world!" `shouldBe` [(1,'h'), (1,'e'), (2,'l'), (1,'o'), (1,' '), (1,'w'),(1,'o'), (1,'r'), (1,'l'), (1,'d'), (1,'!')] ``` ```coffeescript runLengthEncoding "hello world!" # => [[1,'h'], [1,'e'], [2,'l'], [1,'o'], [1,' '], [1,'w'], [1,'o'], [1,'r'], [1,'l'], [1,'d'], [1,'!']] ``` ```javascript runLengthEncoding("hello world!") //=> [[1,'h'], [1,'e'], [2,'l'], [1,'o'], [1,' '], [1,'w'], [1,'o'], [1,'r'], [1,'l'], [1,'d'], [1,'!']] ``` ```python run_length_encoding("hello world!") //=> [[1,'h'], [1,'e'], [2,'l'], [1,'o'], [1,' '], [1,'w'], [1,'o'], [1,'r'], [1,'l'], [1,'d'], [1,'!']] ``` ```ruby rle("hello world!") # => [[1,'h'], [1,'e'], [2,'l'], [1,'o'], [1,' '], [1,'w'], [1,'o'], [1,'r'], [1,'l'], [1,'d'], [1,'!']] ``` ```elixir run_length_encoding("hello world!") # => [[1,"h"], [1,"e"], [2,"l"], [1,"o"], [1," "], [1,"w"], [1,"o"], [1,"r"], [1,"l"], [1,"d"], [1,"!"]] ``` It's very effective if the same data value occurs in many consecutive data elements: ```haskell runLengthEncoding "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbb" `shouldBe` [(34,'a'), (3,'b')] ``` ```coffeescript runLengthEncoding "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbb" # => [[34,'a'], [3,'b']] ``` ```javascript runLengthEncoding("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbb") // => [[34,'a'], [3,'b']] ``` ```python run_length_encoding("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbb") # => [[34,'a'], [3,'b']] ``` ```ruby rle("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbb") # => [[34,'a'], [3,'b']] ``` ```elixir run_length_encoding("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbb") # => [[34,"a"], [3,"b"]] ```
algorithms
from itertools import groupby def run_length_encoding(s): return [[sum(1 for _ in g), c] for c, g in groupby(s)]
Run-length encoding
546dba39fa8da224e8000467
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/546dba39fa8da224e8000467
6 kyu
The method below, is the most simple string search algorithm. It will find the first occurrence of a word in a text string. `haystack = the whole text` `needle = searchword` `wildcard = _` ``` find("strike", "i will strike down upon thee"); // return 7 ``` The find method is already made. The problem is to implement wildcard(s) in the needle. If you have a _ in the needle it will match any character in the haystack. A normal string search algorithm will find the first occurrence of a word(needle) in a text(haystack), starting on index 0. Like this: ``` find("strike", "I will strike down upon thee"); return 7 ``` A wildcard in the needle will match any character in the haystack. The method should work on any types of needle and haystack. You can assume the needle is shorter than(or equal to) the haystack. ``` find("g__d", "That's the good thing about being president"); // return 11 ``` If no match the method should return -1
algorithms
import re def find(needle, haystack): matched = re . search(re . escape(needle). replace('_', '.'), haystack) if matched: return matched . start() return - 1
String searching with wildcard
546c7f89bed2e12fb300056f
[ "Algorithms" ]
https://www.codewars.com/kata/546c7f89bed2e12fb300056f
6 kyu
Given an array (or list) of scores, return the array of _ranks_ for each value in the array. The largest value has rank 1, the second largest value has rank 2, and so on. Ties should be handled by assigning the same rank to all tied values. For example: ranks([9,3,6,10]) = [2,4,3,1] and ranks([3,3,3,3,3,5,1]) = [2,2,2,2,2,1,7] because there is one 1st place value, a five-way tie for 2nd place, and one in 7th place.
algorithms
def ranks(a): sortA = sorted(a, reverse=True) return [sortA . index(s) + 1 for s in a]
Rank Vector
545f05676b42a0a195000d95
[ "Arrays", "Sorting", "Algorithms" ]
https://www.codewars.com/kata/545f05676b42a0a195000d95
6 kyu
There are a **n** balls numbered from 0 to **n-1** (0,1,2,3,etc). Most of them have the same weight, but one is heavier. Your task is to find it. Your function will receive two arguments - a `scales` object, and a ball count. The `scales` object has only one method: ```javascript getWeight(left, right) ``` ```python get_weight(left, right) ``` ```ocaml get_weight left right ``` where `left` and `right` are arrays (or lists, vectors ...) of numbers of balls to put on left and right pan respectively. If the method returns `-1` - left pan is heavier If the method returns `1` - right pan is heavier If the method returns `0` - both pans weigh the same So what makes this the "ubermaster" version of this kata? First, it's not restricted to 8 balls as in the previous versions - your solution has to work for 8-500 balls. Second, you can't use the scale any more than mathematically necessary. Here's a chart: ball count | uses ----------------- 1 | 0 2-3 | 1 4-9 | 2 10-27 | 3 28-81 | 4 82-243 | 5 244-500 | 6 Too hard? Try lower levels by [tiriana](http://www.codewars.com/users/tiriana): * [novice](http://www.codewars.com/kata/544047f0cf362503e000036e) * [conqueror](http://www.codewars.com/kata/54404a06cf36258b08000364) * [master](http://www.codewars.com/kata/find-heavy-ball-level-master)
games
def find_ball(scales, n): select = list(range(n)) while len(select) > 1: left, right, unused = select[:: 3], select[1:: 3], select[2:: 3] if len(select) % 3 == 1: unused . append(left . pop()) select = [left, unused, right][scales . get_weight(left, right) + 1] return select . pop()
Find heavy ball - level: ubermaster
545c4f7682e55d3c6e0011a1
[ "Algorithms", "Logic", "Puzzles" ]
https://www.codewars.com/kata/545c4f7682e55d3c6e0011a1
5 kyu
Maya writes weekly articles to a well known magazine, but she is missing one word each time she is about to send the article to the editor. The article is not complete without this word. Maya has a friend, Dan, and he is very good with words, but he doesn't like to just give them away. He texts Maya a number and she needs to find out the hidden word. The words can contain only the letter: ``` "a", "b", "d", "e", "i", "l", "m", "n", "o", and "t". ``` Luckily, Maya has the key: ``` "a" : 6 "b" : 1 "d" : 7 "e" : 4 "i" : 3 "l" : 2 "m" : 9 "n" : 8 "o" : 0 "t" : 5 ``` You can help Maya by writing a function that will take a number between 100 and 999999 and return a string with the word. The input is always a number, contains only the numbers in the key. The output should be always a string with one word, all lowercase. Maya won't forget to thank you at the end of her article :)
reference
def hidden(n): return "" . join("oblietadnm" [int(d)] for d in str(n))
The Hidden Word
5906a218dfeb0dbb52000005
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/5906a218dfeb0dbb52000005
7 kyu
There are 8 balls numbered from 0 to 7. Seven of them have the same weight. One is heavier. Your task is to find its number. Your function `findBall` will receive single argument - `scales` object. The `scales` object contains an internally stored array of 8 elements (indexes 0-7), each having the same value except one, which is greater. It also has a public method named `getWeight(left, right)` which takes two arrays of indexes and returns -1, 0, or 1 based on the accumulation of the values found at the indexes passed are heavier, equal, or lighter. `getWeight` returns: `-1` if **left** pan is heavier `1` if **right** pan is heavier `0` if both pans weigh the same Examples of `scales.getWeight()` usage: `scales.getWeight([3], [7])` returns `-1` if ball 3 is heavier than ball 7, `1` if ball 7 is heavier, or `0` i these balls have the same weight. `scales.getWeight([3, 4], [5, 2])` returns `-1` if weight of balls 3 and 4 is heavier than weight of balls 5 and 2 etc. So where's the catch, you may ask. Well - the scales is very old. You can use it only **TWICE** before the scale breaks. ``` if:python,ruby,crystal **Note** - Use `scales.get_weight()` in the Python, Crystal and Ruby versions. ``` ``` if:ocaml **Note** - Use `scales#get_weight` in the OCaml version. ``` ```if:c In C `findBall()` takes no argument, and `getWeight()` is accessible directly as a function instead of a method. ``` Too hard ? Try lower levels: * [novice](http://www.codewars.com/kata/544047f0cf362503e000036e) * [conqueror](http://www.codewars.com/kata/54404a06cf36258b08000364) Still too easy ? Try this kata - [ubermaster](http://www.codewars.com/kata/find-heavy-ball-level-ubermaster) (made by by [bellmyer](http://www.codewars.com/users/bellmyer))
games
def find_ball(scales): part = [[None, 0, 1], [2, 3, 4], [5, 6, 7]] res1 = scales . get_weight(part[- 1], part[1]) res2 = scales . get_weight([part[res1][- 1]], [part[res1][1]]) return part[res1][res2]
Find heavy ball - level: master
544034f426bc6adda200000e
[ "Puzzles", "Logic", "Riddles" ]
https://www.codewars.com/kata/544034f426bc6adda200000e
5 kyu
There are 8 balls numbered from 0 to 7. Seven of them have the same weight. One is heavier. Your task is to find its number. Your function ```findBall``` will receive single argument - ```scales``` object. The ```scales``` object contains an internally stored array of 8 elements (indexes 0-7), each having the same value except one, which is greater. It also has a public method named ```getWeight(left, right)``` which takes two arrays of indexes and returns -1, 0, or 1 based on the accumulation of the values found at the indexes passed are heavier, equal, or lighter. ```getWeight``` returns: ```-1``` if **left** pan is heavier ```1``` if **right** pan is heavier ```0``` if both pans weight the same Examples of ```scales.getWeight()``` usage: ```scales.getWeight([3], [7])``` returns ```-1``` if ball 3 is heavier than ball 7, ```1``` if ball 7 is heavier, or ```0``` i these balls have the same weight. ```scales.getWeight([3, 4], [5, 2])``` returns ```-1``` if weight of balls 3 and 4 is heavier than weight of balls 5 and 2 etc. So where's the catch, you may ask. Well - the scales is very old. You can use it only **3 TIMES** before the scale breaks. ``` if:python,ruby,crystal **Note** - Use `scales.get_weight()` in the Python, Crystal and Ruby versions. ``` ``` if:ocaml **Note** - Use `scales#get_weight` in the OCaml version. ``` Too easy ? Too hard ? Try other levels: * [novice](http://www.codewars.com/kata/544047f0cf362503e000036e) * [master](http://www.codewars.com/kata/544034f426bc6adda200000e)
games
def find_ball(scales): balls = [0, 1, 2, 3, 4, 5, 6, 7] while len(balls) > 1: l, r = balls[: len(balls) / / 2], balls[len(balls) / / 2:] w = scales . get_weight(l, r) balls = l if w < 0 else r return balls[0]
Find heavy ball - level: conqueror
54404a06cf36258b08000364
[ "Puzzles", "Logic" ]
https://www.codewars.com/kata/54404a06cf36258b08000364
6 kyu
### Task The __dot product__ is usually encountered in linear algebra or scientific computing. It's also called __scalar product__ or __inner product__ sometimes: > In mathematics, the __dot product__, or __scalar product__ (or sometimes __inner product__ in the context of Euclidean space), is an algebraic operation that takes two equal-length sequences of numbers (usually coordinate vectors) and returns a single number. <cite>[Wikipedia](https://en.wikipedia.org/w/index.php?title=Dot_product&oldid=629717691)</cite> In our case, we define the dot product algebraically for two vectors `a = [a1, a2, …, an]`, `b = [b1, b2, …, bn]` as dot a b = a1 * b1 + a2 * b2 + … + an * bn. Your task is to find permutations of `a` and `b`, such that `dot a b` is minimal, and return that value. For example, the dot product of `[1,2,3]` and `[4,0,1]` is minimal if we switch `0` and `1` in the second vector. ### Examples ```haskell minDot [1,2,3,4,5] [0,1,1,1,0] = 6 minDot [1,2,3,4,5] [0,0,1,1,-4] = -17 minDot [1,3,5] [4,-2,1] = -3 ``` ```javascript minDot( [1,2,3,4,5], [0,1,1,1,0] ) = 6 minDot( [1,2,3,4,5], [0,0,1,1,-4]) = -17 minDot( [1,3,5] , [4,-2,1] ) = -3 ``` ```python min_dot([1,2,3,4,5], [0,1,1,1,0] ) = 6 min_dot([1,2,3,4,5], [0,0,1,1,-4]) = -17 min_dot([1,3,5] , [4,-2,1] ) = -3 ``` ```clojure (minDot [1 2 3 4 5] [0 1 1 1 0]) ; returns 6 (minDot [1 2 3 4 5] [0 0 1 1 -4]) ; returns -17 (minDot [1 3 5] [4 -2 1]) ; returns -3 ``` ```ruby min_dot([1,2,3,4,5], [0,1,1,1,0] ) = 6 min_dot([1,2,3,4,5], [0,0,1,1,-4]) = -17 min_dot([1,3,5] , [4,-2,1] ) = -3 ``` ### Remarks If the list or array is empty, `minDot` should return 0. All arrays or lists will have the same length. Also, for the dynamically typed languages, all inputs will be valid lists or arrays, you don't need to check for `undefined`, `null` etc. Note: This kata is inspired by [GCJ 2008](https://code.google.com/codejam/contest/32016/dashboard#s=p0).
algorithms
def min_dot(a, b): return sum(x * y for (x, y) in zip(sorted(a), sorted(b, reverse=True)))
Permutations and Dot Products
5457ea88aed18536fc000a2c
[ "Linear Algebra", "Algorithms" ]
https://www.codewars.com/kata/5457ea88aed18536fc000a2c
6 kyu
You want to build a standard house of cards, but you don't know how many cards you will need. Write a program which will count the minimal number of cards according to the number of floors you want to have. For example, if you want a one floor house, you will need 7 of them (two pairs of two cards on the base floor, one horizontal card and one pair to get the first floor). Here you can see which kind of house of cards I mean: ``` One floor: /\ β€” /\/\ Four floors: /\ β€” /\/\ β€” β€” /\/\/\ β€” β€” β€” /\/\/\/\ β€” β€” β€” β€” /\/\/\/\/\ ``` (See also http://www.wikihow.com/Build-a-Tower-of-Cards to see what it looks like in real life). ## Note about floors: This kata uses the British numbering system for building floors. If you want your house of cards to have a first floor, it needs a ground floor and then a first floor above that. ### Details (Ruby & JavaScript & Python & R) The input must be an integer greater than 0, for other input raise an error. ### Details (Haskell) The input must be an integer greater than 0, for other input return `Nothing`. ### Details (COBOL) The input will be an integer. If it is inferior or equal to 0, return `-1`.
algorithms
def house_of_cards(n): assert n > 0 return (n + 1) * (3 * n + 4) / / 2
House of cards
543abbc35f0461d28f000c11
[ "Mathematics" ]
https://www.codewars.com/kata/543abbc35f0461d28f000c11
6 kyu
Zonk is an addictive dice game. In each round the player rolls 6 dice. Then (s)he composes combinations of them. Each combination gives certain points. Then player can take one or more dice combinations to their hand and re-roll remaining dice or save the score. Dice in the player's hand won't be taken into account in subsequent rolls. If no combinations can be composed - the situation is called "zonk". The player who rolled zonk loses all points in that round and the next player takes a turn. So it's up to the player to decide when to re-roll and when to stop and keep their score. Your task is simple - just evaluate the current roll and return the maximum number of points that can be scored from it. If no combinations can be made, the function should return `0` (see Note below). The function should not modify the input. _Note: a previous version of this Kata required to return "Zonk" if no combinations possible, but mixing different return types is a bad practice. For backwards compatibility, "Zonk" is accepted as a valid result and is considered zero in some languages._ There are different variations of Zonk. In this kata, we will use most common table of combinations: <table> <tr><td>Combination</td><td>Example roll</td><td>Points</td></tr> <tr><td>Straight (1,2,3,4,5 and 6)</td><td>6 3 1 2 5 4</td><td>1000 points</td></tr> <tr><td>Three pairs of any dice</td><td>2 2 4 4 1 1</td><td>750 points</td></tr> <tr><td>Three of 1</td><td>1 4 1 1</td><td>1000 points</td></tr> <tr><td>Three of 2</td><td>2 3 4 2 2</td><td>200 points</td></tr> <tr><td>Three of 3</td><td>3 4 3 6 3 2</td><td>300 points</td></tr> <tr><td>Three of 4</td><td>4 4 4</td><td>400 points</td></tr> <tr><td>Three of 5</td><td>2 5 5 5 4</td><td>500 points</td></tr> <tr><td>Three of 6</td><td>6 6 2 6</td><td>600 points</td></tr> <tr><td>Four of a kind</td><td>1 1 1 1 4 6</td><td>2 Γ— Three-of-a-kind score (in example, 2000 pts)</td></tr> <tr><td>Five of a kind</td><td>5 5 5 4 5 5</td><td>3 Γ— Three-of-a-kind score (in example, 1500 pts)</td></tr> <tr><td>Six of a kind</td><td>4 4 4 4 4 4</td><td>4 Γ— Three-of-a-kind score (in example, 1600 pts)</td></tr> <tr><td>Every 1</td><td>4 3 1 2 2</td><td>100 points</td></tr> <tr><td>Every 5</td><td>5 2 6</td><td>50 points</td></tr> </table> Each die cannot be used in multiple combinations the same time, so three pairs of 2, 3 and 5 will worth you only ``750`` points (for three pairs), not 850 (for three pairs and two fives). But you can select multiple combinations, ``2 2 2 1 6`` will worth you ``300`` points (200 for three-of-kind `2` plus 100 for single `1` die) <h2>Examples:</h2> ``` [1,2,3] => returns 100 = points from one 1 [3,4,1,1,5] => returns 250 = points from two 1 and one 5 [2,3,2,3,3,2] => returns 500 = three of 2 + three of 3 [1,1,1,1,1,5] => returns 3050 = five 1 + one 5 [2,3,4,3,6,6] => returns 0 = Zonk, no combinations here [2,2,6,6,2,2] => returns 400 = four 2, this cannot be scored as three pairs [1,3,4,3,4,1] => returns 750 = three pairs [3,3,3,3] => returns 600 = four of 3 [1,2,3,4,5] => returns 150 = it's not straight ``` Of course, in the real Zonk game it's sometimes not worth to collect all combination from a roll. Taking less dice and rerolling more remaining may be better, but this task is just to calculate the maximum possible score from a single roll. P.S. Inspired by this kata: https://www.codewars.com/kata/5270d0d18625160ada0000e4
algorithms
from collections import Counter scores = { 1: [100, 200, 1000, 2000, 3000, 4000], 2: [0, 0, 200, 400, 600, 800], 3: [0, 0, 300, 600, 900, 1200], 4: [0, 0, 400, 800, 1200, 1600], 5: [50, 100, 500, 1000, 1500, 2000], 6: [0, 0, 600, 1200, 1800, 2400] } def get_score(dice): dice = dict(Counter(dice)) dice_len = len(dice) if dice_len == 6: return 1000 if dice_len == 3 and all([x == 2 for x in dice . values()]): return 750 return sum([scores[x][y - 1] for x, y in dice . items()]) or 'Zonk'
Zonk game
53837b8c94c170e55f000811
[ "Games", "Algorithms" ]
https://www.codewars.com/kata/53837b8c94c170e55f000811
5 kyu
A circle is defined by three coplanar points that are not aligned. You will be given a list of circles and a point [xP, yP]. You have to create a function, ```count_circles()``` (Javascript ```countCircles()```), that will count the amount of circles that contains the point P inside (the circle border line is included). ```python list_of_circles = ([[[-3,2], [1,1], [6,4]], [[-3,2], [1,1], [2,6]], [[1,1], [2,6], [6,4]], [[[-3,2],[2,6], [6,4]]] point1 = [1, 4] # P1 count_circles(list_of_circles, point1) == 4 #(The four circles have P1 inside) ``` It may happen that the point may be external to all the circles. ```python list_of_circles = ([[[-3,2], [1,1], [6,4]], [[-3,2], [1,1], [2,6]], [[1,1], [2,6], [6,4]], [[-3,2],[2,6], [6,4]]] point2 = [10, 6] # P2 count_circles(list_of_circles, point2) == 0 #(P2 is exterior to the four circles) ``` The point may be in the circle line and that will be consider as an internal point of it, too. For practical purposes a given point ```P``` will be in the circle line if: <p>|r - d|/r < 10<sup>-10</sup> ```r```: radius of the circle that should be calculated from the coordinates of the three given points. ```d```: distance from the point ```P``` to the center of the circle. Again we have to do a calculation, the coordinates of the center should be calculated using the coordinates of the three given points. Let's see a case when the pints is in the circle line. ```python list_of_circles = ([[[-3,2], [1,1], [6,4]], [[-3,2], [1,1], [2,6]], [[1,1], [2,6], [6,4]], [[[-3,2],[2,6], [6,4]]] point3 = point2 = [2, 6] # P3 count_circles(list_of_circles, point3) == 4 #(P3 is an internal point of the four circles) ``` All these three cases are shown in the image below: <a href="http://imgur.com/IHMxQqH"><img src="http://i.imgur.com/IHMxQqH.png" title="source: imgur.com" /></a> Your code should be able to skip these cases: - inexistent circle when we have three points aligned - undefined circles when two or three of given points coincides. First ten people to solve it will receive extra points. Hints: This kata will give you important formulas: <FONT COLOR="235197">```Give The Center And The Radius of Circumscribed Circle. (A warm up challenge)```</FONT> <FONT COLOR="235197">```http://www.codewars.com/kata/give-the-center-and-the-radius-of-circumscribed-circle-a-warm-up-challenge```</FONT> Features of the tests: <FONT COLOR="FAF609">```N: amount of Tests``` ```n: amount of given circles``` ```x, y: coordinates of the points that define the circle``` ```xP, yP: coordinates of the point P```</FONT> <FONT COLOR="CB5151">```N = 500```</FONT> <FONT COLOR="CB5151">```10 < n < 500```</FONT> <FONT COLOR="CB5151">```-500 < x < 500, -500 < y < 500```</FONT> <FONT COLOR="CB5151">```-750 < xP < -750, -750 < yP < -750```</FONT>
reference
def circum_curvat(points): A, B, C = [complex(* p) for p in points] BC, CA, AB = B - C, C - A, A - B D = 2. * (A . real * BC + B . real * CA + C . real * AB). imag if not D: return D, D U = (abs(A) * * 2 * BC + abs(B) * * 2 * CA + abs(C) * * 2 * AB) / D radius = (abs(BC) * abs(CA) * abs(AB)) / abs(D) return - 1j * U, radius def count_circles(circles, point): return sum(abs(complex(* point) - center) < radius for center, radius in map(circum_curvat, circles))
Circles: Count the Circles Having a Given Internal Point.
57b840b2a6fdc7be02000123
[ "Fundamentals", "Data Structures", "Algorithms", "Mathematics", "Logic" ]
https://www.codewars.com/kata/57b840b2a6fdc7be02000123
5 kyu
We define the "unfairness" of a list/array as the *minimal* difference between max(x<sub>1</sub>,x<sub>2</sub>,...x<sub>k</sub>) and min(x<sub>1</sub>,x<sub>2</sub>,...x<sub>k</sub>), for all possible combinations of k elements you can take from the list/array; both minimum and maximum of an empty list/array are considered to be 0. **More info and constraints:** * lists/arrays can contain values repeated more than once, plus there are usually more combinations that generate the required minimum; * the list/array's length can be any value from 0 to 10<sup>6</sup>; * the value of k will range from 0 to the length of the list/array, * the minimum unfairness of an array/list with less than 2 elements is 0. For example: ```python min_unfairness([30,100,1000,150,60,250,10,120,20],3)==20 #from max(30,10,20)-min(30,10,20)==20, minimum unfairness in this sample min_unfairness([30,100,1000,150,60,250,10,120,20],5)==90 #from max(30,100,60,10,20)-min(30,100,60,10,20)==90, minimum unfairness in this sample min_unfairness([1,1,1,1,1,1,1,1,1,2,2,2,2,2,2],10)==1 #from max(1,1,1,1,1,1,1,1,1,2)-min(1,1,1,1,1,1,1,1,1,2)==1, minimum unfairness in this sample min_unfairness([1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],10)==0 #from max(1,1,1,1,1,1,1,1,1,1)-min(1,1,1,1,1,1,1,1,1,1)==0, minimum unfairness in this sample min_unfairness([1,1,-1],2)==0 #from max(1,1)-min(1,1)==0, minimum unfairness in this sample ``` ```ruby min_unfairness([30,100,1000,150,60,250,10,120,20],3)==20 #from max(30,10,20)-min(30,10,20)==20, minimum unfairness in this sample min_unfairness([30,100,1000,150,60,250,10,120,20],5)==90 #from max(30,100,60,10,20)-min(30,100,60,10,20)==90, minimum unfairness in this sample min_unfairness([1,1,1,1,1,1,1,1,1,2,2,2,2,2,2],10)==1 #from max(1,1,1,1,1,1,1,1,1,2)-min(1,1,1,1,1,1,1,1,1,2)==1, minimum unfairness in this sample min_unfairness([1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],10)==0 #from max(1,1,1,1,1,1,1,1,1,1)-min(1,1,1,1,1,1,1,1,1,1)==0, minimum unfairness in this sample min_unfairness([1,1,-1],2)==0 #from max(1,1)-min(1,1)==0, minimum unfairness in this sample ``` ```javascript minUnfairness([30,100,1000,150,60,250,10,120,20],3)==20 //from max(30,10,20)-min(30,10,20)==20, minimum unfairness in this sample minUnfairness([30,100,1000,150,60,250,10,120,20],5)==90 //from max(30,100,60,10,20)-min(30,100,60,10,20)==90, minimum unfairness in this sample minUnfairness([1,1,1,1,1,1,1,1,1,2,2,2,2,2,2],10)==1 //from max(1,1,1,1,1,1,1,1,1,2)-min(1,1,1,1,1,1,1,1,1,2)==1, minimum unfairness in this sample minUnfairness([1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],10)==0 //from max(1,1,1,1,1,1,1,1,1,1)-min(1,1,1,1,1,1,1,1,1,1)==0, minimum unfairness in this sample minUnfairness([1,1,-1],2)==0 //from max(1,1)-min(1,1)==0, minimum unfairness in this sample ``` ```csharp Kata.MinUnfairness([30,100,1000,150,60,250,10,120,20],3)==20 //from max(30,10,20)-min(30,10,20)==20, minimum unfairness in this sample Kata.MinUnfairness([30,100,1000,150,60,250,10,120,20],5)==90 //from max(30,100,60,10,20)-min(30,100,60,10,20)==90, minimum unfairness in this sample Kata.MinUnfairness([1,1,1,1,1,1,1,1,1,2,2,2,2,2,2],10)==1 //from max(1,1,1,1,1,1,1,1,1,2)-min(1,1,1,1,1,1,1,1,1,2)==1, minimum unfairness in this sample Kata.MinUnfairness([1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],10)==0 //from max(1,1,1,1,1,1,1,1,1,1)-min(1,1,1,1,1,1,1,1,1,1)==0, minimum unfairness in this sample Kata.MinUnfairness([1,1,-1],2)==0 //from max(1,1)-min(1,1)==0, minimum unfairness in this sample ``` **Note:** shamelessly taken from [here](https://www.hackerrank.com/challenges/angry-children), where it was created and debatably categorized and ranked.
algorithms
def min_unfairness(arr, k): arr = sorted(arr) return min(b - a for a, b in zip(arr, arr[k - 1:])) if arr and k else 0
Minimum unfairness of a list/array
577bcb5dd48e5180030004de
[ "Algorithms" ]
https://www.codewars.com/kata/577bcb5dd48e5180030004de
5 kyu
Playing ping-pong can be **really fun**! Unfortunatelly after a long and exciting play you can forget who's service turn it is. Let's do something about that! Write a function that takes the **current score** as a string separated by ```:``` sign as an only parameter and returns ```"first"``` or ```"second"``` depending on whose service turn it is. We're playing old-school, so the rule is that players take turn after every 5 services. That is until the score is 20:20 - from that moment each player serves 2 times in his turn. Examples: ``` service("0:0") // => "first" service("3:2") // => "second" service("21:20") // => "first" service("21:22") // => "second" ``` There's no need to check if the passed parameter is valid - the score will be always provided in correct syntax and you don't need to check if one of the players has already won - that won't be the case. P.S. The game ends when one of the players reaches 21 points with minimum 2-point lead. If there's a current score of 20:20, the winner will be the first player to reach 2-point lead.
algorithms
def service(score): turn = sum(int(i) for i in score . split(":")) condition = (turn % 10 < 5) if turn < 40 else (turn % 4 < 2) return "first" if condition else "second"
Ping-Pong service problem
544bdc2ec29fb3456e00064a
[ "Algorithms" ]
https://www.codewars.com/kata/544bdc2ec29fb3456e00064a
6 kyu
The goal of this Kata is to return the greatest distance of index positions between matching number values in an array or 0 if there are no matching values. Example: In an array with the values `[0, 2, 1, 2, 4, 1]` the greatest index distance is between the matching '1' values at index 2 and 5. Executing `greatestDistance`/`greatest_distance`/`GreatestDistance` with this array would return 3. (i.e. 5 - 2) Here are some extra examples: ``` [0, 2, 1, 2, 4, 1] => 3 (1's at indices 2 and 5) [9, 7, 1, 2, 3, 7, 0, -1, -2] => 4 (7's at indices 1 and 5) [0, 7, 0, 2, 3, 7, 0, -1, -2] => 6 (0's at indices 0 and 6) [1, 2, 3, 4] => 0 (no repeated elements) ``` This is based on a Kata I had completed only to realize I has misread the instructions. I enjoyed solving the problem I thought it was asking me to complete so I thought I'd add a new Kata for others to enjoy. There are no tricks in this one, good luck!
algorithms
def greatest_distance(arr): return max(i - arr . index(x) for i, x in enumerate(arr))
Greatest Position Distance Between Matching Array Values
5442e4fc7fc447653a0000d5
[ "Algorithms" ]
https://www.codewars.com/kata/5442e4fc7fc447653a0000d5
6 kyu
In another Kata I came across a weird `sort` function to implement. We had to sort characters as usual ( 'A' before 'Z' and 'Z' before 'a' ) except that the `numbers` had to be sorted **after** the `letters` ( '0' after 'z') !!! <p style='font-size:smaller'>(After a couple of hours trying to solve this unusual-sorting-kata I discovered final tests used **usual** sort (digits **before** letters :-)</p> So, the `unusualSort/unusual_sort` function you'll have to code will sort `letters` as usual, but will put `digits` (or one-digit-long `numbers` ) **after** `letters`. ## Examples ```javascript unusualSort(["a","z","b"]) // -> ["a","b","z"] as usual unusualSort(["a","Z","B"]) // -> ["B","Z","a"] as usual //... but ... unusualSort(["1","z","a"]) // -> ["a","z","1"] unusualSort(["1","Z","a"]) // -> ["Z","a","1"] unusualSort([3,2,1"a","z","b"]) // -> ["a","b","z",1,2,3] unusualSort([3,"2",1,"a","c","b"]) // -> ["a","b","c",1,"2",3] ``` ```python unusual_sort(["a","z","b"]) # -> ["a","b","z"] as usual unusual_sort(["a","Z","B"]) # -> ["B","Z","a"] as usual //... but ... unusual_sort(["1","z","a"]) # -> ["a","z","1"] unusual_sort(["1","Z","a"]) # -> ["Z","a","1"] unusual_sort([3,2,1"a","z","b"]) # -> ["a","b","z",1,2,3] unusual_sort([3,"2",1,"a","c","b"]) # -> ["a","b","c",1,"2",3] ``` ```ruby unusual_sort(["a","z","b"]) # -> ["a","b","z"] as usual unusual_sort(["a","Z","B"]) # -> ["B","Z","a"] as usual //... but ... unusual_sort(["1","z","a"]) # -> ["a","z","1"] unusual_sort(["1","Z","a"]) # -> ["Z","a","1"] unusual_sort([3,2,1"a","z","b"]) # -> ["a","b","z",1,2,3] unusual_sort([3,"2",1,"a","c","b"]) # -> ["a","b","c",1,"2",3] ``` **Note**: `digits` will be sorted **after** "`same-digit-numbers`", eg: `1` is before `"1"`, `"2"` after `2`. ```javascript unusualSort([3,"2",1,"1","3",2]) // -> [1,"1",2,"2",3,"3"] ``` ```python unusual_sort([3,"2",1,"1","3",2]) # -> [1,"1",2,"2",3,"3"] ``` ```ruby unusual_sort([3,"2",1,"1","3",2]) # -> [1,"1",2,"2",3,"3"] ``` You may assume that **argument** will always be an `array/list` of **characters** or **one-digit-long numbers**.
reference
def unusual_sort(array): return sorted(array, key=lambda x: (str(x). isdigit(), str(x), - isinstance(x, int)))
UN-usual Sort
5443b8857fc4473cb90008e4
[ "Sorting", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5443b8857fc4473cb90008e4
6 kyu