description
stringlengths
38
154k
category
stringclasses
5 values
solutions
stringlengths
13
289k
name
stringlengths
3
179
id
stringlengths
24
24
tags
sequencelengths
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 the following rules: - It should make the conversion if the given string only contains a single integer value (and possibly spaces - including tabs, line feeds... - at both ends) - For all other strings (including the ones representing float values), it should return NaN - It should assume that all numbers are not signed and written in base 10
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 ## Notes * Don't pack words together: * e.g. 99 may be "ninety nine" or "ninety-nine"; but not "ninetynine" * e.g 101 may be "one hundred one" or "one hundred and one"; but not "onehundredone" * Don't fret about formatting rules, because if rules are consistently applied it has no effect anyway: * e.g. "one hundred one", "one hundred two"; is same order as "one hundred **and** one", "one hundred **and** two" * e.g. "ninety eight", "ninety nine"; is same order as "ninety-eight", "ninety-nine" ```if:c * For `C` code the input array may be NULL. The return value is freed if non-NULL. ```
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: 'nineteen', 20: 'twenty', 30: 'thirty', 40: 'forty', 50: 'fifty', 60: 'sixty', 70: 'seventy', 80: 'eighty', 90: 'ninety'} assert (0 <= num) if (num < 20): return d[num] if (num < 100): if num % 10 == 0: return d[num] else: return d[num / / 10 * 10] + '-' + d[num % 10] if (num < 1000): if num % 100 == 0: return d[num / / 100] + ' hundred' else: return d[num / / 100] + ' hundred and ' + int_to_word(num % 100) def sort_by_name(arr): return sorted(arr, key=int_to_word)
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 from its handlers - it has an __.emit()__ method, which takes an arbitrary number of arguments and calls all the stored functions with these arguments As this is an elementary example of events, there are some simplifications: - all functions are called with correct arguments (_e.g._ only functions will be passed to unsubscribe) - you should not worry about the order of handlers' execution - the handlers will not attempt to modify an event object (_e.g._ add or remove handlers) - the context of handlers' execution is not important - each handler will be subscribed at most once at any given moment of time. It can still be unsubscribed and then subscribed again Also see an example test fixture for suggested usage
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 were a good child this year. So you may assume, that you'll only get things from your wishlist. You see those presents, you can lift them and you can shake them a bit. Now you can make you assumptions about what you'll get. ## Your Task You will be given a wishlist (array), containing all possible items. Each item is in the format: `{name: "toy car", size: "medium", clatters: "a bit", weight: "medium"}` (Ruby version has an analog hash structure, see example below) You also get a list of presents (array), you see under the christmas tree, which have the following format each: `{size: "small", clatters: "no", weight: "light"}` Your task is to return the names of all wishlisted presents that you might have gotten. ## Rules * Possible values for `size`: "small", "medium", "large" * Possible values for `clatters`: "no", "a bit", "yes" * Possible values for `weight`: "light", "medium", "heavy" * Don't add any item more than once to the result * The order of names in the output doesn't matter * It's possible, that multiple items from your wish list have the same attribute values. If they match the attributes of one of the presents, add all of them. ## Example ```javascript var wishlist = [ {name: "Mini Puzzle", size: "small", clatters: "yes", weight: "light"}, {name: "Toy Car", size: "medium", clatters: "a bit", weight: "medium"}, {name: "Card Game", size: "small", clatters: "no", weight: "light"} ]; var presents = [ {size: "medium", clatters: "a bit", weight: "medium"}, {size: "small", clatters: "yes", weight: "light"} ]; guessGifts(wishlist, presents); // must return ["Toy Car", "Mini Puzzle"] ``` ```coffeescript wishlist = [ {name: "Mini Puzzle", size: "small", clatters: "yes", weight: "light"}, {name: "Toy Car", size: "medium", clatters: "a bit", weight: "medium"}, {name: "Card Game", size: "small", clatters: "no", weight: "light"} ] presents = [ {size: "medium", clatters: "a bit", weight: "medium"}, {size: "small", clatters: "yes", weight: "light"} ] guessGifts(wishlist, presents); # must return ["Toy Car", "Mini Puzzle"] ``` ```ruby wishlist = [ {:name => "mini puzzle", :size => "small", :clatters => "yes", :weight => "light"}, {:name => "toy car", :size => "medium", :clatters => "a bit", :weight => "medium"}, {:name => "card game", :size => "small", :clatters => "no", :weight => "light"} ] presents = [ {:size => "medium", :clatters => "a bit", :weight => "medium"}, {:size => "small", :clatters => "yes", :weight => "light"} ] guess_gifts(wishlist, presents) # must return ['toy car', 'mini puzzle'] ``` ```python wishlist = [{'name': "mini puzzle", 'size': "small", 'clatters': "yes", 'weight': "light"}, {'name': "toy car", 'size': "medium", 'clatters': "a bit", 'weight': "medium"}, {'name': "card game", 'size': "small", 'clatters': "no", 'weight': "light"}] presents = [{'size': "medium", 'clatters': "a bit", 'weight': "medium"}, {'size': "small", 'clatters': "yes", 'weight': "light"}] guess_gifts(wishlist, presents) # => must return ["Toy Car", "Mini Puzzle"] ```
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(result)
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 has 8 reindeers in total, so he can deliver up to 180 presents at once (2 reindeers for Santa and the sleigh + 6 reindeers with 30 presents each). Complete the function `reindeers()`, which takes a number of presents and returns the minimum numbers of required reindeers. If the number of presents is too high, throw an error. ### Examples (input -> output / error) ``` 0 -> 2 1 -> 3 30 -> 3 200 -> throws an error ```
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. The last line having only stars, no spaces.
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. Examples: Present and box respectively ``` [10, 7, 16], [13, 32, 10] --> true, box is bigger than present [5, 7, 9], [9, 5, 7] --> false, present and box are same size [17, 22, 10], [5, 5, 10]) --> false, box is too small ```
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 functions accept a sequence of objects. The first one returns a sequence containing only the names of the nice people, and the other returns a sequence containing only the names of the naughty people. Return an empty sequence `[]` if the result from either of the functions contains no names. The objects in the passed will represent people. Each object contains two properties: `name` and `wasNice`.<br/> `name` - The name of the person<br/> `wasNice` - True if the person was nice this year, false if they were naughty ## Person Object Examples ```javascript { name: 'Warrior reading this kata', wasNice: true } { name: 'xDranik', wasNice: false } ``` ```if:haskell In Haskell, a `Warrior` is simply a tuple `(String, Bool)`: ``` ```haskell type Warrior = (String, Bool) example = ("Warrior reading this kata", True) ``` ```if:csharp In C# the class `Person` is pre-loaded with the properties: ``` ```csharp public string Name { get; set; } public bool WasNice { get; set; } ``` ## Test Examples ```javascript getNiceNames( [ { name: 'Warrior reading this kata', wasNice: true }, { name: 'xDranik', wasNice: false }, { name: 'Santa', wasNice: true } ] ) // => returns [ 'Warrior reading this kata', 'Santa' ] getNaughtyNames( [ { name: 'Warrior reading this kata', wasNice: true }, { name: 'xDranik', wasNice: false }, { name: 'Santa', wasNice: true } ] ) // => returns [ 'xDranik' ] ``` ```haskell warriors = [ ("xDranik", False), ("Santa", True), ("Warrior reading this kata", True) ] getNiceNames warriors == ["Santa", "Warrior reading this kata"] getNaughtyNames warriors == ["xDranik"] ``` ```python get_nice_names( [ { 'name': 'Warrior reading this kata', 'was_nice': True }, { 'name': 'xDranik', 'was_nice': False }, { 'name': 'Santa', 'was_nice': True } ] ) # => returns [ 'Warrior reading this kata', 'Santa' ] ```
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 Reindeer Write a function that accepts a sequence of Reindeer names, and returns a sequence with the Reindeer names sorted by their last names. ### Notes: * It's guaranteed that each string is composed of two words * In case of two identical last names, keep the original order ### Examples For this input: ``` [ "Dasher Tonoyan", "Dancer Moore", "Prancer Chua", "Vixen Hall", "Comet Karavani", "Cupid Foroutan", "Donder Jonker", "Blitzen Claus" ] ``` You should return this output: ``` [ "Prancer Chua", "Blitzen Claus", "Cupid Foroutan", "Vixen Hall", "Donder Jonker", "Comet Karavani", "Dancer Moore", "Dasher Tonoyan", ] ```
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 organizer to order the characters in alphabetical order, but the Elf fell asleep from consuming too much hot chocolate and candy canes! Can you help him out? ### Sort the Gift Code Write a function called `sortGiftCode`/`sort_gift_code`/`SortGiftCode` that accepts a string containing up to 26 unique alphabetical characters, and returns a string containing the same characters in alphabetical order. ### Examples (Input -- => Output): ``` "abcdef" -- => "abcdef" "pqksuvy" -- => "kpqsuvy" "zyxwvutsrqponmlkjihgfedcba" -- => "abcdefghijklmnopqrstuvwxyz" ```
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), `false` otherwise. ~~~if:javascript Keep in mind Javascript's Date month is 0 based! ~~~ ### Examples ```javascript timeForMilkAndCookies(new Date(2013, 11, 24)) // true timeForMilkAndCookies(new Date(2013, 0, 23)) // false timeForMilkAndCookies(new Date(3000, 11, 24)) // true ``` ```coffeescript timeForMilkAndCookies(new Date(2013, 11, 24)) // true timeForMilkAndCookies(new Date(2013, 0, 23)) // false timeForMilkAndCookies(new Date(3000, 11, 24)) // true ``` ```ruby time_for_milk_and_cookies(Date.new(2013, 12, 24)) # true time_for_milk_and_cookies(Date.new(2013, 1, 23)) # false time_for_milk_and_cookies(Date.new(3000, 12, 24)) # true ``` ```python time_for_milk_and_cookies(date(2013, 12, 24)) # True time_for_milk_and_cookies(date(2013, 1, 23)) # False time_for_milk_and_cookies(date(3000, 12, 24)) # True ```
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 fortunately Santa is not alone. His elves keep a list with the names of the children, which already were on Santa's lap. We know, that each child name is unique. If a child tries to get a second gift, the elves will tell Santa. OK, let's help Santa and his elves with a simple function `handOutGift()` (`hand_out_gift` in Ruby/Python, `HandOutGift` in C# ) which takes the name of the next child. If this child already got a gift, it must throw an error in order to remind Santa. Example: ```javascript handOutGift("Peter"); handOutGift("Alison"); handOutGift("John"); handOutGift("Maria"); handOutGift("Peter"); // <-- must throw an error ``` ```ruby hand_out_gift("Peter"); hand_out_gift("Alison"); hand_out_gift("John"); hand_out_gift("Maria"); hand_out_gift("Peter"); # <-- must throw an error ``` ```python hand_out_gift("Peter"); hand_out_gift("Alison"); hand_out_gift("John"); hand_out_gift("Maria"); hand_out_gift("Peter"); # <-- must throw an error ``` ```csharp Christmas.HandOutGift("Peter"); Christmas.HandOutGift("Alison"); Christmas.HandOutGift("John"); Christmas.HandOutGift("Maria"); Christmas.HandOutGift("Peter"); // <-- must throw an ArgumentException ```
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 are neither naughty nor nice. If there is an equal amount of bad and good actions, return ```'naughty'``` Examples: ```python bad_actions = ['broke someone\'s window', 'fought over a toaster', 'killed a bug'] whatListAmIOn(bad_actions) #-> 'naughty' good_actions = ['got someone a new car', 'saved a man from drowning', 'never got into a fight'] what_list_am_i_on(good_actions) #-> 'nice' actions = ['broke a vending machine', 'never got into a fight', 'tied someone\'s shoes'] what_list_am_i_on(actions) #-> 'naughty' ``` ```ruby bad_actions = ['broke someone\'s window', 'fought over a toaster', 'killed a bug'] what_list_am_i_on(bad_actions) #-> 'naughty' good_actions = ['got someone a new car', 'saved a man from drowning', 'never got into a fight'] what_list_am_i_on(good_actions) #-> 'nice' actions = ['broke a vending machine', 'never got into a fight', 'tied someone\'s shoes'] what_list_am_i_on(actions) #-> 'naughty' ``` ```php $bad_actions = ["broke someone's window", "fought over a toaster", "killed a bug"]; what_list_am_i_on($bad_actions); // => "naughty" $good_actions = ["got someone a new car", "saved a man from drowning", "never got into a fight"]; what_list_am_i_on($good_actions); // => "nice" $actions = ["broke a vending machine", "never got into a fight", "tied someone's shoes"]; what_list_am_i_on($actions); // => "naughty" ``` ```crystal bad_actions = ['broke someone\'s window', 'fought over a toaster', 'killed a bug'] what_list_am_i_on(bad_actions) #-> 'naughty' good_actions = ['got someone a new car', 'saved a man from drowning', 'never got into a fight'] what_list_am_i_on(good_actions) #-> 'nice' actions = ['broke a vending machine', 'never got into a fight', 'tied someone\'s shoes'] what_list_am_i_on(actions) #-> 'naughty' ```
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 of [6, 3].</u> ```Disclaimer: only accepts solutions that are faster than his, which has a running time O(nlogn).``` ```ruby max_product([2, 1, 5, 0, 4, 3]) # => 20 max_product([7, 8, 9]) # => 72 max_product([33, 231, 454, 11, 9, 99, 57]) # => 104874 ``` ```javascript maxProduct([2, 1, 5, 0, 4, 3]) // 20 maxProduct([7, 8, 9]) // 72 maxProduct([33, 231, 454, 11, 9, 99, 57]) // 104874 ``` ```python max_product([2, 1, 5, 0, 4, 3]) # => 20 max_product([7, 8, 9]) # => 72 max_product([33, 231, 454, 11, 9, 99, 57]) # => 104874 ``` ```csharp Kata.MaxProduct(new int[] { 2, 1, 5, 0, 4, 3 }); // 20 Kata.MaxProduct(new int[] { 7, 8, 9 }) ; // 72 Kata.MaxProduct(new int[] { 33, 231, 454, 11, 9, 99, 57 }); // 104874 ```
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 during day time. **Note**: If the count exceed 3 please return 'You need extra sleep'. The list of events can contain the following: - You come here, to solve some kata ('cw'). - You have a dog or a cat that just decide to wake up too early ('dog' | 'cat'). - You just watch a movie ('movie'). - Other events can be present and it will be represent by arbitrary string, just ignore this one. Each event can be downcase/lowercase, or uppercase. If it is downcase/lowercase you need 1 coffee by events and if it is uppercase you need 2 coffees.
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](https://www.codewars.com/kata/histogram-v2/) <h2>Background</h2> A 6-sided die is rolled a number of times and the results are plotted as a character-based histogram. Example: ``` 6|##### 5 5| 4|# 1 3|########## 10 2|### 3 1|####### 7 ``` <h2>Task</h2> You will be passed the dice value frequencies, and your task is to write the code to return a string representing a histogram, so that when it is printed it has the same format as the example. <h2>Notes</h2> * There are no trailing spaces on the lines * All lines (including the last) end with a newline ```\n``` * A count is displayed beside each bar except where the count is 0 * The number of rolls may vary but there are never more than 100
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 (n)(n-1)(n-2)....43 (n)(n-1)(n-2)....432 (n)(n-1)(n-2)....4321 ## Examples: pattern(4): 4 43 432 4321 pattern(6): 6 65 654 6543 65432 654321 ```Note: There are no blank spaces``` ```Hint: Use \n in string to jump to next line```
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):` should return the following: ``` 1 1*2 1**3 1***4 1****5 1*****6 1******7 1*******8 1********9 1*********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 the rows end ### Examples pattern(5) 1 1 1 1 1 2 2 2 2 3 3 3 4 4 5 pattern(9) 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 4 4 4 4 4 4 5 5 5 5 5 6 6 6 6 7 7 7 8 8 9 pattern(16) 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5 5 6 6 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8 8 9 9 9 9 9 9 9 9 0 0 0 0 0 0 0 1 1 1 1 1 1 2 2 2 2 2 3 3 3 3 4 4 4 5 5 6
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 56 6 ```Note: There are no blank spaces``` ```Hint: Use \n in string to jump to next line```
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 empty. ## Examples ``` "Hi mom" => "iH mom" " A fun little challenge! " => " A nuf elttil !egnellahc " ```
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 tests, it differs in each translation
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. At the output the water content is only 98%. What is the total weight in kilograms (water content plus dry matter) coming out of the oven? He finds 50 kilograms and he thinks he made a mistake: "So much weight lost for such a small change in water content!" Can you help him? #### Task Write function `potatoes` with - int parameter `p0` - initial percent of water- - int parameter `w0` - initial weight - - int parameter `p1` - final percent of water - `potatoes`should return the final weight coming out of the oven `w1` truncated as an int. #### Example: `potatoes(99, 100, 98) --> 50`
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 { text-align: center; vertical-align: middle; } </style> <table class = "grid"> <tr> <td>00</td> <td>01</td> <td>02</td> <td>03</td> <td>04</td> </tr> <tr> <td>10</td> <td>11</td> <td>12</td> <td>13</td> <td>14</td> </tr> <tr> <td>20</td> <td>21</td> <td>22</td> <td>23</td> <td>24</td> </tr> <tr> <td>30</td> <td>31</td> <td>32</td> <td>33</td> <td>34</td> </tr> <tr> <td>40</td> <td>41</td> <td>42</td> <td>43</td> <td>44</td> </tr> </table><p> The `dir` argument will be a string ``` up down left right ``` If the position is not inside the level grid the method should throw an error and not move the hero
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") self . position = '{:02d}' . format(position) Hero . move = move
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) => a + b) === ['1a', '2b'] var a = [1, 2, 3, 4, 5]; var b = ['a','b','c','d','e']; a.zip(b, (a, b) => a + b.charCodeAt(0)) === [98, 100, 102, 104, 106] ``` ```csharp var a = new object[] { 1, 2, 3, 4, 5 }; var b = new object[] { 'a','b' }; a.ZipIt(b, (c, d) => c + "" + d); --> new object[] { '1a', '2b' } var a = new object[] { 1, 2, 3, 4, 5 }; var b = new object[] {'a','b','c','d','e'}; a.ZipIt(b, (c, d) => (int)c + (int)(char)d)); --> new object[] { 98, 100, 102, 104, 106 } ``` ```ruby a = [1, 2, 3, 4, 5] b = ['a', 'b'] a.zip(b){|x, y| x.to_s + y} => ['1a', '2b'] a = [1, 2, 3, 4, 5] b = ['a','b','c','d','e'] a.zip(b){|x, y| x + y.ord} => [98, 100, 102, 104, 106] ``` ```python a = [1, 2, 3, 4, 5] b = ['a', 'b'] lstzip(a,b, lambda a,b: str(a)+str(b)) a = [1, 2, 3, 4, 5] b = ['a','b','c','d','e'] lstzip(a,b, lambda a, b: a * ord(b[0])) ``` if arrays have different lengths, go up to the minimum length and then stop.
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 assume it will be at least one. So: ```javascript sumCircles(2) == "We have this much circle: 3" sumCircles(2, 3, 4) == "We have this much circle: 23" ``` ```python sum_circles(2) == "We have this much circle: 3" sum_circles(2, 3, 4) == "We have this much circle: 23" ``` ```ruby sum_circles(2) == "We have this much circle: 3" sum_circles(2, 3, 4) == "We have this much circle: 23" ``` Translations and comments (and upvotes!) welcome!
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 expects `Calculator.average(3,4,5)` to return `4`.
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 to add characters from the remaining strings. For example `combineStrings('abcd', '123')` should return `'a1b2c3d'`. The function should take any number of arguments and combine them. For example `combineStrings('abc', '123', '£$%')` should return `'a1£b2$c3%'`. **Note: if only one argument is passed return only that string. If no arguments are passed return an empty string.**
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 with the new things you want "added on it". ## Your Task Complete the code so that when a `Marine` gets a `WeaponUpgrade` it increases the damage by `1`, and if it is a `ArmorUpgrade` then increase the armor by `1`. You have 3 classes: - `Marine`: has a `damage` and an `armor` properties - `MarineWeaponUpgrade` and `MarineArmorUpgrade`: upgrades to apply on marine. Accepts a `Marine` in the constructor and has the same properties as the `Marine` ## Resouces - [PatternCraft > Decorator](https://www.youtube.com/watch?v=17XTOODeWQE) - [SourceMaking > Decorator](https://sourcemaking.com/design_patterns/decorator) - [Wikipedia > Decorator](https://en.wikipedia.org/wiki/Decorator_pattern) # PatternCraft series - [State Pattern](http://www.codewars.com/kata/patterncraft-state/) - [Strategy Pattern](http://www.codewars.com/kata/patterncraft-strategy/) - [Visitor Pattern](http://www.codewars.com/kata/patterncraft-visitor/) - **Decorator Pattern** - [Adapter Pattern](http://www.codewars.com/kata/patterncraft-adapter/) - [Command Pattern](http://www.codewars.com/kata/patterncraft-command/) The original [PatternCraft series (by John Lindquist)](https://www.youtube.com/playlist?list=PL8B19C3040F6381A2) is a collection of Youtube videos that explains some of the design patterns and how they are used (or could be) on StarCraft.
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): self . damage = marine . damage self . armor = marine . armor + 1
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 code so that when a `Tank` goes into `SiegeMode` it cannot move and its damage goes to `20`. When it goes to `TankMode` it should be able to move and the damage should be set to `5`. You have 3 classes: - `Tank`: has a `state`, `canMove` and `damage` properties - `SiegeState` and `TankState`: has `canMove` and `damage` properties **Note**: The tank initial state should be `TankState`. ## Resources - [PatternCraft > State](https://www.youtube.com/watch?v=yZt7mUVDijU) - [SourceMaking > State](https://sourcemaking.com/design_patterns/state) - [Wikipedia > State](https://en.wikipedia.org/wiki/State_pattern) # PatternCraft series - **State Pattern** - [Strategy Pattern](http://www.codewars.com/kata/patterncraft-strategy/) - [Visitor Pattern](http://www.codewars.com/kata/patterncraft-visitor/) - [Decorator Pattern](http://www.codewars.com/kata/patterncraft-decorator/) - [Adapter Pattern](http://www.codewars.com/kata/patterncraft-adapter/) - [Command Pattern](http://www.codewars.com/kata/patterncraft-command/) The original [PatternCraft series (by John Lindquist)](https://www.youtube.com/playlist?list=PL8B19C3040F6381A2) is a collection of Youtube videos that explains some of the design patterns and how they are used (or could be) on StarCraft.
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): self . state = TankState() def can_move(self): return self . state . can_move() def damage(self): return self . state . damage()
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 that when a `Viking` is flying its position increases by `10` each time it moves. If it is walking then the position is increased by `1`. In this Kata, Viking starts as a ground unit when it is created. You have `3` classes: - `Viking`: has a `position`, `moveBehavior` and `move` method. - `Fly` and `Walk`: the move behaviors with the `move(unit)` method. `Fly` has to move `10` positions at a time and `Walk` has to move `1`. ## Resouces - [PatternCraft > Strategy](https://www.youtube.com/watch?v=MOEsKHqLiBM) - [SourceMaking > Strategy](https://sourcemaking.com/design_patterns/strategy) - [Wikipedia > Strategy](https://en.wikipedia.org/wiki/Strategy_pattern) # PatternCraft series - [State Pattern](http://www.codewars.com/kata/patterncraft-state/) - **Strategy Pattern** - [Visitor Pattern](http://www.codewars.com/kata/patterncraft-visitor/) - [Decorator Pattern](http://www.codewars.com/kata/patterncraft-decorator/) - [Adapter Pattern](http://www.codewars.com/kata/patterncraft-adapter/) - [Command Pattern](http://www.codewars.com/kata/patterncraft-command/) The original [PatternCraft series (by John Lindquist)](https://www.youtube.com/playlist?list=PL8B19C3040F6381A2) is a collection of Youtube videos that explains some of the design patterns and how they are used (or could be) on StarCraft.
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(self)
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 ``` ```ruby count_char("fizzbuzz","z") => 4 count_char("Fancy fifth fly aloof","f") => 5 ``` ```python count_char("fizzbuzz","z") => 4 count_char("Fancy fifth fly aloof","f") => 5 ``` ```php count_char("fizzbuzz", "z"); // => 4 count_char("Fancy fifth fly aloof", "f"); // => 5 ``` The character can be any alphanumeric character. Good luck.
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 visitor what to do with itself. ## Your Task Complete the code so that when a `Tank` attacks a `Marine` it takes `21` damage and when a `Tank` attacks a `Marauder` it takes `32` damage. The Marine's initial health should be set to `100` and the Marauder's health should be set to `125`. You have 3 classes: - `Marine`: has a `health` property and `accept(visitor)` method - `Marauder`: has a `health` property and `accept(visitor)` method - `TankBullet`: the visitor class. Has `visitLight(unit)` and `visitArmored(unit)` methods ## Ressources - [PatternCraft > Visitor](https://www.youtube.com/watch?v=KSEyIXnknoY) - [SourceMaking > Visitor](https://sourcemaking.com/design_patterns/visitor) - [Wikipedia > Visitor](https://en.wikipedia.org/wiki/Visitor_pattern) # PatternCraft series - [State Pattern](http://www.codewars.com/kata/patterncraft-state/) - [Strategy Pattern](http://www.codewars.com/kata/patterncraft-strategy/) - **Visitor Pattern** - [Decorator Pattern](http://www.codewars.com/kata/patterncraft-decorator/) - [Adapter Pattern](http://www.codewars.com/kata/patterncraft-adapter/) - [Command Pattern](http://www.codewars.com/kata/patterncraft-command/) The original [PatternCraft series (by John Lindquist)](https://www.youtube.com/playlist?list=PL8B19C3040F6381A2) is a collection of Youtube videos that explains some of the design patterns and how they are used (or could be) on StarCraft.
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, unit): unit . health -= 21 def visit_armored(self, unit): unit . health -= 32
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 object that it is going to adapt and handles it in a way that works with our application. In this example we have the pre-loaded classes: ```javascript class Marine { attack(target) { target.health -= 6; } } class Zealot { attack(target) { target.health -= 8; } } class Zergling { attack(target) { target.health -= 5; } } class Mario { jumpAttack() { console.log('Mamamia!'); return 3; } } ``` ```csharp public class Target { public int Health { get; set; } } public interface IUnit { void Attack(Target target); } public class Marine : IUnit { public void Attack(Target target) { target.Health -= 6; } } public class Zealot : IUnit { public void Attack(Target target) { target.Health -= 8; } } public class Zergling : IUnit { public void Attack(Target target) { target.Health -= 5; } } public class Mario { public int jumpAttack() { Console.WriteLine("Mamamia!"); return 3; } } ``` ```coffeescript class Marine attack: (target) -> target.health -= 6 class Zealot attack: (target) -> target.health -= 8 class Zergling attack: (target) -> target.health -= 5 class Mario jumpAttack: () -> console.log 'Mamamia!' 3 ``` ```python class Target: def __init__(self, health): self.health = health class Marine: @staticmethod def attack(target): target.health -= 6 class Zealot: @staticmethod def attack(target): target.health -= 8 class Zergling: @staticmethod def attack(target): target.health -= 5 class Mario: @staticmethod def jump_attack(): print('Mamamia!') return 3 ``` Complete the code so that we can create a `MarioAdapter` that can attack as other units do. **Note** to calculate how much damage `mario` is going to do you have to call the `jumpAttack` method (`jump_attack` in Python). ## Resources - [PatternCraft > Adapter](https://www.youtube.com/watch?v=hvpXKZhNINc) - [SourceMaking > Adapter](https://sourcemaking.com/design_patterns/adapter) - [Wikipedia > Adapter](https://en.wikipedia.org/wiki/Adapter_pattern) # PatternCraft series - [State Pattern](http://www.codewars.com/kata/patterncraft-state/) - [Strategy Pattern](http://www.codewars.com/kata/patterncraft-strategy/) - [Visitor Pattern](http://www.codewars.com/kata/patterncraft-visitor/) - [Decorator Pattern](http://www.codewars.com/kata/patterncraft-decorator/) - **Adapter Pattern** - [Command Pattern](http://www.codewars.com/kata/patterncraft-command/) The original [PatternCraft series (by John Lindquist)](https://www.youtube.com/playlist?list=PL8B19C3040F6381A2) is a collection of Youtube videos that explains some of the design patterns and how they are used (or could be) on StarCraft.
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_common_factor([46, 14, 20, 88]); // => 2 ``` ```elixir Kata.greatest_common_factor([46, 14, 20, 88]) # == 2 ```
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: - a text `t` of length `l`. - Consider the smallest integer `n` such that `n * n` be greater or equal to `l`. - Complete `t` with the char of ascii code `11` (we suppose that this char is not in our original text) until the length of `t` is `n * n`. - From now on we can transform the new `t` in a squared string `s` of size `n` by inserting `'\n'` where needed. - Apply a clockwise rotation of 90 degrees to `s`: that's it for the coding part. #### Decoding Input: - a squared string `s` resulting from the coding - Apply a counter-clockwise rotation of 90 degrees to `s` - Do some cleaning to have the original text `t` You can see clockwise rotation of 90 degrees: <http://www.codewars.com/kata/56dbeec613c2f63be4000be6> You can see counter-clockwise rotation of 90 degrees: <http://www.codewars.com/kata/56dbf59b0a10feb08c000227> #### Example: t = "I.was.going.fishing.that.morning.at.ten.o'clock" code(t) -> `"c.nhsoI\nltiahi.\noentinw\ncng.nga\nk..mg.s\n\voao.f.\n\v'trtig"` decode(code(t)) == `"I.was.going.fishing.that.morning.at.ten.o'clock"` (Dots indicate spaces since they are quite invisible). #### Notes: - Swift : character `11` is replaced by `"\u{F7}"` (ie `"÷"` - `alt 246` -) - Ocaml : character `11` is replaced by '&' - Perl : character `11` is replaced by '&' - Fortran: Your returned string for both functions are **not** permitted to contain *redundant* leading/trailing whitespace. In return, you *may* safely assume that all input strings passed into your function(s) will *not* contain **redundant** leading/trailing whitespace, i.e. you do not and should **not** trim the input string before operating on it - Don't use this coding to keep your secrets:-)
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 + 1)] for i in range(n)] return '\n' . join('' . join(row) for row in clockwise(square)) def decode(s): return '' . join('' . join(row) for row in counterclockwise(s . split('\n'))). strip(chr(11))
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', 'AaAaAa', 'a' ]); // => 'BbBb' find_uniq([ 'abc', 'acb', 'bac', 'foo', 'bca', 'cab', 'cba' ]); // => 'foo' ``` ```python find_uniq([ 'Aa', 'aaa', 'aaaaa', 'BbBb', 'Aaaa', 'AaAaAa', 'a' ]) # => 'BbBb' find_uniq([ 'abc', 'acb', 'bac', 'foo', 'bca', 'cab', 'cba' ]) # => 'foo' ``` ```cobol FindUniq([ 'Aa', 'aaa', 'aaaaa', 'BbBb', 'Aaaa', 'AaAaAa', 'a' ]) * => result = 'BbBb' FindUniq([ 'abc', 'acb', 'bac', 'foo', 'bca', 'cab', 'cba' ]) * => result = 'foo' ``` Strings may contain spaces. Spaces are not significant, only non-spaces symbols matters. E.g. string that contains only spaces is like empty string. It’s guaranteed that array contains more than 2 strings. This is the second kata in series: 1. [Find the unique number](https://www.codewars.com/kata/585d7d5adb20cf33cb000235) 2. Find the unique string (this kata) 3. [Find The Unique](https://www.codewars.com/kata/5862e0db4f7ab47bed0000e5)
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", "jqbs"]) -> true contain_all_rots( "Ajylvpy", ["Ajylvpy", "ylvpyAj", "jylvpyA", "lvpyAjy", "pyAjylv", "vpyAjyl", "ipywee"]) -> false) ``` #### Note: Though not correct in a mathematical sense - we will consider that there are no rotations of `strng == ""` - and for any array `arr`: `contain_all_rots("", arr) --> true` Ref: <https://en.wikipedia.org/wiki/String_(computer_science)#Rotations> ```if:shell ## Bash: For bash the array is replaced by a string (see "RUN sample tests"). ```
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 smashed out at least 1000 and barely broken a sweat. He counts them in binary, because he thinks coding is cool, and because he is a massive Badass. When his wife arrives home, she starts talking to Chuck, spoiling his count! Your job is to write a function to isolate Chuck's count, and then work out how many push ups he has done! Return your answer as a number. Careful Chuck doesn't lose count! Even if he does, always return the highest number he counted to! If Chuck's wife has left a list of jobs for him he won't be able to do any push ups... if there is no sign of a count, simply return "CHUCK SMASH!!" In the event someone dares to provide Chuck with something other than a string, return 'FAIL!!' in [C++] when numbers not exists in input string then return `-1` all time. Your code should still pass in the case that the binary is mixed up with other characters - maybe Chuck has a cough... e.g.: "1ee1gf00t10h1011tr00" -> "110010101100" -> 3244. Feel the burn!!
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 be greater than 0.<br> The shifting value is always a value from 0 up to the size of the arrays.<br> There are always arrays in the array, so you do not need to check for null or empty.<br> #1. Example: ``` [[1,2,3,4,5,6], [7,7,7,7,7,-7]], 0 1,2,3,4,5,6 7,7,7,7,7,-7 --> [8,9,10,11,12,-1] ``` #2. Example ``` [[1,2,3,4,5,6], [7,7,7,7,7,7]], 3 1,2,3,4,5,6 7,7,7,7,7,7 --> [1,2,3,11,12,13,7,7,7] ``` #3. Example ``` [[1,2,3,4,5,6], [7,7,7,-7,7,7], [1,1,1,1,1,1]], 3 1,2,3,4,5,6 7,7,7,-7,7,7 1,1,1,1,1,1 --> [1,2,3,11,12,13,-6,8,8,1,1,1] ``` Have fun coding it and please don't forget to vote and rank this kata! :-) I have created other katas. Have a look if you like coding and challenges.
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 for the value: The difference from the searched number must be smaller than 0.00002. The compare-function, that your method will get as parameter, takes the guessed number as parameter and returns 0 for the correct number, -1 if your number is smaller than the searched number and 1 if your guessed number is greater than the searched number. ``` Example: Searched number: 6 Compare(1); -> -1 Compare(10); -> 1 Compare(6); -> 0 ``` You do not need a Compare-Call, that returns 0. If your number has a precision of 5 fractional digits, and you are sure, it is the searched number, you can return the number. You will always get the compare-method! So there is no need for a check for null. Have fun coding it and please don't forget to vote and rank this kata! :-)
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 Step5 5/ 5| 5\ 4/ 4| 4\ 1 2 3 4 5 1 2 3/ 1 2 3| 1 2 3\ 6 6 3 ----*---- ----* ----* ----* ----* Fold 2-times: [1,2,3,4,5] -> [9,6] ``` As you see, if the count of numbers is odd, the middle number will stay. Otherwise the fold-point is between the middle-numbers, so all numbers would be added in a way. The array will always contain numbers and will never be null. The parameter runs will always be a positive integer greater than 0 and says how many runs of folding your method has to do. If an array with one element is folded, it stays as the same array. The input array should not be modified! Have fun coding it and please don't forget to vote and rank this kata! :-) I have created other katas. Have a look if you like coding and challenges.
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` instead of `sqrt` doesn't give better results. A "good" answer is `4.99999999999999875... * 1e-16`. Can you modify f(x) to give a good approximation of f(x) in the neighborhood of 0? #### Note: Don't round or truncate your results. See the testing function in `Sample Tests:`.
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 gave you a list of integers of all the party goers. Arthur needs you to return true if he needs to invite more women or false if he is all set. ### Input/Output - `[input]` integer array `L` (`$a` in PHP) An array (guaranteed non-associative in PHP) representing the genders of the attendees, where `-1` represents `women` and `1` represents `men`. `2 <= L.length <= 50` - `[output]` a boolean value `true` if Arthur need to invite more women, `false` otherwise.
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's probably dangerous. Chucks action pants are extra special though. Due to his immense power, and slightly odd fan base, Chuck's used action pants actually increase in value!! That man can make money from anywhere! Your task, to pass the kata and potentially, if Chuck reads this, to be sent a pair of old action pants by the man himself, is as follows: ``` Inputs: Starting price: start (dollars) Use: soil (percentage) Age: age (years) ``` The action pants appreciate every year depending on the level to which they are soiled (soil input): ``` Barely used: 10 Seen a few high kicks: 25 Blood stained: 30 Heavily soiled: 50 ``` You will be given the relevant string as the soil input. Return a string prefixed with $ and to 2 decimal places e.g.: ``` '$25.00' ``` The inputs should be Number, string, Number... if any of those aren't as expected then return 'Chuck is bottomless!'. Same if the soil input is not one of the specified statements. Price that gusset!
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/kata/street-fighter-2-character-selection-part-2/python). **The Kata** You'll have to simulate the video game's character selection screen behaviour, more specifically the selection grid. Such screen looks like this: Screen: ![screen](https://images.duckduckgo.com/iu/?u=http%3A%2F%2Fwww.fightersgeneration.com%2Fnp5%2Fgm%2Fsf2ce-s2.jpg&f=1 "Character Selection Screen for Street Fighter 2") Selection Grid Layout in text: ``` | Ryu | E.Honda | Blanka | Guile | Balrog | Vega | | Ken | Chun Li | Zangief | Dhalsim | Sagat | M.Bison | ``` **Input** - the list of game characters in a 2x6 grid; - the initial position of the selection cursor (top-left is `(0,0)`); - a list of moves of the selection cursor (which are `up`, `down`, `left`, `right`); ~~~if:rust The `preloaded` module defines the following `enum`: ```rust #[derive(Debug)] pub enum Direction { Up, Down, Left, Right, } ``` ~~~ **Output** - the list of characters who have been hovered by the selection cursor after all the moves (ordered and with repetition, all the ones after a move, whether successful or not, see tests); **Rules** Selection cursor is circular *horizontally* but *not vertically*! As you might remember from the game, the selection cursor rotates horizontally but not vertically; that means that if I'm in the leftmost and I try to go left again I'll get to the rightmost (examples: from Ryu to Vega, from Ken to M.Bison) and vice versa from rightmost to leftmost. Instead, if I try to go further up from the upmost or further down from the downmost, I'll just stay where I am located (examples: you can't go lower than lowest row: Ken, Chun Li, Zangief, Dhalsim, Sagat and M.Bison in the above image; you can't go upper than highest row: Ryu, E.Honda, Blanka, Guile, Balrog and Vega in the above image). **Test** For this easy version the fighters grid layout and the initial position will always be the same in all tests, only the list of moves change. **Notice**: changing some of the input data might not help you. **Examples** 1. ``` fighters = [ ["Ryu", "E.Honda", "Blanka", "Guile", "Balrog", "Vega"], ["Ken", "Chun Li", "Zangief", "Dhalsim", "Sagat", "M.Bison"] ] initial_position = (0,0) moves = ['up', 'left', 'right', 'left', 'left'] ``` then I should get: ``` ['Ryu', 'Vega', 'Ryu', 'Vega', 'Balrog'] ``` as the characters I've been hovering with the selection cursor during my moves. Notice: Ryu is the first just because it "fails" the first `up` See test cases for more examples. 2. ``` fighters = [ ["Ryu", "E.Honda", "Blanka", "Guile", "Balrog", "Vega"], ["Ken", "Chun Li", "Zangief", "Dhalsim", "Sagat", "M.Bison"] ] initial_position = (0,0) moves = ['right', 'down', 'left', 'left', 'left', 'left', 'right'] ``` Result: ``` ['E.Honda', 'Chun Li', 'Ken', 'M.Bison', 'Sagat', 'Dhalsim', 'Sagat'] ``` **OFF-TOPIC** Some music to get in the mood for this kata : [Street Fighter 2 - selection theme](https://www.youtube.com/watch?v=GR3d9FMBkC8)
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 = (x + dx) % len(fighters[y]) hovered_fighters . append(fighters[y][x]) return hovered_fighters
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 behalf of the approximate value of pi. The usage is ```Math.PI```. I will no longer introduce one by one, please refer to the manual: - [Math Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math) In this lesson we learn three methods to turn a number into an integer: ```round()```, ```ceil()``` and ```floor()```. Their definitions and detailed information: - [Math.round()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round) - [Math.ceil()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/ceil) - [Math.floor()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor) First of all, we have to understand the first thing, all the methods of the Math object are static methods. It means that you need to use the Math method like this: ```Math.round(1.23)```. Not like this: ```(1.23).round()```. Here we use some examples to understand their usage: ```javascript console.log(Math.round(1.45)); //output:1 console.log(Math.ceil(1.45)); //output:2 console.log(Math.floor(1.45)); //output:1 console.log(Math.round(1.55)); //output:2 console.log(Math.ceil(1.55)); //output:2 console.log(Math.floor(1.55)); //output:1 ``` We can see, ```ceil()``` always rounding up to get a large integer; ```floor()``` always rounding down to get a small integer; ```round()``` according to the fractional part and round it to integer. When the parameter is negative, they still works: ```javascript console.log(Math.round(-1.45)); //output:-1 console.log(Math.ceil(-1.45)); //output:-1 console.log(Math.floor(-1.45)); //output:-2 console.log(Math.round(-1.55)); //output:-2 console.log(Math.ceil(-1.55)); //output:-1 console.log(Math.floor(-1.55)); //output:-2 ``` It should be noted that they are not working on the fractional part. If you want to keep two decimal places or otherwise, you should use [Methods of Number object--toFixed(), toExponential() and toPrecision()](http://www.codewars.com/kata/57256064856584bc47000611), or use the following techniques: ```javascript var n=1.23456 var a=Math.round(n*100)/100 var b=Math.ceil(n*100)/100 var c=Math.floor(n*100)/100 console.log(a,b,c); //output: 1.23 1.24 1.23 ``` In the example above, we first multiply the number by 100, and then round it. the final result is to retain two decimal places. Ok, lesson is over. let's us do some task. ## Task Coding in function ```roundIt```. function accept 1 parameter ```n```. It's a number with a decimal point. Please use different methods based on the location of the decimal point, turn the number into an integer. If the decimal point is on the left side of the number (that is, the count of digits on the left of the decimal point is less than that on the right), Using ```ceil()``` method. ``` roundIt(3.45) should return 4 ``` If the decimal point is on the right side of the number (that is, the count of digits on the left of the decimal point is more than that on the right), Using ```floor()``` method. ``` roundIt(34.5) should return 34 ``` If the decimal point is on the middle of the number (that is, the count of digits on the left of the decimal point is equals that on the right), Using ```round()``` method. ``` roundIt(34.56) should return 35 ``` ## [Series](http://github.com/myjinxin2015/Katas-list-of-Training-JS-series) ( ↑↑↑ Click the link above can get my newest kata list, Please add it to your favorites) - [#1: create your first JS function helloWorld](http://www.codewars.com/kata/571ec274b1c8d4a61c0000c8) - [#2: Basic data types--Number](http://www.codewars.com/kata/571edd157e8954bab500032d) - [#3: Basic data types--String](http://www.codewars.com/kata/571edea4b625edcb51000d8e) - [#4: Basic data types--Array](http://www.codewars.com/kata/571effabb625ed9b0600107a) - [#5: Basic data types--Object](http://www.codewars.com/kata/571f1eb77e8954a812000837) - [#6: Basic data types--Boolean and conditional statements if..else](http://www.codewars.com/kata/571f832f07363d295d001ba8) - [#7: if..else and ternary operator](http://www.codewars.com/kata/57202aefe8d6c514300001fd) - [#8: Conditional statement--switch](http://www.codewars.com/kata/572059afc2f4612825000d8a) - [#9: loop statement --while and do..while](http://www.codewars.com/kata/57216d4bcdd71175d6000560) - [#10: loop statement --for](http://www.codewars.com/kata/5721a78c283129e416000999) - [#11: loop statement --break,continue](http://www.codewars.com/kata/5721c189cdd71194c1000b9b) - [#12: loop statement --for..in and for..of](http://www.codewars.com/kata/5722b3f0bd5583cf44001000) - [#13: Number object and its properties](http://www.codewars.com/kata/5722fd3ab7162a3a4500031f) - [#14: Methods of Number object--toString() and toLocaleString()](http://www.codewars.com/kata/57238ceaef9008adc7000603) - [#15: Methods of Number object--toFixed(), toExponential() and toPrecision()](http://www.codewars.com/kata/57256064856584bc47000611) - [#16: Methods of String object--slice(), substring() and substr()](http://www.codewars.com/kata/57274562c8dcebe77e001012) - [#17: Methods of String object--indexOf(), lastIndexOf() and search()](http://www.codewars.com/kata/57277a31e5e51450a4000010) - [#18: Methods of String object--concat() split() and its good friend join()](http://www.codewars.com/kata/57280481e8118511f7000ffa) - [#19: Methods of String object--toUpperCase() toLowerCase() and replace()](http://www.codewars.com/kata/5728203b7fc662a4c4000ef3) - [#20: Methods of String object--charAt() charCodeAt() and fromCharCode()](http://www.codewars.com/kata/57284d23e81185ae6200162a) - [#21: Methods of String object--trim() and the string template](http://www.codewars.com/kata/5729b103dd8bac11a900119e) - [#22: Unlock new skills--Arrow function,spread operator and deconstruction](http://www.codewars.com/kata/572ab0cfa3af384df7000ff8) - [#23: methods of arrayObject---push(), pop(), shift() and unshift()](http://www.codewars.com/kata/572af273a3af3836660014a1) - [#24: methods of arrayObject---splice() and slice()](http://www.codewars.com/kata/572cb264362806af46000793) - [#25: methods of arrayObject---reverse() and sort()](http://www.codewars.com/kata/572df796914b5ba27c000c90) - [#26: methods of arrayObject---map()](http://www.codewars.com/kata/572fdeb4380bb703fc00002c) - [#27: methods of arrayObject---filter()](http://www.codewars.com/kata/573023c81add650b84000429) - [#28: methods of arrayObject---every() and some()](http://www.codewars.com/kata/57308546bd9f0987c2000d07) - [#29: methods of arrayObject---concat() and join()](http://www.codewars.com/kata/5731861d05d14d6f50000626) - [#30: methods of arrayObject---reduce() and reduceRight()](http://www.codewars.com/kata/573156709a231dcec9000ee8) - [#31: methods of arrayObject---isArray() indexOf() and toString()](http://www.codewars.com/kata/5732b0351eb838d03300101d) - [#32: methods of Math---round() ceil() and floor()](http://www.codewars.com/kata/5732d3c9791aafb0e4001236) - [#33: methods of Math---max() min() and abs()](http://www.codewars.com/kata/5733d6c2d780e20173000baa) - [#34: methods of Math---pow() sqrt() and cbrt()](http://www.codewars.com/kata/5733f948d780e27df6000e33) - [#35: methods of Math---log() and its family](http://www.codewars.com/kata/57353de879ccaeb9f8000564) - [#36: methods of Math---kata author's lover:random()](http://www.codewars.com/kata/5735956413c2054a680009ec) - [#37: Unlock new weapon---RegExp Object](http://www.codewars.com/kata/5735e39313c205fe39001173) - [#38: Regular Expression--"^","$", "." and test()](http://www.codewars.com/kata/573975d3ac3eec695b0013e0) - [#39: Regular Expression--"?", "*", "+" and "{}"](http://www.codewars.com/kata/573bca07dffc1aa693000139) - [#40: Regular Expression--"|", "[]" and "()"](http://www.codewars.com/kata/573d11c48b97c0ad970002d4) - [#41: Regular Expression--"\"](http://www.codewars.com/kata/573e6831e3201f6a9b000971) - [#42: Regular Expression--(?:), (?=) and (?!)](http://www.codewars.com/kata/573fb9223f9793e485000453)
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 this part, it is just for JS ``` ```javascript //a normal function: function plus(a,b){ return a+b; } //or we can write like this: var plus=function(a,b){ return a+b; } //now, wo can use arrow function write it: var plus=(a,b)=>a+b; ~~~~~~~~~~ ------arrow function ``` As you can see, its syntax is: ```python #ignore this part, it is just for JS ``` ```ruby #ignore this part, it is just for JS ``` ```javascript (parameters) => {statement} or expression ``` If only one parameter exists on the left side of the arrow, the bracket can be omitted. If only one expression exists on the right side of the arrow, the curly braces can also be omitted. The example below shows a function with the () and {} omitted. ```python #ignore this part, it is just for JS ``` ```ruby #ignore this part, it is just for JS ``` ```javascript var add=x=>x+1; ``` If the right side of the arrow is a complex statement, you must use curly braces: ```python #ignore this part, it is just for JS ``` ```ruby #ignore this part, it is just for JS ``` ```javascript var pushElement=(arr,el1,el2)=>{ arr.push(el1); arr.push(el2); return arr; } console.log( pushElement([1],2,3) ); //output: [ 1, 2, 3 ] ``` So far, our examples have used function assignment. However, an arrow function can also be used as a parameter to a function call, as well. When used as a parameter, the arrow function does not require a name. Let's rewrite the string.replace() example we saw from a previous training using our new skill: ```python #ignore this part, it is just for JS ``` ```ruby #ignore this part, it is just for JS ``` ```javascript var str="abababab"; console.log( str.replace(/a/g, x=>x.toUpperCase()) ); //output: AbAbAbAb ``` String.replace takes a regular expression and a function. The function is invoked on each substring matching the regex, and return the string replacement of that match. In this case, the arrow function takes the matched string as the parameter ```x```, and returns the upper cased value of ```x```. In the soon to learn the arrayObject and its methods, there are many applications on the arrow function, which is the reason we first learn the arrow function. The arrow function has more complex usage and usage restrictions, but we don't need to learn to be so deep, so we only learn the contents of the above. ## The Spread Operator The second skill is the ```spread operator```. The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected. It looks like this: ...obj. It can be used in three places: 1\. In function calls: ```python def plus(a,b,c,d,e): return a+b+c+d+e arg1=[1,2,3,4,5] arg2=[2,3] print(plus(*arg1)) #output is 15 print(plus(*arg2)) #output is 5 ``` ```ruby def plus(a,b,c,d,e) return a+b+c+d+e end arg1=[1,2,3,4,5] arg2=[2,3] puts plus(...arg1) #output is 15 puts plus(...arg2) #output is 5 ``` ```javascript function plus(a,b,c,d,e){ return a+b+c+d+e; } var arg1=[1,2,3,4,5]; var arg2=[2,3]; console.log(plus(...arg1)); console.log(plus(1,...arg2,4,5)); //output: 15 15 ``` ```...arg1``` spreads all the elements in arg1 into individual parameters to plus(). In Javascript, it's also possible to use the spread operator in the middle of a parameter list, as was done with ```...arg2```. 2\. Creating array literals (JS and Ruby): ```python #ignore this part, it is just for JS and Ruby ``` ```ruby a=[1,2,3] b=[*a,4,5] puts b #output is [ 1, 2, 3, 4, 5 ] ``` ```javascript var a=[1,2,3] var b=[...a,4,5] console.log(b); //output: [ 1, 2, 3, 4, 5 ] ``` ```...a``` spreads out the array's elements, making them individual elements in b. 3\. Used for ```deconstruction```. destructuring is also a new member of ES6. It is the third skill we learn in this training. First, let's look at a simple example of destructuring: ```python a,b=[1,2] #or [a,b]=[1,2] print a #output is 1 print b #output is 2 ``` ```ruby a,b=[1,2] puts a #output is 1 puts b #output is 2 ``` ```javascript var [a,b]=[1,2]; //the old method is var a=1,b=2; console.log(a); console.log(b); //output: 1 2 ``` Destructuring allows us to assign variables in a sentence-like form. Here's a slightly more complicated example: ```python a,b=[1,2] #or [a,b]=[1,2] #old way to swap them: #c=a; a=b; c=b b,a=[a,b] #or [b,a]=[a,b] print a #output is 2 print b #output is 1 ``` ```ruby a,b=[1,2] #old way to swap them: #c=a; a=b; c=b b,a=[a,b] puts a #output is 2 puts b #output is 1 ``` ```javascript var [a,b]=[1,2] //Exchange the values of the two variables //classic method: var c=a; //defined c to help us a=b; b=c; //deconstruction method: var [a,b]=[1,2]; [b,a]=[a,b]; console.log(a); console.log(b); //output: 2 1 ``` With destructuring, we don't need a temporary variable to help us exchange the two values. You can use the spread operator for destructuring like this: ```python #ignore this part, it is just for JS ``` ```ruby #ignore this part, it is just for JS ``` ```javascript var [a,...b]=[1,2,3,4,5]; console.log(a); console.log(b); //output: 1 [ 2, 3, 4, 5 ] ``` Please note: the spread operator must be the last variable: ```[...a,b]=[1,2,3,4,5]``` does not work. ```a``` was assigned to the first element of the array, and``` b ```was initialized with the remaining elements in the array. Javascript note: If you see an ellipse ... in the argument list in a function declaration, it is not a spread operator, it is a structure called rest parameters. The rest parameter syntax allows us to represent an indefinite number of arguments as an array, like this: ```python def plus(*num): rs=0 for x in num: rs+=x return rs print plus(1,2) #output is 3 print plus(3,4,5) #output is 12 ``` ```ruby def plus(*num) rs=0 for x in num: rs+=x return rs end puts plus(1,2) #output is 3 puts plus(3,4,5) #output is 12 ``` ```javascript function plus(...num){ var rs=0 for (x of num) rs+=x; return rs; } console.log(plus(1,2)); console.log(plus(3,4,5)); //output: 3 12 ``` The rest paramater must be the last argument in the function definition argument list. In the next example, we use a rest parameter to collect all the values passed to mul() after the first into an array. We then multiply each of them by the first parameter and return that array: ```python def mul(a,*b): b=list(b) #default type would be tuple for i in xrange(len(b)): b[i]*=a return b print mul(2,1,1,1) #output is [2,2,2] print mul(2,1,2,3,4) #output is [2,4,6,8] ``` ```ruby def mul(a,*b) for i in (0...b.length) do b[i]*=a end return b end puts mul(2,1,1,1) #output is [2,2,2] puts mul(2,1,2,3,4) #output is [2,4,6,8] ``` ```javascript function mul(a,...b){ for (var i=0;i<b.length;i++) b[i]*=a; return b; } console.log(mul(2,1,1,1)); console.log(mul(2,1,2,3,4)); //output: [2,2,2] [2,4,6,8] ``` Ok, the lesson is over. Did you get it all? Let's do a task, now. ## Task Create a function ```shuffleIt```. The function accepts two or more parameters. The first parameter arr is an array of numbers, followed by an arbitrary number of numeric arrays. Each numeric array contains two numbers, which are indices for elements in arr (the numbers will always be within bounds). For every such array, swap the elements. Try to use all your new skills: arrow functions, the spread operator, destructuring, and rest parameters. Example: ``` shuffleIt([1,2,3,4,5],[1,2]) should return [1,3,2,4,5] shuffleIt([1,2,3,4,5],[1,2],[3,4]) should return [1,3,2,5,4] shuffleIt([1,2,3,4,5],[1,2],[3,4],[2,3]) should return [1,3,5,2,4] ``` [Next training (#23 Array Methods) >>](http://www.codewars.com/kata/572af273a3af3836660014a1) ## [Series](http://github.com/myjinxin2015/Katas-list-of-Training-JS-series) ( ↑↑↑ Click the link above can get my newest kata list, Please add it to your favorites) - [#1: create your first JS function helloWorld](http://www.codewars.com/kata/571ec274b1c8d4a61c0000c8) - [#2: Basic data types--Number](http://www.codewars.com/kata/571edd157e8954bab500032d) - [#3: Basic data types--String](http://www.codewars.com/kata/571edea4b625edcb51000d8e) - [#4: Basic data types--Array](http://www.codewars.com/kata/571effabb625ed9b0600107a) - [#5: Basic data types--Object](http://www.codewars.com/kata/571f1eb77e8954a812000837) - [#6: Basic data types--Boolean and conditional statements if..else](http://www.codewars.com/kata/571f832f07363d295d001ba8) - [#7: if..else and ternary operator](http://www.codewars.com/kata/57202aefe8d6c514300001fd) - [#8: Conditional statement--switch](http://www.codewars.com/kata/572059afc2f4612825000d8a) - [#9: loop statement --while and do..while](http://www.codewars.com/kata/57216d4bcdd71175d6000560) - [#10: loop statement --for](http://www.codewars.com/kata/5721a78c283129e416000999) - [#11: loop statement --break,continue](http://www.codewars.com/kata/5721c189cdd71194c1000b9b) - [#12: loop statement --for..in and for..of](http://www.codewars.com/kata/5722b3f0bd5583cf44001000) - [#13: Number object and its properties](http://www.codewars.com/kata/5722fd3ab7162a3a4500031f) - [#14: Methods of Number object--toString() and toLocaleString()](http://www.codewars.com/kata/57238ceaef9008adc7000603) - [#15: Methods of Number object--toFixed(), toExponential() and toPrecision()](http://www.codewars.com/kata/57256064856584bc47000611) - [#16: Methods of String object--slice(), substring() and substr()](http://www.codewars.com/kata/57274562c8dcebe77e001012) - [#17: Methods of String object--indexOf(), lastIndexOf() and search()](http://www.codewars.com/kata/57277a31e5e51450a4000010) - [#18: Methods of String object--concat() split() and its good friend join()](http://www.codewars.com/kata/57280481e8118511f7000ffa) - [#19: Methods of String object--toUpperCase() toLowerCase() and replace()](http://www.codewars.com/kata/5728203b7fc662a4c4000ef3) - [#20: Methods of String object--charAt() charCodeAt() and fromCharCode()](http://www.codewars.com/kata/57284d23e81185ae6200162a) - [#21: Methods of String object--trim() and the string template](http://www.codewars.com/kata/5729b103dd8bac11a900119e) - [#22: Unlock new skills--Arrow function,spread operator and deconstruction](http://www.codewars.com/kata/572ab0cfa3af384df7000ff8) - [#23: methods of arrayObject---push(), pop(), shift() and unshift()](http://www.codewars.com/kata/572af273a3af3836660014a1) - [#24: methods of arrayObject---splice() and slice()](http://www.codewars.com/kata/572cb264362806af46000793) - [#25: methods of arrayObject---reverse() and sort()](http://www.codewars.com/kata/572df796914b5ba27c000c90) - [#26: methods of arrayObject---map()](http://www.codewars.com/kata/572fdeb4380bb703fc00002c) - [#27: methods of arrayObject---filter()](http://www.codewars.com/kata/573023c81add650b84000429) - [#28: methods of arrayObject---every() and some()](http://www.codewars.com/kata/57308546bd9f0987c2000d07) - [#29: methods of arrayObject---concat() and join()](http://www.codewars.com/kata/5731861d05d14d6f50000626) - [#30: methods of arrayObject---reduce() and reduceRight()](http://www.codewars.com/kata/573156709a231dcec9000ee8) - [#31: methods of arrayObject---isArray() indexOf() and toString()](http://www.codewars.com/kata/5732b0351eb838d03300101d) - [#32: methods of Math---round() ceil() and floor()](http://www.codewars.com/kata/5732d3c9791aafb0e4001236) - [#33: methods of Math---max() min() and abs()](http://www.codewars.com/kata/5733d6c2d780e20173000baa) - [#34: methods of Math---pow() sqrt() and cbrt()](http://www.codewars.com/kata/5733f948d780e27df6000e33) - [#35: methods of Math---log() and its family](http://www.codewars.com/kata/57353de879ccaeb9f8000564) - [#36: methods of Math---kata author's lover:random()](http://www.codewars.com/kata/5735956413c2054a680009ec) - [#37: Unlock new weapon---RegExp Object](http://www.codewars.com/kata/5735e39313c205fe39001173) - [#38: Regular Expression--"^","$", "." and test()](http://www.codewars.com/kata/573975d3ac3eec695b0013e0) - [#39: Regular Expression--"?", "*", "+" and "{}"](http://www.codewars.com/kata/573bca07dffc1aa693000139) - [#40: Regular Expression--"|", "[]" and "()"](http://www.codewars.com/kata/573d11c48b97c0ad970002d4) - [#41: Regular Expression--"\"](http://www.codewars.com/kata/573e6831e3201f6a9b000971) - [#42: Regular Expression--(?:), (?=) and (?!)](http://www.codewars.com/kata/573fb9223f9793e485000453)
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) ``` ```split()``` can divided a string into several parts by a specified separator. The result is an array of strings. The split string does not include the separator itself. One of its classic uses is to divide a sentence into an array of words: ```javascript var str="My name is John"; var words=str.split(" "); console.log(words); //output: [ 'My', 'name', 'is', 'John' ] ``` In the example above, we use the space as the separator, divide a sentence into 4 words. If we specify the second parameters, it will be like this: ```javascript var str="My name is John"; var words1=str.split(" ",3); console.log("words1:",words1); var words2=str.split(" ",5); console.log("words2:",words2); //output: words1:[ 'My', 'name', 'is' ] words2:[ 'My', 'name', 'is', 'John' ] ``` When we specify the number of fewer than 4, the result will be a specified number of strings; if the number of the partition is too many, the results will only be the same as the default results. If we use the empty string as the separator, we'll get an array of strings containing each character: ```javascript var str="My name is John"; var words=str.split(""); console.log(words); //output: [ 'M', 'y', ' ', 'n', 'a', 'm', 'e', ' ', 'i', 's', ' ', 'J', 'o', 'h', 'n' ] ``` Split can use regular expressions to split the string. But because we have not learned the use of regular expressions, so we do not have to learn this usage. ```concat()``` can merge many strings into a string like this: ```javascript var str="My".concat("name","is","John"); console.log(str); //output: MynameisJohn ``` In fact, we rarely see the actual use of ```concat()```, because we have a more simple way. that is using the ```+``` operator: ```javascript var str="My"+"name"+"is"+"John"; console.log(str); //output: MynameisJohn ``` But even using the ```+``` operator, the four words are not the perfect combination of a sentence, because there is no space separator. What should we do? Using ```join()``` is the best choice. ```join()``` is the reverse operation of the ```split()``` method. We can see a lot of code in the actual use: ```javascript var str="My name is John"; var words=str.split(" "); console.log("use split():",words); var s=words.join(" "); console.log("use join():",s); console.log("use split() and join():",str.split(" ").join(" ")) //output: use split():[ 'My', 'name', 'is', 'John' ] use join():My name is John use split() and join():My name is John ``` Ok, lesson is over. let's us do some task. ## Task Implement a function which accepts 2 arguments: `string` and `separator`. The expected algorithm: split the `string` into words by spaces, split each word into separate characters and join them back with the specified `separator`, join all the resulting "words" back into a sentence with spaces. For example: ``` splitAndMerge("My name is John", " ") == "M y n a m e i s J o h n" splitAndMerge("My name is John", "-") == "M-y n-a-m-e i-s J-o-h-n" splitAndMerge("Hello World!", ".") == "H.e.l.l.o W.o.r.l.d.!" splitAndMerge("Hello World!", ",") == "H,e,l,l,o W,o,r,l,d,!" ``` ## [Series](http://github.com/myjinxin2015/Katas-list-of-Training-JS-series) ( ↑↑↑ Click the link above can get my newest kata list, Please add it to your favorites) - [#1: create your first JS function helloWorld](http://www.codewars.com/kata/571ec274b1c8d4a61c0000c8) - [#2: Basic data types--Number](http://www.codewars.com/kata/571edd157e8954bab500032d) - [#3: Basic data types--String](http://www.codewars.com/kata/571edea4b625edcb51000d8e) - [#4: Basic data types--Array](http://www.codewars.com/kata/571effabb625ed9b0600107a) - [#5: Basic data types--Object](http://www.codewars.com/kata/571f1eb77e8954a812000837) - [#6: Basic data types--Boolean and conditional statements if..else](http://www.codewars.com/kata/571f832f07363d295d001ba8) - [#7: if..else and ternary operator](http://www.codewars.com/kata/57202aefe8d6c514300001fd) - [#8: Conditional statement--switch](http://www.codewars.com/kata/572059afc2f4612825000d8a) - [#9: loop statement --while and do..while](http://www.codewars.com/kata/57216d4bcdd71175d6000560) - [#10: loop statement --for](http://www.codewars.com/kata/5721a78c283129e416000999) - [#11: loop statement --break,continue](http://www.codewars.com/kata/5721c189cdd71194c1000b9b) - [#12: loop statement --for..in and for..of](http://www.codewars.com/kata/5722b3f0bd5583cf44001000) - [#13: Number object and its properties](http://www.codewars.com/kata/5722fd3ab7162a3a4500031f) - [#14: Methods of Number object--toString() and toLocaleString()](http://www.codewars.com/kata/57238ceaef9008adc7000603) - [#15: Methods of Number object--toFixed(), toExponential() and toPrecision()](http://www.codewars.com/kata/57256064856584bc47000611) - [#16: Methods of String object--slice(), substring() and substr()](http://www.codewars.com/kata/57274562c8dcebe77e001012) - [#17: Methods of String object--indexOf(), lastIndexOf() and search()](http://www.codewars.com/kata/57277a31e5e51450a4000010) - [#18: Methods of String object--concat() split() and its good friend join()](http://www.codewars.com/kata/57280481e8118511f7000ffa) - [#19: Methods of String object--toUpperCase() toLowerCase() and replace()](http://www.codewars.com/kata/5728203b7fc662a4c4000ef3) - [#20: Methods of String object--charAt() charCodeAt() and fromCharCode()](http://www.codewars.com/kata/57284d23e81185ae6200162a) - [#21: Methods of String object--trim() and the string template](http://www.codewars.com/kata/5729b103dd8bac11a900119e) - [#22: Unlock new skills--Arrow function,spread operator and deconstruction](http://www.codewars.com/kata/572ab0cfa3af384df7000ff8) - [#23: methods of arrayObject---push(), pop(), shift() and unshift()](http://www.codewars.com/kata/572af273a3af3836660014a1) - [#24: methods of arrayObject---splice() and slice()](http://www.codewars.com/kata/572cb264362806af46000793) - [#25: methods of arrayObject---reverse() and sort()](http://www.codewars.com/kata/572df796914b5ba27c000c90) - [#26: methods of arrayObject---map()](http://www.codewars.com/kata/572fdeb4380bb703fc00002c) - [#27: methods of arrayObject---filter()](http://www.codewars.com/kata/573023c81add650b84000429) - [#28: methods of arrayObject---every() and some()](http://www.codewars.com/kata/57308546bd9f0987c2000d07) - [#29: methods of arrayObject---concat() and join()](http://www.codewars.com/kata/5731861d05d14d6f50000626) - [#30: methods of arrayObject---reduce() and reduceRight()](http://www.codewars.com/kata/573156709a231dcec9000ee8) - [#31: methods of arrayObject---isArray() indexOf() and toString()](http://www.codewars.com/kata/5732b0351eb838d03300101d) - [#32: methods of Math---round() ceil() and floor()](http://www.codewars.com/kata/5732d3c9791aafb0e4001236) - [#33: methods of Math---max() min() and abs()](http://www.codewars.com/kata/5733d6c2d780e20173000baa) - [#34: methods of Math---pow() sqrt() and cbrt()](http://www.codewars.com/kata/5733f948d780e27df6000e33) - [#35: methods of Math---log() and its family](http://www.codewars.com/kata/57353de879ccaeb9f8000564) - [#36: methods of Math---kata author's lover:random()](http://www.codewars.com/kata/5735956413c2054a680009ec) - [#37: Unlock new weapon---RegExp Object](http://www.codewars.com/kata/5735e39313c205fe39001173) - [#38: Regular Expression--"^","$", "." and test()](http://www.codewars.com/kata/573975d3ac3eec695b0013e0) - [#39: Regular Expression--"?", "*", "+" and "{}"](http://www.codewars.com/kata/573bca07dffc1aa693000139) - [#40: Regular Expression--"|", "[]" and "()"](http://www.codewars.com/kata/573d11c48b97c0ad970002d4) - [#41: Regular Expression--"\"](http://www.codewars.com/kata/573e6831e3201f6a9b000971) - [#42: Regular Expression--(?:), (?=) and (?!)](http://www.codewars.com/kata/573fb9223f9793e485000453)
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) statementa else statementb ``` ```java if (condition) statementa else statementb ``` ```python if condition: statementa else: statementb ``` ```ruby if condition then statementa else statementb end ``` ```csharp if (condition) { doThis(); } else { doThat(); } // Note: This code is valid with or without brackets, but it is strongly recommended to use brackets. ``` It means that if the condition is true, then execute the statementa, otherwise execute the statementb. If the statementa or statementb are more than one line, you need to add `{` and `}` at the head and tail of statements in JS, to keep the same indentation on Python and to put an `end` in Ruby where it indeed ends. For example, if we want to judge whether a number is odd or even, we can write code like this: ```javascript function oddEven(n){ if (n % 2 == 1) return "odd number"; else return "even number"; } ``` ```typescript function oddEven(n: number): string { if (n % 2 == 1) return "odd number"; else return "even number"; } ``` ```coffeescript oddEven=(n)-> if (n % 2 == 1) return "odd number"; else return "even number"; ``` ```java public static string OddEven(final int n){ if (n % 2 == 1) return "odd number"; else return "even number"; } ``` ```python def odd_even(n): if n % 2: return "odd number" else: return "even number" ``` ```ruby def odd_even(n) if n % 2 then return "odd number" else return "even number" end end ``` ```csharp public static string OddEven(int n) { if (n % 2 == 0) { return "even number"; } else { return "odd number"; } } ``` If there is more than one condition to judge, we can use the compound if...else statement. For example: ```javascript function oldYoung(age){ if (age < 16) return "children" else if (age < 50) return "young man" //use "else if" if needed else return "old man" } ``` ```typescript function oldYoung(age: number): string{ if (age < 16) return "children" else if (age < 50) return "young man" //use "else if" if needed else return "old man" } ``` ```coffeescript oldYoung=(age)-> if (age < 16) return "children" else if (age < 50) return "young man" //use "else if" if needed else return "old man" ``` ```java public static string OldYoung(final int age){ if (age < 16) return "children"; else if (age < 50) return "young man"; //use "else if" if needed else return "old man"; } ``` ```python def old_young(age): if age < 16: return "children" elif age < 50: return "young man" #use "else if" if needed else: return "old man" ``` ```ruby def old_young(age): if age < 16 then return "children" elsif age < 50 return "young man" #use "else if" if needed else return "old man" end end ``` ```csharp public static string OldYoung(int age) { if (age < 16) { return "children"; } else if (age < 50) { return "young man"; } // use "else if" if needed else { return "old man"; } } ``` This function returns a different value depending on the parameter age. Looks very complicated? Well, JS and Ruby also support the ```ternary operator``` and Python has something similar too: ```javascript condition ? statementa : statementb ``` ```typescript condition ? statementa : statementb ``` ```coffeescript condition ? statementa : statementb ``` ```java condition ? statementa : statementb ``` ```python statementa if condition else statementb ``` ```ruby condition ? statementa : statementb ``` ```csharp condition ? DoThis() : DoThat(); ``` Condition and statement separated by "?", different statement separated by ":" in both Ruby and JS; in Python you put the condition in the middle of two alternatives. The two examples above can be simplified with ternary operator: ```javascript function oddEven(n){ return n%2 == 1 ? "odd number" : "even number"; } function oldYoung(age){ return age < 16 ? "children" : age < 50 ? "young man" : "old man"; } ``` ```typescript function oddEven(n: number): string { return n % 2 == 1 ? "odd number" : "even number"; } function oldYoung(age: number): string { return age < 16 ? "children" : age < 50 ? "young man" : "old man"; } ``` ```coffeescript oddEven=(n)-> return n % 2 == 1 ? "odd number" : "even number"; oldYoung=(age)-> return age < 16 ? "children" : age < 50 ? "young man" : "old man"; ``` ```java public static string OddEven(final int n){ return n % 2 == 1 ? "odd number" : "even number"; } public static string OldYoung(final int age){ return age < 16 ? "children" : age < 50 ? "young man" : "old man"; } ``` ```python def odd_even(n): return "odd number" if n % 2 else "even number" def old_young(age): return "children" if age < 16 else "young man" if age < 50 else "old man" ``` ```ruby def odd_even(n): return n % 2 == 1 ? "odd number" : "even number" end def old_young(age): return age < 16 ? "children" : age < 50 ? "young man" : "old man" end ``` ```csharp public static int OldYoung(int age) { return age < 16 ? "children" : age < 50 ? "young man" : "old man"; } ``` ## Task: Complete function `saleHotdogs`/`SaleHotDogs`/`sale_hotdogs`, function accepts 1 parameter:`n`, n is the number of hotdogs a customer will buy, different numbers have different prices (refer to the following table), return how much money will the customer spend to buy that number of hotdogs. | number of hotdogs | price per unit (cents)| |------------|-------------| |n < 5 | 100 | |n >= 5 and n < 10 | 95 | |n >= 10 | 90 | You can use if..else or ternary operator to complete it. When you have finished the work, click "Run Tests" to see if your code is working properly. In the end, click "Submit" to submit your code and pass this kata. ## [Series](http://github.com/myjinxin2015/Katas-list-of-Training-JS-series): ( ↑↑↑ Click the link above can get my newest kata list, Please add it to your favorites) - [#1: create your first JS function helloWorld](http://www.codewars.com/kata/571ec274b1c8d4a61c0000c8) - [#2: Basic data types--Number](http://www.codewars.com/kata/571edd157e8954bab500032d) - [#3: Basic data types--String](http://www.codewars.com/kata/571edea4b625edcb51000d8e) - [#4: Basic data types--Array](http://www.codewars.com/kata/571effabb625ed9b0600107a) - [#5: Basic data types--Object](http://www.codewars.com/kata/571f1eb77e8954a812000837) - [#6: Basic data types--Boolean and conditional statements if..else](http://www.codewars.com/kata/571f832f07363d295d001ba8) - [#7: if..else and ternary operator](http://www.codewars.com/kata/57202aefe8d6c514300001fd) - [#8: Conditional statement--switch](http://www.codewars.com/kata/572059afc2f4612825000d8a) - [#9: loop statement --while and do..while](http://www.codewars.com/kata/57216d4bcdd71175d6000560) - [#10: loop statement --for](http://www.codewars.com/kata/5721a78c283129e416000999) - [#11: loop statement --break,continue](http://www.codewars.com/kata/5721c189cdd71194c1000b9b) - [#12: loop statement --for..in and for..of](http://www.codewars.com/kata/5722b3f0bd5583cf44001000) - [#13: Number object and its properties](http://www.codewars.com/kata/5722fd3ab7162a3a4500031f) - [#14: Methods of Number object--toString() and toLocaleString()](http://www.codewars.com/kata/57238ceaef9008adc7000603) - [#15: Methods of Number object--toFixed(), toExponential() and toPrecision()](http://www.codewars.com/kata/57256064856584bc47000611) - [#16: Methods of String object--slice(), substring() and substr()](http://www.codewars.com/kata/57274562c8dcebe77e001012) - [#17: Methods of String object--indexOf(), lastIndexOf() and search()](http://www.codewars.com/kata/57277a31e5e51450a4000010) - [#18: Methods of String object--concat() split() and its good friend join()](http://www.codewars.com/kata/57280481e8118511f7000ffa) - [#19: Methods of String object--toUpperCase() toLowerCase() and replace()](http://www.codewars.com/kata/5728203b7fc662a4c4000ef3) - [#20: Methods of String object--charAt() charCodeAt() and fromCharCode()](http://www.codewars.com/kata/57284d23e81185ae6200162a) - [#21: Methods of String object--trim() and the string template](http://www.codewars.com/kata/5729b103dd8bac11a900119e) - [#22: Unlock new skills--Arrow function,spread operator and deconstruction](http://www.codewars.com/kata/572ab0cfa3af384df7000ff8) - [#23: methods of arrayObject---push(), pop(), shift() and unshift()](http://www.codewars.com/kata/572af273a3af3836660014a1) - [#24: methods of arrayObject---splice() and slice()](http://www.codewars.com/kata/572cb264362806af46000793) - [#25: methods of arrayObject---reverse() and sort()](http://www.codewars.com/kata/572df796914b5ba27c000c90) - [#26: methods of arrayObject---map()](http://www.codewars.com/kata/572fdeb4380bb703fc00002c) - [#27: methods of arrayObject---filter()](http://www.codewars.com/kata/573023c81add650b84000429) - [#28: methods of arrayObject---every() and some()](http://www.codewars.com/kata/57308546bd9f0987c2000d07) - [#29: methods of arrayObject---concat() and join()](http://www.codewars.com/kata/5731861d05d14d6f50000626) - [#30: methods of arrayObject---reduce() and reduceRight()](http://www.codewars.com/kata/573156709a231dcec9000ee8) - [#31: methods of arrayObject---isArray() indexOf() and toString()](http://www.codewars.com/kata/5732b0351eb838d03300101d) - [#32: methods of Math---round() ceil() and floor()](http://www.codewars.com/kata/5732d3c9791aafb0e4001236) - [#33: methods of Math---max() min() and abs()](http://www.codewars.com/kata/5733d6c2d780e20173000baa) - [#34: methods of Math---pow() sqrt() and cbrt()](http://www.codewars.com/kata/5733f948d780e27df6000e33) - [#35: methods of Math---log() and its family](http://www.codewars.com/kata/57353de879ccaeb9f8000564) - [#36: methods of Math---kata author's lover:random()](http://www.codewars.com/kata/5735956413c2054a680009ec) - [#37: Unlock new weapon---RegExp Object](http://www.codewars.com/kata/5735e39313c205fe39001173) - [#38: Regular Expression--"^","$", "." and test()](http://www.codewars.com/kata/573975d3ac3eec695b0013e0) - [#39: Regular Expression--"?", "*", "+" and "{}"](http://www.codewars.com/kata/573bca07dffc1aa693000139) - [#40: Regular Expression--"|", "[]" and "()"](http://www.codewars.com/kata/573d11c48b97c0ad970002d4) - [#41: Regular Expression--"\"](http://www.codewars.com/kata/573e6831e3201f6a9b000971) - [#42: Regular Expression--(?:), (?=) and (?!)](http://www.codewars.com/kata/573fb9223f9793e485000453)
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. Each argument is a two-element array of integers representing the point's X and Y coordinates. Output should be in the same format, giving the X and Y coordinates of point P1. You do not have to validate the input. This kata was inspired by the Hackerrank challenge [Find Point](https://www.hackerrank.com/challenges/find-point)
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 simply how the society was at the time. Freud then wanted to study the illnesses created by this, and so he digged to the root of their desires. This led to some of the most important psychoanalytic theories to this day, Freud being the father of psychoanalysis. Now, basically, when a person hears about Freud, s/he hears *"sex"* because for Freud, everything was related to, and explained by sex. In this kata, the function will take a string as its argument, and return a string with every word replaced by the explanation to everything, according to Freud. Note that an empty string, or no arguments, should return an empty string.
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 ```hotpo``` that takes a positive ```n``` as input and returns the number of times you need to perform this algorithm to get ```n = 1```. #Examples ``` hotpo(1) returns 0 (1 is already 1) hotpo(5) returns 5 5 -> 16 -> 8 -> 4 -> 2 -> 1 hotpo(6) returns 8 6 -> 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 hotpo(23) returns 15 23 -> 70 -> 35 -> 106 -> 53 -> 160 -> 80 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 ``` #References - Collatz conjecture wikipedia page: https://en.wikipedia.org/wiki/Collatz_conjecture
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 of the sleigh, which takes the name of the person, who wants to board the sleigh and a secret password. If, and only if, the name equals "Santa Claus" and the password is "Ho Ho Ho!" *(yes, even Santa has a secret password with uppercase and lowercase letters and special characters :D)*, the return value must be `true`. Otherwise it should return `false`. Examples: ```javascript var sleigh = new Sleigh(); sleigh.authenticate("Santa Claus", "Ho Ho Ho!"); // must return TRUE sleigh.authenticate("Santa", "Ho Ho Ho!"); // must return FALSE sleigh.authenticate("Santa Claus", "Ho Ho!"); // must return FALSE sleigh.authenticate("jhoffner", "CodeWars"); // Nope, even Jake is not allowed to use the sleigh ;) ``` ```python sleigh = Sleigh() sleigh.authenticate('Santa Claus', 'Ho Ho Ho!') # must return True sleigh.authenticate('Santa', 'Ho Ho Ho!') # must return False sleigh.authenticate('Santa Claus', 'Ho Ho!') # must return False sleigh.authenticate('jhoffner', 'CodeWars') # Nope, even Jake is not allowed to use the sleigh ;) ``` ```haskell authenticate "Santa Claus" "Ho Ho Ho!" -- True authenticate "Santa" "Ho Ho Ho!" -- False authenticate "Santa Claus" "Ho Ho!" -- False authenticate "jhoffner" "CodeWars" -- False ``` ```elixir authenticate? "Santa Claus", "Ho Ho Ho!" #=> true authenticate? "Santa", "Ho Ho Ho!" #=> false authenticate? "Santa Claus", "Ho Ho!" #=> false authenticate? "jhoffner", "CodeWars" #=> false ``` ```java sleigh.authenticate("Santa Claus", "Ho Ho Ho!") # must return True sleigh.authenticate("Santa', 'Ho Ho Ho!") # must return False sleigh.authenticate("Santa Claus", "Ho Ho!") # must return False sleigh.authenticate("jhoffner", "CodeWars") # Nope, even Jak ```
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 three = always(3) three() /* returns 3 */ ``` ```haskell let three = always 3 three () -- returns 3 ``` ```clojure (def three (always 3)) (three) ;; returns 3 ``` ```elixir three = always(3) three.() #=> 3 ``` ```cpp function<int (void)> three = always(3); three(); // returns 3 ``` ```csharp Func<int> three = Kata.Always(3); three(); // returns 3 ```
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" remove("!!!Hi !!hi!!! !hi",1) === "!!Hi !!hi!!! !hi" remove("!!!Hi !!hi!!! !hi",3) === "Hi !!hi!!! !hi" remove("!!!Hi !!hi!!! !hi",5) === "Hi hi!!! !hi" remove("!!!Hi !!hi!!! !hi",100) === "Hi hi hi" ```
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 a row of lamps, currently off, each represented by `x`. When these lamps are on, they should be represented by `o`. The `drone` string represents the position of the drone `T` (any better suggestion for character??) and its flight path up until this point `=`. The drone always flies left to right, and always begins at the start of the row of lamps. Anywhere the drone has flown, including its current position, will result in the lamp at that position switching on. Return the resulting `lamps` string. See example tests for more clarity.
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 in your solution should be left-aligned.
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, 16, 19</br></br> You have to write a function that determine if a number is Evil of Odious, function should return "It's Evil!" in case of evil number and "It's Odious!" in case of odious number. good luck :)
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 often the case, return 'Fail!'. The sub arrays may not be the same length. The solution should be case insensitive (ie good, GOOD and gOOd all count as a good idea). All inputs may not be strings.
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. Replaced with archive.org link. <img src="http://weknowmemes.com/wp-content/uploads/2014/08/age-range-compatibility-equation.jpg" style="width: 400px;"/> --> <img src="http://web.archive.org/web/20190206114947if_/http://weknowmemes.com/wp-content/uploads/2014/08/age-range-compatibility-equation.jpg" style="width: 400px;"/> ```minimum age <= your age <= maximum age``` ## Task Given an integer (1 <= n <= 100) representing a person's age, return their minimum and maximum age range. This equation doesn't work when the age <= 14, so use this equation instead: ``` min = age - 0.10 * age max = age + 0.10 * age ``` You should floor all your answers so that an integer is given instead of a float (which doesn't represent age). ```Return your answer in the form [min]-[max]``` ##Examples: ``` age = 27 => 20-40 age = 5 => 4-5 age = 17 => 15-20 ```
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 function should return nil in Clojure and Elixir, Nothing in Haskell, undefined in JavaScript, None in Python. ```clojure (next-item (range 1 10000) 7) ;=> 8 (next-item ["Joe" "Bob" "Sally"] "Bob") ;=> "Sally" ``` ```haskell next 7 [1..10000] -- Just 8 next "Bob" ["Joe", "Bob", "Sally"] -- Just "Sally" ``` ```javascript nextItem([1, 2, 3, 4, 5, 6, 7], 3) # 4 nextItem("testing", "t") # "e" ``` ```elixir next_item([1, 2, 3, 4, 5, 6, 7], 3) #=> 4 next_item(["Joe" "Bob" "Sally"], "Bob") #=> "Sally" ``` ```rust next_item([1, 2, 3, 4, 5, 6, 7], 3) //=> 4 next_item(["Joe" "Bob" "Sally"], "Bob") //=> "Sally" ``` ```python next_item([1, 2, 3, 4, 5, 6, 7], 3) # => 4 next_item(['Joe', 'Bob', 'Sally'], 'Bob') # => "Sally" ```
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’ve been told. I’ll go and get some stock. Alan: Yeah, chicken stock. Phil: Hello Alan. Alan: Lynn, hand me an apple pie. And remove yourself from the theatre of conflict. Lynn: What do you mean? Alan: Go and stand by the yakults. The temperature inside this apple turnover is 1,000 degrees. If I squeeze it, a jet of molten Bramley apple is going to squirt out. Could go your way, could go mine. Either way, one of us is going down. ``` Alan is known for referring to the temperature of the apple turnover as `Hotter than the sun!`. According to <a href="http://www.space.com/17137-how-hot-is-the-sun.html">space.com</a> the temperature of the sun's corona is 2,000,000 degrees Celsius, but we will ignore the science for now. # Task Your job is simple, if `x` squared is more than 1000, return `It's hotter than the sun!!`, else, return `Help yourself to a honeycomb Yorkie for the glovebox.` **Note: Input will either be a positive integer (or a string for untyped languages).** # Other katas in this series: <a href="https://www.codewars.com/kata/alan-partridge-i-partridge-watch">Alan Partridge I - Partridge Watch</a><br> <a href="https://www.codewars.com/kata/alan-partridge-iii-london">Alan Partridge III - London</a>
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 return the right statement depending on the winner! If the winner is George Saint Pierre he will obviously say: - "I am not impressed by your performance." If the winner is Conor McGregor he will most undoubtedly say: - "I'd like to take this chance to apologize.. To absolutely NOBODY!" Good Luck! ## Note The given name may varies in casing, eg., it can be "George Saint Pierre" or "geOrGe saiNT pieRRE". Your solution should treat both as the same thing (case-insensitive).
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 each type of food with the following names: - `sandwiches` - `salads` - `wraps` - `frenchFries` Create a variable named `totalPrice` that finds the cost of all of the food.
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` - `candy` - `chips` - `soda` - `change`
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 the output buffer you should write to. You may assume the output buffer is large enough to hold the result. Return the output buffer. ~~~
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 have an ascribed ‘age’ of 0. Return a new array (a tuple in Python) with [youngest age, oldest age, difference between the youngest and oldest age].
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 separated by spaces. If the input string is empty or the removal of the first and last items would cause the resulting string to be empty, return an empty value (represented as a generic value `NULL` in the examples below). ## Examples ``` "1,2,3" => "2" "1,2,3,4" => "2 3" "1,2,3,4,5" => "2 3 4" "" => NULL "1" => NULL "1,2" => NULL ```
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 to meet the strict character count requirements of the Kata. (no more than 161) **You may assume that all array elements are unique.**
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 method to return the cats name + meows. e.g. <code>'Mr Whiskers meows.'</code> The name attribute is passed with this.name (JS), @name (Ruby) or self.name (Python). Reference: [JS](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), [Ruby](http://rubylearning.com/satishtalim/ruby_inheritance.html), [Python](https://docs.python.org/2/tutorial/classes.html#inheritance).
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 remote control has exactly one button, with the following behaviour. + If the door is closed, a push starts opening the door, and vice-versa + It takes 5 seconds for the door to open or close completely + While the door is moving, one push pauses movement, another push resumes movement in the same direction In order to make the door safer, it has been equipped with resistance-based obstacle detection. When the door detects an obstacle, it must immediately reverse the direction of movement. # Input A string where each character represents one second, with the following possible values. * ```'.'``` No event * ```'P'``` Button has been pressed * ```'O'``` Obstacle has been detected (supersedes P) As an example, ```'..P....'``` means that nothing happens for two seconds, then the button is pressed, then no further events. # Output A string where each character represents one second and indicates the position of the door (0 if fully closed and 5 fully open). The door starts moving immediately, hence its position changes at the same second as the event. # Example ```..P...O.....``` as input should yield ```001234321000``` as output
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(str(state)) return '' . join(out)
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() #doesn't work yet ``` Use method prototypes to enable all Dogs to 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'] -- => 'z' ``` ```clojure (last [1, 2, 3, 4]) ; => 4 (last "xyz") ; => \z ``` ```javascript last([1, 2, 3, 4] ) // => 4 last("xyz") // => "z" last(1, 2, 3, 4) // => 4 ``` ```java last(Arrays.asList(1, 2, 3, 4)); // => 4 last("xyz"); // => "z" last(1, 2, 3, 4); // => 4 last(new int[]{1, 2, 3, 4}); // => 4 ``` ```coffeescript last [1, 2, 3, 4] # => 4 last "xyz" # => "z" last 1, 2, 3, 4 # => 4 ``` ```rust last(&[1, 2, 3, 4]) // => 4 last(&['x', 'y', 'z']) // => 'z' ``` In **javascript** and **CoffeeScript** a **list** will be an `array`, a `string` or the list of `arguments`. (courtesy of [haskell.org](http://www.haskell.org/haskellwiki/99_questions/1_to_10))
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', 'Arizona' ``` This example will return the string `Hello, John Smith! Welcome to Phoenix, Arizona!`
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 on these two numbers. ```if-not:csharp if the variables are not numbers or the sign does not belong to the list above a message "unknown value" must be returned. ``` ```if:csharp If the sign is not a valid sign, throw an ArgumentException. ``` # Example: ```javascript calculator(1,2,"+"); //=> result will be 3 calculator(1,2,"&"); //=> result will be "unknown value" calculator(1,"k","*"); //=> result will be "unknown value" ``` ```php calculator(1, 2, "+"); // 3 calculator(1, 2, "&"); // "unknown value" calculator(1, "k", "*"); // "unknown value" ``` ```csharp Kata.Calculator(1, 2, '+') => 3 Kata.Calculator(1, 2, '$') // throws ArgumentException ``` ```python calculator(1, 2, '+') => 3 calculator(1, 2, '$') # result will be "unknown value" ``` Good luck!
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 truth with his massive biceps, and it automatically becomes false. Your task is to be more like Chuck (ha! good luck!). You must return false without ever actually using the word false... Go show some truth who's boss!
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 battle: ```javascript anyArrows([{range: 5}, {range: 10, damaged: true}, {damaged: true}]) ``` ```python anyArrows([{'range': 5}, {'range': 10, 'damaged': True}, {'damaged': True}]) ``` ```ruby anyArrows([{range=> 5}, {range=> 10, damaged=> true}, {damaged=> true}]) ``` ```elixir any_arrows?([%{"range" => 5}, %{"range" => 10, "damaged" => true}, %{"damaged" => true}]) ``` If an arrow in the quiver does not have a damaged status, it means it's new. The expected result is a boolean, indicating whether you have any good arrows left. Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
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 For `upSpeed = 100, downSpeed = 10 and desiredHeight = 910`, the output should be `10`. ``` After day 1 --> 100 After night 1 --> 90 After day 2 --> 190 After night 2 --> 180 After day 3 --> 280 After night 3 --> 270 After day 4 --> 370 After night 4 --> 360 After day 5 --> 460 After night 5 --> 450 After day 6 --> 550 After night 6 --> 540 After day 7 --> 640 After night 7 --> 630 After day 8 --> 730 After night 8 --> 720 After day 9 --> 820 After night 9 --> 810 After day 10 --> 910 ``` For `upSpeed = 10, downSpeed = 9 and desiredHeight = 4`, the output should be `1`. Because the plant reach to the desired height at day 1(10 meters). ``` After day 1 --> 10 ``` ### Input/Output ```if-not:sql - `[input]` integer `upSpeed` A positive integer representing the daily growth. Constraints: `5 ≤ upSpeed ≤ 100.` - `[input]` integer `downSpeed` A positive integer representing the nightly decline. Constraints: `2 ≤ downSpeed < upSpeed.` - `[input]` integer `desiredHeight` A positive integer representing the threshold. Constraints: `4 ≤ desiredHeight ≤ 1000.` - `[output]` an integer The number of days that it will take for the plant to reach/pass desiredHeight (including the last day in the total count). ``` ```if:sql ## Input ~~~ ----------------------------------------- | Table | Column | Type | |---------------+----------------+------| | growing_plant | down_speed | int | | | up_speed | int | | | desired_height | int | ----------------------------------------- ~~~ ### Columns * `up_speed`: A positive integer representing the daily growth. Constraints: `5 ≤ up_speed ≤ 100.` * `down_speed`: A positive integer representing the nightly decline. Constraints: `2 ≤ down_speed < up_speed.` * `desired_height`: A positive integer representing the threshold. Constraints: `4 ≤ desired_height ≤ 1000.` ## Output ~~~ ------------------- | Column | Type | |----------+------| | id | int | | num_days | int | ------------------- ~~~ `num_days` is the number of days that it will take for the plant to reach/pass desiredHeight (including the last day in the total count). ```
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`; For `n = 91`, the output should be `2`. # Input/Output - `[input]` integer `n` Constraints: 5 ≤ n ≤ 10<sup>9</sup>. - `[output]` an integer
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 needs to cope with the second task, sorting the original array arr, and it's giving him trouble since he modified it. Given the array `shuffled`, consisting of elements a<sub>1</sub>, a<sub>2</sub>, ..., a<sub>n</sub>, and their sumvalue in random order, return the sorted array of original elements a<sub>1</sub>, a<sub>2</sub>, ..., a<sub>n</sub>. ## Example For `shuffled = [1, 12, 3, 6, 2]`, the output should be `[1, 2, 3, 6]`. `1 + 3 + 6 + 2 = 12`, which means that 1, 3, 6 and 2 are original elements of the array. For `shuffled = [1, -3, -5, 7, 2]`, the output should be `[-5, -3, 2, 7]`. ## Input/Output - `[input]` integer array `shuffled` Array of at least two integers. It is guaranteed that there is an index i such that shuffled[i] = shuffled[0] + ... + shuffled[i - 1] + shuffled[i + 1] + ... + shuffled[n]. Constraints: `2 ≤ shuffled.length ≤ 30,` `-300 ≤ shuffled[i] ≤ 300.` - `[output]` an integer array A `sorted` array of shuffled.length - 1 elements.
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` `1000 ≤ year ≤ 9000` - `[output]` an integer the minimum year number that is strictly larger than the input number `year` and all its digits are distinct.
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 ∩ B) / #(A ∪ B)`, where `#(C)` is the number of elements in C, `∩` is intersection of arrays, `∪` is union of arrays. This is known as `Jaccard similarity`. The result is guaranteed to fit any floating-point type without rounding. # Example For `a = [1, 2, 4, 6, 7]` and `b = [2, 3, 4, 7]`: ``` elements [2, 4, 7] are present in both arrays; elements [1, 2, 3, 4, 6, 7] are present in at least one of the arrays. So the similarity equals to 3 / 6 = 0.5.``` # Input/Output - `[input]` integer array `a` A `sorted` array of positive integers. All elements are `different` and are `less than 100`. `1 ≤ a.length ≤ 100` - `[input]` integer array `b` An array in the same format as `a`. - `[output]` a float number The similarity of the arrays. ```Haskell In Haskell the two arrays are passed as a touple. ```
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 numbers A range of numbers starting from `start` and increasing by `step` ```javascript const range = (n, start, step) => ??? range(6, 3, 2) // [3, 5, 7, 9, 11, 13] ``` ## ...random numbers A bunch of random integers between `min` and `max` ```javascript const random = (n, min, max) => ??? random(4, 5, 10) // [5, 9, 10, 7] ``` ## ...prime numbers All primes starting from `2` (obviously)... ```javascript const primes = n => ??? primes(6) // [2, 3, 5, 7, 11, 13] ``` HOTE: All the above functions should take as their first parameter a number that determines the length of the returned array.
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), n) def primes(n): return list(accumulate(range(2, n + 2), func=lambda p, _: next_prime(p)))
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 **12** is the first abundant number. Its proper divisors are 1, 2, 3, 4 and 6 for a total of **16**. The amount by which the sum exceeds the number is the **abundance**. The number **12** has an abundance of **4**, for example. Other initial abundant numbers are : 12, 18, 20, 24, 30, 36, 40, 42, 48, 54 etc . **Infinitely** many **odd** and **even** abundant numbers exist. As you should have guessed by now, in this kata your function will take a positive integer **h** as range input and return a nested array/list that will contain the following informations- * Highest available **odd** or **even** abundant number in that range * It's **abundance** Examples -------- A few examples never hurt nobody, right??? ```rust abundant(15) = [[12], [4]] abundant(19) = [[18], [3]] abundant(100) = [[100], [17]] abundant(999) = [[996], [360]] ``` Tips ---- The problem involves some pretty big random numbers. So try to optimize your code for performance as far as you can. And yes, the input argument will always be positive integers. So no need to check there. Good luck!
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 sorted on Twisted-3-7. 7 Examples from a friend from Twisted-3-7: ``` [1,2,3,4,5,6,7,8,9] -> [1,2,7,4,5,6,3,8,9] [12,13,14] -> [12,14,13] [9,2,4,7,3] -> [2,7,4,3,9] ``` There is no need for a precheck. The array will always be not null and will always contain at least one number. You should not modify the input array! Have fun coding it and please don't forget to vote and rank this kata! :-) I have also created other katas. Take a look if you enjoyed this kata!
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 arguments are not of equal length. ```javascript addArrays([1,2],[4,5]); // => [5,7] addArrays([1,2,3],[4,5]); // => Error ``` Note: Expect array input to either contain numbers or strings only The function should also allow for concatenating string ```javascript addArrays(["a"],["b"]) // => ["ab"] ```
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 to your pc and we'll see! <br> Write a function: `simplify`, that takes a string in input, representing a *multilinear non-constant polynomial in integers coefficients* (like `"3x-zx+2xy-x"`), and returns another string as output where the same expression has been simplified in the following way ( `->` means application of `simplify`): - All possible sums and subtraction of equivalent monomials ("xy==yx") has been done, e.g.:<br> <p>`"cb+cba" -> "bc+abc"`, `"2xy-yx" -> "xy"`, `"-a+5ab+3a-c-2a" -> "-c+5ab"` <br><br> - All monomials appears in order of increasing number of variables, e.g.:<br> <p>`"-abc+3a+2ac" -> "3a+2ac-abc"`, `"xyz-xz" -> "-xz+xyz"` <br><br> - If two monomials have the same number of variables, they appears in <a href="https://en.wikipedia.org/wiki/Lexicographical_order">lexicographic order</a>, e.g.:<br> <p>`"a+ca-ab" -> "a-ab+ac"`, `"xzy+zby" ->"byz+xyz"` <br><br> - There is no leading `+` sign if the first coefficient is positive, e.g.:<br> <p>`"-y+x" -> "x-y"`, but no restrictions for `-`: `"y-x" ->"-x+y"` --- __N.B.__ to keep it simplest, the string in input is restricted to represent only *multilinear non-constant polynomials*, so you won't find something like `-3+yx^2'. **Multilinear** means in this context: **of degree 1 on each variable**. **Warning**: the string in input can contain arbitrary variables represented by lowercase characters in the english alphabet. __Good Work :)__
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 comparison) expanded = [[int(i[0] + (i[1] if i[1] != "" else "1")), '' . join(sorted(i[2]))] for i in matches] # get the unique variables from above list. Sort them first by length, then alphabetically variables = sorted( list(set(i[1] for i in expanded)), key=lambda x: (len(x), x)) # get the sum of coefficients (located in expanded) for each variable coefficients = {v: sum(i[0] for i in expanded if i[1] == v) for v in variables} # clean-up: join them with + signs, remove '1' coefficients, and change '+-' to '-' return '+' . join(str(coefficients[v]) + v for v in variables if coefficients[v] != 0). replace('1', ''). replace('+-', '-')
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 elements in any way, or their values. Consider all of the pairs of numbers in the array where the first one is less than or equal to the second one. From these, find a pair where their positions in the array are farthest apart. Return the difference between the indexes of the two array elements in this pair. -------------------- *Example*: ``` [ 1, 2, 3] returns 2 because here j = 2 and i = 0 and 2 - 0 = 2 ```
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 senator, nor which bottle of wine is poisoned, and the poison is completely indiscernible. However, the King has 10 lab rats. He decides to use them as taste testers to determine which bottle of wine contains the poison. The poison when taken has no effect on the rats, until exactly 24 hours later when the infected rats suddenly die. The King needs to determine which bottle of wine is poisoned by tomorrow, so that the festivities can continue as planned. Hence he only has time for one round of testing, he decides that each rat tastes multiple bottles, according to a certain scheme. ## Your Task You receive an array of integers (`0 to 9`), each of them is the number of a rat which died after tasting the wine bottles. Return the number of the bottle (`1..1000`) which is poisoned. **Good Luck!** *Hint: think of rats as a certain representation of the number of the bottle...*
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> or <code>[[6,3], [2,5]]</code> etc <ol> <li><code>[[2,5], [3,6]]</code> is NOT the same as <code>[[2,3], [5,6]]</code></li> <li>Two empty arrays <code>[]</code> are the same</li> <li><code>[[2,5], [5,2]]</code> is the same as <code>[[2,5], [2,5]]</code> but NOT the same as </code>[[2,5]]</code></li> <li><code>[[2,5], [3,5], [6,2]]</code> is the same as <code>[[2,6], [5,3], [2,5]]</code> or <code>[[3,5], [6,2], [5,2]]</code>, etc</li> <li>An array can be empty or contain a minimun of one array of 2 integers and up to 100 array of 2 integers </li> </ol> Note:<br> 1. [[]] is not applicable because if the array of array are to contain anything, there have to be two numbers.<br> 2. 100 randomly generated tests that can contains either "same" or "not same" arrays.
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 a list of strings (or array of symbols in Ruby) using the pattern mapping below (e. g. `['fib', 'pad', 'pel']` means take the next fibonacci, then the next padovan, then the next pell number and so on). 2. When `n` is 0 or `p` is empty return an empty list. 3. If `n` is more than the length of `p` repeat the pattern. ### Examples ``` 0 1 2 3 4 ----------+------------------ fibonacci:| 0, 1, 1, 2, 3 ... padovan: | 1, 0, 0, 1, 0 ... pell: | 0, 1, 2, 5, 12 ... pattern = ['fib', 'pad', 'pel'] n = 6 # ['fib', 'pad', 'pel', 'fib', 'pad', 'pel'] # result = [fibonacci(0), padovan(0), pell(0), fibonacci(1), padovan(1), pell(1)] result = [0, 1, 0, 1, 0, 1] pattern = ['fib', 'fib', 'pel'] n = 6 # ['fib', 'fib', 'pel', 'fib', 'fib', 'pel'] # result = [fibonacci(0), fibonacci(1), pell(0), fibonacci(2), fibonacci(3), pell(1)] result = [0, 1, 0, 1, 2, 1] ``` ### Sequences * [fibonacci](https://oeis.org/A000045) : 0, 1, 1, 2, 3 ... * [padovan](https://oeis.org/A000931): 1, 0, 0, 1, 0 ... * [jacobsthal](https://oeis.org/A001045): 0, 1, 1, 3, 5 ... * [pell](https://oeis.org/A000129): 0, 1, 2, 5, 12 ... * [tribonacci](https://oeis.org/A000073): 0, 0, 1, 1, 2 ... * [tetranacci](https://oeis.org/A000078): 0, 0, 0, 1, 1 ... ### Pattern mapping * `'fib'` -> fibonacci * `'pad'` -> padovan * `'jac'` -> jacobstahl * `'pel'` -> pell * `'tri'` -> tribonacci * `'tet'` -> tetranacci If you like this kata, check out the [zozonacci](https://www.codewars.com/kata/5b7c80094a6aca207000004d) sequence.
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]), 'pel': nacci([0, 1], [0, 1, 1]), 'tri': nacci([0, 0, 1], [0, 1, 2]), 'tet': nacci([0, 0, 0, 1], [0, 1, 2, 3]), } return pattern and [next(sequences[pattern[i % len(pattern)]]) for i in range(length)]
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.wikipedia.org/wiki/Alan_Turing) - the father of computing - formulated and developed concepts that are the basis of all computers in use today, he did this in response to the vital need to break those military communications. Turing and his colleagues at [Bletchley Park](http://en.wikipedia.org/wiki/Bletchley_Park) are generally recognised as being responsible for shortening WWII by two years and saving an estimated 22 Million lives. The Enigma Machine consisted of a number of parts: Keyboard for input, rotors and plugboard for enciphering, and lampboard for output. We will simulate input and output with strings, and build the rotors, plugboard and mechanism that used them in software. As we progress the code will become more complex, so you are advised to attempt them in order. Step 1: The [plugboard](http://en.wikipedia.org/wiki/Enigma_machine#Plugboard) In this Kata, you must implement the plugboard. ### Physical Description The plugboard crosswired the 26 letters of the latin alphabet togther, so that an input into one letter could generate output as another letter. If a wire was not present, then the input letter was unchanged. Each plugboard came with a maximum of 10 wires, so at least six letters were not cross-wired. For example: * If a wire connects `A` to `B`, then an `A` input will generate a `B` output and a `B` input will generate an `A` output. * If no wire connects to `C`, then only a `C` input will generate a `C` output. ### Note In the actual usage of the original Enigma Machine, punctuation was encoded as words transmitted in the stream, in our code, anything that is not in the range A-Z will be returned unchanged. ### Kata The `Plugboard` class you will implement, will: 1. Take a list of wire pairs at construction in the form of a string, with a default behaviour of no wires configured. E.g. `"ABCD"` would wire `A` <-> `B` and `C` <-> `D`. 2. Validate that the wire pairings are legitimate. Raise an exception if not. 3. Implement the `process` method to translate a single character input into an output. ~~~if:haskell ### Haskell remarks Since Haskell doesn't have classes, `plugboard` is a function that either returns a `Char -> Char` function for processing, or an error message. ~~~ --- ## Examples ```python plugboard = Plugboard("ABCDEFGHIJKLMNOPQRST") plugboard.process("A") ==> "B" plugboard.process("B") ==> "A" plugboard.process("X") ==> "X" plugboard.process(".") ==> "." ``` ```javascript var plugboard = Plugboard("ABCDEFGHIJKLMNOPQRST") plugboard.process("A") ==> "B" plugboard.process("B") ==> "A" plugboard.process("X") ==> "X" plugboard.process(".") ==> "." ``` ```java Plugboard plugboard = new Plugboard("ABCDEFGHIJKLMNOPQRST"); plugboard.process("A") ==> "B" plugboard.process("B") ==> "A" plugboard.process("X") ==> "X" plugboard.process(".") ==> "." ``` ```haskell let (Right process) = plugboard "ABCDEFGHIJKLMNOPQRST" in map process "ABX." `shouldBe` "BAX." ``` ```csharp var plugboard = new Plugboard("ABCDEFGHIJKLMNOPQRST"); plugboard.process('A') ==> "B" plugboard.process('B') ==> "A" plugboard.process('X') ==> "X" plugboard.process('.') ==> "." ``` ```coffeescript plugboard = Plugboard("ABCDEFGHIJKLMNOPQRST") console.log( plugboard.process("A") ) console.log( plugboard.process("B") ) console.log( plugboard.process("X") ) console.log( plugboard.process(".") ) ```
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) == len(set(wiring)), "Duplicate letter(s) in wiring" assert len(wiring) <= 20, "Wiring must consist of no more than 10 wires" self . plugboard = {} for (a, b) in zip(wiring[0:: 2], wiring[1:: 2]): self . plugboard[a] = b self . plugboard[b] = a def process(self, c): return self . plugboard . get(c, c)
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 every other digit, scanning **from right to left**, starting from the second digit (from the right). Another way to think about it is: if there are an **even** number of digits, double every other digit starting with the **first**; if there are an **odd** number of digits, double every other digit starting with the **second**: ``` 1714 ==> [1*, 7, 1*, 4] ==> [2, 7, 2, 4] 12345 ==> [1, 2*, 3, 4*, 5] ==> [1, 4, 3, 8, 5] 891 ==> [8, 9*, 1] ==> [8, 18, 1] ``` * If a resulting number is greater than `9`, replace it with the sum of its own digits (which is the same as subtracting `9` from it): ``` [8, 18*, 1] ==> [8, (1+8), 1] ==> [8, 9, 1] or: [8, 18*, 1] ==> [8, (18-9), 1] ==> [8, 9, 1] ``` * Sum all of the final digits: ``` [8, 9, 1] ==> 8 + 9 + 1 = 18 ``` * Finally, take that sum and divide it by `10`. If the remainder equals zero, the original credit card number is valid. ``` 18 (modulus) 10 ==> 8 , which is not equal to 0, so this is not a valid credit card number ``` ```if:fsharp,csharp For F# and C# users: The input will be a string of spaces and digits `0..9` ```
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), which is narcissistic: ``` 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153 ``` and 1652 (4 digits), which isn't: ``` 1^4 + 6^4 + 5^4 + 2^4 = 1 + 1296 + 625 + 16 = 1938 ``` The Challenge: Your code must return **true** or **false** (not 'true' and 'false') depending upon whether the given number is a Narcissistic number in base 10. ```if-not:swift This may be **True** and **False** in your language, e.g. PHP. ``` Error checking for text strings or other invalid inputs is not required, only valid positive non-zero integers will be passed into the function.
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) # should return 1*3 + 2*4 + 3*5 = 26 a.norm() # should return sqrt(1^2 + 2^2 + 3^2) = sqrt(14) a.add(c) # throws an error ``` ```javascript var a = new Vector([1, 2, 3]); var b = new Vector([3, 4, 5]); var 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); // should return 1*3 + 2*4 + 3*5 = 26 a.norm(); // should return sqrt(1^2 + 2^2 + 3^2) = sqrt(14) a.add(c); // throws an error ``` ```python a = Vector([1, 2, 3]) b = Vector([3, 4, 5]) c = 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) # should return 1*3 + 2*4 + 3*5 = 26 a.norm() # should return sqrt(1^2 + 2^2 + 3^2) = sqrt(14) a.add(c) # raises an exception ``` If you try to add, subtract, or dot two vectors with different lengths, ***you must throw an error***! Also provide: - a `toString` method, so that using the vectors from above, `a.toString() === '(1,2,3)'` (in Python, this is a `__str__` method, so that `str(a) == '(1,2,3)'`) - an `equals` method, to check that two vectors that have the same components are equal **Note:** the test cases will utilize the user-provided `equals` method.
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): return self . math(other, operator . add) def subtract(self, other): return self . math(other, operator . sub) def dot(self, other): return sum(self . math(other, operator . mul)) def norm(self): return self . dot(self) * * 0.5 def equals(self, other): return self == other
Vector class
526dad7f8c0eb5c4640000a4
[ "Object-oriented Programming", "Algorithms", "Linear Algebra" ]
https://www.codewars.com/kata/526dad7f8c0eb5c4640000a4
5 kyu