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 |
|---|---|---|---|---|---|---|---|
This series of katas will introduce you to basics of doing geometry with computers.
Point objects have `x`, `y` attributes.
Circle objects have `center` which is a `Point`, and `radius` which is a number.
Write a function calculating distance between `Circle a` and `Circle b`.
If they're overlapping or one is comple... | reference | def distance_between_circles(a, b):
dis = ((a . center . x - b . center . x) * * 2 + (a . center . y - b . center . y) * * 2) * * 0.5
return max(0, dis - a . radius - b . radius)
| Geometry Basics: Distance between circles in 2D | 58e3031ce265671f6a000542 | [
"Geometry",
"Fundamentals"
] | https://www.codewars.com/kata/58e3031ce265671f6a000542 | 7 kyu |
You get a "text" and have to shift the vowels by "n" positions to the right.<br/>
(Negative value for n should shift to the left.)<br/>
"Position" means the vowel's position if taken as one item in a list of all vowels within the string.<br>
A shift by 1 would mean, that every vowel shifts to the place of the next vowe... | algorithms | import re
from collections import deque
def vowel_shift(text, n):
try:
tokens = re . split(r'([aeiouAEIOU])', text)
if len(tokens) > 1:
vowels = deque(tokens[1:: 2])
vowels . rotate(n)
tokens[1:: 2] = vowels
return '' . join(tokens)
except TypeError:
return None
| Vowel Shifting | 577e277c9fb2a5511c00001d | [
"Strings",
"Regular Expressions",
"Algorithms"
] | https://www.codewars.com/kata/577e277c9fb2a5511c00001d | 6 kyu |
#Make them bark
You have been hired by a dogbreeder to write a program to keep record of his dogs.
You've already made a constructor `Dog`, so no one has to hardcode every puppy.
The work seems to be done. It's high time to collect the payment.
..hold on! The dogbreeder says he wont pay you, until he can ma... | reference | def bark(self):
return "Woof!"
Dog . bark = bark
| Make them bark! | 5535572c1de94ba2db0000f6 | [
"Fundamentals"
] | https://www.codewars.com/kata/5535572c1de94ba2db0000f6 | 7 kyu |
A "Lucky Seven" is the number seven surrounded by numbers that add up to form a perfect cube. The surrounding numbers will be described as the numbers directly above, below, and next to (not diagonally) the number 7. You will be given a 2D array containing at least 1 lucky seven. Your function should return the number ... | reference | def luckySevens(arr):
def check(x, y):
t = sum(arr[x + dx][y + dy]
for dx, dy in dIdx if 0 <= x + dx < lX and 0 <= y + dy < lY)
return abs(t * * (1 / 3) - round(t * * (1 / 3))) <= 1e-8
dIdx = ((1, 0), (- 1, 0), (0, 1), (0, - 1))
lX, lY = len(arr), len(arr[0])
return sum(chec... | Lucky Sevens | 58275b63083e128edb00098d | [
"Fundamentals"
] | https://www.codewars.com/kata/58275b63083e128edb00098d | 6 kyu |
# Task
You are given a string `s`. Every letter in `s` appears once.
Consider all strings formed by rearranging the letters in `s`. After ordering these strings in dictionary order, return the middle term. (If the sequence has a even length `n`, define its middle term to be the `(n/2)`th term.)
# Example
For `s... | games | def middle_permutation(string):
s = sorted(string)
if len(s) % 2 == 0:
return s . pop(len(s) / / 2 - 1) + '' . join(s[:: - 1])
else:
return s . pop(len(s) / / 2) + middle_permutation(s)
| Simple Fun #159: Middle Permutation | 58ad317d1541651a740000c5 | [
"Puzzles"
] | https://www.codewars.com/kata/58ad317d1541651a740000c5 | 4 kyu |
You have to sort the inner content of every word of a string in descending order.
The inner content is the content of a word without first and the last char.
Some examples:
```
"sort the inner content in descending order" --> "srot the inner ctonnet in dsnnieedcg oredr"
"wait for me" --> "wiat for me"
"thi... | algorithms | def sort_the_inner_content(str):
words = str . split()
output = []
for word in words:
if len(word) > 2:
output . append(
word[0] + '' . join(sorted(word[1: - 1], reverse=True)) + word[- 1])
else:
output . append(word)
return ' ' . join(output)
| Srot the inner ctonnet in dsnnieedcg oredr | 5898b4b71d298e51b600014b | [
"Strings",
"Logic",
"Algorithms"
] | https://www.codewars.com/kata/5898b4b71d298e51b600014b | 6 kyu |
<p>You are given an array of unique numbers. The numbers represent points. The higher the number the higher the points.
In the array [1,3,2] 3 is the highest point value so it gets 1st place. 2 is the second highest so it gets second place. 1 is the 3rd highest so it gets 3rd place.
Your task is to return an array ... | reference | def rankings(arr):
dct = {v: i for i, v in enumerate(sorted(arr, reverse=True), 1)}
return [dct[v] for v in arr]
| Ranking System | 58e16de3a312d34d000000bd | [
"Fundamentals"
] | https://www.codewars.com/kata/58e16de3a312d34d000000bd | 6 kyu |
# Task
Consider the following operation:
We take a positive integer `n` and replace it with the sum of its `prime factors` (if a prime number is presented multiple times in the factorization of `n`, then it's counted the same number of times in the sum).
This operation is applied sequentially first to the given... | games | def factor_sum(n):
fs = sum(factors(n))
return fs if fs == n else factor_sum(fs)
def factors(n, p=2):
while p * p <= n:
while not n % p:
yield p
n / /= p
p += 2 - (p == 2)
if n > 1 and p > 2:
yield n
| Simple Fun #115: Factor Sum | 589d2bf7dfdef0817e0001aa | [
"Puzzles"
] | https://www.codewars.com/kata/589d2bf7dfdef0817e0001aa | 6 kyu |
Scheduling is how the processor decides which jobs(processes) get to use the processor and for how long. This can cause a lot of problems. Like a really long process taking the entire CPU and freezing all the other processes. One solution is Shortest Job First(SJF), which today you will be implementing.
SJF works by, ... | algorithms | def SJF(jobs, index):
return sum(j for i, j in enumerate(jobs)
if j < jobs[index] or (j == jobs[index] and i <= index))
| Scheduling (Shortest Job First or SJF) | 550cc572b9e7b563be00054f | [
"Scheduling",
"Queues",
"Algorithms"
] | https://www.codewars.com/kata/550cc572b9e7b563be00054f | 6 kyu |
You are the "computer expert" of a local Athletic Association (C.A.A.).
Many teams of runners come to compete. Each time you get a string of
all race results of every team who has run.
For example here is a string showing the individual results of a team of 5 runners:
` "01|15|59, 1|47|6, 01|17|20, 1|32|34, 2|3|17" `... | reference | def stat(strg):
def get_time(s):
'''Returns the time, in seconds, represented by s.'''
hh, mm, ss = [int(v) for v in s . split('|')]
return hh * 3600 + mm * 60 + ss
def format_time(time):
'''Returns the given time as a string in the form "hh|mm|ss".'''
hh = time / / 3600
mm = t... | Statistics for an Athletic Association | 55b3425df71c1201a800009c | [
"Fundamentals",
"Strings",
"Statistics",
"Mathematics",
"Data Science"
] | https://www.codewars.com/kata/55b3425df71c1201a800009c | 6 kyu |
Some people just have a first name; some people have first and last names and some people have first, middle and last names.
You task is to initialize the middle names (if there is any).
## Examples
```
'Jack Ryan' => 'Jack Ryan'
'Lois Mary Lane' => 'Lois M. Lane'
'Dimitri' ... | reference | def initializeNames(name):
names = name . split()
names[1: - 1] = map(lambda n: n[0] + '.', names[1: - 1])
return ' ' . join(names)
| Initialize my name | 5768a693a3205e1cc100071f | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5768a693a3205e1cc100071f | 7 kyu |
*You are a composer who just wrote an awesome piece of music. Now it's time to present it to a band that will perform your piece, but there's a problem! The singers vocal range doesn't stretch as your piece requires, and you have to transpose the whole piece.*
# Your task
Given a list of notes (represented as strings)... | algorithms | def transpose(song, interval):
altern = {"Bb": "A#", "Db": "C#", "Eb": "D#", "Gb": "F#", "Ab": "G#"}
notes = ['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#']
return [notes[(notes . index(altern . get(i, i)) + interval) % 12] for i in song]
| Transposing a song | 55b6a3a3c776ce185c000021 | [
"Fundamentals",
"Algorithms",
"Strings",
"Lists"
] | https://www.codewars.com/kata/55b6a3a3c776ce185c000021 | 7 kyu |
- Input : an array of integers.
- Output : this array, but sorted in such a way that there are two wings:
- the left wing with numbers decreasing,
- the right wing with numbers increasing.
- the two wings have the same length. If the length of the array is odd
the wings are around the bottom, if the length... | reference | def make_valley(arr):
arr = sorted(arr, reverse=True)
return arr[:: 2] + arr[1:: 2][:: - 1]
| How Green Is My Valley? | 56e3cd1d93c3d940e50006a4 | [
"Fundamentals"
] | https://www.codewars.com/kata/56e3cd1d93c3d940e50006a4 | 7 kyu |
There's a waiting room with N chairs set in single row. Chairs are consecutively numbered from 1 to N. First is closest to the entrance (which is exit as well).
For some reason people choose a chair in the following way
1. Find a place as far from other people as possible
2. Find a place as close to exit as possible... | algorithms | def last_chair(n):
# Propn:
# Given there are n seats, n >= 2. The (n-1)th seat is always the
# last to be taken (taken in iteration n).
# Proof:
# Suppose that, for some n >= 2, the (n-1)th seat is taken on
# iteration i > 2. The nth seat is already taken, since the 2nd
# iteration will alw... | Waiting room | 542f0c36d002f8cd8a0005e5 | [
"Sorting",
"Puzzles",
"Algorithms"
] | https://www.codewars.com/kata/542f0c36d002f8cd8a0005e5 | 7 kyu |
A number is simply made up of digits.
The number 1256 is made up of the digits 1, 2, 5, and 6.
For 1256 there are 24 distinct permutations of the digits:
1256, 1265, 1625, 1652, 1562, 1526, 2156, 2165, 2615, 2651, 2561, 2516,
5126, 5162, 5216, 5261, 5621, 5612, 6125, 6152, 6251, 6215, 6521, 6512.
Your goal ... | algorithms | from itertools import permutations
def permutation_average(n):
perms = [float('' . join(e)) for e in permutations(str(n))]
return int(round(sum(perms) / len(perms)))
| Permutation Average | 56b18992240660a97c00000a | [
"Algorithms"
] | https://www.codewars.com/kata/56b18992240660a97c00000a | 7 kyu |
Write a function that returns the index of the first occurence of the word "Wally". "Wally" must not be part of another word, but it can be directly followed by a punctuation mark. If no such "Wally" exists, return -1.
Examples:
"Wally" => 0
"Where's Wally" => 8
"Where's Waldo" => -1
"DWally Wallyd .Wally" => -... | reference | from re import compile
def wheres_wally(string):
m = compile('(^|.*[\s])(Wally)([\.,\s\']|$)'). match(string)
return m . start(2) if m else - 1
| Where's Wally | 55f91a98db47502cfc00001b | [
"Regular Expressions",
"Fundamentals"
] | https://www.codewars.com/kata/55f91a98db47502cfc00001b | 7 kyu |
Write a function that takes an array/list of numbers and returns a number such that
Explanation
total([1,2,3,4,5]) => 48
<pre>
1+2=3--\ 3+5 => 8 \
2+3=5--/ \ == 8+12=>20\
==>5+7=> 12 / \ 20+28 => 48
3+4=7--\ / == 12+16=>28/
4+5=9--/ 7+9 => 16 /
</pre><br/>
if ... | reference | def total(arr):
while len(arr) > 1:
arr = [x + y for x, y in zip(arr, arr[1:])]
return arr[0]
| sum2total | 559fed8454b12433ff0000a2 | [
"Logic",
"Mathematics",
"Arrays",
"Lists",
"Fundamentals"
] | https://www.codewars.com/kata/559fed8454b12433ff0000a2 | 7 kyu |
Every day we can send from the server a certain limit of e-mails.
## Task:
Write a function that will return the integer number of e-mails sent in the percentage of the limit.
Example:
```
limit - 1000;
emails sent - 101;
return - 10%; // because integer from 10,1 = 10
```
### Arguments:
- `sent`: number... | reference | def get_percentage(sent, limit=1000):
if not sent:
return "No e-mails sent"
elif sent >= limit:
return "Daily limit is reached"
return "{}%" . format(int(sent * 100 / limit))
| How many e-mails we sent today? | 58a369fa5b3daf464200006c | [
"Fundamentals",
"Logic",
"Mathematics"
] | https://www.codewars.com/kata/58a369fa5b3daf464200006c | 7 kyu |
Yet another staple for the functional programmer. You have a sequence of values and some predicate for those values. You want to remove the longest prefix of elements such that the predicate is true for each element. We'll call this the dropWhile function. It accepts two arguments. The first is the sequence of values, ... | algorithms | from itertools import dropwhile
def drop_while(arr, pred):
return list(dropwhile(pred, arr))
| The dropWhile Function | 54f9c37106098647f400080a | [
"Functional Programming",
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/54f9c37106098647f400080a | 7 kyu |
Write a function that appends the items from sequence 2 onto sequence 1, returning the newly formed sequence. Your function should also be able to handle nested sequences.
All inputs will be arrays/nested arrays.
For example:
```
['a','b','c'], [1,2,3] --> ['a','b','c',1,2,3]
[['x','x'],'B'], ['c','D'] --> [['x'... | reference | def append_arrays(seq1, seq2):
return seq1 + seq2
| Array Appender | 53a8a476947277a3020001cc | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/53a8a476947277a3020001cc | 7 kyu |
Write a function that takes two array arguments, and returns a new array populated with the elements **that appear in either array, but not in both. Elements should only appear once in the returned array**.
The order of the elements in the result should follow what appears in the first array, then the second one.
#... | algorithms | def hot_singles(arr1, arr2):
a = []
for x in arr1 + arr2:
if x in set(arr1) ^ set(arr2) and x not in a:
a . append(x)
return a
| noobCode 04: HOT SINGLES...compare two arrays, return the unpaired items ! | 57475353facb0e7431000651 | [
"Arrays",
"Lists",
"Algorithms"
] | https://www.codewars.com/kata/57475353facb0e7431000651 | 7 kyu |
How many licks does it take to get to the tootsie roll center of a tootsie pop?
A group of engineering students from Purdue University reported that its licking machine, modeled after a human tongue, took an average of 364 licks to get to the center of a Tootsie Pop. Twenty of the group's volunteers assumed the lickin... | algorithms | def total_licks(env):
d = 252
vm = 0
for k, v in env . items():
d += v
if v > vm:
vm, km = v, k
return 'It took ' + str(d) + ' licks to get to the tootsie roll center of a tootsie pop.' + (' The toughest challenge was ' + km + '.' if vm > 0 else '')
| 80's Kids #1: How Many Licks Does it Take? | 566091b73e119a073100003a | [
"Algorithms"
] | https://www.codewars.com/kata/566091b73e119a073100003a | 7 kyu |
You have recently discovered that horses travel in a unique pattern - they're either running (at top speed) or resting (standing still).
Here's an example of how one particular horse might travel:
```
The horse Blaze can run at 14 metres/second for 60 seconds, but must then rest for 45 seconds.
After 500 seconds Bla... | games | def travel(total_time, run_time, rest_time, speed):
q, r = divmod(total_time, run_time + rest_time)
return (q * run_time + min(r, run_time)) * speed
| How far will I go? | 56d46b8fda159582e100001b | [
"Puzzles"
] | https://www.codewars.com/kata/56d46b8fda159582e100001b | 7 kyu |
_Friday 13th or Black Friday is considered as unlucky day. Calculate how many unlucky days are in the given year._
Find the number of Friday 13th in the given year.
__Input:__ Year [*in Gregorian calendar*](https://en.wikipedia.org/wiki/Gregorian_calendar) as integer.
__Output:__ Number of Black Fridays in the year ... | reference | from datetime import date
def unlucky_days(year):
return sum(date(year, m, 13). weekday() == 4 for m in range(1, 13))
| Unlucky Days | 56eb0be52caf798c630013c0 | [
"Date Time"
] | https://www.codewars.com/kata/56eb0be52caf798c630013c0 | 7 kyu |
Did you ever want to know how many days old are you? Complete the function which returns your age in days. The birthday is given in the following order: `year, month, day`.
For example if today is 30 November 2015 then
```
ageInDays(2015, 11, 1) returns "You are 29 days old"
```
The birthday is expected to be in th... | reference | from datetime import date
def ageInDays(year, month, day):
return 'You are {} days old' . format((date . today() - date(year, month, day)). days)
| Age in days | 5803753aab6c2099e600000e | [
"Date Time",
"Fundamentals"
] | https://www.codewars.com/kata/5803753aab6c2099e600000e | 7 kyu |
We all want to climb the leaderboard. Even given some of the massive scores on there, it's nice to know how close you are...
In this kata you will be given a username and their score, your score (not your real score) and you need to calculate how many kata you need to complete to *beat* their score, by 1 point exactly... | reference | def leader_b(user, user_score, your_score):
if your_score > user_score:
return "Winning!"
if your_score == user_score:
return "Only need one!"
beta, eight = divmod(user_score - your_score, 3)
dammit = " Dammit!" if beta + eight > 1000 else ""
return f"To beat { user } 's score, I must... | Codewars Leaderboard Climber | 57d28215264276ea010002cf | [
"Fundamentals",
"Strings",
"Mathematics"
] | https://www.codewars.com/kata/57d28215264276ea010002cf | 7 kyu |
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are:
<p>2332
<br>110011
<br>54322345
For a given number ```num```, return its closest numerical palindrome which can either be smaller or larger than ```num```. If there... | reference | def palindrome(num):
def is_palindrome(chunk): return int(chunk) > 9 and chunk == chunk[:: - 1]
if not isinstance(num, int) or num < 0:
return 'Not valid'
i = 0
while (True):
if is_palindrome(str(num + i)):
return num + i
if is_palindrome(str(num - i)):
return num - i
... | Numerical Palindrome #4 | 58df8b4d010a9456140000c7 | [
"Fundamentals"
] | https://www.codewars.com/kata/58df8b4d010a9456140000c7 | 6 kyu |
# Story
<div style='float:right; width: 240px'>

</div>
You are a cook in an alien restaurant at a distant planet called Kahumo.
These aliens have some specific physiology features:
* Aliens eat only one type of food in one... | algorithms | def serve(f, k, m):
s = f / m if k == 1 else f / ((k * * m - 1) / (k - 1))
return [s * k * * i for i in range(m)]
| Feed Kahumolings! | 557b75579b03996942000061 | [
"Algorithms"
] | https://www.codewars.com/kata/557b75579b03996942000061 | 6 kyu |
# Sort an array by value and index
Your task is to sort an array of integer numbers by the product of the value and the index of the positions.
<br><br>
For sorting the index starts at 1, NOT at 0!<br>
The sorting has to be ascending.<br>
The array will never be null and will always contain numbers.
<br><br>
Example:
... | algorithms | def sort_by_value_and_index(arr):
return [y[1] for y in sorted(enumerate(arr), key=lambda x: (x[0] + 1) * x[1])]
| Sort an array by value and index | 58e0cb3634a3027180000040 | [
"Arrays",
"Algorithms",
"Sorting"
] | https://www.codewars.com/kata/58e0cb3634a3027180000040 | 7 kyu |
Write a function that returns a sequence (index begins with 1) of all the even characters from a string. If the string is smaller than two characters or longer than 100 characters, the function should return "invalid string".
For example:
`````
"abcdefghijklm" --> ["b", "d", "f", "h", "j", "l"]
"a" --> "i... | reference | def even_chars(st):
if len(st) < 2 or len(st) > 100:
return 'invalid string'
else:
return [st[i] for i in range(1, len(st), 2)]
| Return a string's even characters. | 566044325f8fddc1c000002c | [
"Fundamentals",
"Strings",
"Arrays"
] | https://www.codewars.com/kata/566044325f8fddc1c000002c | 7 kyu |
Implement a function which filters out array values which satisfy the given predicate.
```javascript
reject([1, 2, 3, 4, 5, 6], (n) => n % 2 === 0) => [1, 3, 5]
```
```csharp
Kata.Reject(new int[] {1, 2, 3, 4, 5, 6}, (n) => n % 2 == 0) => new int[] {1, 3, 5}
```
```php
reject([1, 2, 3, 4, 5, 6], function ($n) {ret... | reference | def reject(seq, predicate):
return [item for item in seq if not predicate(item)]
| The reject() function | 52988f3f7edba9839c00037d | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/52988f3f7edba9839c00037d | 7 kyu |
Write a program that, given a word, computes the scrabble score for that word.
## Letter Values
You'll need these:
```
Letter Value
A, E, I, O, U, L, N, R, S, T 1
D, G 2
B, C, M, P 3
F, H, V, W, Y 4
K ... | reference | def scrabble_score(stg):
return sum(dict_scores . get(c, 0) for c in stg . upper())
| Scrabble Score | 558fa34727c2d274c10000ae | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/558fa34727c2d274c10000ae | 7 kyu |
You'll be passed an array of objects (`list`) - you must sort them in descending order based on the value of the specified property (`sortBy`).
## Example
When sorted by `"a"`, this:
```python
[
{"a": 1, "b": 3},
{"a": 3, "b": 2},
{"a": 2, "b": 40},
{"a": 4, "b": 12}
]
```
should return:
```python
[
{"a":... | reference | def sort_list(sort_key, l):
return sorted(l, key=lambda x: x[sort_key], reverse=True)
| Return a sorted list of objects | 52705ed65de62b733f000064 | [
"Arrays",
"Sorting",
"Fundamentals"
] | https://www.codewars.com/kata/52705ed65de62b733f000064 | 7 kyu |
Write a method that will search an array of strings for all strings that contain another string, ignoring capitalization. Then return an array of the found strings.
The method takes two parameters, the query string and the array of strings to search, and returns an array.
If the string isn't contained in any of the... | reference | def word_search(query, seq):
return [x for x in seq if query . lower() in x . lower()] or ["None"]
| Partial Word Searching | 54b81566cd7f51408300022d | [
"Arrays",
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/54b81566cd7f51408300022d | 7 kyu |
Implement a function which behaves like the 'uniq -c' command in UNIX.
It takes as input a sequence and returns a sequence in which all duplicate elements following each other have been reduced to one instance together with the number of times a duplicate elements occurred in the original array.
## Example:
```java... | algorithms | from itertools import groupby
def uniq_c(seq):
return [(k, sum(1 for _ in g)) for k, g in groupby(seq)]
| uniq -c (UNIX style) | 52250aca906b0c28f80003a1 | [
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/52250aca906b0c28f80003a1 | 5 kyu |
*It seemed a good idea at the time...*
# <span style='color:red'>Why I did it?</span>
After a year on **Codewars** I really needed a holiday...
But not wanting to drift backwards in the honour rankings while I was away, I hatched a cunning plan!
# <span style='color:red'>The Cunning Plan</spac>
So I borrowed my fr... | algorithms | def clonewars(k):
return [2 * * max(k - 1, 0), 2 * * (k + 1) - k - 2]
| Send in the Clones | 58ddffda929dfc2cae0000a5 | [
"Algorithms"
] | https://www.codewars.com/kata/58ddffda929dfc2cae0000a5 | 7 kyu |
Implement the function which should return `true` if given object is a vowel (meaning `a, e, i, o, u`, uppercase or lowercase), and `false` otherwise. | reference | def is_vowel(s):
return s . lower() in set("aeiou")
| Regexp Basics - is it a vowel? | 567bed99ee3451292c000025 | [
"Regular Expressions",
"Fundamentals"
] | https://www.codewars.com/kata/567bed99ee3451292c000025 | 7 kyu |
Create the function `prefill` that returns an array of `n` elements that all have the same value `v`. See if you can do this *without* using a loop.
You have to validate input:
* `v` can be *anything* (primitive or otherwise)
* if `v` is ommited, fill the array with `undefined`
* if `n` is 0, return an empty arra... | reference | def prefill(n=0, v=None):
try:
return [v] * int(n)
except:
raise TypeError(str(n) + ' is invalid')
| Prefill an Array | 54129112fb7c188740000162 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/54129112fb7c188740000162 | 6 kyu |
Complete the function to determine the number of bits required to convert integer `A` to integer `B` (where `A` and `B` >= 0)
The upper limit for `A` and `B` is 2<sup>16</sup>, `int.MaxValue` or similar.
For example, you can change 31 to 14 by flipping the 4th and 0th bit:
```
31 0 0 0 1 1 1 1 1
14 0 0 0 0 1 1 1 ... | algorithms | def convert_bits(a, b):
return bin(a ^ b). count("1")
| Delta Bits | 538948d4daea7dc4d200023f | [
"Bits",
"Binary",
"Algorithms"
] | https://www.codewars.com/kata/538948d4daea7dc4d200023f | 7 kyu |
Write a module Converter that can take ASCII text and convert it to hexadecimal. The class should also be able to take hexadecimal and convert it to ASCII text.
To make the conversion well defined, each ASCII character is represented by exactly two hex digits, left-padding with a `0` if needed.
The conversion from asci... | reference | class Converter ():
@ staticmethod
def to_ascii(h):
return '' . join(chr(int(h[i: i + 2], 16)) for i in range(0, len(h), 2))
@ staticmethod
def to_hex(s):
return '' . join(hex(ord(char))[2:] for char in s)
| ASCII hex converter | 52fea6fd158f0576b8000089 | [
"Fundamentals",
"Bits",
"Strings",
"Object-oriented Programming"
] | https://www.codewars.com/kata/52fea6fd158f0576b8000089 | 6 kyu |
Every Turkish citizen has an identity number whose validity can be checked by these set of rules:
- It is an 11 digit number
- First digit can't be zero
- Take the sum of 1st, 3rd, 5th, 7th and 9th digit and multiply it by 7.
Then subtract the sum of 2nd, 4th, 6th and 8th digits from this value.
Modulus 10 of the resu... | algorithms | def check_valid_tr_number(n):
return type(n) == int and len(str(n)) == 11 and \
8 * sum(map(int, str(n)[: - 1: 2])
) % 10 == sum(map(int, str(n)[: - 1])) % 10 == n % 10
| Turkish National Identity Number | 556021360863a1708900007b | [
"Algorithms"
] | https://www.codewars.com/kata/556021360863a1708900007b | 6 kyu |
Return the century of the input year. The input will always be a 4 digit string, so there is no need for validation.
### Examples
```
"1999" --> "20th"
"2011" --> "21st"
"2154" --> "22nd"
"2259" --> "23rd"
"1124" --> "12th"
"2000" --> "20th"
``` | algorithms | def what_century(year):
n = (int(year) - 1) / / 100 + 1
return str(n) + ("th" if n < 20 else {1: "st", 2: "nd", 3: "rd"}. get(n % 10, "th"))
| What century is it? | 52fb87703c1351ebd200081f | [
"Strings",
"Algorithms",
"Date Time"
] | https://www.codewars.com/kata/52fb87703c1351ebd200081f | 6 kyu |
Write a function that takes a piece of text in the form of a string and returns the letter frequency count for the text. This count excludes numbers, spaces and all punctuation marks. Upper and lower case versions of a character are equivalent and the result should all be in lowercase.
The function should return a l... | algorithms | from collections import Counter
from operator import itemgetter
def letter_frequency(text):
items = Counter(c for c in text . lower() if c . isalpha()). items()
return sorted(
sorted(items, key=itemgetter(0)),
key=itemgetter(1),
reverse=True
)
| Character frequency | 53e895e28f9e66a56900011a | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/53e895e28f9e66a56900011a | 6 kyu |
The year is 2070 and intelligent connected machines have replaced humans in most things. There are still a few critical jobs for mankind including machine software developer, for writing and maintaining the AI software, and machine forward deployed engineer for controlling the intelligent machines in the field. Lorimar... | algorithms | from collections import Counter
def is_prime(n): return n > 1 and all(n % d for d in range(2, int(n * * .5) + 1))
PRIMES = {str(n) for n in range(10 * * 3, 10 * * 4) if str(n)[2] in '23' and is_prime(n)}
def search_disable(log): return ['no match continue', 'match disable bot'][
sum(c for n, c in Co... | AD2070: Help Lorimar troubleshoot his robots-Search and Disable | 57dc0ffed8f92982af0000f6 | [
"Data Structures",
"Mathematics",
"Algorithms",
"Data Science"
] | https://www.codewars.com/kata/57dc0ffed8f92982af0000f6 | 6 kyu |
Modify the `kebabize` function so that it converts a camel case string into a kebab case.
```
"camelsHaveThreeHumps" --> "camels-have-three-humps"
"camelsHave3Humps" --> "camels-have-humps"
"CAMEL" --> "c-a-m-e-l"
```
Notes:
- the returned string should only contain lowercase letters | reference | def kebabize(s):
return '' . join(c if c . islower() else '-' + c . lower() for c in s if c . isalpha()). strip('-')
| Kebabize | 57f8ff867a28db569e000c4a | [
"Fundamentals",
"Strings",
"Regular Expressions"
] | https://www.codewars.com/kata/57f8ff867a28db569e000c4a | 6 kyu |
> In information theory and computer science, the Levenshtein distance is a string metric for measuring the difference between two sequences. Informally, the Levenshtein distance between two words is the minimum number of single-character edits (i.e. insertions, deletions or substitutions) required to change one word i... | algorithms | def levenshtein(a, b):
d = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
d[0][:] = range(len(b) + 1)
for i in range(1, len(a) + 1):
d[i][0] = i
for i, x in enumerate(a):
for j, y in enumerate(b):
d[i + 1][j + 1] = min(1 + d[i][j + 1], 1 + d[i + 1]
[j], d... | Levenshtein Distance | 545cdb4f61778e52810003a2 | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/545cdb4f61778e52810003a2 | 6 kyu |
<b>Linked lists</b> are data structures composed of nested or chained objects, each containing a single value and a reference to the next object.
Here's an example of a list:
```javascript
{value: 1, next: {value: 2, next: {value: 3, next: null}}}
```
```python
class LinkedList:
def __init__(self, value=0, next=... | reference | def list_to_array(lst):
arr = []
while lst != None:
arr . append(lst . value)
lst = lst . next
return arr
| LinkedList -> Array | 557dd2a061f099504a000088 | [
"Data Structures",
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/557dd2a061f099504a000088 | 7 kyu |
# Story
Peter lives on a hill, and he always moans about the way to his home. "It's always just up. I never get a rest". But you're pretty sure that at least at one point Peter's altitude doesn't rise, but fall. To get him, you use a nefarious plan: you attach an altimeter to his backpack and you read the data from his... | reference | def is_monotone(heights):
return sorted(heights) == heights
| Monotone travel | 54466996990c921f90000d61 | [
"Lists",
"Fundamentals"
] | https://www.codewars.com/kata/54466996990c921f90000d61 | 7 kyu |
Dave has a lot of data he is required to apply filters to, which are simple enough, but he wants a shorter way of doing so.
He wants the following functions to work as expected:
```ruby
even # [1,2,3,4,5].even should return [2,4]
odd # [1,2,3,4,5].odd should return [1,3,5]
under # [1,2,3,4,5].under(4) should return [1... | reference | import __builtin__
class CustomList (list):
def ints(self):
return [x for x in self if isinstance(x, int)]
def even(self):
return [x for x in self . ints() if x % 2 == 0]
def odd(self):
return [x for x in self . ints() if x % 2 == 1]
def under(self, ceil):
return [x for x in... | Custom Array Filters | 53fc954904a45eda6b00097f | [
"Arrays",
"Fundamentals",
"Object-oriented Programming"
] | https://www.codewars.com/kata/53fc954904a45eda6b00097f | 6 kyu |
To pass the series of gates guarded by the owls, Kenneth needs to present them each with a highly realistic portrait of one. Unfortunately, he is absolutely rubbish at drawing, and needs some code to return a brand new portrait with a moment's notice.
All owl heads look like this:
''0v0''
Such beautiful eyes!
H... | reference | import re
def owl_pic(text):
str = re . sub('[^ 8,W,T,Y,U,I,O,A,H,X,V,M]', '', text . upper())
return str + "''0v0''" + str[:: - 1]
| The Owls Are Not What They Seem | 55aa7acc42216b3dd6000022 | [
"Regular Expressions",
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/55aa7acc42216b3dd6000022 | 7 kyu |
**This Kata is intended as a small challenge for my students**
All Star Code Challenge #24
Your friend David is an architect who is working on a triangle-focused design. He needs a quick way for knowing the measurement of a right triangle's side, only knowing two of the sides.
He knows about the Pythagorean Theorem,... | reference | import math
def hypotenuse(a, b):
return math . hypot(a, b)
def leg(c, a):
return (c * * 2 - a * * 2) * * .5
| All Star Code Challenge #24 | 5866c6cf442e3f16f9000089 | [
"Fundamentals"
] | https://www.codewars.com/kata/5866c6cf442e3f16f9000089 | 7 kyu |
A very easy task for you!
You have to create a method, that corrects a given date string.
There was a problem in addition, so many of the date strings are broken.
Date-Format is european. That means "DD.MM.YYYY".
<br>
<br>
Some examples:
"30.02.2016" -> "01.03.2016"<br>
"40.06.2015" -> "10.07.2015"<br>
"11.13.2014" -... | reference | import re
from datetime import date, timedelta
def date_correct(text):
if not text:
return text
try:
d, m, y = map(int, re . match(
r'^(\d{2})\.(\d{2})\.(\d{4})$', text). groups())
mo, m = divmod(m - 1, 12)
return (date(y + mo, m + 1, 1) + timedelta(days=d - 1)). strftime('%... | Correct the date-string | 5787628de55533d8ce000b84 | [
"Parsing",
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5787628de55533d8ce000b84 | 7 kyu |
Hello! Your are given x and y and 2D array size tuple (width, height) and you have to:
<ol><li>Calculate the according index in 1D space (zero-based). </li>
<li>Do reverse operation.</li>
</ol>
<pre>Implement:
to_1D(x, y, size):
--returns index in 1D space
to_2D(n, size)
--returns x and y in 2D space</pre>
<pre>
1... | reference | def to_1D(x, y, size):
return y * size[0] + x
def to_2D(n, size):
return (n % size[0], n / / size[0])
| 2D / 1D array coordinates mapping | 588dd9c3dc49de0bd400016d | [
"Arrays",
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/588dd9c3dc49de0bd400016d | 7 kyu |
Given a number `n`, make a down arrow shaped pattern.
For example, when `n = 5`, the output would be:
123454321
1234321
12321
121
1
and for `n = 11`, it would be:
123456789010987654321
1234567890987654321
12345678987654321
123456787654321
1234567654321
... | algorithms | def half(i, n):
return "" . join(str(d % 10) for d in range(1, n - i + 1))
def line(i, n):
h = half(i, n)
return " " * i + h + h[- 2:: - 1]
def get_a_down_arrow_of(n):
return "\n" . join(line(i, n) for i in range(n))
| Down Arrow With Numbers | 5645b24e802c6326f7000049 | [
"Algorithms"
] | https://www.codewars.com/kata/5645b24e802c6326f7000049 | 7 kyu |
# Story&Task
The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all houses in the city were built in one row.
Let's enumerate all the houses from left to right, starting with 0. A house is considered to be luxurious if the number of floors in it is strictl... | algorithms | def luxhouse(houses):
return [max(0, max(houses[i:]) - h + 1) for i, h in enumerate(houses[: - 1], 1)] + [0]
| Simple Fun #200: Luxurious House | 58c8af49fd407dea5f000042 | [
"Algorithms"
] | https://www.codewars.com/kata/58c8af49fd407dea5f000042 | 6 kyu |
# Introduction
<pre style="white-space: pre-wrap;white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;">
Good one Shaggy! We all love to watch Scooby Doo, Shaggy Rogers, Fred Jones, Daphne Blake and Velma Dinkley solve the clues and figure out who was the villain. The story ... | games | import difflib
from string import ascii_lowercase, ascii_uppercase
tbl = str . maketrans(ascii_lowercase + ascii_uppercase,
(ascii_lowercase[5:] + ascii_lowercase[: 5]) * 2)
def scoobydoo(villian, villians):
villian = villian . replace(' ', '')
villian = villian[- 6:: - 1] + vill... | Scooby Doo Puzzle | 58693bbfd7da144164000d05 | [
"Puzzles",
"Cryptography",
"Algorithms"
] | https://www.codewars.com/kata/58693bbfd7da144164000d05 | 6 kyu |
# Task
Given an array `arr` and a number `n`. Call a pair of numbers from the array a `Perfect Pair` if their sum is equal to `n`.
Find all of the perfect pairs and return the sum of their **indices**.
Note that any element of the array can only be counted in one Perfect Pair. If there are multiple correct answers... | algorithms | def pairwise(arr, n):
s = []
for i in range(len(arr) - 1):
for j in range(i + 1, len(arr)):
if j in s or i in s:
continue
if arr[i] + arr[j] == n:
s . append(i)
s . append(j)
return sum(s)
| Simple Fun #162: Pair Wise | 58afa8185eb02ea2a7000094 | [
"Algorithms"
] | https://www.codewars.com/kata/58afa8185eb02ea2a7000094 | 6 kyu |
# Task
You are given two string `a` an `s`. Starting with an empty string we can do the following two operations:
```
append the given string a to the end of the current string.
erase one symbol of the current string.```
Your task is to find the least number of operations needed to construct the given string s. Assume... | games | import re
def string_constructing(a, s):
# "-1" because one empty string is always found at the end
n = len(re . findall('?' . join(list(a)) + '?', s)) - 1
return n + len(a) * n - len(s)
| Simple Fun #122: String Constructing | 58a3a735cebc0630830000c0 | [
"Puzzles"
] | https://www.codewars.com/kata/58a3a735cebc0630830000c0 | 6 kyu |
## Task
An `ATM` ran out of 10 dollar bills and only has `100, 50 and 20` dollar bills.
Given an amount between `40 and 10000 dollars (inclusive)` and assuming that the ATM wants to use as few bills as possible, determinate the minimal number of 100, 50 and 20 dollar bills the ATM needs to dispense (in that order).... | games | def withdraw(n):
n50 = 0
n20, r = divmod(n, 20)
if r == 10:
n20 -= 2
n50 += 1
n100, n20 = divmod(n20, 5)
return [n100, n50, n20]
| Simple Fun #165: Withdraw | 58afce23b0e8046a960000eb | [
"Puzzles"
] | https://www.codewars.com/kata/58afce23b0e8046a960000eb | 6 kyu |
# Task
John is new to spreadsheets. He is well aware of rows and columns, but he is not comfortable with spreadsheets numbering system.
```
Spreadsheet Row Column
A1 R1C1
D5 R5C4
AA48 R48C27
BK12 R12C63```
Since John has a lot of work to do both in row-column and spreadsheet system... | algorithms | import re
def spreadsheet(s):
nums = re . findall(r'(\d+)', s)
if len(nums) == 2:
n, cStr = int(nums[1]), ''
while n:
n, r = divmod(n - 1, 26)
cStr += chr(r + 65)
return "{}{}" . format(cStr[:: - 1], nums[0])
else:
return "R{}C{}" . format(nums[0], sum(26 * * i * (ord(c... | Simple Fun #167: Spreadsheet | 58b38f24c723bf6b660000d8 | [
"Algorithms"
] | https://www.codewars.com/kata/58b38f24c723bf6b660000d8 | 5 kyu |
# Task
Given an array of integers, sum consecutive even numbers and consecutive odd numbers. Repeat the process while it can be done and return the length of the final array.
# Example
For `arr = [2, 1, 2, 2, 6, 5, 0, 2, 0, 5, 5, 7, 7, 4, 3, 3, 9]`
The result should be `6`.
```
[2, 1, 2, 2, 6, 5, 0, 2, 0, 5, 5, 7... | games | from itertools import groupby
def sum_groups(arr):
newarr = [sum(j) for i, j in groupby(arr, key=lambda x: x % 2 == 0)]
return len(newarr) if newarr == arr else sum_groups(newarr)
| Simple Fun #170: Sum Groups | 58b3c2bd917a5caec0000017 | [
"Arrays",
"Algorithms",
"Lists",
"Data Structures"
] | https://www.codewars.com/kata/58b3c2bd917a5caec0000017 | 6 kyu |
# Task
You are given a regular array `arr`. Let's call a `step` the difference between two adjacent elements.
Your task is to sum the elements which belong to the sequence of consecutive elements of length `at least 3 (but as long as possible)`, such that the steps between the elements in this sequence are the sam... | algorithms | def sum_of_regular_numbers(arr):
result = []
new = []
for i in range(len(arr)):
if len(new) < 2 or (len(new) >= 2 and arr[i] - new[- 1] == new[- 1] - new[- 2]):
new . append(arr[i])
else:
if len(new) >= 3:
result += new
new = [new[- 1], arr[i]]
if len(new) > 2:
... | Simple Fun #191: Sum Of Regular Numbers | 58c20c8d61aefc518f0000fd | [
"Algorithms"
] | https://www.codewars.com/kata/58c20c8d61aefc518f0000fd | 6 kyu |
# Task
Given an integer `n`, find the maximal number you can obtain by deleting exactly one digit of the given number.
# Example
For `n = 152`, the output should be `52`;
For `n = 1001`, the output should be `101`.
# Input/Output
- `[input]` integer `n`
Constraints: `10 ≤ n ≤ 1000000.`
- `[output]` ... | games | def delete_digit(n):
s = str(n)
return int(max(s[: i] + s[i + 1:] for i in range(len(s))))
| Simple Fun #79: Delete a Digit | 5894318275f2c75695000146 | [
"Puzzles"
] | https://www.codewars.com/kata/5894318275f2c75695000146 | 6 kyu |
# Task
After becoming famous, CodeBots decided to move to a new building and live together. The building is represented by a rectangular matrix of rooms, each cell containing an integer - the price of the room. Some rooms are free (their cost is 0), but that's probably because they are haunted, so all the bots are afr... | games | def matrix_elements_sum(m):
return sum(sum(e for i, e in enumerate(c) if 0 not in c or i < c . index(0)) for c in zip(* m))
| Simple Fun #65: Matrix Elements Sum | 5893eb36779ce5faab0000da | [
"Puzzles",
"Matrix",
"Algorithms"
] | https://www.codewars.com/kata/5893eb36779ce5faab0000da | 6 kyu |
Modify the spacify function so that it returns the given string with spaces inserted between each character.
```coffeescript
spacify=("hello world") -> # returns "h e l l o w o r l d
```
```crystal
spacify("hello world") # returns "h e l l o w o r l d"
```
```haskell
spacify "hello world" -- returns "h e l l o w... | reference | def spacify(string):
return " " . join(string)
| Spacify | 57f8ee485cae443c4d000127 | [
"Fundamentals",
"Strings",
"Arrays"
] | https://www.codewars.com/kata/57f8ee485cae443c4d000127 | 7 kyu |
Is every value in the array an array?
This should only test the second array dimension of the array. The values of the nested arrays don't have to be arrays.
Examples:
```javascript
[[1],[2]] => true
['1','2'] => false
[{1:1},{2:2}] => false
```
```python
[[1],[2]] => true
['1','2'] => false
[{1:1},{2:2}] => false
... | reference | def arr_check(arr):
return all(isinstance(el, list) for el in arr)
| Is every value in the array an array? | 582c81d982a0a65424000201 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/582c81d982a0a65424000201 | 7 kyu |
Write a function that can return the smallest value of an array or the index of that value. The function's 2nd parameter will tell whether it should return the value or the index.
Assume the first parameter will always be an array filled with at least 1 number and no duplicates. Assume the second parameter will be a s... | reference | def find_smallest(numbers, to_return):
return min(numbers) if to_return == 'value' else numbers . index(min(numbers))
| Smallest value of an array | 544a54fd18b8e06d240005c0 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/544a54fd18b8e06d240005c0 | 7 kyu |
# Task
In the popular `Minesweeper` game you have a board with some mines and those cells that don't contain a mine have a number in it that indicates the total number of mines in the neighboring cells. Starting off with some arrangement of mines we want to create a `Minesweeper` game setup.
# Example
For
```
matri... | games | import numpy as np
from scipy import signal
def minesweeper(matrix):
return signal . convolve2d(np . array(matrix), np . array([[1, 1, 1], [1, 0, 1], [1, 1, 1]]), mode='same'). tolist()
| Simple Fun #83: MineSweeper | 58952e29f0902eae8b0000cb | [
"Puzzles"
] | https://www.codewars.com/kata/58952e29f0902eae8b0000cb | 6 kyu |
You are given two strings (st1, st2) as inputs. Your task is to return a string containing the numbers in st2 which are not in str1. Make sure the numbers are returned in ascending order.
All inputs will be a string of numbers.
Here are some examples:
```javascript
findAdded('4455446', '447555446666'); // '56667'
fi... | reference | from collections import Counter
def findAdded(st1, st2):
return '' . join(sorted((Counter(st2) - Counter(st1)). elements()))
| Find Added | 58de77a2c19f096a5a00013f | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/58de77a2c19f096a5a00013f | 6 kyu |
This series of katas will introduce you to basics of doing geometry with computers.
`Point` objects have `x`, `y`, and `z` attributes. For Haskell there are `Point` data types described with record syntax with fields `x`, `y`, and `z`.
Write a function calculating distance between `Point a` and `Point b`.
Tests rou... | reference | def distance_between_points(a, b):
return ((a . x - b . x) * * 2 + (a . y - b . y) * * 2 + (a . z - b . z) * * 2) * * 0.5
| Geometry Basics: Distance between points in 3D | 58dceee2c9613aacb40000b9 | [
"Geometry",
"Fundamentals"
] | https://www.codewars.com/kata/58dceee2c9613aacb40000b9 | 7 kyu |
The aim of the kata is to try to show how difficult it can be to calculate decimals of an irrational number with a certain precision. We have chosen to get a few decimals of the number "pi" using
the following infinite series (Leibniz 1646–1716):
PI / 4 = 1 - 1/3 + 1/5 - 1/7 + ... which gives an approximation of PI /... | reference | from math import pi
def iter_pi(epsilon):
n = 1
approx = 4
while abs(approx - pi) > epsilon:
n += 1
approx += (- 4, 4)[n % 2] / (n * 2 - 1.0)
return [n, round(approx, 10)]
| PI approximation | 550527b108b86f700000073f | [
"Arrays",
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/550527b108b86f700000073f | 6 kyu |
A [sequence or a series](http://world.mathigon.org/Sequences), in mathematics, is a string of objects, like numbers, that follow a particular pattern. The individual elements in a sequence are called terms. A simple example is `3, 6, 9, 12, 15, 18, 21, ...`, where the pattern is: _"add 3 to the previous term"_.
In thi... | reference | def sum_of_n(n):
return [(- 1 if n < 0 else 1) * sum(xrange(i + 1)) for i in xrange(abs(n) + 1)]
| Basic Sequence Practice | 5436f26c4e3d6c40e5000282 | [
"Fundamentals"
] | https://www.codewars.com/kata/5436f26c4e3d6c40e5000282 | 7 kyu |
[Harshad numbers](http://en.wikipedia.org/wiki/Harshad_number) (also called Niven numbers) are positive numbers that can be divided (without remainder) by the sum of their digits.
For example, the following numbers are Harshad numbers:
* 10, because 1 + 0 = 1 and 10 is divisible by 1
* 27, because 2 + 7 = 9 and 27 is... | reference | from itertools import count, islice
class Harshad:
@ staticmethod
def is_valid(number):
return number % sum(map(int, str(number))) == 0
@ classmethod
def get_next(cls, number):
return next(i for i in count(number + 1) if cls . is_valid(i))
@ classmethod
def get_series(cls,... | Harshad or Niven numbers | 54a0689443ab7271a90000c6 | [
"Fundamentals",
"Mathematics",
"Object-oriented Programming"
] | https://www.codewars.com/kata/54a0689443ab7271a90000c6 | 6 kyu |
<h3>Description:</h3>
Given a string, you need to write a method that order every letter in this string in ascending order.
Also, you should validate that the given string is not empty or null. If so, the method should return:
```
"Invalid String!"
```
<h4>Notes</h4>
• the given string can be lowercase and upperc... | reference | def order_word(s):
return "" . join(sorted(s)) if s else "Invalid String!"
| Ordering the words! | 55d7e5aa7b619a86ed000070 | [
"Strings",
"Sorting",
"Fundamentals"
] | https://www.codewars.com/kata/55d7e5aa7b619a86ed000070 | 7 kyu |
Everybody knows a little german, right? But remembering the correct articles is a tough job. Write yourself a little helper, that returns the noun with the matching article:
- each noun containing less than 2 vowels has the article "das"
- each noun containing 2/3 vowels has the article "die"
- each noun containing mo... | reference | def der_die_das(wort):
a = sum(x in "aAeEiIoOuUäöü" for x in wort)
return f' { "das" if a < 2 else "die" if a < 4 else "der" } { wort } '
| Deutschstunde | 552cd8624a414ec2b2000086 | [
"Fundamentals"
] | https://www.codewars.com/kata/552cd8624a414ec2b2000086 | 7 kyu |
Naming multiple files can be a pain sometimes.
#### Task:
Your job here is to create a function that will take three parameters, `fmt`, `nbr` and `start`, and create an array of `nbr` elements formatted according to `frm` with the starting index `start`. `fmt` will have `<index_no>` inserted at various locations; thi... | reference | def name_file(fmt, nbr, start):
try:
return [fmt . replace('<index_no>', '{0}'). format(i)
for i in range(start, start + nbr)]
except TypeError:
return []
| Naming Files | 5829994cd04efd4373000468 | [
"Fundamentals"
] | https://www.codewars.com/kata/5829994cd04efd4373000468 | 7 kyu |
# Reducing by rules to get the result
Your task is to reduce a list of numbers to one number.<br>
For this you get a list of rules, how you have to reduce the numbers.<br>
You have to use these rules consecutively. So when you get to the end of the list of rules, you start again at the beginning.
An example is cleare... | algorithms | from functools import reduce
from itertools import cycle
def reduce_by_rules(lst, rules):
rs = cycle(rules)
return reduce(lambda x, y: next(rs)(x, y), lst)
| Reducing by rules to get the result | 585ba6dff59b3cef3f000132 | [
"Arrays",
"Logic",
"Algorithms"
] | https://www.codewars.com/kata/585ba6dff59b3cef3f000132 | 6 kyu |
Write a function that will randomly upper and lower characters in a string - `randomCase()` (`random_case()` for Python).
A few examples:
```
randomCase("Lorem ipsum dolor sit amet, consectetur adipiscing elit") == "lOReM ipSum DOloR SiT AmeT, cOnsEcTEtuR aDiPiSciNG eLIt"
randomCase("Donec eleifend cursus lobortis")... | reference | import random
def random_case(x):
return "" . join([random . choice([c . lower(), c . upper()]) for c in x])
| RaNDoM CAsE | 57073869924f34185100036d | [
"Fundamentals"
] | https://www.codewars.com/kata/57073869924f34185100036d | 7 kyu |
Marcus was spending his last summer day playing chess with his friend Rose.
Surprisingly, they had a lot of pieces (we suspect Marcus is a part-time thief, but we will leave that aside), and Marcus wondered in how many different positions could 8 towers (rooks) be in the board, without threatening themselves.
Rose (w... | algorithms | import math
def tower_combination(n):
return math . factorial(n)
| 8 towers | 535bea76cdbf50281a00004c | [
"Algorithms"
] | https://www.codewars.com/kata/535bea76cdbf50281a00004c | 7 kyu |
## Task
Given a number, return the maximum value by rearranging its digits.
Examples:
`(123) => 321` `(786) => 876` `("001") => 100` `(999) => 999` `(10543) => 54310`
*^Note the number may be given as a string* | reference | def rotate_to_max(n):
return int('' . join(sorted(str(n), reverse=True)))
| Rotate to the max | 579fa665bb9944f9340005d2 | [
"Fundamentals",
"Numbers",
"Data Types"
] | https://www.codewars.com/kata/579fa665bb9944f9340005d2 | 7 kyu |
Write a function that accepts two parameters, i) a string (containing a list of words) and ii) an integer (n). The function should alphabetize the list based on the nth letter of each word.
The letters should be compared case-insensitive. If both letters are the same, order them normally (lexicographically), again, c... | reference | def sort_it(list_, n):
return ', ' . join(sorted(list_ . split(', '), key=lambda i: i[n - 1]))
| Alphabetize a list by the nth character | 54eea36b7f914221eb000e2f | [
"Lists",
"Strings",
"Sorting",
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/54eea36b7f914221eb000e2f | 7 kyu |
<img src = https://teamfisticuffs.files.wordpress.com/2011/09/beardfist.jpg>
It has long been rumoured that behind Chuck's beard is not a chin, but another fist!
When shaving, Chuck accidentally punched himself in the face. He is the only man that could take that punch without dying, but that doesn't mean it didn't ... | algorithms | from itertools import chain
def fist_beard(arr):
return '' . join(map(chr, chain(* arr)))
| Chuck Norris IV - Bearded Fist | 57066708cb7293901a0013a1 | [
"Fundamentals",
"Algorithms",
"Arrays",
"Puzzles"
] | https://www.codewars.com/kata/57066708cb7293901a0013a1 | 7 kyu |
Your non-profit company has assigned you the task of calculating some simple statistics on donations. You have an array of integers, representing various amounts of donations your company has been given. In particular, you're interested in the median value for donations.
The median is the middle number of a **sorted l... | reference | from statistics import median
| All Star Code Challenge #14 - Find the median | 5864eb8039c5ab9cd400005c | [
"Fundamentals"
] | https://www.codewars.com/kata/5864eb8039c5ab9cd400005c | 7 kyu |
## Task
The string is called `prime` if it cannot be constructed by concatenating some (more than one) equal strings together.
For example, "abac" is prime, but "xyxy" is not("xyxy"="xy"+"xy").
Given a string determine if it is prime or not.
## Input/Output
- `[input]` string `s`
string containing only low... | games | def prime_string(s):
return (s + s). find(s, 1) == len(s)
| Simple Fun #116: Prime String | 589d36bbb6c071f7c20000f7 | [
"Puzzles"
] | https://www.codewars.com/kata/589d36bbb6c071f7c20000f7 | 6 kyu |
# Task
You are given an array of integers `a` and a non-negative number of operations `k`, applied to the array. Each operation consists of two parts:
```
find the maximum element value of the array;
replace each element a[i] with (maximum element value - a[i]).```
How will the array look like after `k` such operation... | games | def array_operations(a, n):
li = []
for i in range(n):
m = max(a)
a = [m - i for i in a]
if a in li:
if not n & 1:
return li[- 1]
return a
li . append(a)
return a
| Simple Fun #110: Array Operations | 589aca25fef1a81a10000057 | [
"Puzzles"
] | https://www.codewars.com/kata/589aca25fef1a81a10000057 | 6 kyu |
No description!!!
Input :: [10,20,25,0]
Output :: ["+0", "+10", "+15", "-10"]
`Show some love, rank and upvote!` | games | def equalize(arr):
return ["{:+d}" . format(i - arr[0]) for i in arr]
| Equalize the array! | 580a1a4af195dbc9ed00006c | [
"Fundamentals",
"Puzzles",
"Arrays"
] | https://www.codewars.com/kata/580a1a4af195dbc9ed00006c | 7 kyu |
You will be given a string.
You need to return an array of three strings by gradually pulling apart the string.
You should repeat the following steps until the string length is 1:
a) remove the final character from the original string, add to solution string 1.
b) remove the first character from the original string... | reference | def pop_shift(s):
il, ir = len(s) / / 2, (len(s) + 1) / / 2
return [s[: ir - 1: - 1], s[: il], s[il: ir]]
| PopShift | 57cec34272f983e17800001e | [
"Fundamentals",
"Strings",
"Arrays"
] | https://www.codewars.com/kata/57cec34272f983e17800001e | 7 kyu |
The function takes _cents_ value (int) and needs to return the minimum number of coins combination of the same value.
The function should return ***an array*** where
coins[0] = pennies ==> $00.01
coins[1] = nickels ==> $00.05
coins[2] = dimes ==> $00.10
coins[3] = quarters ==> $00.25
So for example: ... | algorithms | def coin_combo(c):
R = []
for p in (25, 10, 5, 1):
R . append(c / / p)
c = c % p
return R[:: - 1]
| Calculator: Coin Combination | 564d0490e96393fc5c000029 | [
"Fundamentals",
"Algorithms"
] | https://www.codewars.com/kata/564d0490e96393fc5c000029 | 7 kyu |
In Star Labs we use password system to unlock the lab doors and only Team Flash is given the password for these labs. The password system is made of a `n x n` keypad (`n > 0`).
One day Zoom saw Cisco using the password. He figured out that the password is symmetric about the centre point (the centre point for a `n x ... | reference | def help_zoom(key):
return 'Yes' if key == key[:: - 1] else 'No'
| Password System | 57a23e3753ba332b8e0008da | [
"Fundamentals"
] | https://www.codewars.com/kata/57a23e3753ba332b8e0008da | 7 kyu |
Given an array of integers (x), and a target (t), you must find out if any two consecutive numbers in the array sum to t. If so, remove the second number.
Example:
x = [1, 2, 3, 4, 5]<br>
t = 3 <br>
1+2 = t, so remove 2. No other pairs = t, so rest of array remains:
[1, 3, 4, 5]
Work through the array from left to... | reference | def trouble(x, t):
arr = [x[0]]
for c in x[1:]:
if c + arr[- 1] != t:
arr . append(c)
return arr
| Double Trouble | 57f7796697d62fc93d0001b8 | [
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/57f7796697d62fc93d0001b8 | 7 kyu |
Given value of sine,implement function which will return sine,cosine,tangent,and cotangent in list. order must be same as in the description and every number must be rounded to 2 decimal places.If tangent or cotangent can not be calculated just don't contain them in result list.
Trygonometry - https://en.wikipedia.org... | reference | def sctc(sin):
cos = (1 - sin * * 2) * * 0.5
if 0 in (sin, cos):
res = [sin, cos, 0.0]
else:
res = [sin, cos, sin / cos, cos / sin]
return list(map(lambda x: round(x, 2), res))
| Sine,cosine and others | 57d52a7f76da830e43000188 | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/57d52a7f76da830e43000188 | 7 kyu |
Implement function which will return sum of roots of a quadratic equation rounded to 2 decimal places, if there are any possible roots, else return **None/null/nil/nothing**. If you use discriminant,when discriminant = 0, x1 = x2 = root => return sum of both roots. There will always be valid arguments.
Quadratic equa... | reference | def roots(a, b, c):
if b * * 2 >= 4 * a * c:
return round(- b / a, 2)
| Find the sum of the roots of a quadratic equation | 57d448c6ba30875437000138 | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/57d448c6ba30875437000138 | 7 kyu |
<img src='http://images.huffingtonpost.com/2016-07-13-1468421604-4642908-IronmanLogo.jpg'>
An Ironman Triathlon is one of a series of long-distance triathlon races organized by the World Triathlon Corporaion (WTC).
It consists of a 2.4-mile swim, a 112-mile bicycle ride and a marathon (26.2-mile) (run, raced in that o... | reference | def i_tri(s):
total = 2.4 + 112 + 26.2
to_go = '%.2f to go!' % (total - s)
return ('Starting Line... Good Luck!' if s == 0 else
{'Swim': to_go} if s < 2.4 else
{'Bike': to_go} if s < 2.4 + 112 else
{'Run': to_go} if s < total - 10 else
{'Run': 'Nearly... | Ironman Triathlon | 57d001b405c186ccb6000304 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/57d001b405c186ccb6000304 | 7 kyu |
Welcome to the Mathematics gameshow. I'm your host, Apex Rhombus, and it's time for the lightning round!
Today we'll talk about a hypothetical bottle. This entire bottle weighs 120 grams. Its contents weigh twice as much as the bottle itself. What, may I ask, do the contents weigh?
...Did you guess 80 grams? Correct!... | algorithms | def content_weight(bottle_weight, scale):
a, _, c = scale . split(" ")
return bottle_weight * int(a) / (int(a) + 1) if c == "larger" else bottle_weight / (int(a) + 1)
| Weight of its Contents | 53921994d8f00b93df000bea | [
"Algorithms",
"Mathematics"
] | https://www.codewars.com/kata/53921994d8f00b93df000bea | 7 kyu |
Paul is an excellent coder and sits high on the CW leaderboard. He solves kata like a banshee but would also like to lead a normal life, with other activities. But he just can't stop solving all the kata!!
Given an array (x) you need to calculate the Paul Misery Score. The values are worth the following points:
```
k... | reference | def paul(x):
points = {'life': 0, 'eating': 1, 'kata': 5, 'Petes kata': 10}
misery = sum(map(points . get, x))
return ['Miserable!', 'Sad!', 'Happy!', 'Super happy!'][(misery < 40) + (misery < 70) + (misery < 100)]
| Paul's Misery | 57ee31c5e77282c24d000024 | [
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/57ee31c5e77282c24d000024 | 7 kyu |
**A number is self-descriptive when the n'th digit describes the amount n appears in the number.**
**Example:**
For the number 21200:
- There are two 0's in the number, so the first digit is 2.
- There is one 1 in the number, so the second digit is 1.
- There are two 2's in the number, so the third digit is 2.
- The... | reference | from collections import Counter
def self_descriptive(num):
s = [int(a) for a in str(num)]
cnt = Counter(s)
return all(cnt[i] == b for i, b in enumerate(s))
| Self-Descriptive Numbers | 56a628758f8d06b59800000f | [
"Fundamentals",
"Mathematics",
"Number Theory"
] | https://www.codewars.com/kata/56a628758f8d06b59800000f | 7 kyu |
In genetic the reverse complement of a sequence is formed by **reversing** the sequence and then taking the complement of each symbol.
The four nucleotides in DNA is Adenine (A), Cytosine (C), Guanine (G) and Thymine (Thymine).
- A is the complement of T
- C is the complement of G.
This is a bi-directional relatio... | algorithms | def reverse_complement(dna):
base_pair = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'}
return "" . join(base_pair[base] for base in dna[:: - 1]. upper()) if set(dna . upper()). issubset({'A', 'T', 'C', 'G', ""}) else "Invalid sequence"
| Reverse complement (DNA ) | 574a7d0dca4a8a0fbe000100 | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/574a7d0dca4a8a0fbe000100 | 7 kyu |
# Task
let F(N) be the sum square of digits of N. So:
`F(1) = 1, F(3) = 9, F(123) = 14`
Choose a number A, the sequence {A0, A1, ...} is defined as followed:
```
A0 = A
A1 = F(A0)
A2 = F(A1) ...
```
if A = 123, we have:
```
123 → 14(1 x 1 + 2 x 2 + 3 x 3)
→ 17(1 x 1 + 4 x 4)
→ 50(1 ... | games | def repeat_sequence_len(n):
s = []
while True:
n = sum(int(i) * * 2 for i in str(n))
if n not in s:
s . append(n)
else:
return len(s[s . index(n):])
| Simple Fun #129: Repeat Sequence Length | 58a3f57ecebc06bfcb00009c | [
"Puzzles"
] | https://www.codewars.com/kata/58a3f57ecebc06bfcb00009c | 7 kyu |
In this kata, you will write a function that returns the positions and the values of the "peaks" (or local maxima) of a numeric array.
For example, the array `arr = [0, 1, 2, 5, 1, 0]` has a peak at position `3` with a value of `5` (since `arr[3]` equals `5`).
~~~if-not:php,cpp,java,csharp,fsharp
The output will be r... | algorithms | def pick_peaks(arr):
pos = []
prob_peak = False
for i in range(1, len(arr)):
if arr[i] > arr[i-1]:
prob_peak = i
elif arr[i] < arr[i-1] and prob_peak:
pos.append(prob_peak)
prob_peak = False
return {'pos':pos, 'peaks':[arr[i] for i in pos]} | Pick peaks | 5279f6fe5ab7f447890006a7 | [
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/5279f6fe5ab7f447890006a7 | 5 kyu |
This is the simple version of [Fastest Code : Equal to 24](http://www.codewars.com/kata/574e890e296e412a0400149c).
## Task
A game I played when I was young: Draw 4 cards from playing cards, use ```+ - * / and ()``` to make the final results equal to 24.
You will coding in function ```equalTo24```. Function accept 4... | games | from itertools import permutations
def equal_to_24(*aceg):
ops = '+-*/'
for b in ops:
for d in ops:
for f in ops:
for (a,c,e,g) in permutations(aceg):
for s in make_string(a,b,c,d,e,f,g):
try:
if ev... | T.T.T.#2: Equal to 24 | 574be65a974b95eaf40008da | [
"Puzzles",
"Games"
] | https://www.codewars.com/kata/574be65a974b95eaf40008da | 4 kyu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.