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
# Description: Count the number of exclamation marks and question marks, return the product. # Examples ``` "" ---> 0 "!" ---> 0 "!ab? ?" ---> 2 "!!" ---> 0 "!??" ---> 2 "!???" ---> 3 "!!!??" ---> 6 "!!!???" ---> 9 "!???!!" ---> 9 "!????!!!?" ---> 20...
reference
def product(s): return s . count("?") * s . count("!")
Exclamation marks series #13: Count the number of exclamation marks and question marks, return the product
57fb142297e0860073000064
[ "Fundamentals" ]
https://www.codewars.com/kata/57fb142297e0860073000064
7 kyu
JavaScript provides a built-in parseInt method. It can be used like this: - `parseInt("10")` returns `10` - `parseInt("10 apples")` also returns `10` We would like it to return `"NaN"` (as a string) for the second case because the input string is not a valid number. You are asked to write a `myParseInt` method with...
reference
def my_parse_int(s): try: return int(s) except ValueError: return 'NaN'
String to integer conversion
54fdadc8762e2e51e400032c
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/54fdadc8762e2e51e400032c
7 kyu
# Hey You ! Sort these integers for me ... By name ... Do it now ! --- ## Input * Range is ```0```-```999``` * There may be duplicates * The array may be empty ## Example * Input: 1, 2, 3, 4 * Equivalent names: "one", "two", "three", "four" * Sorted by name: "four", "one", "three", "two" * Output: 4, 1, 3, 2...
reference
def int_to_word(num): d = {0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten', 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: ...
Sort - one, three, two
56f4ff45af5b1f8cd100067d
[ "Sorting", "Strings", "Algorithms" ]
https://www.codewars.com/kata/56f4ff45af5b1f8cd100067d
5 kyu
Your goal is to write an __Event__ constructor function, which can be used to make __event__ objects. An __event__ object should work like this: - it has a __.subscribe()__ method, which takes a function and stores it as its handler - it has an __.unsubscribe()__ method, which takes a function and removes it f...
reference
class Event (): def __init__(self): self . handlers = set() def subscribe(self, func): self . handlers . add(func) def unsubscribe(self, func): self . handlers . remove(func) def emit(self, * args): map(lambda f: f(* args), self . handlers)
Simple Events
52d3b68215be7c2d5300022f
[ "Design Patterns", "Event Handling", "Fundamentals" ]
https://www.codewars.com/kata/52d3b68215be7c2d5300022f
5 kyu
It's Christmas! You had to wait the whole year for this moment. You can already see all the presents under the Christmas tree. But you have to wait for the next morning in order to unwrap them. You really want to know, what's inside those boxes. But as a clever child, you can do your assumptions already. You know, you...
algorithms
def guess_gifts(wishlist, presents): result = [] for present in presents: for item in wishlist: if (present['size'] == item['size'] and present['clatters'] == item['clatters'] and present['weight'] == item['weight']): result . append(item['name']) return set...
Guess The Gifts!
52ae6b6623b443d9090002c8
[ "Algorithms" ]
https://www.codewars.com/kata/52ae6b6623b443d9090002c8
5 kyu
Santa puts all the presents into the huge sack. In order to let his reindeers rest a bit, he only takes as many reindeers with him as he is required to do. The others may take a nap. Two reindeers are always required for the sleigh and Santa himself. Additionally he needs 1 reindeer per 30 presents. As you know, Santa...
algorithms
from math import ceil def reindeer(presents): if presents > 180: raise ValueError("Too many presents") return ceil(presents / 30.0) + 2
How Many Reindeers?
52ad1db4b2651f744d000394
[ "Algorithms" ]
https://www.codewars.com/kata/52ad1db4b2651f744d000394
6 kyu
Create a function that returns a christmas tree of the correct height. For example: `height = 5` should return: ``` * *** ***** ******* ********* ``` Height passed is always an integer between 0 and 100. Use `\n` for newlines between each line. Pad with spaces so each line is the same length. ...
algorithms
def christmas_tree(height: int) - > str: return '\n' . join(('*' * i). center(2 * height - 1) for i in range(1, height * 2, 2))
Christmas tree
52755006cc238fcae70000ed
[ "Strings", "ASCII Art", "Algorithms" ]
https://www.codewars.com/kata/52755006cc238fcae70000ed
6 kyu
Santa's elves are boxing presents, and they need your help! Write a function that takes two sequences of dimensions of the present and the box, respectively, and returns a Boolean based on whether or not the present will fit in the box provided. The box's walls are one unit thick, so be sure to take that in to account....
algorithms
def will_fit(present: tuple, box: tuple) - > bool: return all([a - 1 > b for a, b in zip(sorted(box), sorted(present))])
Will the present fit?
52b23340c65ea422b1000045
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/52b23340c65ea422b1000045
6 kyu
## Happy Holidays fellow Code Warriors! It's almost Christmas! That means Santa's making his list, and checking it twice. Unfortunately, elves accidentally mixed the Naughty and Nice list together! Santa needs your help to save Christmas! ## Save Christmas! Santa needs you to write two functions. Both of the function...
reference
def get_nice_names(people): return [p['name'] for p in people if p['was_nice']] def get_naughty_names(people): return [p['name'] for p in people if not p['was_nice']]
Naughty or Nice?
52a6b34e43c2484ac10000cd
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/52a6b34e43c2484ac10000cd
7 kyu
### Happy Holidays fellow Code Warriors! Now, Dasher! Now, Dancer! Now, Prancer, and Vixen! On, Comet! On, Cupid! On, Donder and Blitzen! That's the order Santa wanted his reindeer...right? What do you mean he wants them in order by their last names!? Looks like we need your help Code Warrior! ### Sort Santa's Reinde...
algorithms
def sort_reindeer(reindeer_names): return sorted(reindeer_names, key=lambda s: s . split()[1])
Sort Santa's Reindeer
52ab60b122e82a6375000bad
[ "Sorting", "Arrays", "Strings", "Algorithms" ]
https://www.codewars.com/kata/52ab60b122e82a6375000bad
7 kyu
### Happy Holidays fellow Code Warriors! Santa's senior gift organizer Elf developed a way to represent up to 26 gifts by assigning a unique alphabetical character to each gift. After each gift was assigned a character, the gift organizer Elf then joined the characters to form the gift ordering code. Santa asked his ...
reference
def sort_gift_code(code): return "" . join(sorted(code))
Sort the Gift Code
52aeb2f3ad0e952f560005d3
[ "Sorting", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/52aeb2f3ad0e952f560005d3
7 kyu
### Happy Holidays fellow Code Warriors! It's almost Christmas Eve, so we need to prepare some milk and cookies for Santa! Wait... when exactly do we need to do that? ### Time for Milk and Cookies Complete the function function that accepts a `Date` object, and returns `true` if it's Christmas Eve (December 24th), `fa...
reference
def time_for_milk_and_cookies(dt): return dt . month == 12 and dt . day == 24
Milk and Cookies for Santa
52af7bf41f5a1291a6000025
[ "Date Time", "Fundamentals" ]
https://www.codewars.com/kata/52af7bf41f5a1291a6000025
7 kyu
Santa is handing out gifts in the kindergarten. Many toddlers are around there and everyone should have the opportunity to have a seat on Santa's lap. But there's Peter, a 5 year old boy, who is a bit naughty. He tries to get two gifts. After he got the first one, he lines up again in the queue of children. But fortun...
algorithms
def hand_out_gift(name, childs=[]): if name in childs: raise childs . append(name)
Only One Gift Per Child
52af0d380fcae83a560008af
[ "Algorithms" ]
https://www.codewars.com/kata/52af0d380fcae83a560008af
7 kyu
In this kata, you will write a function that receives an array of string and returns a string that is either ```'naughty'``` or ```'nice'```. Strings that start with the letters ```b```, ```f```, or ```k``` are ```naughty```. Strings that start with the letters ```g```, ```s```, or ```n``` are ```nice```. Other strings...
reference
def whatListAmIOn(actions): nice, naut = 0, 0 for item in actions: if item . startswith(('b', 'f', 'k')): nice += 1 elif item . startswith(('g', 's', 'n')): naut += 1 return 'nice' if nice < naut else 'naughty'
Naughty or Nice?
585eaef9851516fcae00004d
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/585eaef9851516fcae00004d
7 kyu
Rick wants a faster way to get the product of the largest pair in an array. Your task is to create a <b>performant</b> solution to find the product of the largest two integers in a <b>unique</b> array of <b>positive</b> numbers.<br> <u>All inputs will be valid.</u><br> <u>Passing [2, 6, 3] should return 18, the product...
reference
def max_product(a): m1 = max(a) a . remove(m1) m2 = max(a) return m1 * m2
Product of Largest Pair
5784c89be5553370e000061b
[ "Fundamentals", "Arrays", "Algorithms", "Sorting" ]
https://www.codewars.com/kata/5784c89be5553370e000061b
7 kyu
Everybody know that you passed to much time awake during night time... Your task here is to define how much coffee you need to stay awake after your night. You will have to complete a function that take an array of events in arguments, according to this list you will return the number of coffee you need to stay awake...
reference
cs = {'cw': 1, 'CW': 2, 'cat': 1, 'CAT': 2, 'dog': 1, 'DOG': 2, 'movie': 1, 'MOVIE': 2} def how_much_coffee(events): c = sum(cs . get(e, 0) for e in events) return 'You need extra sleep' if c > 3 else c
How much coffee do you need?
57de78848a8b8df8f10005b1
[ "Arrays", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/57de78848a8b8df8f10005b1
7 kyu
<img src="https://i.imgur.com/ta6gv1i.png?1" title="source: imgur.com" /> <hr/> **Kata in this series** * [Histogram - H1](https://www.codewars.com/kata/histogram-h1/) * [Histogram - H2](https://www.codewars.com/kata/histogram-h2/) * [Histogram - V1](https://www.codewars.com/kata/histogram-v1/) * [Histogram - V2](htt...
algorithms
def histogram(results): return "" . join("{}|{} {}\n" . format(7 - i, f * "#", f) for i, f in enumerate(reversed(results), 1)). replace(" 0", "")
Histogram - H1
57d532d2164a67cded0001c7
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/57d532d2164a67cded0001c7
7 kyu
## Task: You have to write a function **pattern** which creates the following pattern upto n number of rows. *If the Argument is 0 or a Negative Integer then it should return "" i.e. empty string.* ## Pattern: (n) (n)(n-1) (n)(n-1)(n-2) ................ ................. (n)(n-1)(n-2)....4 ...
reference
def pattern(n): return '\n' . join('' . join(str(i) for i in range(n, j, - 1)) for j in range(n - 1, - 1, - 1))
Complete The Pattern #3 (Horizontal Image of #2)
557341907fbf439911000022
[ "ASCII Art", "Fundamentals" ]
https://www.codewars.com/kata/557341907fbf439911000022
7 kyu
## Task Using `n` as a parameter in the function `pattern`, where `n>0`, complete the codes to get the pattern (take the help of examples): **Note:** There is no newline in the end (after the pattern ends) ### Examples `pattern(3)` should return `"1\n1*2\n1**3"`, e.g. the following: ``` 1 1*2 1**3 ``` `pattern(10...
reference
def pattern(n): return "\n1" . join("*" * i + str(i + 1) for i in range(n))
Number-Star ladder
5631213916d70a0979000066
[ "ASCII Art", "Fundamentals" ]
https://www.codewars.com/kata/5631213916d70a0979000066
7 kyu
## Task Raj has got into a problem, he solved the triangle pattern but stuck in the codes of "inverse triangle". Help him with the codes and remember to get the output as per given in examples below. ### Rules: * Take input as 'n' which is always a natural number * Space between each digit * No space after...
reference
def pattern(_n): return '\n' . join(' ' * i + (' ' + str((i + 1) % 10)) * (_n - i) for i in range(_n))
Upturn Numeral Triangle
564f3d49a06556d27c000077
[ "ASCII Art", "Fundamentals" ]
https://www.codewars.com/kata/564f3d49a06556d27c000077
7 kyu
## Task: You have to write a function **pattern** which creates the following pattern upto n number of rows. *If the Argument is 0 or a Negative Integer then it should return "" i.e. empty string.* ## Examples: pattern(4): 1234 234 34 4 pattern(6): 123456 23456 3456 456 ...
reference
def pattern(n): return '\n' . join('' . join(str(j) for j in range(i, n + 1)) for i in range(1, n + 1))
Complete The Pattern #4
55736129f78b30311300010f
[ "ASCII Art", "Fundamentals" ]
https://www.codewars.com/kata/55736129f78b30311300010f
7 kyu
Take a sentence (string) and reverse each word in the sentence. Do not reverse the order of the words, just the letters in each word. If there is punctuation, it should be interpreted as a regular character; no special rules. If there is spacing before/after the input string, leave them there. String will not be emp...
reference
def reverser(sentence): return ' ' . join(i[:: - 1] for i in sentence . split(' '))
Reverse Letters in Sentence
57ebdf944cde58f973000405
[ "Fundamentals", "Loops", "Control Flow", "Basic Language Features", "Strings", "Data Types" ]
https://www.codewars.com/kata/57ebdf944cde58f973000405
7 kyu
Print all numbers up to `3rd` parameter which are multiple of both `1st` and `2nd` parameter. Python, Javascript, Java, Ruby versions: return results in a list/array NOTICE: 1. Do NOT worry about checking zeros or negative values. 2. To find out if `3rd` parameter (the upper limit) is inclusive or not, check the tes...
reference
# Pyton version: return multiples of 2 numbers in a list def multiples(s1, s2, s3): return [x for x in range(s1, s3) if x % s1 == 0 and x % s2 == 0]
Show multiples of 2 numbers within a range
583989556754d6f4c700018e
[ "Fundamentals" ]
https://www.codewars.com/kata/583989556754d6f4c700018e
7 kyu
Complete the function that takes one argument, a list of words, and returns the length of the longest word in the list. For example: ```python ['simple', 'is', 'better', 'than', 'complex'] ==> 7 ``` Do not modify the input list.
reference
def longest(words): return max(map(len, words))
Thinkful - List Drills: Longest word
58670300f04e7449290000e5
[ "Lists", "Fundamentals" ]
https://www.codewars.com/kata/58670300f04e7449290000e5
7 kyu
All we eat is water and dry matter. Let us begin with an example: John bought potatoes: their weight is 100 kilograms. Potatoes contain water and dry matter. The water content is 99 percent of the total weight. He thinks they are too wet and puts them in an oven - at low temperature - for them to lose some water. A...
reference
def potatoes(p0, w0, p1): return w0 * (100 - p0) / / (100 - p1)
Drying Potatoes
58ce8725c835848ad6000007
[ "Fundamentals", "Puzzles" ]
https://www.codewars.com/kata/58ce8725c835848ad6000007
7 kyu
## Create the hero move method Create a move method for your hero to move through the level. Adjust the hero's position by changing the `position` attribute. The level is a grid with the following values: <style> .grid { width: 20em; } .grid tr, td { border: 2px solid grey; } .grid td { tex...
reference
def move(self, dir): position = int(self . position) if dir == "up": position -= 10 elif dir == "down": position += 10 elif dir == "left": position -= 1 else: position += 1 if position < 0 or position > 44 or position % 10 > 4: raise Exception("Invalid direction") ...
Terminal Game #2
55e8beb4e8fc5b7697000036
[ "Fundamentals" ]
https://www.codewars.com/kata/55e8beb4e8fc5b7697000036
7 kyu
Write ```javascript Array.prototype.zip = function (arr, fn) {} ``` ```ruby Array#zip ``` ```python lstzip ``` that merges the corresponding elements of two sequences using a specified selector function ```fn``` (a `block` in Ruby) For example: ```javascript var a = [1, 2, 3, 4, 5]; var b = ['a','b']; a.zip(b, (a, b) ...
reference
def lstzip(a, b, fn): return [fn(* c) for c in zip(a, b)]
Zip it!
56aaf25213edd3a88a000002
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/56aaf25213edd3a88a000002
7 kyu
Write a function that takes as its parameters *one or more numbers which are the diameters of circles.* The function should return the *total area of all the circles*, rounded to the nearest integer in a string that says "We have this much circle: xyz". You don't know how many circles you will be given, but you can...
reference
import math def sum_circles(* args): t = round(sum([math . pi * (d * * 2) / 4 for d in args])) return 'We have this much circle: {}' . format(int(t))
Some Circles
56143efa9d32b3aa65000016
[ "Fundamentals", "Geometry", "Algebra" ]
https://www.codewars.com/kata/56143efa9d32b3aa65000016
7 kyu
Let's build a calculator that can calculate the average for an arbitrary number of arguments. The test expects you to provide a Calculator object with an average method: ``` Calculator.average() ``` The test also expects that when you pass no arguments, it returns 0. The arguments are expected to be integers. It exp...
reference
class Calculator: @ staticmethod def average(* args): return sum(args) / len(args) if args else 0
Basic JS - Calculating averages
529f32794a6db5d32a00071f
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/529f32794a6db5d32a00071f
7 kyu
Write a function that takes an arbitrary number of strings and interlaces them (combines them by alternating characters from each string). For example `combineStrings('abc', '123')` should return `'a1b2c3'`. If the strings are different lengths the function should interlace them until each string runs out, continuing...
reference
from itertools import zip_longest def combine_strings(* args): return '' . join('' . join(x) for x in zip_longest(* args, fillvalue=''))
Interlace an arbitrary Number of Strings
5836ebe4f7e1c56e1a000033
[ "Fundamentals" ]
https://www.codewars.com/kata/5836ebe4f7e1c56e1a000033
6 kyu
The [Decorator Design Pattern](https://www.youtube.com/watch?v=17XTOODeWQE) can be used, for example, in the StarCraft game to manage upgrades. The pattern consists in "incrementing" your base class with extra functionality. A decorator will receive an instance of the base class and use it to create a new instance w...
reference
class Marine: def __init__(self, damage, armor): self . damage = damage self . armor = armor class Marine_weapon_upgrade: def __init__(self, marine): self . damage = marine . damage + 1 self . armor = marine . armor class Marine_armor_upgrade: def __init__(self, marine): ...
PatternCraft - Decorator
5682e545fb263ecf7b000069
[ "Design Patterns", "Fundamentals" ]
https://www.codewars.com/kata/5682e545fb263ecf7b000069
6 kyu
The [State Design Pattern](https://www.youtube.com/watch?v=yZt7mUVDijU) can be used, for example, to manage the state of a tank in the StarCraft game. The pattern consists in isolating the state logic in different classes rather than having multiple `if`s to determine what should happen. ## Your Task Complete the co...
reference
class State (object): def can_move(self): return self . _can_move def damage(self): return self . _damage class TankState (State): _can_move = True _damage = 5 class SiegeState (State): _can_move = False _damage = 20 class Tank (object): def __init__(self): ...
PatternCraft - State
5682e72eb7354b2f39000021
[ "Design Patterns", "Fundamentals" ]
https://www.codewars.com/kata/5682e72eb7354b2f39000021
6 kyu
The [Strategy Design Pattern](https://www.youtube.com/watch?v=MOEsKHqLiBM) can be used, for example, to determine how a unit moves in the StarCraft game. The pattern consists in having a different strategy to one functionality. A unit, for example, could move by walking or flying. ## Your Task Complete the code so t...
reference
class Fly: @ staticmethod def move(unit): unit . position += 10 class Walk: @ staticmethod def move(unit): unit . position += 1 class Viking: def __init__(self): self . move_behavior = Walk() self . position = 0 def move(self): self . move_behavior . move...
PatternCraft - Strategy
5682e809386707366d000024
[ "Design Patterns", "Fundamentals" ]
https://www.codewars.com/kata/5682e809386707366d000024
6 kyu
The goal of this kata is to write a function that takes two inputs: a string and a character. The function will count the number of times that character appears in the string. The count is case insensitive. For example: ```javascript countChar("fizzbuzz","z") => 4 countChar("Fancy fifth fly aloof","f") => 5 ``` ```r...
algorithms
def count_char(s, c): return s . lower(). count(c . lower())
Count the Characters
577ad961ae2807182f000c29
[ "Fundamentals", "Regular Expressions", "Algorithms" ]
https://www.codewars.com/kata/577ad961ae2807182f000c29
7 kyu
The [Visitor Design Pattern](https://www.youtube.com/watch?v=KSEyIXnknoY) can be used, for example, to determine how an attack deals a different amount of damage to a unit in the StarCraft game. The pattern consists of delegating the responsibility to a different class. When a unit takes damage it can tell the visito...
reference
class Marine: def __init__(self): self . health = 100 def accept(self, visitor): visitor . visit_light(self) class Marauder: def __init__(self): self . health = 125 def accept(self, visitor): visitor . visit_armored(self) class TankBullet: def visit_light(self,...
PatternCraft - Visitor
5682e646d5eddc1e21000017
[ "Design Patterns", "Fundamentals" ]
https://www.codewars.com/kata/5682e646d5eddc1e21000017
7 kyu
The [Adapter Design Pattern](https://www.youtube.com/watch?v=hvpXKZhNINc) can be used, for example in the StarCraft game, to insert an external character in the game. The pattern consists in having a wrapper class that will adapt the code from the external source. ## Your Task The adapter receives an instance of the...
reference
class MarioAdapter: def __init__(self, mario): self . mario = mario def attack(self, target): target . health -= self . mario . jump_attack()
PatternCraft - Adapter
56919e637b2b971492000036
[ "Design Patterns", "Fundamentals" ]
https://www.codewars.com/kata/56919e637b2b971492000036
7 kyu
Write a function that returns the greatest common factor of an array of positive integers. Your return value should be a number, you will only receive positive integers. ```python greatest_common_factor([46, 14, 20, 88]) # == 2 ``` ```javascript greatestCommonFactor([46, 14, 20, 88]); // --> 2 ``` ```php greatest_comm...
algorithms
from functools import reduce from math import gcd def greatest_common_factor(seq): return reduce(gcd, seq)
Greatest Common Factor of an Array
5849169a6512c5964000016e
[ "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/5849169a6512c5964000016e
6 kyu
A squared string has n lines, each substring being n characters long: For example: `s = "abcd\nefgh\nijkl\nmnop"` is a squared string of size `4`. We will use squared strings to code and decode texts. To make things easier we suppose that our original text doesn't include the character '\n'. #### Coding Input: - ...
reference
from math import ceil, sqrt def clockwise(arr): return [list(reversed(row)) for row in zip(* arr)] def counterclockwise(arr): return [list(row) for row in reversed(list(zip(* arr)))] def code(s): n = ceil(sqrt(len(s))) s = s . ljust(n * n, chr(11)) square = [s[n * i: n * (i +...
Coding with Squared Strings
56fcc393c5957c666900024d
[ "Fundamentals", "Strings", "Ciphers", "Cryptography" ]
https://www.codewars.com/kata/56fcc393c5957c666900024d
5 kyu
There is an array of strings. All strings contains similar _letters_ except one. Try to find it! ```javascript findUniq([ 'Aa', 'aaa', 'aaaaa', 'BbBb', 'Aaaa', 'AaAaAa', 'a' ]) === 'BbBb' findUniq([ 'abc', 'acb', 'bac', 'foo', 'bca', 'cab', 'cba' ]) === 'foo' ``` ```php find_uniq([ 'Aa', 'aaa', 'aaaaa', 'BbBb', 'Aaaa...
algorithms
from collections import defaultdict def find_uniq(a): d = {} c = defaultdict(int) for e in a: t = frozenset(e . strip(). lower()) d[t] = e c[t] += 1 return d[next(filter(lambda k: c[k] == 1, c))]
Find the unique string
585d8c8a28bc7403ea0000c3
[ "Fundamentals", "Algorithms", "Arrays", "Strings" ]
https://www.codewars.com/kata/585d8c8a28bc7403ea0000c3
5 kyu
Input: - a string `strng` - an array of strings `arr` Output of function `contain_all_rots(strng, arr) (or containAllRots or contain-all-rots)`: - a boolean `true` if all rotations of `strng` are included in `arr` - `false` otherwise #### Examples: ``` contain_all_rots( "bsjq", ["bsjq", "qbsj", "sjqb", "twZNsslC...
reference
def contain_all_rots(s, l): return all(s[i:] + s[: i] in l for i in range(len(s)))
All Inclusive?
5700c9acc1555755be00027e
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/5700c9acc1555755be00027e
7 kyu
Chuck Norris loves push ups. That's just a fact. It has been said that when Chuck Norris does a push up, he isn't pushing himself up, he's pushing the world down! Today, Chuck got home from work 10 minutes earlier than his wife. Naturally he decided to bang out some push ups. By the time she arrives home he can have s...
algorithms
from re import sub def chuck_push_ups(s): try: return max((int(b, 2) for b in sub('[^01 ]', '', s). split()), default='CHUCK SMASH!!') except: return 'FAIL!!'
Chuck Norris I - Push Ups
570564e838428f2eca001d73
[ "Fundamentals", "Binary", "Regular Expressions", "Algorithms" ]
https://www.codewars.com/kata/570564e838428f2eca001d73
7 kyu
#Adding values of arrays in a shifted way You have to write a method, that gets two parameter: ```markdown 1. An array of arrays with int-numbers 2. The shifting value ``` #The method should add the values of the arrays to one new array. The arrays in the array will all have the same size and this size will always ...
algorithms
from itertools import zip_longest as zl def sum_arrays(arrays, shift): shifted = [[0] * shift * i + arr for i, arr in enumerate(arrays)] return [sum(t) for t in zl(* shifted, fillvalue=0)]
Adding values of arrays in a shifted way
57c7231c484cf9e6ac000090
[ "Mathematics", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/57c7231c484cf9e6ac000090
7 kyu
You should find a searched number by approximation. The searched number will always be between 0 and 100. You have to write a method, that will get only a function to compare your guess number with the searched number.<br> Your method have to find the number with a precision of 5 fractional digits.<br> The tolerance...
algorithms
def find_number(compare, lo=0, hi=100, tolerance=1e-5): mid = None while hi - lo > tolerance: mid = (lo + hi) / 2 if compare(mid) == 0: return mid if compare(mid) < 0: lo = mid else: hi = mid return mid
These aren't the numbers you're looking for! (Find a number by approximation)
57d93978950d8486a3000def
[ "Fundamentals", "Logic", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/57d93978950d8486a3000def
6 kyu
In this kata you have to write a method that folds a given array of integers by the middle x-times. An example says more than thousand words: ``` Fold 1-times: [1,2,3,4,5] -> [6,6,3] A little visualization (NOT for the algorithm but for the idea of folding): Step 1 Step 2 Step 3 Step 4 St...
algorithms
def fold_array(array, runs): mid = len(array) / / 2 a = [sum(pair) for pair in zip(array[: mid] + [0], reversed(array[mid:]))] return fold_array(a, runs - 1) if runs > 1 else a
Fold an array
57ea70aa5500adfe8a000110
[ "Fundamentals", "Logic", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/57ea70aa5500adfe8a000110
6 kyu
Consider the function `f: x -> sqrt(1 + x) - 1` at `x = 1e-15`. We get: `f(x) = 4.44089209850062616e-16` or something around that, depending on the language. This function involves the subtraction of a pair of similar numbers when x is near 0 and the results are significantly erroneous in this region. Using `pow...
reference
from math import sqrt def f(x): return x / (1 + sqrt(1 + x))
Floating-point Approximation (I)
58184387d14fc32f2b0012b2
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/58184387d14fc32f2b0012b2
6 kyu
### Task King Arthur and his knights are having a New Years party. Last year Lancelot was jealous of Arthur, because Arthur had a date and Lancelot did not, and they started a duel. To prevent this from happening again, Arthur wants to make sure that there are at least as many women as men at this year's party. He g...
games
def invite_more_women(arr): return sum(arr) > 0
Simple Fun #152: Invite More Women?
58acfe4ae0201e1708000075
[ "Puzzles" ]
https://www.codewars.com/kata/58acfe4ae0201e1708000075
7 kyu
<img src = https://pbs.twimg.com/media/CWTTemEWcAER1Rk.jpg> What do action men wear? Isn't it obvious? 1) Shirt. 2) Cowboy Boots. 3) ACTION PANTS!! Any self respecting action hero heading out to cause some trouble knows the uniform... If you see a man striding towards you in this outfit you should be very careful, he'...
algorithms
def price(start, soil, age): yrate = {'Barely used': 1.1, 'Seen a few high kicks': 1.25, 'Blood stained': 1.3, 'Heavily soiled': 1.5} try: return f"$ { start * ( yrate . get ( soil )) * * age : 0.2 f } " except: return "Chuck is bottomless!"
Chuck Norris VI - Shopping with Chuck
5706be574f2c297a7b00060d
[ "Fundamentals", "Strings", "Algorithms" ]
https://www.codewars.com/kata/5706be574f2c297a7b00060d
7 kyu
**Short Intro** Some of you might remember spending afternoons playing Street Fighter 2 in some Arcade back in the 90s or emulating it nowadays with the numerous emulators for retro consoles. Can you solve this kata? Suuure-You-Can! UPDATE: a new kata's harder version is available [here](https://www.codewars.com/kat...
reference
MOVES = {"up": (- 1, 0), "down": (1, 0), "right": (0, 1), "left": (0, - 1)} def street_fighter_selection(fighters, initial_position, moves): y, x = initial_position hovered_fighters = [] for move in moves: dy, dx = MOVES[move] y += dy if not 0 <= y < len(fighters): y -= dy x...
Street Fighter 2 - Character Selection
5853213063adbd1b9b0000be
[ "Arrays", "Lists", "Fundamentals", "Graph Theory" ]
https://www.codewars.com/kata/5853213063adbd1b9b0000be
6 kyu
From this lesson, we learn about JS static object: ```Math```. It mainly helps us to carry out mathematical calculations. It has a lot of properties and methods. Some of the properties and methods we rarely used. So we only learn some common methods. The properties of the Math object are some constants, such as PI, on...
reference
from math import ceil def round_it(n): left, right = (len(part) for part in str(n). split(".")) return ceil(n) if left < right else int(n) if left > right else round(n)
Training JS #32: methods of Math---round() ceil() and floor()
5732d3c9791aafb0e4001236
[ "Fundamentals", "Tutorials" ]
https://www.codewars.com/kata/5732d3c9791aafb0e4001236
8 kyu
OK, my warriors! Now that you beat the big BOSS, you can unlock three new skills. (Does it sound like we're playing an RPG? ;-) ## The Arrow Function (JS only) The first skill is the arrow function. Let's look at some examples to see how it works: ```python #ignore this part, it is just for JS ``` ```ruby #ignore th...
reference
def shuffle_it(A, * T): for x, y in T: A[x], A[y] = A[y], A[x] return A
Training Time
572ab0cfa3af384df7000ff8
[ "Fundamentals", "Tutorials" ]
https://www.codewars.com/kata/572ab0cfa3af384df7000ff8
7 kyu
This time we learn two methods to split or merge string:```split()``` and ```concat()```. also learn a good friend of the split() method: ```join()```. It is an Array method. Their usage: ```javascript stringObject.split(separator,howmany) stringObject.concat(string1,string2,...,stringx) arrayObject.join(separator) ``...
reference
def split_and_merge(string, sp): return ' ' . join(sp . join(word) for word in string . split())
Training JS #18: Methods of String object--concat() split() and its good friend join()
57280481e8118511f7000ffa
[ "Fundamentals", "Tutorials" ]
https://www.codewars.com/kata/57280481e8118511f7000ffa
8 kyu
In JavaScript, ```if..else``` is the most basic conditional statement, it consists of three parts:```condition, statement1, statement2```, like this: ```javascript if (condition) statementa else statementb ``` ```typescript if (condition) statementa else statementb ``` ```coffeescript if (condition)...
reference
def sale_hotdogs(n): return n * (100 if n < 5 else 95 if n < 10 else 90)
Training JS #7: if..else and ternary operator
57202aefe8d6c514300001fd
[ "Fundamentals", "Tutorials" ]
https://www.codewars.com/kata/57202aefe8d6c514300001fd
8 kyu
"Point reflection" or "point symmetry" is a basic concept in geometry where a given point, P, at a given position relative to a mid-point, Q has a corresponding point, P1, which is the same distance from Q but in the opposite direction. ## Task Given two points P and Q, output the symmetric point of point P about Q. ...
algorithms
def symmetric_point(p, q): return [2 * q[0] - p[0], 2 * q[1] - p[1]]
Points of Reflection
57bfea4cb19505912900012c
[ "Mathematics", "Geometry", "Algorithms" ]
https://www.codewars.com/kata/57bfea4cb19505912900012c
8 kyu
You probably know that number 42 is *"the answer to life, the universe and everything"* according to Douglas Adams' *"The Hitchhiker's Guide to the Galaxy"*. For Freud, the answer was quite different... In the society he lived in, people - women in particular - had to repress their sexual needs and desires. This was s...
reference
def to_freud(sentence): return ' ' . join('sex' for _ in sentence . split())
Freudian translator
5713bc89c82eff33c60009f7
[ "Fundamentals" ]
https://www.codewars.com/kata/5713bc89c82eff33c60009f7
8 kyu
Write a function that rearranges an integer into its largest possible value. Example (**Input** --> **Output**) ``` 123456 --> 654321 105 --> 510 12 --> 21 ``` If the argument passed through is single digit or is already the maximum possible integer, your function should simply return it.
algorithms
def super_size(n): return int('' . join(sorted(str(n), reverse=True)))
noobCode 01: SUPERSIZE ME.... or rather, this integer!
5709bdd2f088096786000008
[ "Algorithms", "Integers", "Data Types", "Numbers", "Arrays", "Strings", "split", "Haskell Packages" ]
https://www.codewars.com/kata/5709bdd2f088096786000008
8 kyu
The Collatz conjecture (also known as 3n+1 conjecture) is a conjecture that applying the following algorithm to any number we will always eventually reach one: ``` [This is writen in pseudocode] if(number is even) number = number / 2 if(number is odd) number = 3*number + 1 ``` #Task Your task is to make a function `...
algorithms
def hotpo(n): cnt = 0 while n != 1: n = 3 * n + 1 if n % 2 else n / 2 cnt += 1 return cnt
Collatz Conjecture (3n+1)
577a6e90d48e51c55e000217
[ "Fundamentals", "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/577a6e90d48e51c55e000217
8 kyu
Christmas is coming and many people dreamed of having a ride with Santa's sleigh. But, of course, only Santa himself is allowed to use this wonderful transportation. And in order to make sure, that only he can board the sleigh, there's an authentication mechanism. Your task is to implement the `authenticate()` method ...
reference
class Sleigh (object): def authenticate(self, name, password): return name == 'Santa Claus' and password == 'Ho Ho Ho!'
Sleigh Authentication
52adc142b2651f25a8000643
[ "Fundamentals" ]
https://www.codewars.com/kata/52adc142b2651f25a8000643
8 kyu
Given an input n, write a function `always` that returns a __function__ which returns n. Ruby should return a __lambda__ or a __proc__. ```javascript var three = always(3); three(); // returns 3 ``` ```coffeescript three = always(3) three() # returns 3 ``` ```ruby three = always(3) three.call # returns 3 ``` ```python...
reference
def always(n=0): return lambda: n
A function within a function
53844152aa6fc137d8000589
[ "Fundamentals" ]
https://www.codewars.com/kata/53844152aa6fc137d8000589
null
### Description: Remove `n` exclamation marks in the sentence from left to right. `n` is positive integer. ### Examples ``` remove("Hi!",1) === "Hi" remove("Hi!",100) === "Hi" remove("Hi!!!",1) === "Hi!!" remove("Hi!!!",100) === "Hi" remove("!Hi",1) === "Hi" remove("!Hi!",1) === "Hi!" remove("!Hi!",100) === "Hi" re...
reference
def remove(s, n): return s . replace("!", "", n)
Exclamation marks series #6: Remove n exclamation marks in the sentence from left to right
57faf7275c991027af000679
[ "Fundamentals" ]
https://www.codewars.com/kata/57faf7275c991027af000679
8 kyu
![](http://www.grindtv.com/wp-content/uploads/2015/08/drone.jpg) The other day I saw an amazing video where a guy hacked some wifi controlled lightbulbs by flying a drone past them. Brilliant. In this kata we will recreate that stunt... sort of. You will be given two strings: `lamps` and `drone`. `lamps` represents ...
reference
def fly_by(lamps, drone): return lamps . replace('x', 'o', drone . count('=') + 1)
Drone Fly-By
58356a94f8358058f30004b5
[ "Fundamentals", "Strings", "Arrays" ]
https://www.codewars.com/kata/58356a94f8358058f30004b5
7 kyu
<h1><strong>100th Kata</strong></h1> You are given a message (text) that you choose to read in a mirror (weirdo). Return what you would see, complete with the mirror frame. Example:<br> 'Hello World' would give: <img src="http://res.cloudinary.com/dfvyityr2/image/upload/v1477656440/kata_examp_ypboka.png"> Words i...
reference
def mirror(text): words = [w[:: - 1] for w in text . split()] max_len = max(map(len, words)) border = ['*' * (max_len + 4)] words = ['* {} *' . format(w . ljust(max_len)) for w in words] return '\n' . join(border + words + border)
Framed Reflection
581331293788bc1702001fa6
[ "Fundamentals", "Strings", "Arrays" ]
https://www.codewars.com/kata/581331293788bc1702001fa6
6 kyu
The number n is <b>Evil</b> if it has an even number of 1's in its binary representation.</br> The first few Evil numbers: 3, 5, 6, 9, 10, 12, 15, 17, 18, 20</br></br> The number n is <b>Odious</b> if it has an odd number of 1's in its binary representation.</br> The first few Odious numbers: 1, 2, 4, 7, 8, 11, 13, 14,...
reference
def evil(n): return "It's Evil!" if bin(n). count('1') % 2 == 0 else "It's Odious!"
Evil or Odious
56fcfad9c7e1fa2472000034
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/56fcfad9c7e1fa2472000034
8 kyu
For every good kata idea there seem to be quite a few bad ones! In this kata you need to check the provided 2 dimensional array (x) for good ideas 'good' and bad ideas 'bad'. If there are one or two good ideas, return 'Publish!', if there are more than 2 return 'I smell a series!'. If there are no good ideas, as is of...
reference
def well(arr): good_ideas = str(arr). lower(). count('good') return 'I smell a series!' if (good_ideas > 2) else 'Fail!' if not (good_ideas) else 'Publish!'
Well of Ideas - Harder Version
57f22b0f1b5432ff09001cab
[ "Fundamentals", "Arrays", "Strings" ]
https://www.codewars.com/kata/57f22b0f1b5432ff09001cab
7 kyu
Everybody knows the classic ["half your age plus seven"](https://en.wikipedia.org/wiki/Age_disparity_in_sexual_relationships#The_.22half-your-age-plus-seven.22_rule) dating rule that a lot of people follow (including myself). It's the 'recommended' age range in which to date someone. <!-- Original link is dead. Repla...
reference
def dating_range(age): if age <= 14: min = age - 0.10 * age max = age + 0.10 * age else: min = (age / 2) + 7 max = (age - 7) * 2 return str(int(min)) + '-' + str(int(max))
Age Range Compatibility Equation
5803956ddb07c5c74200144e
[ "Fundamentals" ]
https://www.codewars.com/kata/5803956ddb07c5c74200144e
8 kyu
Given a sequence of items and a specific item in that sequence, return the item immediately following the item specified. If the item occurs more than once in a sequence, return the item after the first occurence. This should work for a sequence of any type. When the item isn't present or nothing follows it, the funct...
reference
def next_item(xs, item): it = iter(xs) for x in it: if x == item: break return next(it, None)
What's up next?
542ebbdb494db239f8000046
[ "Fundamentals", "Data Structures", "Logic" ]
https://www.codewars.com/kata/542ebbdb494db239f8000046
8 kyu
# Backstory <img src="https://pbs.twimg.com/media/BQRHvcFCQAABGH6.jpg"> As a treat, I'll let you read part of the script from a classic 'I'm Alan Partridge episode: ``` Lynn: Alan, there’s that teacher chap. Alan: Michael, if he hits me, will you hit him first? Michael: No, he’s a customer. I cannot hit customers. I’v...
reference
def apple(x): return "It's hotter than the sun!!" if int(x) * * 2 > 1000 else "Help yourself to a honeycomb Yorkie for the glovebox."
Alan Partridge II - Apple Turnover
580a094553bd9ec5d800007d
[ "Fundamentals", "Strings", "Mathematics" ]
https://www.codewars.com/kata/580a094553bd9ec5d800007d
8 kyu
This is a beginner friendly kata especially for UFC/MMA fans. It's a fight between the two legends: Conor McGregor vs George Saint Pierre in Madison Square Garden. Only one fighter will remain standing, and after the fight in an interview with Joe Rogan the winner will make his legendary statement. It's your job to r...
reference
statements = { 'george saint pierre': "I am not impressed by your performance.", 'conor mcgregor': "I'd like to take this chance to apologize.. To absolutely NOBODY!" } def quote(fighter): return statements[fighter . lower()]
For UFC Fans (Total Beginners): Conor McGregor vs George Saint Pierre
582dafb611d576b745000b74
[ "Fundamentals" ]
https://www.codewars.com/kata/582dafb611d576b745000b74
8 kyu
## Ordering food You are in charge of ordering food for a party. You are going to need 4 sandwiches, 6 salads, 5 wraps, and 10 orders of french fries. The cost per item of food is: food | price ---|--- sandwich | $8.00 salad | $7.00 wrap | $6.50 french fries | $1.20 --- Create 4 variables to store the quantity of e...
reference
sandwiches, salads, wraps, frenchFries = 4, 6, 5, 10 totalPrice = 8.00 * sandwiches + 7.00 * salads + 6.5 * wraps + 1.2 * frenchFries
Grasshopper - Shopping list
560c31275c39c481c4000022
[ "Fundamentals", "Variables", "Basic Language Features" ]
https://www.codewars.com/kata/560c31275c39c481c4000022
8 kyu
## Get change You go to the store and have a 10 dollar bill to spend. You buy candy, chips, and soda. Find out how much change you get back from the cashier. Item | Cost --- | --- Candy | $1.42 Chips | $2.40 Soda | $1.00 Create 5 variables and use the cost from the table above to set their values. - `money` - `cand...
reference
money = 10 candy = 1.42 chips = 2.40 soda = 1 change = money - (candy + chips + soda)
Grasshopper - Make change
560dab9f8b50f89fd6000070
[ "Fundamentals" ]
https://www.codewars.com/kata/560dab9f8b50f89fd6000070
8 kyu
Write a function that returns a string in which firstname is swapped with last name. **Example(Input --> Output)** ``` "john McClane" --> "McClane john" ``` ~~~if:riscv RISC-V: The function signature is: ```c char *name_shuffler(char *shuffled, const char *name); ``` `name` is the input string and `shuffled` is th...
reference
def name_shuffler(str_): return ' ' . join(str_ . split(' ')[:: - 1])
Name Shuffler
559ac78160f0be07c200005a
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/559ac78160f0be07c200005a
8 kyu
At the annual family gathering, the family likes to find the oldest living family member’s age and the youngest family member’s age and calculate the difference between them. You will be given an array of all the family members' ages, in any order. The ages will be given in whole numbers, so a baby of 5 months, will ...
algorithms
def difference_in_ages(ages): # your code here return (min(ages), max(ages), max(ages) - min(ages))
Find the Difference in Age between Oldest and Youngest Family Members
5720a1cb65a504fdff0003e2
[ "Algorithms", "Arrays" ]
https://www.codewars.com/kata/5720a1cb65a504fdff0003e2
8 kyu
This is a spin off of [my first kata](http://www.codewars.com/kata/56bc28ad5bdaeb48760009b0). You are given a string containing a sequence of character sequences separated by commas. Write a function which returns a new string containing the same character sequences except the first and the last ones but this time se...
reference
def array(strng): return ' ' . join(strng . split(',')[1: - 1]) or None
Remove First and Last Character Part Two
570597e258b58f6edc00230d
[ "Fundamentals", "Arrays", "Strings" ]
https://www.codewars.com/kata/570597e258b58f6edc00230d
8 kyu
# Be Concise IV - Index of an element in an array ## Task Provided is a function ```Kata``` which accepts two parameters in the following order: ```array, element``` and ```return```s the **index** of the element if found and ```"Not found"``` otherwise. Your task is to shorten the code as much as possible in order ...
refactoring
def find(arr, elem): return arr . index(elem) if elem in arr else 'Not found'
Be Concise IV - Index of an element in an array
5703c093022cd1aae90012c9
[ "Refactoring" ]
https://www.codewars.com/kata/5703c093022cd1aae90012c9
8 kyu
Create a function that takes a string and an integer (`n`). The function should return a string that repeats the input string `n` number of times. If anything other than a string is passed in you should return `"Not a string"` ## Example ``` "Hi", 2 --> "HiHi" 1234, 5 --> "Not a string" ```
reference
def repeat_it(string, n): return string * n if isinstance(string, str) else 'Not a string'
repeatIt
557af9418895e44de7000053
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/557af9418895e44de7000053
8 kyu
<h1>Classy Extensions</h1> Classy Extensions, this kata is mainly aimed at the new JS ES6 Update introducing <em>extends</em> keyword. You will be preloaded with the Animal class, so you should only edit the Cat class. <h3>Task</h3> Your task is to complete the Cat class which Extends Animal and replace the speak meth...
reference
class Cat (Animal): def speak(self): return self . name + ' meows.'
Classy Extentions
55a14aa4817efe41c20000bc
[ "Fundamentals", "Object-oriented Programming" ]
https://www.codewars.com/kata/55a14aa4817efe41c20000bc
8 kyu
# Situation You have been hired by a company making electric garage doors. Accidents with the present product line have resulted in numerous damaged cars, broken limbs and several killed pets. Your mission is to write a safer version of their controller software. # Specification We always start with a closed door. The...
reference
def controller(events): out, state, dir, moving = [], 0, 1, False for c in events: if c == 'O': dir *= - 1 elif c == 'P': moving = not moving if moving: state += dir if state in [0, 5]: moving, dir = False, 1 if state == 0 else - 1 out . append(st...
Killer Garage Door
58b1ae711fcffa34090000ea
[ "State Machines", "Fundamentals" ]
https://www.codewars.com/kata/58b1ae711fcffa34090000ea
6 kyu
Teach snoopy and scooby doo how to bark using object methods. Currently only snoopy can bark and not scooby doo. ```javascript snoopy.bark(); // return "Woof" scoobydoo.bark(); // undefined ``` ```python snoopy.bark() #return "Woof" scoobydoo.bark() #undefined ``` ```ruby snoopy.bark() #return "Woof" scoobydoo.bark(...
reference
class Dog (): def __init__(self, breed): self . breed = breed def bark(self): return "Woof" snoopy = Dog("Beagle") scoobydoo = Dog("Great Dane")
Barking mad
54dba07f03e88a4cec000caf
[ "Fundamentals", "Object-oriented Programming" ]
https://www.codewars.com/kata/54dba07f03e88a4cec000caf
8 kyu
Find the last element of the given argument(s). ## Examples ```python last([1, 2, 3, 4]) ==> 4 last("xyz") ==> "z" last(1, 2, 3, 4) ==> 4 ``` ```ruby last([1, 2, 3, 4]) # => 4 last("xyz") # => "z" last(1, 2, 3, 4) # => 4 ``` ```haskell last [1, 2, 3, 4] -- => 4 last ['x', 'y', 'z'] -- => '...
reference
def last(* args): return args[- 1] if not hasattr(args[- 1], "__getitem__") else args[- 1][- 1]
Last
541629460b198da04e000bb9
[ "Lists", "Fundamentals" ]
https://www.codewars.com/kata/541629460b198da04e000bb9
7 kyu
Create a method that takes as input a name, city, and state to welcome a person. Note that `name` will be an array consisting of one or more values that should be joined together with one space between each, and the length of the `name` array in test cases will vary. Example: ``` ['John', 'Smith'], 'Phoenix', 'Arizon...
reference
def say_hello(name, city, state): return "Hello, {}! Welcome to {}, {}!" . format(" " . join(name), city, state)
Welcome to the City
5302d846be2a9189af0001e4
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5302d846be2a9189af0001e4
8 kyu
You are required to create a simple calculator that returns the result of addition, subtraction, multiplication or division of two numbers. Your function will accept three arguments:<br> The first and second argument should be numbers.<br> The third argument should represent a sign indicating the operation to perform ...
reference
def calculator(x, y, op): return eval(f' { x }{ op }{ y } ') if type(x) == type(y) == int and str(op) in '+-*/' else 'unknown value'
simple calculator
5810085c533d69f4980001cf
[ "Fundamentals" ]
https://www.codewars.com/kata/5810085c533d69f4980001cf
8 kyu
<img src = http://republicbuzz.com/wp-content/uploads/2015/04/12268_Chuck-Norris.jpg > It's a well known fact that anything Chuck Norris wants, he gets. As a result Chuck very rarely has to use the word false. It is a less well known fact that if something is true, and Chuck doesn't want it to be, Chuck can scare the...
algorithms
def ifChuckSaysSo(): return 0
Chuck Norris VII - True or False? (Beginner)
570669d8cb7293a2d1001473
[ "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/570669d8cb7293a2d1001473
8 kyu
<h1>Check your arrows</h1> You have a quiver of arrows, but some have been damaged. The quiver contains arrows with an optional range information (different types of targets are positioned at different ranges), so each item is an arrow. You need to verify that you have some good ones left, in order to prepare for batt...
reference
def any_arrows(arrows): return any(not i . get("damaged", False) for i in arrows)
Are there any arrows left?
559f860f8c0d6c7784000119
[ "Fundamentals" ]
https://www.codewars.com/kata/559f860f8c0d6c7784000119
8 kyu
### Task Each day a plant is growing by `upSpeed` meters. Each night that plant's height decreases by `downSpeed` meters due to the lack of sun heat. Initially, plant is 0 meters tall. We plant the seed at the beginning of a day. We want to know when the height of the plant will reach a certain level. ### Example F...
algorithms
def growing_plant(upSpeed, downSpeed, desiredHeight): days = 1 height = upSpeed while (height < desiredHeight): height += upSpeed - downSpeed days += 1 return days
Simple Fun #74: Growing Plant
58941fec8afa3618c9000184
[ "Algorithms" ]
https://www.codewars.com/kata/58941fec8afa3618c9000184
7 kyu
# Task Let's define digit degree of some positive integer as the number of times we need to replace this number with the sum of its digits until we get to a one digit number. Given an integer `n`, find its digit degree. # Example For `n = 5`, the output should be `0`; For `n = 100`, the output should be `1`; ...
games
def digit_degree(n): return 1 + digit_degree(sum(map(int, str(n)))) if len(str(n)) > 1 else 0
Simple Fun #75: Digit Degree
589422431a88082ea600002a
[ "Puzzles" ]
https://www.codewars.com/kata/589422431a88082ea600002a
7 kyu
## Task A noob programmer was given two simple tasks: sum and sort the elements of the given array `arr` = [a<sub>1</sub>, a<sub>2</sub>, ..., a<sub>n</sub>]. He started with summing and did it easily, but decided to store the sum he found in some random position of the original array which was a bad idea. Now he ...
games
def shuffled_array(s): result = sorted(s) result . remove(sum(result) / / 2) return result
Simple Fun #87: Shuffled Array
589573e3f0902e8919000109
[ "Puzzles" ]
https://www.codewars.com/kata/589573e3f0902e8919000109
7 kyu
# Task The year of `2013` is the first year after the old `1987` with only distinct digits. Now your task is to solve the following problem: given a `year` number, find the minimum year number which is strictly larger than the given one and has only distinct digits. # Input/Output - `[input]` integer `year` `1...
algorithms
def distinct_digit_year(year): year += 1 while len(set(str(year))) != 4: year += 1 return year # coding and coding..
Simple Fun #144: Distinct Digit Year
58aa68605aab54a26c0001a6
[ "Algorithms" ]
https://www.codewars.com/kata/58aa68605aab54a26c0001a6
7 kyu
# Task Your task is to find the similarity of given sorted arrays `a` and `b`, which is defined as follows: you take the number of elements which are present in both arrays and divide it by the number of elements which are present in at least one array. It also can be written as a formula `similarity(A, B) = #(A...
games
def similarity(a, b): try: return len(set(a) & set(b)) / len(set(a) | set(b)) except: return 0
Simple Fun #138: Similarity
58a6841442fd72aeb4000080
[ "Puzzles" ]
https://www.codewars.com/kata/58a6841442fd72aeb4000080
7 kyu
Following on from [Part 1](http://www.codewars.com/kata/filling-an-array-part-1/), part 2 looks at some more complicated array contents. So let's try filling an array with... ## ...square numbers The numbers from `1` to `n*n` ```javascript const squares = n => ??? squares(5) // [1, 4, 9, 16, 25] ``` ## ...a range of...
reference
from itertools import accumulate from gmpy2 import next_prime from random import sample def squares(n): return [x * * 2 for x in range(1, n + 1)] def num_range(n, start, step): return list(range(start, start + n * step, step)) def rand_range(n, mn, mx): return sample(range(mn, mx + 1...
Filling an array (part 2)
571e9af407363dbf5700067c
[ "Arrays", "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/571e9af407363dbf5700067c
6 kyu
In number theory, an **[abundant](https://en.wikipedia.org/wiki/Abundant_number)** number or an **[excessive](https://en.wikipedia.org/wiki/Abundant_number)** number is one for which the sum of it's **[proper divisors](http://mathworld.wolfram.com/ProperDivisor.html)** is greater than the number itself. The integer *...
algorithms
def abundant(h): for n in range(h, 0, - 1): s = sum(i for i in range(1, n) if n % i == 0) if s > h: return [[n], [s - n]]
Abundant Numbers
57f3996fa05a235d49000574
[ "Fundamentals", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/57f3996fa05a235d49000574
6 kyu
#Sorting on planet Twisted-3-7 There is a planet... in a galaxy far far away. It is exactly like our planet, but it has one difference: #The values of the digits 3 and 7 are twisted. Our 3 means 7 on the planet Twisted-3-7. And 7 means 3. Your task is to create a method, that can sort an array the way it would be sor...
algorithms
def sort_twisted37(arr): def key(x): return int(str(x). translate(str . maketrans('37', '73'))) return sorted(arr, key=key)
Sorting on planet Twisted-3-7
58068479c27998b11900056e
[ "Mathematics", "Sorting", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/58068479c27998b11900056e
6 kyu
**This Kata is intended as a small challenge for my students** All Star Code Challenge #20 Create a function called addArrays() that combines two arrays of equal length, summing each element of the first with the corresponding element in the second, returning the "combined" summed array. Raise an error if input arg...
reference
def add_arrays(arr1, arr2): if len(arr1) != len(arr2): raise "Input arguments are not of equal length" return [x + y for x, y in zip(arr1, arr2)]
All Star Code Challenge #20
5865a75da5f19147370000c7
[ "Fundamentals" ]
https://www.codewars.com/kata/5865a75da5f19147370000c7
7 kyu
<!--- For translators: sorry if I am a noob with markdown (it's my very first time...). You are invited to make all the changes you think are needed --> When we attended middle school were asked to simplify mathematical expressions like "3x-yx+2xy-x" (or usually bigger), and that was easy-peasy ("2x+xy"). But tell that...
reference
def simplify(poly): # I'm feeling verbose today # get 3 parts (even if non-existent) of each term: (+/-, coefficient, variables) import re matches = re . findall(r'([+\-]?)(\d*)([a-z]+)', poly) # get the int equivalent of coefficient (including sign) and the sorted variables (for later compar...
Simplifying multilinear polynomials
55f89832ac9a66518f000118
[ "Mathematics", "Strings", "Regular Expressions", "Parsing", "Fundamentals" ]
https://www.codewars.com/kata/55f89832ac9a66518f000118
4 kyu
*Summary*: Write a function which takes an array `data` of numbers and returns the largest difference in indexes `j - i` such that `data[i] <= data[j]` -------------------- *Long Description*: The `largestDifference` takes an array of numbers. That array is not sorted. Do not sort it or change the order of the eleme...
algorithms
def largest_difference(data): maxi = 0 for i in range(len(data) - 1): for j in range(i + 1, len(data)): if data[i] <= data[j]: maxi = max(j - i, maxi) return maxi
Largest Difference in Increasing Indexes
52503c77e5b972f21600000e
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/52503c77e5b972f21600000e
5 kyu
## The Riddle The King of a small country invites 1000 senators to his annual party. As a tradition, each senator brings the King a bottle of wine. Soon after, the Queen discovers that one of the senators is trying to assassinate the King by giving him a bottle of poisoned wine. Unfortunately, they do not know which s...
games
def find(r): return sum(2 * * i for i in r)
What's Your Poison?
58c47a95e4eb57a5b9000094
[ "Puzzles", "Riddles", "Algorithms", "Bits", "Fundamentals" ]
https://www.codewars.com/kata/58c47a95e4eb57a5b9000094
6 kyu
Given two arrays, the purpose of this Kata is to check if these two arrays are the same. "The same" in this Kata means the two arrays contains arrays of 2 numbers which are same and not necessarily sorted the same way. i.e. <code>[[2,5], [3,6]]</code> is same as <code>[[5,2], [3,6]]</code> or <code>[[6,3], [5,2]]</code...
reference
def same(arr_a, arr_b): return sorted(map(sorted, arr_a)) == sorted(map(sorted, arr_b))
Same Array?
558c04ecda7fb8f48b000075
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/558c04ecda7fb8f48b000075
6 kyu
This is the first of my "-nacci" series. If you like this kata, check out the [zozonacci](https://www.codewars.com/kata/5b7c80094a6aca207000004d) sequence too. # Task 1. Mix `-nacci` sequences using a given pattern `p`. 2. Return the first `n` elements of the mixed sequence. ### Rules 1. The pattern `p` is given as...
reference
def mixbonacci(pattern, length): def nacci(starts, sum_indexes): while 1: yield starts[0] starts = starts[1:] + [sum(starts[i] for i in sum_indexes)] sequences = { 'fib': nacci([0, 1], [0, 1]), 'pad': nacci([1, 0, 0], [0, 1]), 'jac': nacci([0, 1], [0, 0, 1]), ...
Mixbonacci
5811aef3acdf4dab5e000251
[ "Fundamentals" ]
https://www.codewars.com/kata/5811aef3acdf4dab5e000251
5 kyu
In this series of Kata, we will be implementing a software version of the [Enigma Machine](http://en.wikipedia.org/wiki/Enigma_machine). The Enigma Machine was a message enciphering/deciphering machine used during the Second World War for disguising the content of military communications. [Alan Turing](http://en.wiki...
reference
from string import ascii_uppercase as LETTERS class Plugboard (object): def __init__(self, wiring=''): if wiring: assert wiring . isalpha() and wiring . isupper( ), "Wiring must only contain capital latin letters" assert not len(wiring) % 2, "Odd length of wiring string" assert len(wiring) == ...
The Enigma Machine - Part 1: The Plugboard
5523b97ac8f5025c45000900
[ "Fundamentals", "Algorithms", "Object-oriented Programming" ]
https://www.codewars.com/kata/5523b97ac8f5025c45000900
6 kyu
In this Kata, you will implement the [Luhn Algorithm](http://en.wikipedia.org/wiki/Luhn_algorithm), which is used to help validate credit card numbers. Given a positive integer of up to 16 digits, return ```true``` if it is a valid credit card number, and ```false``` if it is not. Here is the algorithm: * Double e...
algorithms
def validate(n): digits = [int(x) for x in str(n)] even = [x * 2 if x * 2 <= 9 else x * 2 - 9 for x in digits[- 2:: - 2]] odd = [x for x in digits[- 1:: - 2]] return (sum(even + odd) % 10) == 0
Validate Credit Card Number
5418a1dd6d8216e18a0012b2
[ "Algorithms" ]
https://www.codewars.com/kata/5418a1dd6d8216e18a0012b2
6 kyu
A [Narcissistic Number](https://en.wikipedia.org/wiki/Narcissistic_number) (or Armstrong Number) is a positive number which is the sum of its own digits, each raised to the power of the number of digits in a given base. In this Kata, we will restrict ourselves to decimal (base 10). For example, take 153 (3 digits), w...
algorithms
def narcissistic(value): return value == sum(int(x) * * len(str(value)) for x in str(value))
Does my number look big in this?
5287e858c6b5a9678200083c
[ "Algorithms" ]
https://www.codewars.com/kata/5287e858c6b5a9678200083c
6 kyu
Create a Vector object that supports addition, subtraction, dot products, and norms. So, for example: ```coffeescript a = new Vector([1, 2, 3]) b = new Vector([3, 4, 5]) c = new Vector([5, 6, 7, 8]) a.add(b) # should return a new Vector([4, 6, 8]) a.subtract(b) # should return a new Vector([-2, -2, -2]) a.dot(b)...
algorithms
import operator class Vector (list): def __str__(self): return "" . join(str(tuple(self)). split()) def math(self, other, op): result = Vector() for i in range(max([len(self), len(other)])): result . append(op(self[i], other[i])) return result def add(self, other): re...
Vector class
526dad7f8c0eb5c4640000a4
[ "Object-oriented Programming", "Algorithms", "Linear Algebra" ]
https://www.codewars.com/kata/526dad7f8c0eb5c4640000a4
5 kyu