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 |
|---|---|---|---|---|---|---|---|
Two red beads are placed between every two blue beads. There are N blue beads. After looking at the arrangement below work out the number of red beads.
<p>
<font color="blue">@</font>
<font color="red">@</font><font color="red">@</font>
<font color="blue">@</font>
<font color="red">@</font><font color="red">@</font>
<f... | reference | def count_red_beads(nb):
return max(0, 2 * (nb - 1))
| Simple beads count | 58712dfa5c538b6fc7000569 | [
"Fundamentals"
] | https://www.codewars.com/kata/58712dfa5c538b6fc7000569 | 7 kyu |
Count the number of divisors of a positive integer `n`.
Random tests go up to `n = 500000`.
### Examples (input --> output)
```
4 --> 3 // we have 3 divisors - 1, 2 and 4
5 --> 2 // we have 2 divisors - 1 and 5
12 --> 6 // we have 6 divisors - 1, 2, 3, 4, 6 and 12
30 --> 8 // we have 8 divisors - 1, 2, 3, 5, 6, 10, 1... | reference | def divisors(n):
return len([l_div for l_div in range(1, n + 1) if n % l_div == 0])
| Count the divisors of a number | 542c0f198e077084c0000c2e | [
"Number Theory",
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/542c0f198e077084c0000c2e | 7 kyu |
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).
Derive function `abundantNumber(num)/abundant_number(num)` which returns `true... | reference | def abundant_number(num):
return (sum([e for e in range(1, num) if num % e == 0]) > num)
| Excessively Abundant Numbers | 56a75b91688b49ad94000015 | [
"Fundamentals",
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/56a75b91688b49ad94000015 | 7 kyu |
Many people choose to obfuscate their email address when displaying it on the Web. One common way of doing this is by substituting the `@` and `.` characters for their literal equivalents in brackets.
Example 1:
```
user_name@example.com
=> user_name [at] example [dot] com
```
Example 2:
```
af5134@borchmore.edu
=> a... | algorithms | def obfuscate(email):
return email . replace("@", " [at] "). replace(".", " [dot] ")
| Email Address Obfuscator | 562d8d4c434582007300004e | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/562d8d4c434582007300004e | 7 kyu |
#### Task:
Your job here is to write a function (`keepOrder` in JS/CoffeeScript, `keep_order` in Ruby/Crystal/Python, `keeporder` in Julia), which takes a sorted array `ary` and a value `val`, and returns the lowest index where you could insert `val` to maintain the sorted-ness of the array. The input array will alway... | reference | from bisect import bisect_left as keep_order
| Keep the Order | 582aafca2d44a4a4560000e7 | [
"Fundamentals"
] | https://www.codewars.com/kata/582aafca2d44a4a4560000e7 | 7 kyu |
We all use 16:9, 16:10, 4:3 etc. ratios every day. Main task is to determine image ratio by its width and height dimensions.
Function should take width and height of an image and return a ratio string (ex."16:9").
If any of width or height entry is 0 function should throw an exception (or return `Nothing`). | algorithms | from fractions import Fraction
def calculate_ratio(w, h):
if w * h == 0:
raise ValueError
f = Fraction(w, h)
return f" { f . numerator } : { f . denominator } "
| Width-Height Ratio | 55486cb94c9d3251560000ff | [
"Algorithms"
] | https://www.codewars.com/kata/55486cb94c9d3251560000ff | 7 kyu |
Make a function that receives a value, ```val``` and outputs the smallest higher number than the given value, and this number belong to a set of positive integers that have the following properties:
- their digits occur only once
- they are odd
- they are multiple of three
```python
next_numb(12) == 15
next_numb(... | reference | def next_numb(val):
i = val + 1
while i <= 9999999999:
if i % 3 == 0 and i % 2 and len(str(i)) == len(set(str(i))):
return i
i += 1
return 'There is no possible number that fulfills those requirements'
| Next Featured Number Higher than a Given Value | 56abc5e63c91630882000057 | [
"Fundamentals"
] | https://www.codewars.com/kata/56abc5e63c91630882000057 | 7 kyu |
*`This kata is a tribute/fanwork to the TV-show: Supernatural`*
Balls!
Those wayward Winchester boys are in trouble again, hunting something down in New Orleans.
You are Bobby Singer, you know how "idjits" they can be, so you have to prepare.
They will call you any minute with the race of the thing, and you want to ... | reference | def bob(what):
return "%s, idjits!" % drunkenDoodling . get(what, "I have friggin no idea yet")
| Supernatural | 55c9a8cda33889d69e00008b | [
"Games",
"Fundamentals"
] | https://www.codewars.com/kata/55c9a8cda33889d69e00008b | 7 kyu |
Punky loves wearing different colored socks, but Henry can't stand it.
Given an array of different colored socks, return a pair depending on who was picking them out.
Example:
```javascript
getSocks('Punky', ['red','blue','blue','green']) -> ['red', 'blue']
```
```coffeescript
getSocks('Punky', ['red','blue','blue','... | algorithms | def get_socks(name, socks):
if name == 'Punky':
if socks:
for s in socks[1:]:
if s != socks[0]:
return [socks[0], s]
elif name == 'Henry':
seen = set()
for s in socks:
if s in seen:
return [s, s]
seen . add(s)
else:
raise ValueError
return []
| 80's Kids #3: Punky Brewster's Socks | 5662292ee7e2da24e900012f | [
"Fundamentals",
"Algorithms",
"Arrays"
] | https://www.codewars.com/kata/5662292ee7e2da24e900012f | 7 kyu |
Change every letter in a given string to the next letter in the alphabet. The function takes a single parameter `s` (string).
Notes:
* Spaces and special characters should remain the same.
* Capital letters should transfer in the same way but remain capitilized.
## Examples
```
"Hello" --> "Ifmmp"
"W... | reference | def next_letter(string):
return "" . join(chr(ord(c) + (- 25 if c in 'zZ' else 1)) if c . isalpha() else c for c in string)
| Weird words | 57b2020eb69bfcbf64000375 | [
"Strings",
"Regular Expressions",
"Fundamentals"
] | https://www.codewars.com/kata/57b2020eb69bfcbf64000375 | 7 kyu |
Create a function that returns the total of a meal including tip and tax. You should not tip on the tax.
You will be given the subtotal, the tax as a percentage and the tip as a percentage. Please round your result to two decimal places. | games | def calculate_total(subtotal, tax, tip):
return round(subtotal * (1 + tax / 100.0 + tip / 100.0), 2)
| Calculate Meal Total | 58545549b45c01ccab00058c | [
"Fundamentals"
] | https://www.codewars.com/kata/58545549b45c01ccab00058c | 7 kyu |
Given a string, determine if it's a valid identifier.
## Here is the syntax for valid identifiers:
* Each identifier must have at least one character.
* The first character must be picked from: alpha, underscore, or dollar sign. The first character cannot be a digit.
* The rest of the characters (besides the first) ca... | reference | import re
def is_valid(idn):
return re . compile('^[a-z_\$][a-z0-9_\$]*$', re . IGNORECASE). match(idn) != None
| Is valid identifier? | 563a8656d52a79f06c00001f | [
"Fundamentals",
"Regular Expressions",
"Strings"
] | https://www.codewars.com/kata/563a8656d52a79f06c00001f | 7 kyu |
Lucy loves to travel. Luckily she is a renowned computer scientist and gets to travel to international conferences using her department's budget.
Each year, Society for Exciting Computer Science Research (SECSR) organizes several conferences around the world. Lucy always picks one conference from that list that is h... | reference | def conference_picker(cities_visited, cities_offered):
for city in cities_offered:
if city not in cities_visited:
return city
return 'No worthwhile conferences this year!'
| Conference Traveller | 56f5594a575d7d3c0e000ea0 | [
"Fundamentals",
"Arrays",
"Lists"
] | https://www.codewars.com/kata/56f5594a575d7d3c0e000ea0 | 7 kyu |
Create a function that takes two arguments:
1) An array of objects which feature the season, the team and the country of the Champions League winner.
2) Country (as a string, for example, 'Portugal')
You function should then return the number which represents the number of times a team from a given country has won. ... | algorithms | def countWins(winnerList, country):
return sum(x . get('country') == country for x in winnerList)
| Find how many times did a team from a given country win the Champions League? | 581b30af1ef8ee6aea0015b9 | [
"Strings",
"Arrays",
"Data Structures",
"Algorithms"
] | https://www.codewars.com/kata/581b30af1ef8ee6aea0015b9 | 7 kyu |
Create a function that receives a (square) matrix and calculates the sum of both diagonals (main and secondary)
> Matrix = array of `n` length whose elements are `n` length arrays of integers.
3x3 example:
```javascript
diagonals( [
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
] );
returns -> 30 // 1 + 5 + 9 + 3 +... | algorithms | import numpy as np
def sum_diagonals(matrix):
# your code here
matrix = np . matrix(matrix)
return sum(np . diag(matrix, 0)) + sum(np . diag(np . flip(matrix, axis=1), 0))
| Diagonals sum | 5592fc599a7f40adac0000a8 | [
"Matrix",
"Algorithms"
] | https://www.codewars.com/kata/5592fc599a7f40adac0000a8 | 7 kyu |
Write a function that checks whether all elements in an array are square numbers. The function should be able to take any number of array elements.
Your function should return true if all elements in the array are square numbers and false if not.
An empty array should return `undefined` / `None` / `nil` /`false` (for... | reference | def is_square(arr):
if arr:
return all((a * * 0.5). is_integer() for a in arr)
| Are they square? | 56853c44b295170b73000007 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/56853c44b295170b73000007 | 7 kyu |
You have two arrays in this kata, every array contains unique elements only. Your task is to calculate number of elements in the first array which are also present in the second array. | reference | def match_arrays(v, r):
return sum(x in r for x in v)
# DON'T remove
verbose = False # set to True to diplay arrays being tested in the random tests
| Array comparator | 561046a9f629a8aac000001d | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/561046a9f629a8aac000001d | 7 kyu |
## The Problem
James is a DJ at a local radio station. As it's getting to the top of the hour, he needs to find a song to play that will be short enough to fit in before the news block. He's got a database of songs that he'd like you to help him filter in order to do that.
## What To Do
Create `longestPossible`(`lon... | algorithms | def calculate_seconds(s):
minutes, seconds = [int(x) for x in s . split(':')]
return minutes * 60 + seconds
def longest_possible ( playback ):
candidates = [ song for song in songs if calculate_seconds ( song [ 'playback' ]) <= playback ]
return sorted ( candidates , key = lambda x : calculate_seconds ( x... | Radio DJ helper function | 561bbcb0fbbfb0f5010000ee | [
"Sorting",
"Filtering",
"Algorithms"
] | https://www.codewars.com/kata/561bbcb0fbbfb0f5010000ee | 7 kyu |
Your task is to write an update for a lottery machine. Its current version produces a sequence of random letters and integers (passed as a string to the function). Your code must filter out all letters and return **unique** integers as a string, in their order of first appearance. If there are no integers in the string... | reference | def lottery(s):
return "" . join(dict . fromkeys(filter(str . isdigit, s))) or "One more run!"
| Lottery machine | 5832db03d5bafb7d96000107 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5832db03d5bafb7d96000107 | 7 kyu |
An array is given with palindromic and non-palindromic numbers. A *palindromic* number is a number that is the same from a reversed order. For example `122` is not a palindromic number, but `202` is one.
Your task is to write a function that returns an array with only `1`s and `0`s, where all palindromic numbers ... | algorithms | def convert_palindromes(numbers):
return [str(n) == str(n)[:: - 1] for n in numbers]
| Palindromes Here and There | 5838a66eaed8c259df000003 | [
"Algorithms"
] | https://www.codewars.com/kata/5838a66eaed8c259df000003 | 7 kyu |
Spoonerize... with numbers... numberize?... numboonerize?... noonerize? ...anyway! If you don't yet know what a spoonerism is and haven't yet tried my spoonerism kata, please do [check it out](http://www.codewars.com/kata/spoonerize-me) first.
You will create a function which takes an array of two positive integers, ... | algorithms | def noonerize(numbers):
try:
num1 = int(str(numbers[1])[0] + str(numbers[0])[1:])
num2 = int(str(numbers[0])[0] + str(numbers[1])[1:])
except ValueError:
return "invalid array"
return abs(num1 - num2)
| Noonerize Me | 56dbed3a13c2f61ae3000bcd | [
"Mathematics",
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/56dbed3a13c2f61ae3000bcd | 7 kyu |
The [Chinese zodiac](https://en.wikipedia.org/wiki/Chinese_zodiac) is a repeating cycle of 12 years, with each year being represented by an animal and its reputed attributes. The lunar calendar is divided into cycles of 60 years each, and each year has a combination of an animal and an element. There are 12 animals and... | reference | animals = ['Rat', 'Ox', 'Tiger', 'Rabbit', 'Dragon', 'Snake',
'Horse', 'Goat', 'Monkey', 'Rooster', 'Dog', 'Pig']
elements = ['Wood', 'Fire', 'Earth', 'Metal', 'Water']
def chinese_zodiac(year):
year -= 1984
return elements[year / / 2 % 5] + " " + animals[year % 12]
| Chinese Zodiac | 57a73e697cb1f31dd70000d2 | [
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/57a73e697cb1f31dd70000d2 | 7 kyu |
When a warrior wants to talk with another one about peace or war he uses a smartphone. In one distinct country warriors who spent all time in training kata not always have enough money. So if they call some number they want to know which operator serves this number.
Write a function which **accepts number and retu... | reference | OPERATORS = {
'039': 'Golden Telecom', '050': 'MTS', '063': 'Life:)', '066': 'MTS',
'067': 'Kyivstar', '068': 'Beeline', '093': 'Life:)', '095': 'MTS',
'096': 'Kyivstar', '097': 'Kyivstar', '098': 'Kyivstar', '099': 'MTS'}
def detect_operator(num):
return OPERATORS . get(str(num)[1: 4], 'no inf... | Mobile operator detector | 55f8ba3be8d585b81e000080 | [
"Logic",
"Strings",
"Regular Expressions",
"Fundamentals"
] | https://www.codewars.com/kata/55f8ba3be8d585b81e000080 | 7 kyu |
Write function which will create a string from a list of strings, separated by space.
Example:
```["hello", "world"] -> "hello world"``` | reference | def words_to_sentence(words):
return ' ' . join(words)
| Words to sentence | 57a06005cf1fa5fbd5000216 | [
"Fundamentals"
] | https://www.codewars.com/kata/57a06005cf1fa5fbd5000216 | 7 kyu |
It's your birthday. Your colleagues buy you a cake. The numbers of candles on the cake is provided (`candles`). Please note this is not reality, and your age can be anywhere up to 1000. Yes, you would look a mess.
As a surprise, your colleagues have arranged for your friend to hide inside the cake and burst out. They ... | reference | import string
def cake(candles: int, debris: str) - > str:
fallen_candles = sum(
string . ascii_letters . index(char) if index % 2 else ord(char)
for index, char in enumerate(debris)
)
return "Fire!" if candles and fallen_candles > candles * 0.7 else "That was close!"
| Birthday I - Cake | 5805ed25c2799821cb000005 | [
"Fundamentals",
"Arrays",
"Mathematics"
] | https://www.codewars.com/kata/5805ed25c2799821cb000005 | 7 kyu |
A spoonerism is a spoken phrase in which the first letters of two of the words are swapped around, often with amusing results.
In its most basic form a spoonerism is a two word phrase in which only the first letters of each word are swapped:
```"not picking" --> "pot nicking"```
Your task is to create a function tha... | algorithms | def spoonerize(words):
a, b = words . split()
return '{}{} {}{}' . format(b[0], a[1:], a[0], b[1:])
| Spoonerize Me | 56b8903933dbe5831e000c76 | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/56b8903933dbe5831e000c76 | 7 kyu |
Write reverseList function that simply reverses lists. | reference | def reverse_list(lst):
return lst[:: - 1]
| Reverse list | 57a04da9e298a7ee43000111 | [
"Fundamentals",
"Lists"
] | https://www.codewars.com/kata/57a04da9e298a7ee43000111 | 7 kyu |
A grid is a perfect starting point for many games (Chess, battleships, Candy Crush!).
Making a digital chessboard I think is an interesting way of visualising how loops can work together.
Your task is to write a function that takes two integers `rows` and `columns` and returns a chessboard pattern as a two dimensiona... | algorithms | def chess_board(rows, columns):
return [["OX" [(row + col) % 2] for col in range(columns)] for row in range(rows)]
| draw me a chessboard | 56242b89689c35449b000059 | [
"Puzzles",
"Fundamentals",
"ASCII Art",
"Algorithms"
] | https://www.codewars.com/kata/56242b89689c35449b000059 | 7 kyu |
Write
```javascript
function remove(str, what)
```
```csharp
public static string Remove(string str, Dictionary<char,int> what)
```
```python
remove(text, what)
```
```ruby
remove(text, what)
```
that takes in a string ```str```(```text``` in Python) and an object/hash/dict/Dictionary ```what``` and returns a string wi... | reference | def remove(text, what):
for char in what:
text = text . replace(char, '', what[char])
return text
| Not all but sometimes all | 564ab935de55a747d7000040 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/564ab935de55a747d7000040 | 7 kyu |
There were and still are many problem in CW about palindrome numbers and palindrome strings. We suposse that you know which kind of numbers they are. If not, you may search about them using your favourite search engine.
In this kata you will be given a positive integer, ```val``` and you have to create the function ``... | reference | def next_pal(val):
val += 1
while str(val) != str(val)[:: - 1]:
val += 1
return val
| Next Palindromic Number. | 56a6ce697c05fb4667000029 | [
"Fundamentals",
"Data Structures",
"Algorithms",
"Mathematics",
"Logic",
"Strings"
] | https://www.codewars.com/kata/56a6ce697c05fb4667000029 | 7 kyu |
The four bases found in DNA are adenine (A), cytosine (C), guanine (G) and thymine (T).
In genetics, GC-content is the percentage of Guanine (G) and Cytosine (C) bases on a DNA molecule that are either guanine or cytosine.
Given a DNA sequence (a string) return the GC-content in percent, rounded up to 2 decimal digi... | algorithms | def gc_content(seq):
if not seq:
return 0.0
else:
res = seq . count("C") + seq . count("G")
return round(res * 100 / len(seq), 2)
| DNA GC-content | 5747a9bbe2fab9a0c400012f | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/5747a9bbe2fab9a0c400012f | 7 kyu |
<img src = http://images.wired.it/wp-content/uploads/2014/03/1394467702_chuck_norris_epic_split_3.jpg>
Chuck has lost count of how many asses he has kicked...
Chuck stopped counting at 100,000 because he prefers to kick things in the face instead of counting. That's just who he is.
To stop having to count like a mer... | algorithms | from re import search
def body_count(code):
return bool(search(r'(?:[A-Z]\d){5}\.-[A-Z]%\d\.\d{2}\.', code))
| Chuck Norris V - Body Count | 57066ad6cb72934c8400149e | [
"Regular Expressions",
"Algorithms"
] | https://www.codewars.com/kata/57066ad6cb72934c8400149e | 7 kyu |
Thanks to the effects of El Nino this year my holiday snorkelling trip was akin to being in a washing machine... Not fun at all.
Given a string made up of '~' and '\_' representing waves and calm respectively, your job is to check whether a person would become seasick.
Changes from calm to wave or wave to calm will a... | reference | def sea_sick(sea):
return "Throw Up" if (sea . count("~_") + sea . count("_~")) / len(sea) > 0.2 else "No Problem"
| Holiday V - SeaSick Snorkelling | 57e90bcc97a0592126000064 | [
"Fundamentals",
"Strings",
"Arrays"
] | https://www.codewars.com/kata/57e90bcc97a0592126000064 | 7 kyu |
You've arrived at a carnival and head straight for the duck shooting tent. Why wouldn't you?
You will be given a set amount of ammo, and an aim rating of between 1 and 0. No your aim is not always perfect - hey maybe someone fiddled with the sights on the gun...
Anyway your task is to calculate how many successful sh... | games | def duck_shoot(ammo, aim, ducks):
return ducks . replace('2', 'X', int(ammo * aim))
| Duck Shoot - Easy Version | 57d27a0a26427672b900046f | [
"Strings",
"Arrays"
] | https://www.codewars.com/kata/57d27a0a26427672b900046f | 7 kyu |
One of the first chain emails I ever received was about a supposed Cambridge University study that suggests your brain can read words no matter what order the letters are in, as long as the first and last letters of each word are correct.
Your task is to **create a function that can take any string and randomly jumbl... | reference | import re
from random import sample
def mix_words(string):
return re . sub(
r'(?<=[a-zA-Z])([a-zA-Z]{2,})(?=[a-zA-Z])',
lambda match: '' . join(
sample(match . group(1), len(match . group(1)))),
string)
| Cambridge Word Scramble | 564e48ebaaad20181e000024 | [
"Strings",
"Regular Expressions",
"Fundamentals"
] | https://www.codewars.com/kata/564e48ebaaad20181e000024 | 6 kyu |
Given a string and an array of index numbers, return the characters of the string rearranged to be in the order specified by the accompanying array.
Ex:
scramble('abcd', [0,3,1,2]) -> 'acdb'
The string that you will be returning back will have: 'a' at index 0, 'b' at index 3, 'c' at index 1, 'd' at index 2, because... | reference | def scramble(string, array):
return "" . join(v for _, v in sorted(zip(array, string)))
| String Scramble | 5822d89270ca28c85c0000f3 | [
"Fundamentals",
"Strings",
"Arrays"
] | https://www.codewars.com/kata/5822d89270ca28c85c0000f3 | 7 kyu |
There are just some things you can't do on television. In this case, you've just come back from having a "delicious" Barth burger and you're set to give an interview. The Barth burger has made you queezy, and you've forgotten some of the import rules of the "You Can't Do That on Television" set.
If you say any of the ... | algorithms | import re
WATER_PATTERN = re . compile(r"water|wet|wash", re . I)
SLIME_PATTERN = re . compile(r"\bI don't know\b|slime", re . I)
def bucket_of(said):
water = WATER_PATTERN . search(said)
slime = SLIME_PATTERN . search(said)
if water:
return 'sludge' if slime else 'water'
return 'slime... | 80's Kids #5: You Can't Do That on Television | 5667525f0f157f7a0a000004 | [
"Fundamentals",
"Algorithms",
"Strings",
"Regular Expressions"
] | https://www.codewars.com/kata/5667525f0f157f7a0a000004 | 7 kyu |
You should write a function that takes a string and a positive integer `n`, splits the string into parts of length `n` and returns them in an array. It is ok for the last element to have less than `n` characters.
If `n` is not a number or not a valid size (`> 0`) (or is absent), you should return an empty array.
If `... | reference | def string_chunk(xs, n=None):
try:
return [xs[i: i + n] for i in range(0, len(xs), n)]
except:
return []
| String chunks | 55b4f9906ac454650900007d | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/55b4f9906ac454650900007d | 7 kyu |
You are given a string of words and numbers. Extract the expression including:
1. the operator: either addition (`"gains"`) or subtraction (`"loses"`)
2. the two numbers that we are operating on
Return the result of the calculation.
**Notes:**
* `"loses"` and `"gains"` are the only two words describing operators
* N... | reference | def calculate(s):
x = [int(i) for i in s . split() if i . isdigit()]
return sum(x) if 'gains' in s . split() else x[0] - x[1]
| Fruit string calculator | 57b9fc5b8f5813384a000aa3 | [
"Strings",
"Regular Expressions",
"Fundamentals"
] | https://www.codewars.com/kata/57b9fc5b8f5813384a000aa3 | 7 kyu |
This series of katas will introduce you to basics of doing geometry with computers.
`Point` objects have `x`, `y` attributes. `Triangle` objects have attributes `a`, `b`, `c` describing their corners, each of them is a `Point`.
Write a function calculating area of a `Triangle` defined this way.
Tests round answers t... | reference | def triangle_area(t):
a, b, c = t . a, t . b, t . c
return round(abs(a . x * (b . y - c . y) + b . x * (c . y - a . y) + c . x * (a . y - b . y)) / 2, 6)
| Geometry Basics: Triangle Area in 2D | 58e4377c46e371aee7001262 | [
"Geometry",
"Fundamentals"
] | https://www.codewars.com/kata/58e4377c46e371aee7001262 | 6 kyu |
In computer science, a programming language is said to have first-class functions if it treats functions as first-class citizens. Specifically, this means the language supports passing functions as arguments to other functions, returning them as the values from other functions, and assigning them to variables or storin... | reference | def func(n):
return int(n) % 2 == 0
def map ( arr , somefunction ):
try :
return [ somefunction ( a ) for a in arr ]
except ValueError :
return 'array should contain only numbers'
except TypeError :
return 'given argument is not a function' | Map function issue | 560fbc2d636966b21e00009e | [
"Functional Programming",
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/560fbc2d636966b21e00009e | 7 kyu |
Given any number of boolean flags function should return true if and only if one of them is true while others are false. If function is called without arguments it should return false.
```javascript
onlyOne() --> false
onlyOne(true, false, false) --> true
onlyOne(true, false, false, true) --> false
onlyOne(fal... | algorithms | def only_one(* args):
return sum(args) == 1
| Only one | 5734c38da41454b7f700106e | [
"Algorithms"
] | https://www.codewars.com/kata/5734c38da41454b7f700106e | 7 kyu |
Chingel is practicing for a rowing competition to be held on this saturday. He is trying his best to win this tournament for which he needs to figure out how much time it takes to cover a certain distance.
**Input**
You will be provided with the total distance of the journey, speed of the boat and whether he is goin... | reference | def time(distance, boat_speed, stream):
river_speed = int(stream . replace(
"Downstream ", '+'). replace("Upstream ", '-'))
return round(distance / (boat_speed + river_speed), 2)
| Upstream/Downstream | 58162692c2a518f03a000189 | [
"Fundamentals"
] | https://www.codewars.com/kata/58162692c2a518f03a000189 | 7 kyu |
Write function which takes a string and make an acronym of it.
Rule of making acronym in this kata:
1. split string to words by space char
2. take every first letter from word in given string
3. uppercase it
4. join them toghether
Eg:
```
Code wars -> C, w -> C W -> CW
```
**Note: There will be at least two words... | reference | def to_acronym(input):
# only call upper() once
return '' . join(word[0] for word in input . split()). upper()
| Make acronym | 57a60bad72292d3e93000a5a | [
"Fundamentals"
] | https://www.codewars.com/kata/57a60bad72292d3e93000a5a | 7 kyu |
You have stumbled across the divine pleasure that is owning a dog and a garden. Now time to pick up all the cr@p! :D
Given a 2D array to represent your garden, you must find and collect all of the dog cr@p - represented by '@'.
You will also be given the number of bags you have access to (bags), and the capactity of ... | reference | from collections import Counter
from itertools import chain
def crap(garden, bags, cap):
c = Counter(chain(* garden))
return 'Dog!!' if c['D'] else ('Clean', 'Cr@p')[c['@'] > bags * cap]
| Clean up after your dog | 57faa6ff9610ce181b000028 | [
"Fundamentals",
"Strings",
"Arrays",
"Mathematics"
] | https://www.codewars.com/kata/57faa6ff9610ce181b000028 | 7 kyu |
Write function ```splitSentence``` which will create a list of strings from a string.
Example:
```"hello world" -> ["hello", "world"]``` | reference | def splitSentence(s):
return s . split()
| Sentence to words | 57a05e0172292dd8510001f7 | [
"Fundamentals"
] | https://www.codewars.com/kata/57a05e0172292dd8510001f7 | 7 kyu |
Imagine there's a big cube consisting of `$ n^3 $` small cubes. Calculate, how many small cubes are not visible from outside.
For example, if we have a cube which has 4 cubes in a row, then the function should return 8, because there are 8 cubes inside our cube (2 cubes in each dimension)
For a visual representation:... | games | def not_visible_cubes(n):
return max(n - 2, 0) * * 3
| Invisible cubes | 560d6ebe7a8c737c52000084 | [
"Puzzles"
] | https://www.codewars.com/kata/560d6ebe7a8c737c52000084 | 7 kyu |
The notorious Captain Schneider has given you a very straight forward mission. Any data that comes through the system make sure that only non-special characters see the light of day.
Create a function that given a string, retains only the letters A-Z (upper and lowercase), 0-9 digits, and whitespace characters. Also, ... | reference | import re
def nothing_special(s):
try:
return re . sub('[^a-z0-9\s]', '', s, flags=re . IGNORECASE)
except:
return 'Not a string!'
| Nothing special | 57029e77005264a3b9000eb5 | [
"Fundamentals",
"Regular Expressions"
] | https://www.codewars.com/kata/57029e77005264a3b9000eb5 | 7 kyu |
Bob is a chicken sexer. His job is to sort baby chicks into a Male(M) and Female(F) piles. When bob can't guess can throw his hands up and declare it with a '?'.
Bob's bosses don't trust Bob's ability just yet, so they have paired him with an expert sexer. All of Bob's decisions will be checked against the expert's ch... | reference | def correctness(bob, exp):
return sum(b == e or 0.5 * (b == '?' or e == '?') for b, e in zip(bob, exp))
| Chicken Sexing | 57ed40e3bd793e9c92000fcb | [
"Fundamentals"
] | https://www.codewars.com/kata/57ed40e3bd793e9c92000fcb | 7 kyu |
This just a simple physics problem:
A race car accelerates uniformly from `18.5 m/s` to `46.1 m/s` in `2.47 seconds`. Determine the acceleration of the car and the distance traveled.
Create a function `solveit(vi, vf, t)` that takes in all three values and outputs a list of acceleration and distance in format `[accel... | reference | def solveit(vi, vf, t):
a = (vf - vi) / t
d = vi * t + 0.5 * a * (t * * 2)
return [round(a, 2), round(d, 2)] if vi <= vf else []
| Simple Physics Problem | 57c3eb9fd6cf0ffd68000222 | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/57c3eb9fd6cf0ffd68000222 | 7 kyu |
Hey CodeWarrior,
we've got a lot to code today!
I hope you know the basic string manipulation methods, because this kata will be all about them.
Here we go...
## Background
We've got a very long string, containing a bunch of User IDs. This string is a listing, which seperates each user ID with a comma and a whites... | reference | def get_users_ids(string):
return [w . replace("uid", "", 1). strip() for w in string . lower(). replace("#", ""). split(",")]
| String basics | 56326c13e63f90538d00004e | [
"Strings",
"Fundamentals",
"Regular Expressions"
] | https://www.codewars.com/kata/56326c13e63f90538d00004e | 7 kyu |
Write a function that adds from two invocations.
All inputs will be integers.
```
add(3)(4) // 7
add(12)(20) // 32
``` | reference | def add(a): return lambda b: a + b
| Test Your Knowledge Of Function Scope | 56d344c7fd3a52566700124b | [
"Fundamentals"
] | https://www.codewars.com/kata/56d344c7fd3a52566700124b | 7 kyu |
# Task
Write the processArray function, which takes an array and a callback function as parameters. The callback function can be, for example, a mathematical function that will be applied on each element of this array. Optionally, also write tests similar to the examples below.
# Examples
1) Array `[4, 8, 2, 7, 5]` a... | algorithms | def process_array(arr, callback):
return list(map(callback, arr))
| Easy mathematical callback | 54b7c8d2cd7f51a839000ebf | [
"Algorithms"
] | https://www.codewars.com/kata/54b7c8d2cd7f51a839000ebf | 7 kyu |
<img src=http://www.myteespot.com/images/Images_d/d_7531.jpg>
It's Friday night, and Chuck is bored. He's already run 1,000 miles, stopping only to eat a family sized bag of Heatwave Doritos and a large fistful of M&Ms. He just can't stop thinking about kicking something!
There is only one thing for it, Chuck heads ... | algorithms | def head_smash(arr):
try:
return [a . replace('O', ' ') for a in arr] or 'Gym is empty'
except TypeError:
return "This isn't the gym!!"
| Chuck Norris III - Cage Match | 57061b6fcb7293901a000ac7 | [
"Fundamentals",
"Arrays",
"Regular Expressions",
"Algorithms"
] | https://www.codewars.com/kata/57061b6fcb7293901a000ac7 | 7 kyu |
Suzuki has a long list of chores required to keep the monastery in good order. Each chore can be completed independently of the others and assigned to any student. Knowing there will always be an even number of chores and that the number of students isn't limited, Suzuki needs to assign two chores to each student in a ... | algorithms | def chore_assignment(chores):
chores . sort()
return sorted([chores[i] + chores[- 1 - i] for i in range(len(chores) / / 2)])
| Help Suzuki complete his chores! | 584dc1b7766c2bb158000226 | [
"Algorithms"
] | https://www.codewars.com/kata/584dc1b7766c2bb158000226 | 7 kyu |
**This Kata is intended as a small challenge for my students**
All Star Code Challenge #22
Create a function that takes an integer argument of seconds and converts the value into a string describing how many hours and minutes comprise that many seconds.
Any remaining seconds left over are ignored.
Note:
The strin... | reference | def to_time(seconds):
return f' { seconds / / 3600 } hour(s) and {( seconds / / 60 ) % 60 } minute(s)'
| All Star Code Challenge #22 | 5865cff66b5699883f0001aa | [
"Fundamentals"
] | https://www.codewars.com/kata/5865cff66b5699883f0001aa | 7 kyu |
The 26 letters of the English alphabets are randomly divided into 5 groups of 5 letters with the remaining letter being ignored. Each of the group is assigned a score of more than 0. The ignored letter always has a score of 0.
With this kata, write a function ```nameScore(name)``` to work out the score of a name tha... | algorithms | def name_score(name):
return {name: sum(alpha[key] for c in name for key in alpha if c . upper() in key)}
| What is my name score? #1 | 576a29ab726f4bba4b000bb1 | [
"Strings",
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/576a29ab726f4bba4b000bb1 | 7 kyu |
# Backstory
<img src="https://images-eu.ssl-images-amazon.com/images/I/61FUCzdEinL._AA300_.jpg" align="middle">
To celebrate today's launch of my Hero's new book: `Alan Partridge: Nomad`, We have a new series of kata arranged around the great man himself.
# Task
Given an array of terms, if any of those terms relate t... | reference | def part(arr):
l = ["Partridge", "PearTree", "Chat", "Dan",
"Toblerone", "Lynn", "AlphaPapa", "Nomad"]
s = len([i for i in arr if i in l])
return "Mine's a Pint" + "!" * s if s > 0 else 'Lynn, I\'ve pierced my foot on a spike!!'
| Alan Partridge I - Partridge Watch | 5808c8eff0ed4210de000008 | [
"Fundamentals",
"Arrays",
"Strings"
] | https://www.codewars.com/kata/5808c8eff0ed4210de000008 | 7 kyu |
You are given an array including a list of basketball teams and their scores showing points scored vs points lost:
```javascript
const basketballResults = [
['Dallas Mavericks', '492:513'],
['Los Angeles Lakers', '641:637'],
['Houston Rockets', '494:458'],
['Los Angeles Clippers', '382:422'],
['New Orleans P... | algorithms | import re
def get_los_angeles_points(results):
pattern = re . compile('Los Angeles [A-Z][a-z]+')
return sum(int(k[1]. split(':')[0]) for k in results if pattern . fullmatch(k[0]))
| How many points did the teams from Los Angeles score? | 580559b17ab3396c58000abb | [
"Algorithms",
"Data Structures",
"Arrays",
"Regular Expressions"
] | https://www.codewars.com/kata/580559b17ab3396c58000abb | 7 kyu |
We have a matrix of integers with m rows and n columns.
```math
\begin{pmatrix}
a_{11} & a_{12} & \cdots &a_{1n} \\
a_{21} & a_{22} &\cdots &a_{2n} \\
\cdots & \cdots & \cdots & \cdots \\
\cdots & \cdots & \cdots & \cdots \\
a_{m1} & a_{m2} & \cdots &a_{mn}
\end{pmatrix}
```
We want to calculate the... | reference | def score_matrix(matrix):
return sum((- 1) * * (i + j) * matrix[i][j] for i in range(len(matrix)) for j in range(len(matrix[i])))
| #1 Matrices : Making an Alternating Sum | 5720eb05e8d6c5b24a0014c5 | [
"Fundamentals",
"Data Structures",
"Algorithms",
"Mathematics",
"Logic",
"Matrix"
] | https://www.codewars.com/kata/5720eb05e8d6c5b24a0014c5 | 7 kyu |
We need a method in the ```List Class``` that may count specific digits from a given list of integers. This marked digits will be given in a second list.
The method ```.count_spec_digits()/.countSpecDigits()``` will accept two arguments, a list of an uncertain amount of integers ```integers_lists/integersLists``` (and ... | reference | from collections import Counter
class List (object):
@ staticmethod
def count_spec_digits(integers_list, digits_list):
counts = Counter('' . join(str(abs(a)) for a in integers_list))
return [(b, counts[str(b)]) for b in digits_list]
| Method For Counting Total Occurence Of Specific Digits | 56311e4fdd811616810000ce | [
"Fundamentals",
"Algorithms",
"Data Structures"
] | https://www.codewars.com/kata/56311e4fdd811616810000ce | 7 kyu |
In genetics, a sequence’s motif is a nucleotides (or amino-acid) sequence pattern. Sequence motifs have a biological significance. For more information you can take a look [here](https://en.wikipedia.org/wiki/Sequence_motif).
For this kata you need to complete the function `motif_locator`. This function receives 2 ar... | algorithms | def motif_locator(sequence, motif):
res, i = [], 0
while True:
i = sequence . find(motif, i) + 1
if not i:
return res
res . append(i)
| Find the motif in DNA sequence. | 5760c1c7f2717b91e20001a4 | [
"Algorithms",
"Strings"
] | https://www.codewars.com/kata/5760c1c7f2717b91e20001a4 | 7 kyu |
Quantum mechanics tells us that a molecule is only allowed to have specific, discrete amounts of internal energy. The 'rigid rotor model', a model for describing rotations, tells us that the amount of rotational energy a molecule can have is given by:
`E = B * J * (J + 1)`,
where J is the state the molecule is in... | reference | def rot_energies(B, Jmin, Jmax):
return [B * J * (J + 1) for J in range(Jmin, Jmax + 1)] if B > 0 else []
| Rotational energy levels | 587b6a5e8726476f9b0000e7 | [
"Fundamentals"
] | https://www.codewars.com/kata/587b6a5e8726476f9b0000e7 | 7 kyu |
Polly is 8 years old. She is eagerly awaiting Christmas as she has a bone to pick with Santa Claus. Last year she asked for a horse, and he brought her a dolls house. Understandably she is livid.
The days seem to drag and drag so Polly asks her friend to help her keep count of how long it is until Christmas, in days. ... | algorithms | from datetime import date
def days_until_christmas(day):
christmas = date(day . year, 12, 25)
if day > christmas:
christmas = date(day . year + 1, 12, 25)
return (christmas - day). days
| Countdown to Christmas | 56f6b23c9400f5387d000d48 | [
"Date Time",
"Algorithms"
] | https://www.codewars.com/kata/56f6b23c9400f5387d000d48 | 7 kyu |
## Task
Create a function called `one` that accepts two params:
* a sequence
* a function
and returns `true` only if the function in the params returns `true` for exactly one (`1`) item in the sequence.
## Example
```
one([1, 3, 5, 6, 99, 1, 3], bigger_than_ten) -> true
one([1, 3, 5, 6, 99, 88, 3], bigger_than_t... | reference | def one(sq, fun):
return sum(map(fun, sq)) == 1
| Enumerable Magic #5- True for Just One? | 54599705cbae2aa60b0011a4 | [
"Fundamentals"
] | https://www.codewars.com/kata/54599705cbae2aa60b0011a4 | 7 kyu |
I'm sure you're familiar with factorials – that is, the product of an integer and all the integers below it.
For example, `5! = 120`, as `5 * 4 * 3 * 2 * 1 = 120`
Your challenge is to create a function that takes any number and returns the number that it is a factorial of. So, if your function receives `120`, it sho... | reference | def reverse_factorial(num):
c = f = 1
while f < num:
c += 1
f *= c
return 'None' if f > num else "%d!" % c
| Reverse Factorials | 58067088c27998b119000451 | [
"Fundamentals"
] | https://www.codewars.com/kata/58067088c27998b119000451 | 7 kyu |
## Task
You need to implement two functions, `xor` and `or`, that replicate the behaviour of their respective operators:
- `xor` = Takes 2 values and returns `true` if, and only if, one of them is truthy.
- `or` = Takes 2 values and returns `true` if either one of them is truthy.
When doing so, **you cannot use the o... | reference | def func_or(a, b):
return not (bool(a) == bool(b) == False)
def func_xor(a, b):
return not (bool(a) == bool(b))
| Boolean logic from scratch | 584d2c19766c2b2f6a00004f | [
"Logic",
"Fundamentals"
] | https://www.codewars.com/kata/584d2c19766c2b2f6a00004f | 7 kyu |
Ready! Set! Fire... but where should you fire?
The battlefield is 3x3 wide grid. HQ has already provided you with an array for easier computing:
```javascript
var grid = ['top left', 'top middle', 'top right',
'middle left', 'center', 'middle right',
'bottom left', 'bottom middle'... | reference | def fire(x, y):
return grid[x + 3 * y]
| Grid blast! | 54fdfe14762e2edf4a000a33 | [
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/54fdfe14762e2edf4a000a33 | 7 kyu |
Given an Array and an Example-Array to sort to, write a function that sorts the Array following the Example-Array.
Assume Example Array catalogs all elements possibly seen in the input Array. However, the input Array does not necessarily have to have all elements seen in the Example.
Example:
Arr:
[1,3,4,4,4,4,5]
E... | reference | def example_sort(arr, example_arr):
return sorted(arr, key=example_arr . index)
| Sort by Example | 5747fcfce2fab91f43000697 | [
"Arrays",
"Sorting",
"Fundamentals"
] | https://www.codewars.com/kata/5747fcfce2fab91f43000697 | 7 kyu |
Challenge:
Given a two-dimensional array, return a new array which carries over only those arrays from the original, which were not empty and whose items are all of the same type (i.e. homogenous). For simplicity, the arrays inside the array will only contain characters and integers.
Example:
Given [[1, 5, 4], ['a',... | reference | def filter_homogenous(arrays):
return [a for a in arrays if len(set(map(type, a))) == 1]
| Homogenous arrays | 57ef016a7b45ef647a00002d | [
"Arrays",
"Fundamentals",
"Functional Programming"
] | https://www.codewars.com/kata/57ef016a7b45ef647a00002d | 7 kyu |
# Sports league table
Your local sports team manager wants to know how the team is doing in the league. You have been asked to write the manager a function that will allow them to update the league table.
## League details
The possible results in the league are `'draw'` and `'win'` with `3` points for a win and `1` ... | algorithms | def league_calculate(team1, team2, result, league_table):
for t in league_table:
if t[0] == team1:
if result == 'win':
t[1] += 3
elif result == 'draw':
t[1] += 1
elif t[0] == team2:
if result == 'draw':
t[1] += 1
return sorted(league_table, key=lambda x: (- x[1], x[0]))... | Sports league table - help your local team! | 566fd169d39cf89e1e000044 | [
"Fundamentals",
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/566fd169d39cf89e1e000044 | 7 kyu |
KISS stands for Keep It Simple Stupid.
It is a design principle for keeping things simple rather than complex.
You are the boss of Joe.
Joe is submitting words to you to publish to a blog. He likes to complicate things.
Define a function that determines if Joe's work is simple or complex.
Input will be non emtpy st... | games | def is_kiss(words):
wordsL = words . split(' ')
l = len(wordsL)
for word in wordsL:
if len(word) > l:
return "Keep It Simple Stupid"
return "Good work Joe!"
| KISS - Keep It Simple Stupid | 57eeb8cc5f79f6465a0015c1 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/57eeb8cc5f79f6465a0015c1 | 7 kyu |
Jenny is 9 years old. She is the youngest detective in North America. Jenny is a 3rd grader student, so when a new mission comes up, she gets a code to decipher in a form of a sticker (with numbers) in her math notebook and a comment (a sentence) in her writing notebook. All she needs to do is to figure out one word, f... | reference | def missing(nums, s):
ans = []
s = s . replace(' ', '')
try:
for i in sorted(nums):
ans . append(s[i])
return '' . join(ans). lower()
except IndexError:
return ("No mission today")
| Jenny the youngest detective | 58b972cae826b960a300003e | [
"Strings",
"Arrays",
"Algorithms",
"Fundamentals"
] | https://www.codewars.com/kata/58b972cae826b960a300003e | 7 kyu |
# Two samurai generals are discussing dinner plans after a battle, but they can't seem to agree.
The discussion gets heated and you are cannot risk favoring either of them as this might damage your political standing with either of the two clans the samurai generals belong to. Thus, the only thing left to do is find w... | reference | def common_ground(s1, s2):
lst = []
for w in s2 . split():
if w in s1 . split() and w not in lst:
lst . append(w)
return ' ' . join(lst) if lst else "death"
| Dinner Plans | 57212c55b6fa235edc0002a2 | [
"Strings",
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/57212c55b6fa235edc0002a2 | 7 kyu |
# Description
Write a function that checks whether a credit card number is correct or not, using the Luhn algorithm.
The algorithm is as follows:
* From the rightmost digit, which is the check digit, moving left, double the value of every second digit; if the product of this doubling operation is greater than 9 (e.g.... | algorithms | def valid_card(card):
s = list(map(int, str(card . replace(' ', ''))))
s[0:: 2] = [d * 2 - 9 if d * 2 > 9 else d * 2 for d in s[0:: 2]]
return sum(s) % 10 == 0
| Credit Card Checker | 56d55dcdc87df58c81000605 | [
"Fundamentals",
"Algorithms"
] | https://www.codewars.com/kata/56d55dcdc87df58c81000605 | 7 kyu |
Create a function that will return true if all numbers in the sequence follow the same counting pattern. If the sequence of numbers does not follow the same pattern, the function should return false.
Sequences will be presented in an array of varied length. Each array will have a minimum of 3 numbers in it.
The seque... | reference | def validate_sequence(seq):
return len({a - b for a, b in zip(seq, seq[1:])}) == 1
| Simple Sequence Validator | 553f01db29490a69ff000049 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/553f01db29490a69ff000049 | 7 kyu |
We have the number ```12385```. We want to know the value of the closest cube but higher than 12385. The answer will be ```13824```.
Now, another case. We have the number ```1245678```. We want to know the 5th power, closest and higher than that number. The value will be ```1419857```.
We need a function ```find_next... | reference | def find_next_power(val, pow_):
return int(val * * (1.0 / pow_) + 1) * * pow_
| Find the smallest power higher than a given a value | 56ba65c6a15703ac7e002075 | [
"Fundamentals",
"Mathematics",
"Logic"
] | https://www.codewars.com/kata/56ba65c6a15703ac7e002075 | 7 kyu |
Given a list of rows of a square matrix, find the product of the main diagonal.
Examples:
```
[[1, 0], [0, 1]] should return 1
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] should return 45
```
http://en.wikipedia.org/wiki/Main_diagonal
| algorithms | def main_diagonal_product(mat):
prod = 1
for i in range(0, len(mat)):
prod *= mat[i][i]
return prod
| Product of the main diagonal of a square matrix. | 551204b7509063d9ba000b45 | [
"Matrix",
"Linear Algebra",
"Algorithms"
] | https://www.codewars.com/kata/551204b7509063d9ba000b45 | 7 kyu |
<h2>Description</h2>
In English we often use "neutral vowel sounds" such as "umm", "err", "ahh" as fillers in conversations to help them run smoothly.
Bob always finds himself saying "err". Infact he adds an "err" to every single word he says that ends in a consonant! Because Bob is odd, he likes to stick to this hab... | reference | def err_bob(s):
res = ""
for i, c in enumerate(s):
res += c
if i == len(s) - 1 or s[i + 1] in " .,:;!?":
if c . islower() and c not in "aeiou":
res += "err"
if c . isupper() and c not in "AEIOU":
res += "ERR"
return res
| Please help Bob | 5751fef5dcc1079ac5001cff | [
"Fundamentals"
] | https://www.codewars.com/kata/5751fef5dcc1079ac5001cff | 7 kyu |
You're in ancient Greece and giving Philoctetes a hand in preparing a training exercise for Hercules! You've filled a pit with two different ferocious mythical creatures for Hercules to battle!
**Orthus**

**Hydra**
![... | reference | def beasts(h, t):
out = [(5 * t - h) / 3, (h - 2 * t) / 3]
return all(x . is_integer() and x >= 0 for x in out) and out or 'No solutions'
| Mythical Heads and Tails | 5751aa92f2dac7695d000fb0 | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/5751aa92f2dac7695d000fb0 | 7 kyu |
Create a function that takes a number and returns an array of strings containing the number cut off at each digit.
### Examples
* `420` should return ``["4", "42", "420"]``
* `2017` should return `["2", "20", "201", "2017"]`
* `2010` should return `["2", "20", "201", "2010"]`
* `4020` should return `["4", "40", "402"... | reference | def create_array_of_tiers(n):
n = str(n)
return [n[: i] for i in range(1, len(n) + 1)]
| Number to digit tiers | 586bca7fa44cfc833e00005c | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/586bca7fa44cfc833e00005c | 7 kyu |
You will be given an array which will include both integers and characters.
Return an array of length 2 with a[0] representing the mean of the ten integers as a floating point number. There will always be 10 integers and 10 characters. Create a single string with the characters and return it as a[1] while maintaining... | reference | def mean(lst):
return [sum(int(n) for n in lst if n . isdigit()) / 10.0, "" . join(c for c in lst if c . isalpha())]
| Calculate mean and concatenate string | 56f7493f5d7c12d1690000b6 | [
"Fundamentals"
] | https://www.codewars.com/kata/56f7493f5d7c12d1690000b6 | 7 kyu |
Write a function that takes an array of strings as an argument and returns a sorted array containing the same strings, ordered from shortest to longest.
For example, if this array were passed as an argument:
``` ["Telescopes", "Glasses", "Eyes", "Monocles"] ```
Your function would return the following array:
``` ["... | reference | def sort_by_length(arr):
return sorted(arr, key=len)
| Sort array by string length | 57ea5b0b75ae11d1e800006c | [
"Sorting",
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/57ea5b0b75ae11d1e800006c | 7 kyu |
Write a function that takes an array of **unique** integers and returns the minimum number of integers needed to make the values of the array consecutive from the lowest number to the highest number.
## Example
```
[4, 8, 6] --> 2
Because 5 and 7 need to be added to have [4, 5, 6, 7, 8]
[-1, -5] --> 3
Because -2, -... | reference | def consecutive(arr):
return max(arr) - min(arr) + 1 - len(arr) if arr else 0
| How many consecutive numbers are needed? | 559cc2d2b802a5c94700000c | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/559cc2d2b802a5c94700000c | 7 kyu |
The Cat In The Hat has cat A under his hat, cat A has cat B under his hat and so on until Z
The Cat In The Hat is 2,000,000 cat units tall.
Each cat is 2.5 times bigger than the cat underneath their hat.
Find the total height of the cats if they are standing on top of one another.
Counting starts from the Cat In Th... | reference | def height(n):
height = cat = 2000000
for i in range(n):
cat /= 2.5
height += cat
return f' { height : .3 f } '
| Cats in hats | 57b5907920b104772c00002a | [
"Fundamentals"
] | https://www.codewars.com/kata/57b5907920b104772c00002a | 7 kyu |
Removed due to copyright infringement.
<!---
### Task
Given two cells on the standard chess board, determine whether they have the same color or not.
### Example
For `cell1 = "A1" and cell2 = "C3"`, the output should be `true`.
:
return (ord(a[0]) + int(a[1])) % 2 == (ord(b[0]) + int(b[1])) % 2
| Chess Fun #1: Chess Board Cell Color | 5894134c8afa3618c9000146 | [
"Puzzles",
"Games"
] | https://www.codewars.com/kata/5894134c8afa3618c9000146 | 6 kyu |
This is the first part of this kata series. Second part is [here](https://www.codewars.com/kata/assembler-interpreter-part-ii/).
We want to create a simple interpreter of assembler which will support the following instructions:
- `mov x y` - copies `y` (either a constant value or the content of a register) into regis... | algorithms | def simple_assembler(program):
d, i = {}, 0
while i < len(program):
cmd, r, v = (program[i] + ' 0'). split()[: 3]
if cmd == 'inc':
d[r] += 1
if cmd == 'dec':
d[r] -= 1
if cmd == 'mov':
d[r] = d[v] if v in d else int(v)
if cmd == 'jnz' and (d[r] if r in d else int(r)):... | Simple assembler interpreter | 58e24788e24ddee28e000053 | [
"Interpreters",
"Algorithms"
] | https://www.codewars.com/kata/58e24788e24ddee28e000053 | 5 kyu |
# Task
You are given two strings s and t of the same length, consisting of uppercase English letters. Your task is to find the minimum number of "replacement operations" needed to get some `anagram` of the string t from the string s. A replacement operation is performed by picking exactly one character from the string... | games | from collections import Counter
def create_anagram(s, t):
return sum((Counter(s) - Counter(t)). values())
| Simple Fun #32: Create Anagram | 5887099cc815166a960000c6 | [
"Puzzles"
] | https://www.codewars.com/kata/5887099cc815166a960000c6 | 7 kyu |
# Task
Given some points(array `A`) on the same line, determine the minimum number of line segments with length `L` needed to cover all of the given points. A point is covered if it is located inside some segment or on its bounds.
# Example
For `A = [1, 3, 4, 5, 8]` and `L = 3`, the output should be `2`.
Check ou... | games | def segment_cover(A, L):
n = 1
s = min(A)
for i in sorted(A):
if s + L < i:
s = i
n += 1
return n
| Simple Fun #109: Segment Cover | 589ac16a0cccbff11d000115 | [
"Puzzles"
] | https://www.codewars.com/kata/589ac16a0cccbff11d000115 | 7 kyu |
If you're faced with an input box, like this:
+--------------+
Enter the price of the item, in dollars: | |
+--------------+
do you put the $ sign in, or not? Inevitably, some people will type a $ sign and... | reference | def money_value(s):
try:
return float(s . replace("$", ""). replace(" ", ""))
except:
return 0.0
| Unwanted dollars | 587309155cfd6b9fb60000a0 | [
"Fundamentals"
] | https://www.codewars.com/kata/587309155cfd6b9fb60000a0 | 6 kyu |
**This Kata is intended as a small challenge for my students**
All Star Code Challenge #29
Your friend Nhoj has dislexia, but can easily read messages if the words are written backwards.
Create a function called `reverseSentence()/reverse_sentence()` that accepts a string argument. The function returns a string of ... | reference | def reverse_sentence(sentence):
return ' ' . join(w[:: - 1] for w in sentence . split())
| All Star Code Challenge #29 | 5866ec8b2e8d9cec7e0000bb | [
"Fundamentals"
] | https://www.codewars.com/kata/5866ec8b2e8d9cec7e0000bb | 7 kyu |
# Task
You have some people who are betting money, and they all start with the same amount of money (this number>0).
Find out if the given end-state of amounts is possible after the betting is over and money is redistributed.
# Input/Output
- `[input]` integer array arr
the proposed end-state showing final a... | games | def learn_charitable_game(arr):
return sum(arr) % len(arr) == 0 and sum(arr) > 0
| Simple Fun #131: Learn Charitable Game | 58a651ff27f95429f80000d0 | [
"Puzzles"
] | https://www.codewars.com/kata/58a651ff27f95429f80000d0 | 7 kyu |
Program a function `sumAverage(arr)` where `arr` is an array containing arrays full of numbers, for example:
```javascript
sumAverage([[1, 2, 2, 1], [2, 2, 2, 1]]);
```
```python
sum_average([[1, 2, 2, 1], [2, 2, 2, 1]]);
```
```ruby
sum_average([[1, 2, 2, 1], [2, 2, 2, 1]]);
```
```php
sumAverage([[1, 2, 2, 1], [2, 2... | algorithms | from statistics import mean
from math import floor
def sum_average(arr):
return floor(sum(map(mean, arr)))
| Sum of Array Averages | 56d5166ec87df55dbe000063 | [
"Arrays",
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/56d5166ec87df55dbe000063 | 7 kyu |
This series of katas will introduce you to basics of doing geometry with computers.
`Point` objects have `x`, `y` attributes. `Triangle` objects have attributes `a`, `b`, `c` describing their corners, each of them is a `Point`.
Write a function calculating perimeter of a `Triangle` defined this way.
Tests round answ... | reference | from math import hypot
def triangle_perimeter(t):
return sum(
hypot(p1 . x - p2 . x, p1 . y - p2 . y)
for p1, p2 in [(t . a, t . b), (t . b, t . c), (t . c, t . a)]
)
| Geometry Basics: Triangle Perimeter in 2D | 58e3e62f20617b6d7700120a | [
"Geometry",
"Fundamentals"
] | https://www.codewars.com/kata/58e3e62f20617b6d7700120a | 7 kyu |
You have to create a function that converts integer given as string into ASCII uppercase letters or spaces.
All ASCII characters have their numerical order in table.
For example,
```
from ASCII table, character of number 65 is "A".
```
Numbers will be next to each other, So you have to split given number to two di... | reference | def convert(number):
return '' . join(chr(int(number[a: a + 2])) for a in range(0, len(number), 2))
| ASCII letters from Number | 589ebcb9926baae92e000001 | [
"Fundamentals"
] | https://www.codewars.com/kata/589ebcb9926baae92e000001 | 7 kyu |
# Task
Alireza and Ali have a `3×3 table` and playing on that. They have 4 tables (2×2) A,B,C and D in this table.
At beginning all of 9 numbers in 3×3 table is zero.
Alireza in each move choose a 2×2 table from A, B, C and D and increase all of 4 numbers in that by one.
He asks Ali, how much he increase tabl... | algorithms | def table_game(table):
(a, ab, b), (ac, abcd, bd), (c, cd, d) = table
if (a + b == ab) and (c + d == cd) and (a + c == ac) and (b + d == bd) and (a + b + c + d == abcd):
return [a, b, c, d]
return [- 1]
| Simple Fun #145: Table Game | 58aa7f18821a769a7d000190 | [
"Algorithms"
] | https://www.codewars.com/kata/58aa7f18821a769a7d000190 | 7 kyu |
Complete the function which takes a non-zero integer as its argument.
If the integer is divisible by 3, return the string `"Java"`.
If the integer is divisible by 3 and divisible by 4, return the string `"Coffee"`
If one of the condition above is true and the integer is even, add `"Script"` to the end of the string.... | reference | def caffeineBuzz(n):
buzz = "mocha_missing!"
if n % 3 == 0:
buzz = "Java"
if n % 4 == 0:
buzz = "Coffee"
if n % 2 == 0:
buzz += "Script"
return buzz
| Caffeine Script | 5434283682b0fdb0420000e6 | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/5434283682b0fdb0420000e6 | 7 kyu |
# Task
We have a N×N `matrix` (N<10) and a robot.
We wrote in each point of matrix x and y coordinates of a point of matrix.
When robot goes to a point of matrix, reads x and y and transfer to point with x and y coordinates.
For each point in the matrix we want to know if robot returns back to it after `EXA... | games | def robot_transfer(matrix, k):
mt = {(i, j): tuple(map(int, c . split(',')))
for i, r in enumerate(matrix) for j, c in enumerate(r)}
res = 0
for m in mt:
cur = m
for j in range(k):
cur = mt[cur]
if cur == m:
break
res += (cur == m and j == k - 1)
return... | Simple Fun #150: Robot Transfer | 58aaa3ca821a767300000017 | [
"Puzzles"
] | https://www.codewars.com/kata/58aaa3ca821a767300000017 | 6 kyu |
# Task
Given string `s`, which contains only letters from `a to z` in lowercase.
A set of alphabet is given by `abcdefghijklmnopqrstuvwxyz`.
2 sets of alphabets mean 2 or more alphabets.
Your task is to find the missing letter(s). You may need to output them by the order a-z. It is possible that there is more ... | games | from collections import Counter
from string import ascii_lowercase
def missing_alphabets(s):
c = Counter(s)
m = max(c . values())
return '' . join(letter * (m - c[letter]) for letter in ascii_lowercase)
| Simple Fun #135: Missing Alphabets | 58a664bb586e986c940001d5 | [
"Puzzles"
] | https://www.codewars.com/kata/58a664bb586e986c940001d5 | 6 kyu |
To introduce the problem think to my neighbor who drives a tanker truck.
The level indicator is down and he is worried
because he does not know if he will be able to make deliveries.
We put the truck on a horizontal ground and measured the height of the liquid in the tank.
Fortunately the tank is a perfect cylinder ... | reference | import math
def tankvol(h, d, vt):
r = d / 2
theta = math . acos((r - h) / r)
return int(vt * (theta - math . sin(theta) * (r - h) / r) / math . pi)
| Tank Truck | 55f3da49e83ca1ddae0000ad | [
"Mathematics",
"Geometry"
] | https://www.codewars.com/kata/55f3da49e83ca1ddae0000ad | 6 kyu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.