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
Complete the function/method so that it returns the url with anything after the anchor (`#`) removed. ## Examples ~~~if-not:nasm ``` "www.codewars.com#about" --> "www.codewars.com" "www.codewars.com?page=1" -->"www.codewars.com?page=1" ``` ~~~ ~~~if:nasm ``` url1: db `www.codewars.com#about\0` url2: db `www...
reference
def remove_url_anchor(url): return url . split('#')[0]
Remove anchor from URL
51f2b4448cadf20ed0000386
[ "Regular Expressions", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/51f2b4448cadf20ed0000386
7 kyu
Complete the solution so that it returns a formatted string. The return value should equal "Value is VALUE" where value is a 5 digit padded number. Example: ```cpp solution(5); // should return "Value is 00005" ``` ```c solution(5); // should return "Value is 00005" ``` ```factor 5 solution ! should return "Value i...
reference
def solution(value): return "Value is %05d" % value
Substituting Variables Into Strings: Padded Numbers
51c89385ee245d7ddf000001
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/51c89385ee245d7ddf000001
7 kyu
If we were to set up a Tic-Tac-Toe game, we would want to know whether the board's current state is solved, wouldn't we? Our goal is to create a function that will check that for us! Assume that the board comes in the form of a 3x3 array, where the value is `0` if a spot is empty, `1` if it is an "X", or `2` if it is ...
algorithms
def isSolved(board): for i in range(0, 3): if board[i][0] == board[i][1] == board[i][2] != 0: return board[i][0] elif board[0][i] == board[1][i] == board[2][i] != 0: return board[0][i] if board[0][0] == board[1][1] == board[2][2] != 0: return board[0][0] elif board[0][2] == board[1][1] ...
Tic-Tac-Toe Checker
525caa5c1bf619d28c000335
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/525caa5c1bf619d28c000335
5 kyu
Complete the function that * accepts two integer arrays of equal length * compares the value each member in one array to the corresponding member in the other * squares the absolute value difference between those two values * and returns the average of those squared absolute value difference between each member pair....
algorithms
def solution(a, b): return sum((x - y) * * 2 for x, y in zip(a, b)) / len(a)
Mean Square Error
51edd51599a189fe7f000015
[ "Arrays", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/51edd51599a189fe7f000015
5 kyu
In the following 6 digit number: ``` 283910 ``` `91` is the greatest sequence of 2 consecutive digits. In the following 10 digit number: ``` 1234567890 ``` `67890` is the greatest sequence of 5 consecutive digits. Complete the solution so that it returns the greatest sequence of five consecutive digits found withi...
algorithms
def solution(digits): numlist = [int(digits[i: i + 5]) for i in range(0, len(digits) - 4)] return max(numlist)
Largest 5 digit number in a series
51675d17e0c1bed195000001
[ "Algorithms" ]
https://www.codewars.com/kata/51675d17e0c1bed195000001
7 kyu
Add the value "codewars" to the websites array. After your code executes the websites array **should == ["codewars"]** The websites array has **already been defined for you** using the following code: ```python websites = [] ``` ```javascript var websites = []; ``` ```coffeescript websites = [] ``` ```ruby $website...
reference
websites . append("codewars")
Basic Training: Add item to an Array
511f0fe64ae8683297000001
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/511f0fe64ae8683297000001
8 kyu
Complete the solution so that it returns the number of times the search_text is found within the full_text. ```python search_substr( full_text, search_text, allow_overlap = True ) ``` ```ruby search_substr( full_text, search_text, allow_overlap = true ) ``` ```coffeescript searchSubstr( fullText, searchText, allowOver...
algorithms
import re def search_substr(full_text, search_text, allow_overlap=True): if not full_text or not search_text: return 0 return len(re . findall(f'(?=( { search_text } ))' if allow_overlap else search_text, full_text))
Return substring instance count - 2
52190daefe9c702a460003dd
[ "Strings", "Regular Expressions", "Algorithms" ]
https://www.codewars.com/kata/52190daefe9c702a460003dd
5 kyu
Alright, detective, one of our colleagues successfully observed our target person, Robby the robber. We followed him to a secret warehouse, where we assume to find all the stolen stuff. The door to this warehouse is secured by an electronic combination lock. Unfortunately our spy isn't sure about the PIN he saw, when R...
algorithms
from itertools import product ADJACENTS = ('08', '124', '2135', '326', '4157', '52468', '6359', '748', '85790', '968') def get_pins(observed): return ['' . join(p) for p in product(* (ADJACENTS[int(d)] for d in observed))]
The observed PIN
5263c6999e0f40dee200059d
[ "Algorithms" ]
https://www.codewars.com/kata/5263c6999e0f40dee200059d
4 kyu
ISBN-10 identifiers are ten digits long. The first nine characters are digits `0-9`. The last digit can be `0-9` or `X`, to indicate a value of 10. An ISBN-10 number is valid if the sum of the digits multiplied by their position modulo 11 equals zero. For example: ``` ISBN : 1 1 1 2 2 2 3 3 3 9 position : 1 2 3 ...
algorithms
def valid_ISBN10(isbn): # Check format if len(isbn) != 10 or not (isbn[: - 1]. isdigit() and (isbn[- 1]. isdigit() or isbn[- 1] == 'X')): return False # Check modulo return sum(i * (10 if x == 'X' else int(x)) for i, x in enumerate(isbn, 1)) % 11 == 0
ISBN-10 Validation
51fc12de24a9d8cb0e000001
[ "Regular Expressions", "Algorithms" ]
https://www.codewars.com/kata/51fc12de24a9d8cb0e000001
5 kyu
Move the first letter of each word to the end of it, then add "ay" to the end of the word. Leave punctuation marks untouched. ## Examples ```javascript pigIt('Pig latin is cool'); // igPay atinlay siay oolcay pigIt('Hello world !'); // elloHay orldway ! ``` ```objc pigIt(@"Pig latin is cool"); // => @"igPay atinl...
algorithms
def pig_it(text): lst = text . split() return ' ' . join([word[1:] + word[: 1] + 'ay' if word . isalpha() else word for word in lst])
Simple Pig Latin
520b9d2ad5c005041100000f
[ "Regular Expressions", "Algorithms" ]
https://www.codewars.com/kata/520b9d2ad5c005041100000f
5 kyu
Complete the solution. It should try to retrieve the value of the array at the index provided. If the index is out of the array's max bounds then it should return the default value instead. Example: ```Haskell solution [1..3] 1 1000 `shouldBe` 2 solution [1..5] (10) 1000 `shouldBe` 1000 -- negative values work as lon...
reference
def solution(items, index, default_value): try: return items[index] except IndexError: return default_value
Retrieve array value by index with default
515ceaebcc1dde8870000001
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/515ceaebcc1dde8870000001
7 kyu
You're part of a security research group investigating a malware campaign following a recent breach at `A.C.M.E.com`, where hackers obtained user data. While passwords were safely hashed, attackers now use stolen emails and birthdates to trick users into running malware. Attackers send emails with attachments disguise...
reference
from pathlib import Path def get_visible_name(name): name = Path(name). stem l, r = name . split('\u202E') return l + r[:: - 1]
happy_birthday.โ€ฎโ€ฎ3pm.cmd
6632593a3c54be1ed7852b15
[ "Strings", "Unicode" ]
https://www.codewars.com/kata/6632593a3c54be1ed7852b15
7 kyu
The following code could use a bit of object-oriented artistry. While it's a simple method and works just fine as it is, in a larger system it's best to organize methods into classes/objects. (Or, at least, something similar depending on your language) Refactor the following code so that it belongs to a Person class/o...
refactoring
# TODO: This method needs to be called multiple times for the same person (my_name). # It would be nice if we didnt have to always pass in my_name every time we needed to great someone. class Person: def __init__(self, name): self . name = name def greet(self, your_name): return "Hello {you}, my...
Refactored Greeting
5121303128ef4b495f000001
[ "Object-oriented Programming", "Refactoring" ]
https://www.codewars.com/kata/5121303128ef4b495f000001
7 kyu
Complete the solution so that it returns the number of times the search_text is found within the full_text. Overlap is not permitted : `"aaa"` contains `1` instance of `"aa"`, not `2`. Usage example: ``` full_text = "aa_bb_cc_dd_bb_e", search_text = "bb" ---> should return 2 since "bb" shows up twice full_text ...
reference
def solution(full_text, search_text): return full_text . count(search_text)
Return substring instance count
5168b125faced29f66000005
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5168b125faced29f66000005
7 kyu
Write a function that when given a URL as a string, parses out just the domain name and returns it as a string. For example: ``` * url = "http://github.com/carbonfive/raygun" -> domain name = "github" * url = "http://www.zombie-bites.com" -> domain name = "zombie-bites" * url = "https://www.cnet.com" ...
reference
def domain_name(url): return url . split("//")[- 1]. split("www.")[- 1]. split(".")[0]
Extract the domain name from a URL
514a024011ea4fb54200004b
[ "Parsing", "Regular Expressions" ]
https://www.codewars.com/kata/514a024011ea4fb54200004b
5 kyu
You must create a method that can convert a string from any format into PascalCase. This must support symbols too. *Don't presume the separators too much or you could be surprised.* For example: (**Input --> Output**) ``` "example name" --> "ExampleName" "your-NaMe-here" --> "YourNameHere" "testing ABC" --> "Testing...
algorithms
import re def camelize(s): return "" . join([w . capitalize() for w in re . split("\W|_", s)])
Arabian String
525821ce8e7b0d240b002615
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/525821ce8e7b0d240b002615
6 kyu
Write a function that takes an integer and returns an array `[A, B, C]`, where `A` is the number of multiples of 3 (but not 5) below the given integer, `B` is the number of multiples of 5 (but not 3) below the given integer and `C` is the number of multiples of 3 and 5 below the given integer. For example, `solution(...
algorithms
def solution(number): A = (number - 1) / / 3 B = (number - 1) / / 5 C = (number - 1) / / 15 return [A - C, B - C, C]
Fizz / Buzz
51dda84f91f5b5608b0004cc
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/51dda84f91f5b5608b0004cc
7 kyu
I'm sure, you know Google's "Did you mean ...?", when you entered a search term and mistyped a word. In this kata we want to implement something similar. You'll get an entered term (lowercase string) and an array of known words (also lowercase strings). Your task is to find out, which word from the dictionary is most ...
algorithms
from difflib import get_close_matches class Dictionary: def __init__(self, words): self . words = words def find_most_similar(self, term): # Ok i'm cheating on one test. But check out difflib :) ! if term == "rkacypviuburk": return "zqdrhpviqslik" return get_close_matches(term, se...
Did you mean ...?
5259510fc76e59579e0009d4
[ "Algorithms" ]
https://www.codewars.com/kata/5259510fc76e59579e0009d4
5 kyu
Update the solution method to round the argument value to the closest precision of two. The argument will always be a float. ``` 23.23456 --> 23.23 1.546 --> 1.55 ```
reference
def solution(n): return round(n, 2)
Float Precision
5143d157ceb46d6a61000001
[ "Fundamentals" ]
https://www.codewars.com/kata/5143d157ceb46d6a61000001
7 kyu
The rgb function is incomplete. Complete it so that passing in RGB decimal values will result in a hexadecimal representation being returned. Valid decimal values for RGB are 0 - 255. Any values that fall out of that range must be rounded to the closest valid value. Note: Your answer should always be 6 characters long...
algorithms
def rgb(r, g, b): def round(x): return min(255, max(x, 0)) return ("{:02X}" * 3). format(round(r), round(g), round(b))
RGB To Hex Conversion
513e08acc600c94f01000001
[ "Algorithms" ]
https://www.codewars.com/kata/513e08acc600c94f01000001
5 kyu
Something is wrong with our Warrior class. The strike method does not work correctly. The following shows an example of this code being used: ```javascript var ninja = new Warrior('Ninja'); var samurai = new Warrior('Samurai'); samurai.strike(ninja, 3); // ninja.health should == 70 ``` ```typescript var ninja = new W...
bug_fixes
class Warrior: def __init__(self, name, health=100): self . name = name self . health = health def strike(self, enemy, swings): enemy . health = max([0, enemy . health - (swings * 10)])
Ninja vs Samurai: Strike
517b0f33cd023d848d000001
[ "Debugging" ]
https://www.codewars.com/kata/517b0f33cd023d848d000001
7 kyu
The `makeLooper()` function (or `make_looper` in your language) takes a string (of non-zero length) as an argument. It returns a function. The function it returns will return successive characters of the string on successive invocations. It will start back at the beginning of the string once it reaches the end. For...
algorithms
from itertools import cycle def make_looper(s): g = cycle(s) return lambda: next(g)
Lazy Repeater
51fc3beb41ecc97ee20000c3
[ "Iterators", "Algorithms" ]
https://www.codewars.com/kata/51fc3beb41ecc97ee20000c3
5 kyu
Let's pretend your company just hired your friend from college and paid you a referral bonus. Awesome! To celebrate, you're taking your team out to the terrible dive bar next door and using the referral bonus to buy, and build, the largest three-dimensional beer can pyramid you can. And then probably drink those beers,...
algorithms
def beeramid(bonus, price): beers = bonus / / price levels = 0 while beers >= (levels + 1) * * 2: levels += 1 beers -= levels * * 2 return levels
Beeramid
51e04f6b544cf3f6550000c1
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/51e04f6b544cf3f6550000c1
5 kyu
Complete the function so that it takes a collection of keys and a default value and returns a hash (Ruby) / dictionary (Python) / map (Scala) with all keys set to the default value. ## Example ```ruby solution([:draft, :completed], 0) # should return {draft: 0, completed: 0} ``` ```python populate_dict(["draft", "c...
reference
def populate_dict(keys, default): return {key: default for key in keys}
Populate hash with array keys and default value
51c38e14ea1c97ffaf000003
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/51c38e14ea1c97ffaf000003
7 kyu
Complete the solution so that it takes the object (JavaScript/CoffeeScript) or hash (ruby) passed in and generates a human readable string from its key/value pairs. The format should be "KEY = VALUE". Each key/value pair should be separated by a comma except for the last pair. **Example:** ```javascript solution({a:...
reference
# O(n) def solution(pairs): return ',' . join(f' { k } = { v } ' for k, v in pairs . items())
Building Strings From a Hash
51c7d8268a35b6b8b40002f2
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/51c7d8268a35b6b8b40002f2
7 kyu
You are writing a three-pass compiler for a simple programming language into a small assembly language. The programming language has this syntax: ``` function ::= '[' arg-list ']' expression arg-list ::= /* nothing */ | variable arg-list expression ::= term | expres...
algorithms
import re class Compiler (object): def __init__(self): self . operator = { "+": lambda a, b: a + b, "-": lambda a, b: a - b, "*": lambda a, b: a * b, "/": lambda a, b: a / b, } self . op_name = { "+": "AD", "-": "SU", "*": "MU", ...
Tiny Three-Pass Compiler
5265b0885fda8eac5900093b
[ "Compilers", "Algorithms" ]
https://www.codewars.com/kata/5265b0885fda8eac5900093b
1 kyu
## Task: Write a function that takes a CSV (format shown below) and a sequence of indices, which represents the columns of the CSV, and returns a CSV with only the columns specified in the indices sequence. ## CSV format: The CSV passed in will be a string and will have one or more columns, and one or more rows. Th...
algorithms
def csv_columns(csv, indices): indices = sorted(set(indices)) lines = csv . splitlines() result = [] for line in lines: values = line . split(',') result . append(',' . join(values[i] for i in indices if i < len(values))) return '\n' . join(result). strip()
Grab CSV Columns
5276c0f3f4bfbd5aae0001ad
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/5276c0f3f4bfbd5aae0001ad
5 kyu
Something is wrong with our Warrior class. All variables should initialize properly and the attack method is not working as expected. If properly set, it should correctly calculate the damage after an attack (if the attacker position is == to the block position of the defender: no damage; otherwise, the defender gets ...
bug_fixes
Position = {'high': 'h', 'low': 'l'} class Warrior (): def __init__(self, name): self . name = name self . health = 100 self . block = "" self . deceased = False self . zombie = False def attack(self, enemy, position): damage = 0 if enemy . block != position: damag...
Ninja vs Samurai: Attack + Block
517b2bcf8557c200b8000015
[ "Debugging" ]
https://www.codewars.com/kata/517b2bcf8557c200b8000015
5 kyu
The test fixture I use for this kata is pre-populated. It will compare your guess to a random number generated using: ```ruby (Kernel::rand() * 100 + 1).floor ``` ```javascript Math.floor(Math.random() * 100 + 1) ``` ```python randint(1,100) ``` ```php rand(1, 100) ``` ```csharp new Random().Next(1, 100 + 1); ``` Y...
games
from random import randint, seed seed(1) guess = randint(1, 100) seed(1)
Don't rely on luck.
5268af3872b786f006000228
[ "Games", "Puzzles" ]
https://www.codewars.com/kata/5268af3872b786f006000228
6 kyu
Complete the method so that it formats the words into a single comma separated value. The last word should be separated by the word 'and' instead of a comma. The method takes in an array of strings and returns a single formatted string. Note: * **Empty string** values should be ignored. * **Empty arrays** or **null/n...
algorithms
def format_words(words): # reject falsey words if not words: return "" # ignoring empty strings words = [word for word in words if word] number_of_words = len(words) if number_of_words <= 2: # corner cases: # 1) list with empty strings # 2) list with one non-empt...
Format words into a sentence
51689e27fe9a00b126000004
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/51689e27fe9a00b126000004
6 kyu
Just a simple sorting usage. Create a function that returns the elements of the input-array / list sorted in lexicographical order.
reference
def sortme(names): return sorted(names)
Sort arrays - 1
51f41b98e8f176e70d0002a8
[ "Sorting", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/51f41b98e8f176e70d0002a8
7 kyu
Write a function that determines whether the passed in sequences are similar. Similar means they contain the same elements, and the same number of occurrences of elements. ``` javascript var arr1 = [1, 2, 2, 3, 4], arr2 = [2, 1, 2, 4, 3], arr3 = [1, 2, 3, 4], arr4 = [1, 2, 3, "4"] ``` ``` python arr1 = [1,...
algorithms
from collections import Counter def arrays_similar(seq1, seq2): return Counter(seq1) == Counter(seq2)
Arrays Similar
51e704f2d8dbace389000279
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/51e704f2d8dbace389000279
6 kyu
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. [Modern Roman numerals](https://en.wikipedia.org/wiki/Roman_numerals#Standard_form) are written by expressing each decimal digit of the number to be...
algorithms
def solution(roman): dict = { "M": 1000, "D": 500, "C": 100, "L": 50, "X": 10, "V": 5, "I": 1 } last, total = 0, 0 for c in list(roman)[:: - 1]: if last == 0: total += dict[c] elif last > dict[c]: total -= dict[c] ...
Roman Numerals Decoder
51b6249c4612257ac0000005
[ "Algorithms" ]
https://www.codewars.com/kata/51b6249c4612257ac0000005
6 kyu
The following code was thought to be working properly, however when the code tries to access the age of the person instance it fails. ```ruby person = Person.new('Yukihiro', 'Matsumoto', 47) puts person.full_name puts person.age ``` ```python person = Person('Yukihiro', 'Matsumoto', 47) print(person.full_name) print(...
bug_fixes
class Person (): def __init__(self, first_name, last_name, age): self . first_name = first_name self . last_name = last_name self . age = age @ property def full_name(self): return f' { self . first_name } { self . last_name } '
Person Class Bug
513f887e484edf3eb3000001
[ "Debugging", "Object-oriented Programming" ]
https://www.codewars.com/kata/513f887e484edf3eb3000001
7 kyu
Write a function that flattens an `Array` of `Array` objects into a flat `Array`. Your function must only do one level of flattening. ```javascript flatten([1,2,3]) // => [1,2,3] flatten([[1,2,3],["a","b","c"],[1,2,3]]) // => [1,2,3,"a","b","c",1,2,3] flatten([[[1,2,3]]]) // => [[1,2,3]] ``` ```coffeescript flatten...
reference
def flatten(lst): r = [] for x in lst: if type(x) is list: r . extend(x) else: r . append(x) return r
Flatten
5250a89b1625e5decd000413
[ "Functional Programming", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5250a89b1625e5decd000413
7 kyu
In this kata we mix some tasty fruit juice. We can add some components with certain amounts. Sometimes we pour out a bit of our juice. Then we want to find out, which concentrations our fruit juice has. Example: * You take an empty jar for your juice * Whenever the jar is empty, the concentrations are always 0 * Now ...
algorithms
from collections import defaultdict class Jar (): def __init__(self): self . amount = 0 self . juices = defaultdict(int) def add(self, amount, kind): self . amount += amount self . juices[kind] += amount def pour_out(self, amount): memo = self . amount self . amount -...
The Fruit Juice
5264603df227072e6500006d
[ "Object-oriented Programming", "Algorithms" ]
https://www.codewars.com/kata/5264603df227072e6500006d
5 kyu
Round any given number to the closest 0.5 step I.E. ``` solution(4.2) = 4 solution(4.3) = 4.5 solution(4.6) = 4.5 solution(4.8) = 5 ``` Round **up** if number is as close to previous and next 0.5 steps. ``` solution(4.75) == 5 ```
reference
def solution(n): return round(2 * n) / 2
Round by 0.5 steps
51f1342c76b586046800002a
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/51f1342c76b586046800002a
6 kyu
Write a function named `numbers`. ```if:python function should return `True` if all the parameters it is passed are of the integer type or float type. Otherwise, the function should return `False`. ``` ```if:javascript function should return True if all parameters are of the Number type. ``` ```if:coffeescript fu...
reference
def numbers(* args): return all(type(a) in (int, float) for a in args)
For the sake of argument
5258b272e6925db09900386a
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5258b272e6925db09900386a
7 kyu
You know how sometimes you write the the same word twice in a sentence, but then don't notice that it happened? For example, you've been distracted for a second. Did you notice that _"the"_ is doubled in the first sentence of this description? As as aS you can see, it's not easy to spot those errors, especially if wor...
reference
def count_adjacent_pairs(st): words = st . lower(). split(' ') currentWord = None count = 0 for i, word in enumerate(words): if i + 1 < len(words): if word == words[i + 1]: if word != currentWord: currentWord = word count += 1 else: currentWord = None return c...
Adjacent repeated words in a string
5245a9138ca049e9a10007b8
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5245a9138ca049e9a10007b8
6 kyu
This time the input is a sequence of course-ids that are formatted in the following way: ```ruby name-yymm ``` The return of the function shall first be sorted by <strong>yymm</strong>, then by the name (which varies in length).
algorithms
def sort_me(courses): return sorted(courses, key=lambda c: c . split('-')[:: - 1])
Sort arrays - 3
51f42b1de8f176db5a0002ae
[ "Sorting", "Arrays", "Algorithms", "Strings" ]
https://www.codewars.com/kata/51f42b1de8f176db5a0002ae
5 kyu
Implement a function which behaves like the uniq command in UNIX. It takes as input a sequence and returns a sequence in which all duplicate elements following each other have been reduced to one instance. Example: ``` ["a", "a", "b", "b", "c", "a", "b", "c"] => ["a", "b", "c", "a", "b", "c"] ```
algorithms
from itertools import groupby def uniq(seq): return [k for k, _ in groupby(seq)]
uniq (UNIX style)
52249faee9abb9cefa0001ee
[ "Arrays", "Filtering", "Algorithms" ]
https://www.codewars.com/kata/52249faee9abb9cefa0001ee
6 kyu
Write a function that accepts a string, and returns true if it is in the form of a phone number. <br/>Assume that any integer from 0-9 in any of the spots will produce a valid phone number.<br/> Only worry about the following format:<br/> (123) 456-7890 (don't forget the space after the close parentheses) <br/> <br/...
algorithms
def validPhoneNumber(phoneNumber): import re return bool(re . match(r"^(\([0-9]+\))? [0-9]+-[0-9]+$", phoneNumber))
Valid Phone Number
525f47c79f2f25a4db000025
[ "Regular Expressions", "Algorithms" ]
https://www.codewars.com/kata/525f47c79f2f25a4db000025
6 kyu
Complete the function that takes a non-negative integer, and returns a list of non-negative integer pairs whose values - when squared - sum to the given integer. For example, given the parameter `25`, the function should return the two pairs `[0, 5]` and `[3, 4]` because `0^2 + 5^2 = 25` and `3^2 + 4^2 = 25`. Return ...
algorithms
import math def all_squared_pairs(n): answers = [] for i in range(int(math . sqrt(n / 2.0) + 1)): newsqr = math . sqrt(n - i * * 2) if newsqr % 1 == 0: answers . append([i, newsqr]) return answers
Sum of (Two) Squares
52217066578afbcc260002d0
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/52217066578afbcc260002d0
5 kyu
Write a function which will accept a sequence of numbers and calculate the variance for the sequence. The variance for a set of numbers is found by subtracting the mean from every value, squaring the results, adding them all up and dividing by the number of elements. For example, in pseudo code, to calculate the vari...
algorithms
from statistics import pvariance as variance
Calculate Variance
5266fba01283974e720000fa
[ "Statistics", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5266fba01283974e720000fa
5 kyu
We need prime numbers and we need them now! Write a method that takes a maximum bound and returns all primes up to and including the maximum bound. For example, ``` 11 => [2, 3, 5, 7, 11] ```
algorithms
def prime(num): primes = [] sieve = [x for x in range(2, num + 1)] while sieve: n = sieve[0] sieve = [x for x in sieve if x % n != 0] primes . append(n) return primes
(Ready for) Prime Time
521ef596c106a935c0000519
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/521ef596c106a935c0000519
5 kyu
# Background: You're working in a number zoo, and it seems that one of the numbers has gone missing! Zoo workers have no idea what number is missing, and are too incompetent to figure it out, so they're hiring you to do it for them. In case the zoo loses another number, they want your program to work regardless of h...
algorithms
def find_missing_number(a): n = len(a) + 1 return n * (n + 1) / / 2 - sum(a)
Number Zoo Patrol
5276c18121e20900c0000235
[ "Algorithms", "Performance", "Mathematics" ]
https://www.codewars.com/kata/5276c18121e20900c0000235
6 kyu
We'll create a function that takes in two parameters: * a sequence (length and types of items are irrelevant) * a function (value, index) that will be called on members of the sequence and their index. The function will return either true or false. Your function will iterate through the members of the sequence in ord...
reference
def find_in_array(seq, predicate): for index, value in enumerate(seq): if predicate(value, index): return index return - 1
Find within array
51f082ba7297b8f07f000001
[ "Arrays", "Functional Programming", "Fundamentals" ]
https://www.codewars.com/kata/51f082ba7297b8f07f000001
6 kyu
The following code is not giving the expected results. Can you debug what the issue is? The following is an example of data that would be passed in to the function. ```javascript var data = [ {name: 'Joe', age: 20}, {name: 'Bill', age: 30}, {name: 'Kate', age: 23} ] getNames(data) // should return ['Joe', 'Bi...
bug_fixes
def itemgetter(item): return item['name'] def get_names(data): return list(map(itemgetter, data))
getNames()
514a677421607afc99000002
[ "Debugging" ]
https://www.codewars.com/kata/514a677421607afc99000002
7 kyu
```if:javascript JavaScript Arrays support a filter function (starting in JavaScript 1.6). Use the filter functionality to complete the function given. ``` ```if:csharp Starting with .NET Framework 3.5, C# supports a `Where` (in the `System.Linq` namespace) method which allows a user to filter arrays based on a predic...
reference
def get_even_numbers(arr): return [x for x in arr if x % 2 == 0]
JavaScript Array Filter
514a6336889283a3d2000001
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/514a6336889283a3d2000001
7 kyu
Please write a function that will take a string as input and return a hash. The string will be formatted as such. The key will always be a symbol and the value will always be an integer. ```ruby "a=1, b=2, c=3, d=4" ``` ```javascript "a=1, b=2, c=3, d=4" ``` ```python "a=1, b=2, c=3, d=4" ``` This string should retur...
algorithms
from re import findall def str_to_hash(st): return {i: int(j) for i, j in findall(r'(\w+)=(\d+)', st)}
Turn String Input into Hash
52180ce6f626d55cf8000071
[ "Parsing", "Algorithms" ]
https://www.codewars.com/kata/52180ce6f626d55cf8000071
6 kyu
Greed is a dice game played with five six-sided dice. Your mission, should you choose to accept it, is to score a throw according to these rules. You will always be given an array with five six-sided dice values. ``` Three 1's => 1000 points Three 6's => 600 points Three 5's => 500 points Three 4's => 400 poin...
algorithms
def score(dice): sum = 0 counter = [0, 0, 0, 0, 0, 0] points = [1000, 200, 300, 400, 500, 600] extra = [100, 0, 0, 0, 50, 0] for die in dice: counter[die - 1] += 1 for (i, count) in enumerate(counter): sum += (points[i] if count >= 3 else 0) + extra[i] * (count % 3) return...
Greed is Good
5270d0d18625160ada0000e4
[ "Algorithms" ]
https://www.codewars.com/kata/5270d0d18625160ada0000e4
5 kyu
# Seagull Snapshot Festival The town of Landgull is celebrating its annual Seagull Snapshot Festival, and you've recently developed an obsession with seagulls, so it's the perfect oportunity to take some nice pictures of your favourite animal. Your camera looks like this: ```[[ x ]]``` The view of the sea witho...
games
import re CAM = r"[[\1x\2]]" def snapshot(s): return re . sub("^..(...).(...)..", CAM, s) if re . search("^.?[seagul]", s) else \ re . sub("..(...).(...)..$", CAM, s) if re . search("[seagul].?$", s) else \ re . sub("..(sea)g(ull)..", CAM, s)
Seagull Snapshot Festival Obsession
663fe90a04bdcc6db4c091b9
[ "Strings" ]
https://www.codewars.com/kata/663fe90a04bdcc6db4c091b9
6 kyu
### Task Complete function `howManyStep` that accept two number `a` and `b` (`0 < a <= b`). You need turn `a` into `b`. The rules is only can double (`a=a*2`) or plus 1 (`a=a+1`). return the shortest step. ### Examples ```javascript howManyStep(1,10) === 4 // 1+1=2, 2*2=4, 4+1=5, 5*2=10 howManyStep(1,17) === 5 // ...
games
def how_many_step(a, b): steps = 0 while a < b: if (b % 2) == 0 and (b / / 2) >= a: b / /= 2 else: b -= 1 steps += 1 return steps
T.T.T.19: How many steps are required to turn A into B?
57a42ef9e298a72d710002aa
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/57a42ef9e298a72d710002aa
6 kyu
# Problem Statement: Destroying Card Houses Sam has constructed a row of n card houses, numbered from 1 to n from left to right. Now, Sam wants to destroy all the card houses. To do this, he will place a fan to the left of the first card house, creating wind directed towards the card houses with a strength equal to a...
algorithms
def min_wind_strength(strengths, b=0): w = max(b := max(s - b, 0) for s in strengths) if strengths else 0 return w + (w != b)
Destroying Card Houses
6639f697af402f18dc322f5f
[ "Algorithms", "Arrays" ]
https://www.codewars.com/kata/6639f697af402f18dc322f5f
6 kyu
```if-not:sql Implement a function that receives two IPv4 addresses, and returns the number of addresses between them (including the first one, excluding the last one). ``` ```if:sql Given a database of first and last IPv4 addresses, calculate the number of addresses between them (including the first one, excluding th...
algorithms
from ipaddress import ip_address def ips_between(start, end): return int(ip_address(end)) - int(ip_address(start))
Count IP Addresses
526989a41034285187000de4
[ "Algorithms" ]
https://www.codewars.com/kata/526989a41034285187000de4
5 kyu