description stringlengths 38 154k | category stringclasses 5
values | solutions stringlengths 13 289k | name stringlengths 3 179 | id stringlengths 24 24 | tags listlengths 0 13 | url stringlengths 54 54 | rank_name stringclasses 8
values |
|---|---|---|---|---|---|---|---|
You're given a string containing a sequence of words separated with whitespaces. Let's say it is a sequence of patterns: a name and a corresponding number - like this:
```"red 1 yellow 2 black 3 white 4"```
You want to turn it into a different **string** of objects you plan to work with later on - like this:
```"[{n... | reference | import re
def words_to_object(s):
return "[" + re . sub("([^ ]+) ([^ ]+)", r"{name : '\1', id : '\2'},", s). strip(',') + "]"
| Creating a string for an array of objects from a set of words | 5877786688976801ad000100 | [
"Fundamentals",
"Strings",
"Regular Expressions"
] | https://www.codewars.com/kata/5877786688976801ad000100 | 6 kyu |
Because my other two parts of the serie were pretty well received I decided to do another part.
# Puzzle Tiles
You will get two **Integer** `n`(width) and `m` (height) and your task is to draw following pattern. Each line is seperated with `'\n'`.
- Both integers are equal or greater than 1. No need to check for inv... | algorithms | def puzzle_tiles(width, height):
def f():
yield ' ' + ' _( )__' * width
for i in range(height):
if i % 2 == 0:
yield ' _|' + ' _|' * width
yield '(_' + ' _ (_' * width
yield ' |' + '__( )_|' * width
else:
yield ' |_' + ' |_' * width
yield ' _)' + ' _ _)' * width
yield ' |' + ... | ASCII Fun #3: Puzzle Tiles | 5947d86e07693bcf000000c4 | [
"ASCII Art"
] | https://www.codewars.com/kata/5947d86e07693bcf000000c4 | 6 kyu |
Motivation
---------
When compressing sequences of symbols, it is useful to have many equal symbols follow each other, because then they can be encoded with a run length encoding. For example, RLE encoding of `"aaaabbbbbbbbbbbcccccc"` would give something like `4a 11b 6c`.
(Look [here](http://www.codewars.com/kata/ru... | algorithms | def encode(s):
lst = sorted(s[i or len(s):] + s[: i or len(s)]
for i in reversed(range(len(s))))
return '' . join(ss[- 1] for ss in lst), s and lst . index(s) or 0
def decode(s, n):
out, lst = [], sorted((c, i) for i, c in enumerate(s))
for _ in range(len(s)):
c, n = lst[... | Burrows-Wheeler-Transformation | 54ce4c6804fcc440a1000ecb | [
"Lists",
"Puzzles",
"Algorithms"
] | https://www.codewars.com/kata/54ce4c6804fcc440a1000ecb | 4 kyu |
If you like Taco Bell, you will be familiar with their signature doritos locos taco. They're very good.
Why can't everything be a taco? We're going to attempt that here, turning every word we find into the taco bell recipe with each ingredient.
We want to input a word as a string, and return a list representing tha... | reference | import re
TACODICT = {
't': 'tomato',
'l': 'lettuce',
'c': 'cheese',
'g': 'guacamole',
's': 'salsa'
}
def tacofy(word):
return ['shell'] + [TACODICT . get(c, 'beef') for c in re . sub('[^aeioutlcgs]+', '', word . lower())] + ['shell']
| Turn any word into a beef taco | 59414b46d040b7b8f7000021 | [
"Fundamentals"
] | https://www.codewars.com/kata/59414b46d040b7b8f7000021 | 7 kyu |
Find the difference between two collections. The difference means that either the character is present in one collection or it is present in other, but not in both. Return a sorted list with the difference.
The collections can contain any character and can contain duplicates.
## Example
```
A = [a, a, t, e, f, i, j]... | algorithms | def diff(a, b):
return sorted(set(a) ^ set(b))
| Difference between two collections | 594093784aafb857f0000122 | [
"Fundamentals",
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/594093784aafb857f0000122 | 7 kyu |
Given an array of numbers, return a string made up of four parts:
* a four character 'word', made up of the characters derived from the first two and last two numbers in the array. order should be as read left to right (first, second, second last, last),
* the same as above, post sorting the array into ascending orde... | reference | def extract(arr): return '' . join(arr[: 2] + arr[- 2:])
def sort_transform(arr):
arr = list(map(chr, arr))
w1 = extract(arr)
arr . sort()
w2 = extract(arr)
return f' { w1 } - { w2 } - { w2 [:: - 1 ]} - { w2 } '
| Sort and Transform | 57cc847e58a06b1492000264 | [
"Fundamentals",
"Strings",
"Arrays",
"Sorting",
"Algorithms"
] | https://www.codewars.com/kata/57cc847e58a06b1492000264 | 7 kyu |
# Introduction
There is a war and nobody knows - the alphabet war!
There are two groups of hostile letters. The tension between left side letters and right side letters was too high and the war began. The letters have discovered a new unit - a priest with Wo lo looooooo power.
<img src="https://i.imgur.com/AUaPiip.... | reference | SWAP = {'j': {'w': 'm', 'p': 'q', 'b': 'd', 's': 'z'},
't': {'m': 'w', 'q': 'p', 'd': 'b', 'z': 's'}}
def alphabet_war(fight):
s = 0
for l, c, r in zip(' ' + fight, fight, fight[1:] + ' '):
if l + r not in 'tjt':
c = SWAP . get(l, {}). get(c, c)
c = SWAP . get(r, {}). get(c, c)
... | Alphabet war - Wo lo loooooo priests join the war | 59473c0a952ac9b463000064 | [
"Strings",
"Regular Expressions"
] | https://www.codewars.com/kata/59473c0a952ac9b463000064 | 5 kyu |
*This is the second Kata in the Ciphers series. This series is meant to test our coding knowledge.*
## Ciphers #2 - The reversed Cipher
This is a lame method I use to write things such that my friends don't understand. It's still fairly readable if you think about it.
## How this cipher works
First, you need to rever... | reference | def encode(s):
return ' ' . join(w[- 2:: - 1] + w[- 1] for w in s . split())
| Ciphers #2 - The reversed Cipher | 59474c656ff02b21e20000fc | [
"Fundamentals"
] | https://www.codewars.com/kata/59474c656ff02b21e20000fc | 6 kyu |
In this exercise, you will have to create a function named tiyFizzBuzz. This function will take on a string parameter and will return that string with some characters replaced, depending on the value:
- If a letter is a upper case consonants, replace that character with "Iron".
- If a letter is a lower case consonants... | reference | def tiy_fizz_buzz(s):
return "" . join(("Iron " * c . isupper() + "Yard" * (c . lower() in "aeiou")). strip() or c for c in s)
| TIY-FizzBuzz | 5889177bf148eddd150002cc | [
"Fundamentals"
] | https://www.codewars.com/kata/5889177bf148eddd150002cc | 7 kyu |
# Find the gatecrashers on CocoBongo parties
CocoBongo is a club with very nice parties. However, you only can get inside if you know at least one other guest. Unfortunately, some gatecrashers can appear at those parties. The gatecrashers do not know any other party member and should not be at our amazing party!
We w... | reference | def find_gatecrashers(people, invitations):
crashersSet = {elt for i, li in invitations for elt in [i] + li}
return [p for p in people if p not in crashersSet]
| Find the gatecrashers on CocoBongo parties | 5945fe7d9b33194f960000df | [
"Arrays",
"Performance",
"Fundamentals",
"Graph Theory"
] | https://www.codewars.com/kata/5945fe7d9b33194f960000df | 6 kyu |
Every Friday and Saturday night, farmer counts amount of sheep returned back to his farm (sheep returned on Friday stay and don't leave for a weekend).
Sheep return in groups each of the days -> you will be given two arrays with these numbers (one for Friday and one for Saturday night). Entries are always positive int... | reference | def lost_sheep(friday, saturday, total):
return total - (sum(friday) + sum(saturday))
| Count all the sheep on farm in the heights of New Zealand | 58e0f0bf92d04ccf0a000010 | [
"Fundamentals",
"Mathematics",
"Algorithms",
"Algebra"
] | https://www.codewars.com/kata/58e0f0bf92d04ccf0a000010 | 7 kyu |
Construct a function 'coordinates', that will return the distance between two points on a cartesian plane, given the x and y coordinates of each point.
There are two parameters in the function, ```p1``` and ```p2```. ```p1``` is a list ```[x1,y1]``` where ```x1``` and ```y1``` are the x and y coordinates of the first ... | reference | def coordinates(p1, p2, precision=0):
return round(sum((b - a) * * 2 for a, b in zip(p1, p2)) * * .5, precision)
| Distance Between 2 Points on a Cartesian Plane | 5944f3f8d7b6a5748d000233 | [
"Mathematics",
"Algebra",
"Fundamentals"
] | https://www.codewars.com/kata/5944f3f8d7b6a5748d000233 | 7 kyu |
Write a function that always returns `5`
Sounds easy right? Just bear in mind that you can't use any of the following characters: `0123456789*+-/`
Good luck :)
| reference | def unusual_five():
return len("five!")
| 5 without numbers !! | 59441520102eaa25260000bf | [
"Restricted",
"Fundamentals",
"Puzzles"
] | https://www.codewars.com/kata/59441520102eaa25260000bf | 8 kyu |
Most substitution ciphers involve the use of a shift value. The simplest ones apply the same shift value to all letters. Some are slightly more sophisticated, but there is still a consistent rule governing the shift.
This kata is different. Your task here is to create a random substitution cipher.
There is no input t... | reference | from random import *
def random_sub():
s = 'abcdefghijklmnopqrstuvwxyz'
return dict(zip(s, sample(s, k=26)))
| Random Substitution Cipher | 5943bf2895d5f74cfb000032 | [
"Fundamentals"
] | https://www.codewars.com/kata/5943bf2895d5f74cfb000032 | 6 kyu |
Write a function that takes a positive integer and returns the next smaller positive integer containing the same digits.
For example:
```javascript
nextSmaller(21) == 12
nextSmaller(531) == 513
nextSmaller(2071) == 2017
```
```haskell
nextSmaller(21) == 12
nextSmaller(531) == 513
nextSmaller(2071) == 2017
```
```csha... | algorithms | def next_smaller(n):
s = list(str(n))
i = j = len(s) - 1
while i > 0 and s[i - 1] <= s[i]:
i -= 1
if i <= 0:
return - 1
while s[j] >= s[i - 1]:
j -= 1
s[i - 1], s[j] = s[j], s[i - 1]
s[i:] = reversed(s[i:])
if s[0] == '0':
return - 1
return int('' . jo... | Next smaller number with the same digits | 5659c6d896bc135c4c00021e | [
"Strings",
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/5659c6d896bc135c4c00021e | 4 kyu |
# Introduction
There is a war and nobody knows - the alphabet war!
The letters hide in their nuclear shelters. The nuclear strikes hit the battlefield and killed a lot of them.
# Task
Write a function that accepts `battlefield` string and returns letters that survived the nuclear strike.
- The `battlefield` str... | reference | import re
def alphabet_war(b):
if '#' not in b:
return re . sub(r"[\[\]]", "", b)
p = re . compile('([a-z#]*)\[([a-z]+)\](?=([a-z#]*))')
return '' . join(e[1] if (e[0] + e[2]). count('#') < 2 else '' for e in p . findall(b))
| Alphabet wars - nuclear strike | 59437bd7d8c9438fb5000004 | [
"Strings",
"Regular Expressions",
"Fundamentals"
] | https://www.codewars.com/kata/59437bd7d8c9438fb5000004 | 5 kyu |
Just another day in the world of Minecraft, Steve is getting ready to start his next exciting project -- building a railway system!

But first, Steve needs to melt some iron ores in the furnace to get the m... | reference | t = ((800, "lava"), (120, "blaze rod"),
(80, "coal"), (15, "wood"), (1, "stick"))
def calc_fuel(n):
s, r = n * 11, {}
for d, e in t:
r[e], s = divmod(s, d)
return r
| [Minecraft Series #2] Minimum amount of fuel needed to get some iron ingots | 583a02740b0a9fdf5900007c | [
"Fundamentals"
] | https://www.codewars.com/kata/583a02740b0a9fdf5900007c | 6 kyu |
Write three functions `add`, `subtract`, and `multiply` such that each require two invocations.
For example:
```javascript
add(3)(4) // 7
subtract(3)(4) // -1
multiply(3)(4) // 12
```
```python
add(3)(4) # 7
subtract(3)(4) # -1
multiply(3)(4) # 12
```
Once you have done this. Write a function `apply` that... | reference | def add(a):
return lambda b: a + b
def subtract(a):
return lambda b: a - b
def multiply(a):
return lambda b: a * b
def apply(op):
return op
| The Crockford Invocation | 57e7d21f6603f6e31f00007c | [
"Fundamentals"
] | https://www.codewars.com/kata/57e7d21f6603f6e31f00007c | 7 kyu |
## A Man and his Umbrellas ##
Each morning a man walks to work, and each afternoon he walks back home.
If it is raining in the morning and he has an umbrella at home, he takes an umbrella for the journey so he doesn't get wet, and stores it at work. Likewise, if it is raining in the afternoon and he has an umbrella... | reference | def min_umbrellas(weather):
home = work = 0
for i, w in enumerate(weather):
if w not in ['rainy', 'thunderstorms']:
continue
if i % 2 == 0:
work += 1
home = max(home - 1, 0)
else:
home += 1
work = max(work - 1, 0)
return home + work
| A Man and his Umbrellas | 58298e19c983caf4ba000c8d | [
"Logic",
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/58298e19c983caf4ba000c8d | 5 kyu |

Create a class called `Warrior` which calculates and keeps track of their level and skills, and ranks them as the warrior they've proven to be.
<b><span style="color:#00BFFF">Business Rules:</span></b>
- A warrior s... | algorithms | class Warrior ():
def __init__(self):
self . _experience = 100
self . rs = ["Pushover", "Novice", "Fighter", "Warrior", "Veteran",
"Sage", "Elite", "Conqueror", "Champion", "Master", "Greatest"]
self . achievements = []
def training(self, train):
if (train[2] > self . l... | The Greatest Warrior | 5941c545f5c394fef900000c | [
"Algorithms",
"Object-oriented Programming"
] | https://www.codewars.com/kata/5941c545f5c394fef900000c | 4 kyu |
## Welcome to my (amazing) kata!
You are given a gigantic number to decode. Each number is a code that alternates in a pattern between encoded text and a smaller, encoded number. The pattern's length varies with every test, but the alternation between encoded text and an encoded number will always be there. Followi... | reference | def decode(number):
return ', ' . join(
str(int(w, 2)) if i % 2 else
'' . join(chr(int(w[x: x + 3]) - 4) for x in range(0, len(w), 3))
for i, w in enumerate(str(number). strip('98'). split('98'))
)
| Number Decoding | 5940ec284aafb87ef3000028 | [
"Fundamentals"
] | https://www.codewars.com/kata/5940ec284aafb87ef3000028 | 6 kyu |
Most languages have a `split` function that lets you turn a string like `“hello world”` into an array like`[“hello”, “world”]`. But what if we don't want to lose the separator? Something like `[“hello”, “ world”]`.
#### Task:
Your job is to implement a function, (`split_without_loss` in Ruby/Crystal, and `splitWithou... | reference | def split_without_loss(s, split_p):
return [i for i in s . replace(split_p . replace('|', ''), split_p). split('|') if i]
| Split Without Loss | 581951b3704cccfdf30000d2 | [
"Fundamentals"
] | https://www.codewars.com/kata/581951b3704cccfdf30000d2 | 6 kyu |
>When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said
# Description
Given a list of integers `A`, for each pair of integers `(first, last)` in list `ranges`, calculate the sum of the values in `A` between indices `first` and... | algorithms | from itertools import accumulate
def max_sum(a, ranges):
prefix = list(accumulate(a, initial=0))
return max(prefix[j + 1] - prefix[i] for i, j in ranges)
| The maximum sum value of ranges -- Challenge version | 583d171f28a0c04b7c00009c | [
"Algorithms"
] | https://www.codewars.com/kata/583d171f28a0c04b7c00009c | 5 kyu |
You are given two positive integers ```a``` and ```b```.
You can perform the following operations on ```a``` so as to obtain ```b``` :
```
(a-1)/2 (if (a-1) is divisible by 2)
a/2 (if a is divisible by 2)
a*2
```
```b``` will always be a power of 2.
You are to write a function ```operation(a,b)``` that effici... | reference | from math import log2
def operation(a, b, n=0):
while log2(a) % 1:
n += 1
a / /= 2
return n + abs(log2(a / b))
| Operation Transformation | 579ef9607cb1f38113000100 | [
"Fundamentals",
"Algorithms"
] | https://www.codewars.com/kata/579ef9607cb1f38113000100 | 6 kyu |
The number `1035` is the smallest integer that exhibits a non frequent property: one its multiples, `3105 = 1035 * 3`, has its same digits but in different order, in other words, `3105`, is one of the permutations of `1035`.
The number `125874` is the first integer that has this property when the multiplier is `2`, th... | reference | def search_perm_mult(n, k):
# your code here
return len([x for x in range(n, 0, - 1) if x % k == 0 and sorted([i for i in str(x)]) == sorted([i for i in str(x / / k)])])
| Multiples by permutations | 55f1a53d9c77b0ed4100004e | [
"Algorithms",
"Data Structures",
"Permutations",
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/55f1a53d9c77b0ed4100004e | 6 kyu |
# Task:
Write a function that accepts an integer `n` and returns **the sum of the factorials of the first **`n`** Fibonacci numbers**
## Examples:
```python
sum_fib(2) = 2 # 0! + 1! = 2
sum_fib(3) = 3 # 0! + 1! + 1! = 3
sum_fib(4) = 5 # 0! + 1! + 1! + 2! = 5
sum_fib(10) = 295232799039604140898709551821456... | reference | from math import factorial
def sum_fib(n):
a, b, s = 0, 1, 0
while n:
s += factorial(a)
a, b = b, a + b
n -= 1
return s
| Fib Factorials | 589926bf7a2a3992050014f1 | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/589926bf7a2a3992050014f1 | 6 kyu |
Implement a function, `multiples(m, n)`, which returns an array of the first `m` multiples of the real number `n`. Assume that `m` is a positive integer.
Ex.
```
multiples(3, 5.0)
```
should return
```
[5.0, 10.0, 15.0]
```
| reference | def multiples(m, n):
return [i * n for i in range(1, m + 1)]
| Return the first M multiples of N | 593c9175933500f33400003e | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/593c9175933500f33400003e | 7 kyu |
It's the most hotly anticipated game of the school year - Gryffindor vs Slytherin! Write a function which returns the winning team.
You will be given two arrays with two values.
The first given value is the number of points scored by the team's Chasers and the second a string with a 'yes' or 'no' value if the team ... | reference | def game_winners(gryffindor, slytherin):
g, s = (team[0] + 150 * (team[1] == 'yes')
for team in [gryffindor, slytherin])
return 'Gryffindor wins!' if g > s else 'Slytherin wins!' if s > g else "It's a draw!"
| Gryffindor vs Slytherin Quidditch Game | 5840946ea3d4c78e90000068 | [
"Fundamentals"
] | https://www.codewars.com/kata/5840946ea3d4c78e90000068 | 7 kyu |
*This is my first Kata in the Ciphers series. This series is meant to test our coding knowledge.*
## Ciphers #1 - The 01 Cipher
This cipher doesn't exist, I just created it by myself. It can't actually be used, as there isn't a way to decode it. It's a hash. Multiple sentences may also have the same result.
## How th... | reference | def encode(s):
return '' . join(str(1 - ord(c) % 2) if c . isalpha() else c for c in s)
| Ciphers #1 - The 01 Cipher | 593f50f343030bd35e0000c6 | [
"Fundamentals"
] | https://www.codewars.com/kata/593f50f343030bd35e0000c6 | 7 kyu |
For a given large number (num), write a function which returns the number with the second half of digits changed to 0.
In cases where the number has an odd number of digits, the middle digit onwards should be changed to 0.
<b>Example</b>:
192827764920 --> 192827000000
938473 --> 938000
2837743 --> 2830000
| reference | def manipulate(n):
n = str(n)
middle = len(n) / / 2
return int(n[: middle] + '0' * len(n[middle:]))
| Number Manipulation I (Easy) | 5890579a34a7d44f3b00009e | [
"Fundamentals"
] | https://www.codewars.com/kata/5890579a34a7d44f3b00009e | 7 kyu |
You have to create a function named`one_two` (`oneTwo` for Java or `Preloaded.OneTwo` for C#) that returns 1 or 2 with equal probabilities. `one_two` is already defined in a global scope and can be called everywhere.
Your goal is to create a function named `one_two_three` (`oneTwoThree` for Java or `OneTwoThree` for C... | games | def one_two_three():
res = one_two(), one_two()
return (1 if res == (1, 1) else
2 if res == (1, 2) else
3 if res == (2, 1) else
one_two_three())
| Return 1, 2, 3 randomly | 593e84f16e836ca9a9000054 | [
"Probability",
"Puzzles"
] | https://www.codewars.com/kata/593e84f16e836ca9a9000054 | 6 kyu |
Given a matrix represented as a list of string, such as
```
###.....
..###...
....###.
.....###
.....###
....###.
..###...
###.....
```
write a function
```if:javascript
`rotateClockwise(matrix)`
```
```if:ruby,python
`rotate_clockwise(matrix)`
```
that return its 90° clockwise rotation, for our example:
```
#......#
... | reference | def rotate_clockwise(m):
return ['' . join(l[:: - 1]) for l in zip(* m)]
| Matrix Rotation | 593e978a3bb47a8308000b8f | [
"Matrix",
"Fundamentals"
] | https://www.codewars.com/kata/593e978a3bb47a8308000b8f | 6 kyu |
# Introduction
There is a war and nobody knows - the alphabet war!
The letters called airstrikes to help them in war - dashes and dots are spread everywhere on the battlefield.
# Task
Write a function that accepts `reinforces` array of strings and `airstrikes` array of strings.
The `reinforces` strings consist o... | reference | def alphabet_war(r, airstrikes):
rIdx = [0] * (len(r[0]) + 2)
for a in airstrikes:
massacre = {i + d for i, c in enumerate(a, 1)
for d in range(- 1, 2) if c == '*'}
for i in massacre:
rIdx[i] += 1
return '' . join(r[row][i] if row < len(r) else "_" for i, row in enumer... | Alphabet wars - reinforces massacre | 593e2077edf0d3e2d500002d | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/593e2077edf0d3e2d500002d | 6 kyu |
You are very very happy and very very very excited to solve this Kata.
Show it to us by creating a function `iam` such as:
```javascript
iam('happy') // returns the string "I am happy"
iam('excited') // returns the string "I am excited"
iam()('scared') // returns the string "I am very scared"
iam()()('interested') //... | reference | def iam(* s, n=0):
return f'I am { " very" * n } { s [ 0 ] } ' if s else lambda * s: iam(* s, n=n + 1)
| I am very very very.... | 58402cdc5225619d0c0000cb | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/58402cdc5225619d0c0000cb | 6 kyu |
A faro shuffle of a deck of playing cards is a shuffle in which the deck is split exactly in half and then the cards in the two halves are perfectly interwoven, such that the original bottom card is still on the bottom and the original top card is still on top.
For example, faro shuffling the list
```python
['ace', '... | reference | def faro_cycles(n):
x, cnt = 2, 1
while x != 1 and n > 3:
cnt += 1
x = x * 2 % (n - 1)
return cnt
| Faro Shuffle Count | 57bc802c615f0ba1e3000029 | [
"Lists",
"Iterators",
"Fundamentals"
] | https://www.codewars.com/kata/57bc802c615f0ba1e3000029 | 6 kyu |
You need to cook pancakes, but you are very hungry. As known, one needs to fry a pancake one minute on each side. What is the minimum time you need to cook `n` pancakes, if you can put on the frying pan only `m` pancakes at a time? `n` and `m` are positive integers between 1 and 1000. | reference | from math import ceil
def cook_pancakes(n, m):
if m > n:
return 2
else:
return ceil((n / m) * 2)
| Fast cooking pancakes | 58552bdb68b034a1a80001fb | [
"Logic",
"Fundamentals"
] | https://www.codewars.com/kata/58552bdb68b034a1a80001fb | 7 kyu |
# Task
Smartphones software security has become a growing concern related to mobile telephony. It is particularly important as it relates to the security of available personal information.
For this reason, Ahmed decided to encrypt phone numbers of contacts in such a way that nobody can decrypt them. At first he tri... | games | def decrypt(s):
for n in range(1, 11):
res, mod = divmod(int(str(n) + s), 11)
if mod == 0:
return str(res)
return 'impossible'
| Simple Fun #126: Decrypt Number | 58a3cb34623e8c119d0000d5 | [
"Puzzles"
] | https://www.codewars.com/kata/58a3cb34623e8c119d0000d5 | 6 kyu |
Find the longest substring within a string that contains at most 2 unique characters.
```
substring("a") => "a"
substring("aaa") => "aaa"
substring("abacd") => "aba"
substring("abacddcd") => "cddcd"
substring("cefageaacceaccacca") => "accacca"
```
This function will take alphanumeric characters as input.
In cases wh... | algorithms | def substring(s):
r, rm = [], []
for i, x in enumerate(s):
if x in r or len(set(r)) < 2:
r += x
else:
if len(r) > len(rm):
rm = r[:]
r = [y for y in r[- 1:: - 1] if y == r[- 1]] + [x]
if len(r) > len(rm):
rm = r[:]
return '' . join(rm)
| Longest 2-character substring | 55bc0c54147a98798f00003e | [
"Algorithms"
] | https://www.codewars.com/kata/55bc0c54147a98798f00003e | 6 kyu |
Your task is to create a new implementation of `modpow` so that it computes `(x^y)%n` for large `y`. The problem with the current implementation is that the output of `Math.pow` is so large on our inputs that it won't fit in a 64-bit float.
You're also going to need to be efficient, because we'll be testing some prett... | algorithms | def power_mod(b, e, m):
res, b = 1, b % m
while e > 0:
if e & 1:
res = res * b % m
e >>= 1
b = b * b % m
return res
| Efficient Power Modulo n | 52fe629e48970ad2bd0007e6 | [
"Mathematics",
"Algorithms",
"Performance"
] | https://www.codewars.com/kata/52fe629e48970ad2bd0007e6 | 5 kyu |
For a given list `[x1, x2, x3, ..., xn]` compute the last (decimal) digit of
`x1 ^ (x2 ^ (x3 ^ (... ^ xn)))`.
E. g., with the input `[3, 4, 2]`, your code should return `1` because `3 ^ (4 ^ 2) = 3 ^ 16 = 43046721`.
_Beware:_ powers grow incredibly fast. For example, `9 ^ (9 ^ 9)` has more than 369 millions of dig... | algorithms | def last_digit(lst):
n = 1
for x in reversed(lst):
n = x * * (n if n < 4 else n % 4 + 4)
return n % 10
| Last digit of a huge number | 5518a860a73e708c0a000027 | [
"Algorithms",
"Mathematics"
] | https://www.codewars.com/kata/5518a860a73e708c0a000027 | 3 kyu |
In this country soldiers are poor but they need a certain level of secrecy for their communications so, though they do not know Caesar cypher, they reinvent it in the following way.
The action of a Caesar cipher is to replace each plaintext letter (plaintext letters are from 'a' to 'z' or from 'A' to 'Z') with a diffe... | reference | def shift_char(c, i):
r = c
if ord('a') <= ord(c) <= ord('z'):
o = (ord(c) - ord('a') + i) % 26
r = chr(o + ord('a'))
elif ord('A') <= ord(c) <= ord('Z'):
o = (ord(c) - ord('A') + i) % 26
r = chr(o + ord('A'))
return r
def encode_str(strng, shift):
encoded = ""
c =... | Second Variation on Caesar Cipher | 55084d3898b323f0aa000546 | [
"Fundamentals",
"Ciphers",
"Cryptography"
] | https://www.codewars.com/kata/55084d3898b323f0aa000546 | 5 kyu |
## Task
You are given a car odometer which displays the miles traveled as an integer.
The odometer has a defect, however: it proceeds from digit `3` to digit `5` always skipping the digit `4`. This defect shows up in all positions (ones, tens, hundreds, etc).
For example, if the odometer displays `15339` and t... | algorithms | tr = str . maketrans('56789', '45678')
def faulty_odometer(n):
return int(str(n). translate(tr), 9)
| Simple Fun #178: Faulty Odometer | 58b8d22560873d9068000085 | [
"Algorithms"
] | https://www.codewars.com/kata/58b8d22560873d9068000085 | 5 kyu |
A common problem in number theory is to find x given a such that:
a * x = 1 mod [n]
Then x is called the inverse of a modulo n.
Your goal is to code a function inverseMod wich take a and n as parameters and return x.
You may be interested by these pages:
http://en.wikipedia.org/wiki/Modular_multiplicative_invers... | algorithms | from math import gcd
def inverseMod(a, m):
if gcd(a, m) == 1:
return pow(a, - 1, m)
| Modular Multiplicative Inverse | 53c945d750fe7094ee00016b | [
"Algorithms",
"Mathematics"
] | https://www.codewars.com/kata/53c945d750fe7094ee00016b | 6 kyu |
This Kata is a continuation of [Part 1](http://www.codewars.com/kata/the-fusc-function-part-1). The `fusc` function is defined recursively as follows:
fusc(0) = 0
fusc(1) = 1
fusc(2n) = fusc(n)
fusc(2n + 1) = fusc(n) + fusc(n + 1)
Your job is to produce the code for the `fusc` function. In this ka... | algorithms | def fusc(n):
a, b = 1, 0
for i in bin(n)[2:]:
if i == '1':
b += a
else:
a += b
return b
| The fusc function -- Part 2 | 57040e445a726387a1001cf7 | [
"Algorithms",
"Recursion"
] | https://www.codewars.com/kata/57040e445a726387a1001cf7 | 4 kyu |
Every natural number, ```n```, may have a prime factorization like:
<a href="http://imgur.com/M5n0WCg"><img src="http://i.imgur.com/M5n0WCg.png?1" title="source: imgur.com" /></a>
We define the arithmetic derivative of ```n```, ```n'``` the value of the expression:
<a href="http://imgur.com/D9Ckb8P"><img src="http:/... | reference | from collections import Counter
def factorization(n):
res, cur = Counter(), 2
while n > 1 and n >= cur * * 2:
if n % cur == 0:
res[cur] += 1
n / /= cur
else:
cur += (1 if cur == 2 else 2)
if n > 1:
res[n] += 1
return res
def arithm_deriv(n):
return ... | Building Chains Using the Arithmetic Derivative of a Number | 572ced1822719279fa0005ea | [
"Fundamentals",
"Mathematics",
"Recursion"
] | https://www.codewars.com/kata/572ced1822719279fa0005ea | 6 kyu |
Ever since you started work at the grocer, you have been faithfully logging down each item and its category that passes through. One day, your boss walks in and asks, "Why are we just randomly placing the items everywhere? It's too difficult to find anything in this place!" Now's your chance to improve the system, impr... | reference | def group_groceries(groceries):
categories = {"fruit": [], "meat": [], "other": [], "vegetable": []}
for entry in groceries . split(","):
category, item = entry . split("_")
categories[category if category in categories else "other"]. append(item)
return "\n" . join([f" { category } : { ',' . j... | Grocer Grouping | 593c0ebf8b90525a62000221 | [
"Fundamentals"
] | https://www.codewars.com/kata/593c0ebf8b90525a62000221 | 6 kyu |
Create a combat function that takes the player's current health and the amount of damage recieved, and returns the player's new health.
Health can't be less than <b>0<b>. | reference | def combat(health, damage):
return max(0, health - damage)
| Grasshopper - Terminal game combat function | 586c1cf4b98de0399300001d | [
"Fundamentals"
] | https://www.codewars.com/kata/586c1cf4b98de0399300001d | 8 kyu |
<div style="border:1px solid;position:relative;padding:1ex 1ex 1ex 11.1em;"><div style="position:absolute; left:0;top:0;bottom:0; width:10em; padding:1ex;text-align:center;border:1px solid;margin:0 1ex 0 0;color:#000;background-color:#eee;font-variant:small-caps">Part of Series 3/3</div><div>This kata is part of a seri... | algorithms | import re
def decodeBitsAdvanced(bits):
out, bits = '', bits . strip('0')
if bits == "":
return bits
len1, len0 = map(len, re . findall(r'1+', bits)
), map(len, re . findall(r'0+', bits))
mlen1 = min(len1)
mlen0 = min(len0) if len0 else mlen1
lenbit = ma... | Decode the Morse code, for real | 54acd76f7207c6a2880012bb | [
"Algorithms"
] | https://www.codewars.com/kata/54acd76f7207c6a2880012bb | 2 kyu |
Mrs Jefferson is a great teacher. One of her strategies that helped her to reach astonishing results in the learning process is to have some fun with her students. At school, she wants to make an arrangement of her class to play a certain game with her pupils. For that, she needs to create the arrangement with **the mi... | reference | def shortest_arrang(n):
# For odd n, we can always construct n with 2 consecutive integers.
if n % 2 == 1:
return [n / / 2 + 1, n / / 2]
# For even n, n is the sum of either an odd number or even number of
# consecutive positive integers. Moreover, this property is exclusive.
for i in ra... | Help Mrs Jefferson | 59321f29a010d5aa80000066 | [
"Fundamentals",
"Data Structures",
"Arrays",
"Mathematics"
] | https://www.codewars.com/kata/59321f29a010d5aa80000066 | 6 kyu |
You will be given a certain array of length ```n```, such that ```n > 4```, having positive and negative integers but there will be no zeroes and all the elements will occur once in it.
We may obtain an amount of ```n``` sub-arrays of length ```n - 1```, removing one element at a time (from left to right).
For each ... | reference | from functools import reduce
from operator import mul
def select_subarray(arr):
total = sum(arr)
m = reduce(mul, arr)
qs = [
(abs((m / / x) / (total - x)) if total - x else float("inf"), i)
for i, x in enumerate(arr)
]
q = min(qs)
result = [[i, arr[i]] for x, i in q... | Remove a Specific Element of an Array | 581bb3c1c221fb8e790001ef | [
"Fundamentals",
"Data Structures",
"Algorithms",
"Mathematics",
"Logic"
] | https://www.codewars.com/kata/581bb3c1c221fb8e790001ef | 6 kyu |
# Task
Your task is to create a `Funnel` data structure. It consists of three basic methods: `fill()`, `drip()` and `toString()/to_s/__str__`. Its maximum capacity is 15 data.
Data should be arranged in an inverted triangle, like this:
```
\1 2 3 4 5/
\7 8 9 0/
\4 5 6/
\2 3/
\1/
```
The string me... | algorithms | class Funnel (object):
SIZE = 5
def __init__(self):
self . fun = [[None] * (x + 1) for x in range(self . SIZE)]
def fill(self, * args):
genBlanks = ((x, y) for x, r in enumerate(self . fun)
for y, v in enumerate(r) if v is None)
for v, (x, y) in zip(args, genBlanks)... | Create a funnel | 585b373ce08bae41b800006e | [
"Algorithms"
] | https://www.codewars.com/kata/585b373ce08bae41b800006e | 4 kyu |
## Getting the Minimum Absolute Difference
### Task
Given an array of integers with at least 2 elements: `a1, a2, a3, a4, ... aN`
The absolute difference between two array elements `ai` and `aj`, where `i != j`, is the absolute value of `ai - aj`.
Return the minimum absolute difference (MAD) between any two element... | algorithms | def getting_mad(arr):
xs = sorted(arr)
return min(b - a for a, b in zip(xs, xs[1:]))
| Getting MAD | 593a061b942a27ac940000a7 | [
"Fundamentals",
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/593a061b942a27ac940000a7 | 6 kyu |
Given a hash of letters and the number of times they occur, recreate all of the possible anagram combinations that could be created using all of the letters, sorted alphabetically.
The inputs will never include numbers, spaces or any special characters, only lowercase letters a-z.
E.g. get_words({2=>["a"], 1=>["b", "... | games | from itertools import permutations
def get_words(letters):
word = "" . join(
qty * char for qty in letters for chars in letters[qty] for char in chars)
return sorted({"" . join(permutation) for permutation in permutations(word)})
| Get All Possible Anagrams from a Hash | 543e926d38603441590021dd | [
"Puzzles"
] | https://www.codewars.com/kata/543e926d38603441590021dd | 6 kyu |
The Binomial Form of a polynomial has many uses, just as the standard form does. For comparison, if p(x) is in Binomial Form and q(x) is in standard form, we might write
p(x) := a<sub>0</sub> \* xC0 + a<sub>1</sub> \* xC1 + a<sub>2</sub> \* xC2 + ... + a<sub>N</sub> \* xCN
q(x) := b<sub>0</sub> + b<sub>1</sub> \* x ... | reference | from math import prod, factorial
def comb(x, y):
return prod(x - i for i in range(y)) / factorial(y)
def value_at(poly_spec, x):
return round(sum(v * comb(x, i) for i, v in enumerate(reversed(poly_spec))), 2)
| Polynomial Evaluation - Binomial Form | 56782b25c05cad45f700000f | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/56782b25c05cad45f700000f | 6 kyu |
Given a string of space separated words, return the longest word.
If there are multiple longest words, return the rightmost longest word.
#### Examples
"red white blue" => "white"
"red blue gold" => "gold" | reference | def longest_word(string_of_words):
return max(reversed(string_of_words . split()), key=len)
| Inspiring Strings | 5939ab6eed348a945f0007b2 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5939ab6eed348a945f0007b2 | 7 kyu |
In this kata, you should determine the values in an unknown array of numbers.
You'll be given a function `f`, which you can call like this:
```haskell
f a b -- returns an Integral
```
```csharp
f(a, b);
```
```python
f(a, b)
```
```rust
f(a, b)
```
where `a` and `b` are indexes of two different elements in the unk... | games | from itertools import accumulate
def guess(f, n):
return [* accumulate(range(n - 1), lambda x, i: f(i, i + 1) - x, initial=f(0, 1) + f(0, 2) - f(1, 2) >> 1)]
| Guess the array | 59392ff00203d9686a0000c6 | [
"Puzzles",
"Algorithms",
"Arrays"
] | https://www.codewars.com/kata/59392ff00203d9686a0000c6 | 6 kyu |
<img src="https://i.imgur.com/ta6gv1i.png?1" title="source: imgur.com" />
# Story
A freak power outage at the zoo has caused all of the electric cage doors to malfunction and swing open...
All the animals are out and some of them are eating each other!
# <span style='color:red'>It's a Zoo Disaster!</span>
Here is ... | reference | EATERS = {"antelope": {"grass"},
"big-fish": {"little-fish"},
"bug": {"leaves"},
"bear": {"big-fish", "bug", "chicken", "cow", "leaves", "sheep"},
"chicken": {"bug"},
"cow": {"grass"},
"fox": {"chicken", "sheep"},
"giraffe": {"leaves"},
... | The Hunger Games - Zoo Disaster! | 5902bc7aba39542b4a00003d | [
"Fundamentals"
] | https://www.codewars.com/kata/5902bc7aba39542b4a00003d | 5 kyu |
Our cells go through a process called protein synthesis to translate the instructions in DNA into an amino acid chain, or polypeptide.
Your job is to replicate this!
---
**Step 1: Transcription**
Your input will be a string of DNA that looks like this:
`"TACAGCTCGCTATGAATC"`
You then must transcribe it to mRNA. ... | reference | import re
TABLE = str . maketrans('ACGT', 'UGCA')
def protein_synthesis(dna):
rna = re . findall(r'.{1,3}', dna . translate(TABLE))
return ' ' . join(rna), ' ' . join(x for x in map(CODON_DICT . get, rna) if x)
| Protein Synthesis: From DNA to Polypeptide | 58df2d65808fbcdfc800004a | [
"Fundamentals"
] | https://www.codewars.com/kata/58df2d65808fbcdfc800004a | 6 kyu |
# Introduction
There is a war...between alphabets!
There are two groups of hostile letters. The tension between left side letters and right side letters was too high and the war began. The letters called airstrike to help them in war - dashes and dots are spread throughout the battlefield.
Who will win?
# Task
Wr... | reference | import re
powers = {
'w': - 4, 'p': - 3, 'b': - 2, 's': - 1,
'm': + 4, 'q': + 3, 'd': + 2, 'z': + 1,
}
def alphabet_war(fight):
fight = re . sub('.(?=\*)|(?<=\*).', '', fight)
result = sum(powers . get(c, 0) for c in fight)
if result < 0:
return 'Left side wins!'
elif result > ... | Alphabet war - airstrike - letters massacre | 5938f5b606c3033f4700015a | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/5938f5b606c3033f4700015a | 6 kyu |
# Church Numbers
Church Numbers are representations of natural numbers (non-negative integers) as functions. Not only as functions, but as functions that can perform a task upon a value a set number of times. This is an important concept of Lambda Calculus, so naturally we'll have to talk about Lambda Calculus.
# Lamb... | algorithms | def church_add(c1): return lambda c2: lambda f: lambda x: c1(f)(c2(f)(x))
def church_mul(c1): return lambda c2: lambda f: c1(c2(f))
def church_pow(cb): return lambda ce: ce(cb)
| Church Numbers - Add, Multiply, Exponents | 55c0c452de0056d7d800004d | [
"Algorithms"
] | https://www.codewars.com/kata/55c0c452de0056d7d800004d | 3 kyu |
<h2>Task:</h2>
<p>Complete the function <code>piecesValue</code>/<code>pieces_value</code> that accepts two arguments, an 8x8 array (arr),representing a chess board and a string (s). Depending on the value of the string <code>s</code> (which can be either <code>"white"</code> or <code>"black"</code>) calculate the val... | reference | values = {
'queen': 9,
'rook': 5,
'bishop': 3,
'knight': 3,
'pawn': 1,
}
def pieces_value(arr, s):
return sum(values . get(x[2:], 0) for x in sum(arr, []) if x[0] == s[0])
| Chess piece values | 5832514f64a4cecd1c000013 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/5832514f64a4cecd1c000013 | 6 kyu |
As a part of this Kata, you need to create a function that when provided with a triplet, returns the index of the numerical element that lies between the other two elements.
The input to the function will be an array of three distinct numbers (Haskell: a tuple).
For example:
gimme([2, 3, 1]) => 0
*2* is the num... | reference | def gimme(inputArray):
# Implement this function
return inputArray . index(sorted(inputArray)[1])
| Find the middle element | 545a4c5a61aa4c6916000755 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/545a4c5a61aa4c6916000755 | 7 kyu |
This is the simple version of Shortest Code series. If you need some challenges, please try the [challenge version](http://www.codewars.com/kata/56fc7a29fca8b900eb001fac)
## Task:
Give you an number array ```arr```, and a number ```n```(n>=0), In accordance with the rules of kata, returns the array after ```n``` ti... | games | def sc(arr, n):
for _ in range(n):
out, vs = [], iter(arr)
for v in vs:
if v & 1:
out . append(3 * v + 1 + next(vs, 0))
else:
out . extend((v / / 2, v / / 2))
arr = out
return arr
| Coding 3min: Collatz Array(Split or merge) | 56fe9d579b7bb6b027000001 | [
"Puzzles",
"Games"
] | https://www.codewars.com/kata/56fe9d579b7bb6b027000001 | 6 kyu |
## Problem
There are `n` apples that need to be divided into four piles. We need two mysterious number `x` and `y`. Let The number of first pile equals to `x+y`, the number of second pile equals to `x-y`, the number of third pile equals to `x*y`, the number of fourth pile equals to `x/y`. We need to calculate how many... | games | def four_piles(n, y):
x, r = divmod(n * y, (y + 1) * * 2)
return [] if r or x == y else [x + y, x - y, x * y, x / / y]
| T.T.T.27: Four piles of apples | 57aae4facf1fa57b3300005d | [
"Puzzles",
"Games"
] | https://www.codewars.com/kata/57aae4facf1fa57b3300005d | 7 kyu |
Let's define `increasing` numbers as the numbers whose digits, read from left to right, are never less than the previous ones: 234559 is an example of increasing number.
Conversely, `decreasing` numbers have all the digits read from left to right so that no digits is bigger than the previous one: 97732 is an example o... | games | from math import factorial as fac
def xCy(x, y):
return fac(x) / / fac(y) / / fac(x - y)
def total_inc_dec(x):
return 1 + sum([xCy(8 + i, i) + xCy(9 + i, i) - 10 for i in range(1, x + 1)])
| Total increasing or decreasing numbers up to a power of 10 | 55b195a69a6cc409ba000053 | [
"Number Theory",
"Combinatorics",
"Puzzles"
] | https://www.codewars.com/kata/55b195a69a6cc409ba000053 | 4 kyu |
Function receive a two-dimensional square array of random integers.
On the main diagonal, all the negative integers must be changed to `0`, while the others must be changed to 1 (Note: `0` is considered non-negative, here).
(_You can mutate the input if you want, but it is a better practice to not mutate the input_)
... | reference | def matrix(arr):
for z in range(len(arr)):
if arr[z][z] < 0:
arr[z][z] = 0
else:
arr[z][z] = 1
return arr
| Change two-dimensional array | 581214d54624a8232100005f | [
"Arrays",
"Algorithms",
"Fundamentals"
] | https://www.codewars.com/kata/581214d54624a8232100005f | 7 kyu |
# Introduction
There is a war and nobody knows - the alphabet war!
There are two groups of hostile letters. The tension between left side letters and right side letters was too high and the war began.
# Task
Write a function that accepts `fight` string consists of only small letters and return who wins the fight. ... | reference | def alphabet_war(fight):
d = {'w': 4, 'p': 3, 'b': 2, 's': 1,
'm': - 4, 'q': - 3, 'd': - 2, 'z': - 1}
r = sum(d[c] for c in fight if c in d)
return {r == 0: "Let's fight again!",
r > 0: "Left side wins!",
r < 0: "Right side wins!"
}[True]
| Alphabet war | 59377c53e66267c8f6000027 | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/59377c53e66267c8f6000027 | 7 kyu |
# Introduction
Ka ka ka cypher is a cypher used by small children in some country. When a girl wants to pass something to the other girls and there are some boys nearby, she can use Ka cypher. So only the other girls are able to understand her. <br/>
She speaks using KA, ie.: <br>
`ka thi ka s ka bo ka y ka i ka s ka... | reference | import re
KA_PATTERN = re . compile(r'(?![aeiou]+$)([aeiou]+)', re . I)
def ka_co_ka_de_ka_me(word):
return 'ka' + KA_PATTERN . sub(r'\1ka', word)
| Ka Ka Ka cypher - words only vol 1 | 5934d648d95386bc8200010b | [
"Fundamentals"
] | https://www.codewars.com/kata/5934d648d95386bc8200010b | 6 kyu |
A local birthing center is interested in names!
They have arrays of all the baby names they see each year, but the lists are sooo long! They don’t know how to calculate how many times one name is used.
Given an array of names and a specific name string, return the number of times that specific name appears in the arr... | reference | def count_name(arr, name):
return arr . count(name)
| ScholarStem: Unit 6- Baby count! | 5702f077e55d30a7af000115 | [
"Fundamentals"
] | https://www.codewars.com/kata/5702f077e55d30a7af000115 | 7 kyu |
Raj was to move up through a pattern of stairs of a given number **(n)**. Help him to get to the top using the function **stairs**.
##Keep in mind :
* If **n<1** then return ' ' .
* There are a lot of spaces before the stair starts except for **pattern(1)**
##Examples :
pattern(1)
1 1
patte... | reference | def stairs(n):
return "\n" . join(step(i). rjust(4 * n - 1) for i in range(1, n + 1))
def step(n):
h = " " . join(str(i % 10) for i in range(1, n + 1))
return f" { h } { h [:: - 1 ]} "
| Walk-up Stairs | 566c3f5b9de85fdd0e000026 | [
"ASCII Art",
"Fundamentals"
] | https://www.codewars.com/kata/566c3f5b9de85fdd0e000026 | 6 kyu |
From a sentence, deduce the total number of animals.
For example :
"I see 3 zebras, 5 lions and 6 giraffes."
The answer must be 14
"Mom, 3 rhinoceros and 6 snakes come to us!"
The answer must be 9 | reference | def CountAnimals(s): return sum(int(e) for e in s . split() if e . isdigit())
| How many animals are there? | 593406b8f3d071d83c00005d | [
"Fundamentals"
] | https://www.codewars.com/kata/593406b8f3d071d83c00005d | 7 kyu |
# Task
An IP address contains four numbers(0-255) and separated by dots. It can be converted to a number by this way:
Given a string `s` represents a number or an IP address. Your task is to convert it to another representation(`number to IP address` or `IP address to number`).
You can assume that all inputs are va... | algorithms | from ipaddress import IPv4Address
def numberAndIPaddress(s):
return str(int(IPv4Address(s))) if '.' in s else str(IPv4Address(int(s)))
| Simple Fun #319: Number And IP Address | 5936371109ca68fe6900000c | [
"Algorithms"
] | https://www.codewars.com/kata/5936371109ca68fe6900000c | 6 kyu |
# Task
Your task is to sort the characters in a string according to the following rules:
```
- Rule1: English alphabets are arranged from A to Z, case insensitive.
ie. "Type" --> "epTy"
- Rule2: If the uppercase and lowercase of an English alphabet exist
at the same time, they are arranged in the order of oringal ... | algorithms | def sort_string(s):
a = iter(sorted((c for c in s if c . isalpha()), key=str . lower))
return '' . join(next(a) if c . isalpha() else c for c in s)
| Simple Fun #318: Sort String | 5936256f2e2a27edc9000047 | [
"Algorithms",
"Strings",
"Sorting"
] | https://www.codewars.com/kata/5936256f2e2a27edc9000047 | 6 kyu |
# Task:
Based on the received dimensions, `a` and `b`, of an ellipse, calculare its area and perimeter.
## Example:
```javascript
Input: elipse(5,2)
Output: "Area: 31.4, perimeter: 23.1"
```
```python
Input: ellipse(5,2)
Output: "Area: 31.4, perimeter: 23.1"
```
**Note:** The perimeter approximation formula you sh... | reference | from math import pi
def ellipse(a, b):
return f"Area: { pi * a * b : .1 f } , perimeter: { pi * ( 1.5 * ( a + b ) - ( a * b ) * * .5 ): .1 f } "
| Area and perimeter of the ellipse | 5830e7feff1a3ce8d4000062 | [
"Fundamentals"
] | https://www.codewars.com/kata/5830e7feff1a3ce8d4000062 | 6 kyu |
What is the most asked question on CodeWars?
> [Can](https://www.google.com/search?q=site%3Acodewars.com+"can+someone+explain") [someone](https://www.google.com/search?q=site%3Acodewars.com+"can+you+explain") [explain](https://www.google.com/search?q=site%3Acodewars.com+"can+anyone+explain") `/*...*/`?
You need to wr... | reference | def detect(comment):
return comment . startswith('Can someone explain')
| The most asked question on CodeWars | 5935ecef7705f9614500002d | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5935ecef7705f9614500002d | null |
**This Kata is intended as a small challenge for my students**
All Star Code Challenge #19
You work for an ad agency and your boss, Bob, loves a catchy slogan. He's always jumbling together "buzz" words until he gets one he likes. You're looking to impress Boss Bob with a function that can do his job for him.
Create... | reference | def slogan_maker(array):
print(array)
from itertools import permutations
array = remove_duplicate(array)
return [' ' . join(element) for element in list(permutations(array, len(array)))]
def remove_duplicate(old_list):
final_list = []
for num in old_list:
if num not in final_li... | All Star Code Challenge #19 | 5865a407b359c45982000036 | [
"Strings",
"Combinatorics",
"Permutations",
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/5865a407b359c45982000036 | 5 kyu |
**This Kata is intended as a small challenge for my students**
Create a function that takes a string argument and returns that same string with all vowels removed (vowels are "a", "e", "i", "o", "u").
Example (**Input** --> **Output**)
```
"drake" --> "drk"
"aeiou" --> ""
```
```cpp
remove_vowels("drake") // => "drk... | reference | def remove_vowels(strng):
return '' . join([i for i in strng if i not in 'aeiou'])
| All Star Code Challenge #3 | 58640340b3a675d9a70000b9 | [
"Fundamentals"
] | https://www.codewars.com/kata/58640340b3a675d9a70000b9 | 7 kyu |
**This Kata is intended as a small challenge for my students**
All Star Code Challenge #16
Create a function called noRepeat() that takes a string argument and returns a single letter string of the **first** not repeated character in the entire string.
```javascript
noRepeat("aabbccdde") // => "e"
noRepeat("wxyz") /... | reference | def no_repeat(s):
return next(c for c in s if s . count(c) == 1)
| All Star Code Challenge #16 | 586566b773bd9cbe2b000013 | [
"Fundamentals"
] | https://www.codewars.com/kata/586566b773bd9cbe2b000013 | 7 kyu |
Reverse every other word in a given string, then return the string. Throw away any leading or trailing whitespace, while ensuring there is exactly one space between each word. Punctuation marks should be treated as if they are a part of the word in this kata.
| reference | def reverse_alternate(string):
return " " . join(y[:: - 1] if x % 2 else y for x, y in enumerate(string . split()))
| Reverse every other word in the string | 58d76854024c72c3e20000de | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/58d76854024c72c3e20000de | 6 kyu |
# Task
Since the weather was good, some students decided to go for a walk in the park after the first lectures of the new academic year. There they saw a squirrel, which climbed a tree in a spiral at a constant angle to the ground. They calculated that in one loop the squirrel climbes `h` meters (vertical height), the... | games | def squirrel(h, H, S): return round(H / h * (h * * 2 + S * * 2) * * 0.5, 4)
| One Line Task: Squirrel And Tree | 59016379ee5456d8cc00000f | [
"Puzzles",
"Restricted"
] | https://www.codewars.com/kata/59016379ee5456d8cc00000f | 4 kyu |
Zalgo text is text that leaks into our plane of existence from a corrupted dimension of Unicode. For example:
```
H̗̪͇͓̙͎̣̄ͬa͚̯̦͉̖̥v͆ͩ̃͆̓̐ͥe̟͎͖͕͍̎ ̰͚̩̟͕̰͊̽̍ͯ̌͊ā̖̪͉͍̥͙̿ͩ̃ͅ ̬̥͎͑̿ͧg̰̳̺͔̦͉ͫ̀̐̓̐r̝̫̱̘̰͐͋ͯͭͭͭ͆e͙͕̖̗͙̰͌ͭä͓͚̝͓́̌͑ͪ͊ṱͥ ̱ͣd͎͔͎͇̫̪̘̃͐̇à͕̮̈͋ͪy̼̳̱ͮ!̳̥̰̭͇̔ͮ̽̓
```
Complete the function that converts a string of Za... | reference | def read_zalgo(zalgotext):
return "" . join([c for c in zalgotext if c . isascii()])
| Zalgo text reader | 588fe9eaadbbfb44b70001fc | [
"Regular Expressions",
"Fundamentals"
] | https://www.codewars.com/kata/588fe9eaadbbfb44b70001fc | 7 kyu |
Given an array representing the height of towers on a 2d plane, with each tower being of width 1, Whats's the maximum amount of units of water that can be captured between the towers when it rains?
Each tower is immediately next to the tower next to it in the array, except in instances where a height of 0 is shown, t... | games | from itertools import accumulate
def rain_volume(towers):
a = accumulate(towers, max)
b = accumulate(towers[:: - 1], max)
a = [max(0, i - j) for i, j in zip(a, towers)]
b = [max(0, i - j) for i, j in zip(b, towers[:: - 1])]
return sum(min(i, j) for i, j in zip(a, b[:: - 1]))
| City Swim - 2D (TowerFlood And PlainFlood) | 58e77c88fd2d893a77000102 | [
"Puzzles",
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/58e77c88fd2d893a77000102 | 5 kyu |
Format any integer provided into a string with "," (commas) in the correct places.
**Example:**
```
For n = 100000 the function should return '100,000';
For n = 5678545 the function should return '5,678,545';
for n = -420902 the function should return '-420,902'.
```
| reference | def number_format(n):
return f' { n :,} '
| Number Format | 565c4e1303a0a006d7000127 | [
"Regular Expressions",
"Fundamentals"
] | https://www.codewars.com/kata/565c4e1303a0a006d7000127 | 6 kyu |
#Rotate a square matrix like a vortex
Your task is to rotate a square matrix of numbers like a vortex.
```
In most vortices, the fluid flow velocity is greatest next to its axis and decreases in inverse proportion to the distance from the axis.
```
So the rotation speed increases with every ring nearer to the middle.... | algorithms | import numpy as np
def rotate_like_a_vortex(matrix):
fuck = np . array(matrix)
for num in range(len(matrix) / / 2):
fuck[num: len(matrix) - num, num: len(matrix) - num] = np . rot90(
fuck[num: len(matrix) - num, num: len(matrix) - num], k=1, axes=(0, 1))
return fuck . tolist()
| Rotate a square matrix like a vortex | 58d3cf477a4ea9bb2f000103 | [
"Logic",
"Arrays",
"Algorithms",
"Matrix"
] | https://www.codewars.com/kata/58d3cf477a4ea9bb2f000103 | 5 kyu |
# Hooray - It's "Spaghetti Night" again !
Spaghetti is my favourite meal, so I always like to save the longest piece for last...
But since my <a href="https://www.codewars.com/kata/57d7805cec167081a50014ac">last "Spaghetti Night"</a> the price of my special ID spaghetti has really gone through the roof and so I have ... | algorithms | def spaghetti_code(plate):
def is_noodle(c): return 'A' <= c <= 'Z'
def is_inside(a, b): return 0 <= a < X and 0 <= b < Y
def flood(i, j):
typ_s . add(board[i][j])
board[i][j] = '_'
return 1 + sum(flood(x, y) for x, y in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]
... | Spaghetti Code - #2 Hard | 586dd5f4a44cfc48bb000011 | [
"Algorithms"
] | https://www.codewars.com/kata/586dd5f4a44cfc48bb000011 | 4 kyu |
Define a regular expression which tests if a given string representing a binary number is divisible by 5.
### Examples:
```csharp
// 5 divisable by 5
Regex.IsMatch('101', DivisibleByFive) == true
// 135 divisable by 5
Regex.IsMatch('10000111', DivisibleByFive) == true
// 666 not divisable by 5
Regex.IsMatch('000000... | algorithms | # build a DFA (Deterministic Finite Automaton)
# then use steps from
# https://stackoverflow.com/questions/34476333/regular-expression-for-binary-numbers-divisible-by-5
# to reduce the DFA graph to the final regular expression.
# At the end, the + character has been used, instead of *, to reject empty strings
PATTERN =... | Regular expression for binary numbers divisible by 5 | 5647c3858d4acbbe550000ad | [
"Binary",
"Algorithms",
"Regular Expressions"
] | https://www.codewars.com/kata/5647c3858d4acbbe550000ad | 4 kyu |
Your task is to convert a given number into a string with commas added for easier readability. The number should be rounded to 3 decimal places and the commas should be added at intervals of three digits before the decimal point. There does not need to be a comma at the end of the number.
You will receive both positi... | reference | def commas(num):
return "{:,.3f}" . format(num). rstrip("0"). rstrip(".")
| Add commas to a number | 56a115cadb39a2faa000001e | [
"Regular Expressions",
"Fundamentals"
] | https://www.codewars.com/kata/56a115cadb39a2faa000001e | 6 kyu |
# Task
Find the integer from `a` to `b` (included) with the greatest number of divisors. For example:
```
divNum(15, 30) ==> 24
divNum(1, 2) ==> 2
divNum(0, 0) ==> 0
divNum(52, 156) ==> 120
```
If there are several numbers that have the same (maximum) number of divisors, the smallest among them should be ... | reference | import numpy as np
s = np . ones(100000)
for i in range(2, 100000):
s[i:: i] += 1
def div_num(a, b):
return max(range(a, b + 1), key=lambda i: (s[i], - i), default='Error')
| Find Number With Maximum Number Of Divisors | 588c0a38b7cd14085300003f | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/588c0a38b7cd14085300003f | 6 kyu |
Given an array of integers, return the smallest common factors of all integers in the array.
When i say **Smallest Common Factor** i mean the smallest number above 1 that can divide all numbers in the array without a remainder.
```javascript
scf([200, 30, 18, 8, 64, 34]) //=> 2
scf([21, 45, 51, 27, 33]) //=> 3
scf([1... | algorithms | def scf(arr):
for i in range(2, (min(arr) if arr else 1) + 1):
if all(x % i == 0 for x in arr):
return i
return 1
| Get Smallest Common Factor | 5933af2db328fbc731000010 | [
"Algorithms",
"Mathematics"
] | https://www.codewars.com/kata/5933af2db328fbc731000010 | 7 kyu |
## Explanation
Write a function that shortens a string to a given length. Instead of cutting the string from the end, your function will shorten it from the middle like shrinking.
For example:
```
sentence = "The quick brown fox jumps over the lazy dog"
res = shorten(sentence, 27)
res === "The quick br...the lazy do... | reference | def shorten(string, length, glue="..."):
if len(string) < length:
return string
if length < len(glue) + 2:
return string[: length]
l1, l2 = (length - len(glue)) / / 2, (length - len(glue) + 1) / / 2
return string[: l1] + glue + string[- l2:]
| String Shortener (shrink) | 557d18803802e873170000a0 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/557d18803802e873170000a0 | 6 kyu |
Your friend invites you out to a cool floating pontoon around 1km off the beach. Among other things, the pontoon has a huge slide that drops you out right into the ocean, a small way from a set of stairs used to climb out.
As you plunge out of the slide into the water, you see a shark hovering in the darkness under t... | reference | def shark(pontoon_distance, shark_distance, you_speed, shark_speed, dolphin):
if dolphin:
shark_speed = shark_speed / 2
shark_eat_time = shark_distance / shark_speed
you_safe_time = pontoon_distance / you_speed
return "Shark Bait!" if you_safe_time > shark_eat_time else "Alive!"
| Holiday VI - Shark Pontoon | 57e921d8b36340f1fd000059 | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/57e921d8b36340f1fd000059 | 8 kyu |
You are given an array of positive and negative integers and a number ```n``` and ```n > 1```. The array may have elements that occurs more than once.
Find all the combinations of n elements of the array that their sum are 0.
```python
arr = [1, -1, 2, 3, -2]
n = 3
find_zero_sum_groups(arr, n) == [-2, -1, 3] # -2 - 1 +... | reference | from itertools import combinations
def find_zero_sum_groups(arr, n):
combos = sorted(sorted(c)
for c in combinations(set(arr), n) if sum(c) == 0)
return combos if len(combos) > 1 else combos[0] if combos else "No combinations" if arr else "No elements to combine"
| Search The 0 Sums Combinations in an Array | 5711fc7c159cde6ac70003e2 | [
"Fundamentals",
"Data Structures",
"Algorithms",
"Mathematics",
"Logic"
] | https://www.codewars.com/kata/5711fc7c159cde6ac70003e2 | 6 kyu |
Create a function that takes in the sum and age difference of two people, calculates their individual ages, and returns a pair of values (oldest age first) if those exist or `null/None` or `{-1, -1} in C` if:
* `sum < 0`
* `difference < 0`
* Either of the calculated ages come out to be negative
| reference | def get_ages(a, b):
x = (a + b) / 2
y = (a - b) / 2
return None if a < 0 or b < 0 or x < 0 or y < 0 else (x, y)
| Calculate Two People's Individual Ages | 58e0bd6a79716b7fcf0013b1 | [
"Fundamentals",
"Algorithms",
"Arrays"
] | https://www.codewars.com/kata/58e0bd6a79716b7fcf0013b1 | 7 kyu |
Given an array of integers.
Return a number that is the sum of
1. The product of all the non-negative numbers
2. The sum of all the negative numbers
# Edge cases
- If there are no non-negative numbers, assume the product of them to be 1.
- Similarly, if there are no negative numbers, assume the sum of them to be 0.
... | reference | from math import prod
def math_engine(arr):
return 0 if arr is None else prod(a for a in arr if a >= 0) + sum(a for a in arr if a < 0)
| Math engine | 587854330594a6fb7e000057 | [
"Fundamentals"
] | https://www.codewars.com/kata/587854330594a6fb7e000057 | 7 kyu |
You are developing an image hosting website.
You have to create a function for generating random and unique image filenames.
Create a function for generating a random 6 character string which will be used to access the photo URL.
To make sure the name is not already in use, you are given access to an PhotoManager o... | reference | import uuid
def generateName():
return str(uuid . uuid4())[: 6]
| Image host filename generator | 586a933fc66d187b6e00031a | [
"Logic",
"Object-oriented Programming",
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/586a933fc66d187b6e00031a | 6 kyu |
In Dark Souls, players level up trading souls for stats. 8 stats are upgradable this way: vitality, attunement, endurance, strength, dexterity, resistance, intelligence, and faith. Each level corresponds to adding one point to a stat of the player's choice. Also, there are 10 possible classes each having their own star... | games | D = {"warrior": (4, 86), "knight": (5, 86), "wanderer": (3, 86), "thief": (5, 86), "bandit": (4, 86),
"hunter": (4, 86), "sorcerer": (3, 82), "pyromancer": (1, 84), "cleric": (2, 84), "deprived": (6, 88)}
def count(x): return round(pow(x, 3) * 0.02 +
pow(x, 2) * 3.06 + 105.6 * x -... | Dark Souls: Prepare To Die - Soul Level | 592a5f9fa3df0a28730000e7 | [
"Puzzles"
] | https://www.codewars.com/kata/592a5f9fa3df0a28730000e7 | 6 kyu |
## Story
Your friend Bob is working as a taxi driver. After working for a month he is frustrated in the city's traffic lights. He asks you to write a program for a new type of traffic light. It is made so it turns green for the road with the most congestion.
## Task
Given 2 pairs of values each representing a road (... | reference | class SmartTrafficLight:
def __init__(self, a, b):
self . a = [] if a[0] == b[0] else sorted((a, b))
def turngreen(self):
if self . a:
return self . a . pop()[1]
| Smart Traffic Lights | 58587905ed1b4dad6e0000c6 | [
"Fundamentals",
"Object-oriented Programming"
] | https://www.codewars.com/kata/58587905ed1b4dad6e0000c6 | 6 kyu |
## Graphics Series #3: Repair the LED display
### Story
There is a huge LED monitor, because it's too old,
Its digital display module is faulty. Can you fix it?
### Rules
Normal display data is stored in an array, its name is `nums`. It has been preload, you can use it directly.
Fault types are:
| 1. Flip up ... | games | from preloaded import nums
import numpy as np
def check_led(a):
a = np . array(a)
for i in range(0, len(a[0]), 5):
digit = a[:, i: i + 5]
for x in (digit[:: - 1], digit[:, :: - 1], digit[:: - 1, :: - 1]):
if x . tolist() in nums:
a[:, i: i + 5] = x
return a . tolist()
| Graphics Series #3: Repair the LED display | 5763a557f716cad8fb00039d | [
"Puzzles",
"Games"
] | https://www.codewars.com/kata/5763a557f716cad8fb00039d | 5 kyu |
>When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said
# Description:
In kindergarten, the teacher gave the children some candies. The number of candies each child gets is not always the same. Here is an array `candies`(all e... | reference | def distribution_of_candy(candies):
steps = 0
while len(set(candies)) > 1:
candies = [(a + 1) / / 2 + (b + 1) / / 2
for a, b in zip(candies, candies[- 1:] + candies)]
steps += 1
return [steps, candies . pop()]
| Children and candies | 582933a3c983ca0cef0003de | [
"Puzzles",
"Fundamentals"
] | https://www.codewars.com/kata/582933a3c983ca0cef0003de | 6 kyu |
**This Kata is intended as a small challenge for my students**
Create a function, called insurance(), that computes the cost of renting a car. The function takes 3 arguments: the age of the renter, the size of the car, and the number days for the rental. The function should return an integer number of the calculated t... | reference | def insurance(age, size, num_of_days):
if num_of_days <= 0:
return 0
cost = 0
one_day_cost = 50
if size == "medium":
one_day_cost += 10
elif size != 'economy':
one_day_cost += 15
if age < 25:
one_day_cost += 10
cost = one_day_cost * num_of_days
return cost
| Cost of my ride | 586430a5b3a675296a000395 | [
"Fundamentals"
] | https://www.codewars.com/kata/586430a5b3a675296a000395 | 7 kyu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.