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 |
---|---|---|---|---|---|---|---|
The function must return the sequence of titles that match the string passed as an argument.
```if:javascript
TITLES is a preloaded sequence of strings.
```
```javascript
TITLES = ['Rocky 1', 'Rocky 2', 'My Little Poney']
search('ock') --> ['Rocky 1', 'Rocky 2']
```
```python
titles = ['Rocky 1', 'Rocky 2', 'My Little Poney']
search(titles, 'ock') --> ['Rocky 1', 'Rocky 2']
```
But the function return some weird result and skip some of the matching results.
Does the function have special movie taste?
Let's figure out ! | bug_fixes | def search(titles, term):
return list(filter(lambda title: term in title . lower(), titles))
| Breaking search bad | 52cd53948d673a6e66000576 | [
"Regular Expressions",
"Debugging"
] | https://www.codewars.com/kata/52cd53948d673a6e66000576 | 6 kyu |
Dear Coder,
We at [SomeLargeCompany] have decided to expand on the functionality of our online text editor.
We have written a new function that accepts a phrase, a word and an array of indexes.
We want this function to return the phrase, with the word inserted at each of the indexes given by the array.
However, our current function only gets the first insertion right, but all of the following ones are out of place!
Please fix this for us, and you will be showered with money.
Yours Sincerely,
[SomeLargeCompany]
Note :
- the indicies are always in range and passed as a sorted array
- note if the index array is empty, just return the initial phrase | bug_fixes | def insert_at_indexes(phrase, word, indexes):
for i in indexes[:: - 1]:
phrase = phrase[: i] + word + phrase[i:]
return phrase
| Inserting multiple strings into another string | 52f3eeb274c7e693a600288e | [
"Strings",
"Debugging"
] | https://www.codewars.com/kata/52f3eeb274c7e693a600288e | 6 kyu |
<h1 id="heading">Debug the functions</h1>
<i>Should be easy, begin by looking at the code. Debug the code and the functions should work.</i>
<i>There are three functions: ```Multiplication (x)``` ```Addition (+)``` and ```Reverse (!esreveR)```</i>
<style>
i {
font-size:16px;
}
#heading {
padding: 2em;
text-align: center;
background-color: #0033FF;
width: 100%;
height: 5em;
}
</style> | bug_fixes | from functools import reduce
from operator import mul
def multi(l_st):
return reduce(mul, l_st)
def add(l_st):
return sum(l_st)
def reverse(s):
return s[:: - 1]
| Debug the functions EASY | 5844a422cbd2279a0c000281 | [
"Debugging"
] | https://www.codewars.com/kata/5844a422cbd2279a0c000281 | 7 kyu |
<h1>Reducing Problems - Bug Fixing #8</h1>
<p>
Oh no! Timmy's reduce is causing problems, Timmy's goal is to calculate the two teams scores and return the winner but timmy has gotten confused and sometimes teams don't enter their scores, total the scores out of 3! Help timmy fix his program!
Return true if team 1 wins or false if team 2 wins!
</p>
<br><br><br><br>
<select id="collectionSelect"/>
<iframe style="visibility:hidden;display:none;" onload="
(function(e){
var COLLECTION = 'https://www.codewars.com/collections/bug-fixing';
var qCode = String.fromCharCode(34);
function ioa(str, f) {
var a=[],i=-1;
while((i=str.indexOf(f,i+1)) >= 0) a.push(i);
return a;
}
function fc(op,cl) {
var arr=[], d=0;
op = op.map(a => {return {i:a,q:'<'};});
cl = cl.map(a => {return {i:a,q:'>'};});
var cmb = [].concat(op,cl).sort((a,b) =>a.i-b.i);
for(var i=0;i<cmb.length-1;i++) {
d += cmb[i].q === '<' ? 1 : -1;
if(d === 0 || (i > 2 && d === 2))
return cmb[i].i;
}
return -1;
}
function processKataData(data) {
var kataData = {};
var inx1 = data.indexOf('data-title='+qCode)+12;
var kataTitle = data.slice(inx1).slice(0,data.slice(inx1).indexOf(qCode))
var inx2 = data.indexOf('href='+qCode)+6;
var kataLink = data.slice(inx2).slice(0,data.slice(inx2).indexOf(qCode))
kataData.title = kataTitle;
kataData.link = kataLink;
return kataData;
}
function processData(msg) {
var data = msg.split('\n');
var dindex = data.slice(7,8).join('').indexOf('<div class='+qCode+'nine columns prn'+qCode+'>');
var filteredData = data.slice(7,8).join('').split('').filter((a,i) => i>=dindex).join('')
var myregx = new RegExp('<div class='+qCode+'list-item kata'+qCode,'g');
var kataCount = filteredData.match(myregx).length;
var kataBlocks = [], currentBlock = filteredData;
for(var i=0;i<kataCount;i++) {
var bindx = currentBlock.indexOf('<div class='+qCode+'list-item kata'+qCode+''),
block = currentBlock.slice(bindx),
closingBlock = fc(ioa(block, '<div').slice(0,10),ioa(block, '</div').slice(0,10)),
kataData = block.slice(0,closingBlock).replace(/(<)/g,'[').replace(/(>)/g,']');
kataBlocks.push(kataData);
currentBlock = block.slice(closingBlock+3);
}
var kataDatas = kataBlocks.map(processKataData);
return kataDatas;
}
function getData() {
$.ajax({
type: 'GET',
url: COLLECTION,
headers: {
Host: 'www.codewars.com',
Accept: 'text/html, */*; q=0.01',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate, br',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-PJAX': 'true',
'X-PJAX-Container': 'body',
'X-Requested-With': 'XMLHttpRequest',
Referer: 'https://www.codewars.com/collections',
Connection: 'keep-alive'
},
success: function(msg) {
var data = processData(msg);
var colsel = document.getElementById('collectionSelect');
for(var i=0;i<data.length;i++) {
var option = document.createElement('option');
option.text = data[i].title;
option.value = data[i].link
colsel.add(option);
}
function onchanging(e) {
alert(e);
}
colsel.addEventListener(
'change',
function(e) {
var options = colsel.options;
if(colsel.selectedIndex < options.length) {
var selected = options[colsel.selectedIndex];
if(selected) {
console.log(selected.value);
window.location.href = 'https://www.codewars.com' + selected.value;
}
}
},
false
);
}
});
}
getData();
})(this)" /> | bug_fixes | def calculate_total(team1, team2):
return sum(team1) > sum(team2)
| Reducing Problems - Bug Fixing #8 | 55d2603d506a40e162000056 | [
"Debugging",
"Arrays"
] | https://www.codewars.com/kata/55d2603d506a40e162000056 | 7 kyu |
Here we have a function that help us spam our hearty laughter. But is not working! I need you to find out why...
Expected results:
```javascript
spam(1); // hue
spam(6); // huehuehuehuehuehue
spam(14); // huehuehuehuehuehuehuehuehuehuehuehuehuehue
```
```php
spam(1); // 'hue'
spam(6); // 'huehuehuehuehuehue'
spam(14); // 'huehuehuehuehuehuehuehuehuehuehuehuehuehue'
```
```haskell
spam 1 -- hue
spam 6 -- huehuehuehuehuehue
spam 14 -- huehuehuehuehuehuehuehuehuehuehuehuehuehue
```
```ruby
spam(1) # "hue"
spam(6) # "huehuehuehuehuehue"
spam(14) # "huehuehuehuehuehuehuehuehuehuehuehuehuehue"
```
```python
spam(1) ==> "hue"
spam(6) ==> "huehuehuehuehuehue"
spam(14) ==> "huehuehuehuehuehuehuehuehuehuehuehuehuehue"
```
```csharp
Kata.Spam(1) => "hue";
Kata.Spam(6) => "huehuehuehuehuehue";
Kata.Spam(14) => "huehuehuehuehuehuehuehuehuehuehuehuehuehue";
``` | bug_fixes | # fix this code!
def spam(number):
return 'hue' * number
| Multiply characters | 52e9aa89b5acdd26d3000127 | [
"Strings",
"Fundamentals",
"Debugging"
] | https://www.codewars.com/kata/52e9aa89b5acdd26d3000127 | 7 kyu |
**Debug** a function called calculate that takes 3 values. The first and third values are numbers. The second value is a character. If the character is "+" , "-", "\*", or "/", the function will return the result of the corresponding mathematical function on the two numbers. If the string is not one of the specified characters, the function should return null.
```
calculate(2,"+", 4); //Should return 6
calculate(6,"-", 1.5); //Should return 4.5
calculate(-4,"*", 8); //Should return -32
calculate(49,"/", -7); //Should return -7
calculate(8,"m", 2); //Should return null
calculate(4,"/",0) //should return null
```
Kind of a fork (not steal :)) of [Basic Calculator][1] kata by [TheDoctor][2].
[1]: http://www.codewars.com/kata/basic-calculator/javascript
[2]: http://www.codewars.com/users/528c45adbd9daa384300068d | bug_fixes | def calculate(a, o, b):
if o == "+":
return a + b
if o == "-":
return a - b
if o == "*":
return a * b
if o == "/" and b != 0:
return a / b
# one-liner
# return [a+b, a-b, a*b, a/b if b else None, None]["+-*/".find(o)]
| Debug Basic Calculator | 56368f37d464c0a43c00007f | [
"Fundamentals",
"Debugging"
] | https://www.codewars.com/kata/56368f37d464c0a43c00007f | 7 kyu |
<h1>Failed Sort - Bug Fixing #4</h1>
Oh no, Timmy's Sort doesn't seem to be working? Your task is to fix the sortArray function to sort all numbers in ascending order
| bug_fixes | def sort_array(value):
return "" . join(sorted(value))
| Failed Sort - Bug Fixing #4 | 55c7f90ac8025ebee1000062 | [
"Debugging",
"Sorting"
] | https://www.codewars.com/kata/55c7f90ac8025ebee1000062 | 7 kyu |
# Class conundrum - Bug Fixing #7
Oh no! Timmy's `List` class has broken! Can you help Timmy and fix his class? Timmy has a `List` class he has created, this is used for type strict arrays (which Timmy calls Lists).
When Timmy calls the `count` property of the list it still remains at `0` when adding items.
Also it fails when Timmy tries to chain the adds e.g.
```javascript <!-- this needs to remain on top -->
myList.add(0).add(1)
```
```python
my_list.add(0).add(1)
```
```ruby
my_list.add(0).add(1)
``` | bug_fixes | class List:
def __init__(self, list_type):
self . type = list_type
self . items = []
self . count = 0
def add(self, item):
if type(item) != self . type:
return "This item is not of type: {}" . format(self . type . __name__)
self . items += [item]
self . count += 1
return self
| Class conundrum - Bug Fixing #7 | 55cd4ce59382498cbd000080 | [
"Debugging"
] | https://www.codewars.com/kata/55cd4ce59382498cbd000080 | 7 kyu |
You have an award-winning garden and every day the plants need exactly 40mm of water. You created a great piece of JavaScript to calculate the amount of water your plants will need when you have taken into consideration the amount of rain water that is forecast for the day. Your jealous neighbour hacked your computer and filled your code with bugs.
Your task is to debug the code before your plants die!
| reference | def rain_amount(mm):
if mm < 40:
return "You need to give your plant " + str(40 - mm) + "mm of water"
else:
return "Your plant has had more than enough water for today!"
| Fix your code before the garden dies! | 57158fb92ad763bb180004e7 | [
"Fundamentals",
"Debugging"
] | https://www.codewars.com/kata/57158fb92ad763bb180004e7 | 8 kyu |
Here is a piece of code:
```javascript
function getStatus(isBusy) {
var msg = (isBusy ? "busy" : "available");
return
{
status: msg
}
}
```
```python
def get_status(is_busy):
status = "busy" if is_busy else "available"
return status
```
```ruby
def get_status(is_busy)
status = is_busy ? "busy" : "available"
return status
end
```
```java
public class Kata {
public static HashMap <String, String> getStatus(boolean isBusy) {
HashMap<String, String> status;
if (isBusy) {
status = "busy";
} else {
status = "available";
}
return status;
}
}
```
## Expected Behaviour
Function should return a dictionary/Object/Hash with `"status"` as a key, whose value can : `"busy"` or `"available"` depending on the truth value of the argument `is_busy`.
But as you will see after clicking `RUN` or `ATTEMPT` this code has several bugs, please fix them.
| bug_fixes | def get_status(is_busy):
status = "busy" if is_busy else "available"
return {"status": status}
| Unexpected parsing | 54fdaa4a50f167b5c000005f | [
"Debugging"
] | https://www.codewars.com/kata/54fdaa4a50f167b5c000005f | 8 kyu |
Jack really likes his number five: the trick here is that you have to multiply each number by 5 raised to the number of digits of each numbers, so, for example:
```
3 --> 15 ( 3 * 5¹)
10 --> 250 ( 10 * 5²)
200 --> 25000 (200 * 5³)
0 --> 0 ( 0 * 5¹)
-3 --> -15 ( -3 * 5¹)
``` | reference | def multiply(n):
return n * 5 * * len(str(abs(n)))
| Multiply the number | 5708f682c69b48047b000e07 | [
"Fundamentals"
] | https://www.codewars.com/kata/5708f682c69b48047b000e07 | 8 kyu |
# Fix the Bugs (Syntax) - My First Kata
## Overview
Hello, this is my first Kata so forgive me if it is of poor quality.
In this Kata you should fix/create a program that ```return```s the following values:
- ```false/False``` if either a or b (or both) are not numbers
- ```a % b``` plus ```b % a``` if both arguments are numbers
You may assume the following:
1. If ```a``` and ```b``` are both numbers, neither of ```a``` or ```b``` will be ```0```.
## Language-Specific Instructions
### Javascript and PHP
In this Kata you should try to fix all the syntax errors found in the code.
Once you think all the bugs are fixed run the code to see if it works. A correct solution should return the values specified in the overview.
**Extension: Once you have fixed all the syntax errors present in the code (basic requirement), you may attempt to optimise the code or try a different approach by coding it from scratch.** | bug_fixes | def my_first_kata(a, b):
# your code here
if type(a) == int and type(b) == int:
return a % b + b % a
else:
return False
| Fix the Bugs (Syntax) - My First Kata | 56aed32a154d33a1f3000018 | [
"Debugging"
] | https://www.codewars.com/kata/56aed32a154d33a1f3000018 | 8 kyu |
Some new animals have arrived at the zoo. The zoo keeper is concerned that perhaps the animals do not have the right tails. To help her, you must correct the broken function to make sure that the second argument (tail), is the same as the last letter of the first argument (body) - otherwise the tail wouldn't fit!
If the tail is right return true, else return false.
The arguments will always be non empty strings, and normal letters.
| bug_fixes | def correct_tail(body, tail):
return body . endswith(tail)
| Is this my tail? | 56f695399400f5d9ef000af5 | [
"Debugging"
] | https://www.codewars.com/kata/56f695399400f5d9ef000af5 | 8 kyu |
We want an array, but not just any old array, an array with contents!
Write a function that produces an array with the numbers `0` to `N-1` in it.
For example, the following code will result in an array containing the numbers `0` to `4`:
```
arr(5) // => [0,1,2,3,4]
```
Note: The parameter is optional. So you have to give it a default value.
| reference | def arr(n=0):
return list(range(n))
| Filling an array (part 1) | 571d42206414b103dc0006a1 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/571d42206414b103dc0006a1 | 8 kyu |
Your boss decided to save money by purchasing some cut-rate optical character recognition software for scanning in the text of old novels to your database. At first it seems to capture words okay, but you quickly notice that it throws in a lot of numbers at random places in the text.
### Examples (input -> output)
```
'! !' -> '! !'
'123456789' -> ''
'This looks5 grea8t!' -> 'This looks great!'
```
Your harried co-workers are looking to you for a solution to take this garbled text and remove all of the numbers. Your program will take in a string and clean out all numeric characters, and return a string with spacing and special characters `~#$%^&!@*():;"'.,?` all intact.
| reference | def string_clean(s):
return '' . join(x for x in s if not x . isdigit())
| String cleaning | 57e1e61ba396b3727c000251 | [
"Regular Expressions",
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/57e1e61ba396b3727c000251 | 8 kyu |
The number ```$89$``` is the first integer with more than one digit that fulfills the property partially introduced in the title of this kata.
What's the use of saying "Eureka"? Because this sum gives the same number: ```$89 = 8^1 + 9^2$```
The next number in having this property is ```$135$```:
See this property again: ```$135 = 1^1 + 3^2 + 5^3$```
## Task ##
We need a function to collect these numbers, that may receive two integers ```$a$```, ```$b$``` that defines the range ```$[a, b]$``` (inclusive) and outputs a list of the sorted numbers in the range that fulfills the property described above.
## Examples ##
Let's see some cases (input -> output):
```
1, 10 --> [1, 2, 3, 4, 5, 6, 7, 8, 9]
1, 100 --> [1, 2, 3, 4, 5, 6, 7, 8, 9, 89]
```
If there are no numbers of this kind in the range `$[a, b]$` the function should output an empty list.
```
90, 100 --> []
```
Enjoy it!!
| reference | def dig_pow(n):
return sum(int(x) * * y for y, x in enumerate(str(n), 1))
def sum_dig_pow(a, b):
return [x for x in range(a, b + 1) if x == dig_pow(x)]
| Take a Number And Sum Its Digits Raised To The Consecutive Powers And ....¡Eureka!! | 5626b561280a42ecc50000d1 | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/5626b561280a42ecc50000d1 | 6 kyu |
You are given an *odd-length* array of integers, in which all of them are the same, except for one single number.
Complete the method which accepts such an array, and returns that single different number.
**The input array will always be valid!** (odd-length >= 3)
## Examples
```
[1, 1, 2] ==> 2
[17, 17, 3, 17, 17, 17, 17] ==> 3
``` | reference | def stray(arr):
for x in arr:
if arr . count(x) == 1:
return x
| Find the stray number | 57f609022f4d534f05000024 | [
"Fundamentals",
"Algorithms"
] | https://www.codewars.com/kata/57f609022f4d534f05000024 | 7 kyu |
```if-not:javascript,python
Write function `parseFloat` which takes an input and returns a number or `Nothing` if conversion is not possible.
```
```if:python
Write function `parse_float` which takes a string/list and returns a number or 'none' if conversion is not possible.
```
```if:javascript
Write function `parseF` which takes an input and returns a number or null if conversion is not possible. The input can be one of many different types so be aware.
``` | reference | def parse_float(string):
try:
return float(string)
except:
return None
| Parse float | 57a386117cb1f31890000039 | [
"Fundamentals"
] | https://www.codewars.com/kata/57a386117cb1f31890000039 | 8 kyu |
There are 32 letters in the Polish alphabet: 9 vowels and 23 consonants.
Your task is to change the letters with diacritics:
```
ą -> a,
ć -> c,
ę -> e,
ł -> l,
ń -> n,
ó -> o,
ś -> s,
ź -> z,
ż -> z
```
and print out the string without the use of the Polish letters.
For example:
```
"Jędrzej Błądziński" --> "Jedrzej Bladzinski"
``` | reference | def correct_polish_letters(s):
return s . translate(str . maketrans("ąćęłńóśźż", "acelnoszz"))
| Polish alphabet | 57ab2d6072292dbf7c000039 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/57ab2d6072292dbf7c000039 | 8 kyu |
Write a simple function that takes a `Date` as a parameter and returns a `Boolean` representing whether the date is today or not.
Make sure that your function does not return a false positive by only checking the day. | games | from datetime import datetime
def is_today(date):
return date . date() == datetime . today(). date()
| Is the date today | 563c13853b07a8f17c000022 | [
"Date Time",
"Puzzles"
] | https://www.codewars.com/kata/563c13853b07a8f17c000022 | 8 kyu |
Ahoy matey!
You are a leader of a small pirate crew. And you have a plan.
With the help of OOP you wish to make a pretty efficient system to identify ships with heavy booty on board!
Unfortunately for you, people weigh a lot these days, so how do you know if a ship is full of gold and not people?
You begin with writing a generic Ship class / struct:
```javascript
class Ship {
constructor(draft, crew) {
this.draft = draft
this.crew = crew
}
}
```
```python
class Ship:
def __init__(self, draft, crew):
self.draft = draft
self.crew = crew
```
```csharp
public class Ship
{
public int Draft;
public int Crew;
public Ship(int draft, int crew)
{
Draft = draft;
Crew = crew;
}
}
```
```rust
struct Ship {
draft: u32,
crew: u32,
}
```
```java
public class Ship {
private final double draft;
private final int crew;
public Ship(double draft, int crew) {
this.draft = draft;
this.crew = crew;
}
}
```
```ruby
class Ship
def initialize(draft,crew)
@draft=draft
@crew=crew
end
end
```
Every time your spies see a new ship enter the dock, they will create a new ship object based on their observations:
* draft - an estimate of the ship's weight based on how low it is in the water
* crew - the count of crew on board
```javascript
const titanic = new Ship(15, 10);
```
```python
Titanic = Ship(15, 10)
```
```csharp
Ship titanic = new Ship(15, 10);
```
```rust
let titanic = Ship {
draft : 15,
crew : 10,
};
```
```java
Ship titanic = new Ship(15, 10);
```
```ruby
titanic = Ship.new(15, 10)
```
## Task
You have access to the ship "draft" and "crew". "Draft" is the total ship weight and "crew" is the number of humans on the ship.
Each crew member adds `1.5` units to the ship draft. If after removing the weight of the crew, the draft is still more than `20`, then the ship is worth looting. Any ship weighing that much must have a lot of booty!
Add the method
```javascript
isWorthIt
```
```python
is_worth_it
```
```rust
is_worth_it(&self)
```
```csharp
IsWorthIt
```
```java
isWorthIt
```
```ruby
is_worth_it
```
to decide if the ship is worthy to loot. For example:
```javascript
titanic.isWorthIt() // return false
```
```python
Titanic.is_worth_it()
False
```
```csharp
titanic.IsWorthIt() => false
```
```rust
titanic.is_worth_it() -> false
```
```java
titanic.isWorthIt() == false
```
```ruby
titanic.is_worth_it() # false
```
Good luck and may you find GOOOLD!
| reference | class Ship:
def __init__(self, draft, crew):
self . draft = draft
self . crew = crew
# Your code here
def is_worth_it(self):
return self . draft - self . crew * 1.5 > 20
| OOP: Object Oriented Piracy | 54fe05c4762e2e3047000add | [
"Object-oriented Programming",
"Fundamentals"
] | https://www.codewars.com/kata/54fe05c4762e2e3047000add | 8 kyu |
## Task Description
You're re-designing a blog, and the blog's posts have the `Weekday Month Day, time` format for showing the date and time when a post was made, e.g., `Friday May 2, 7pm`.
You're running out of screen real estate, and on some pages you want to display a shorter format, `Weekday Month Day` that omits the time.
Write a function that takes the website date/time in its original string format and returns the shortened format.
## Input
Input will always be a string, e.g., `"Friday May 2, 7pm"`.
## Output
Output will be the shortened string, e.g., `"Friday May 2"`. | reference | def shorten_to_date(long_date):
return long_date . split(',')[0]
| Remove the time | 56b0ff16d4aa33e5bb00008e | [
"Date Time",
"Parsing",
"Fundamentals"
] | https://www.codewars.com/kata/56b0ff16d4aa33e5bb00008e | 8 kyu |
In this kata, we will make a function to test whether a period is late.
Our function will take three parameters:
last - The Date object with the date of the last period
today - The Date object with the date of the check
cycleLength - Integer representing the length of the cycle in days
Return true if the number of days passed from last to today is greater than cycleLength. Otherwise, return false. | reference | def period_is_late(last, today, cycle_length):
return (today - last). days > cycle_length
| Is your period late? | 578a8a01e9fd1549e50001f1 | [
"Fundamentals",
"Date Time"
] | https://www.codewars.com/kata/578a8a01e9fd1549e50001f1 | 8 kyu |
# Classy Classes
Basic Classes, this kata is mainly aimed at the new JS ES6 Update introducing classes
### Task
Your task is to complete this Class, the Person class has been created. You must fill in the Constructor method to accept a name as string and an age as number, complete the get Info property and getInfo method/Info getter which should return <code>johns age is 34</code>
```if:javascript
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
```
```if:csharp
Reference: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/using-properties
```
```if:python
Reference: https://docs.python.org/3/tutorial/classes.html
``` | reference | class Person:
def __init__(self, name, age):
self . name = name
self . age = age
@ property
def info(self):
return '{}s age is {}' . format(self . name, self . age)
| Classy Classes | 55a144eff5124e546400005a | [
"Fundamentals",
"Object-oriented Programming"
] | https://www.codewars.com/kata/55a144eff5124e546400005a | 8 kyu |
# Invalid Login - Bug Fixing #11
Oh NO! Timmy has moved divisions... but now he's in the field of security. Timmy, being the top coder he is, has allowed some bad code through. You must help Timmy and filter out any injected code!
## Task
Your task is simple, search the password string for any injected code (Injected code is any thing that would be used to exploit flaws in the current code, so basically anything that contains `||` or `//`) if you find any you must return `"Wrong username or password!"` because no one likes someone trying to cheat their way in!
## Preloaded
You will be given a preloaded class called `Database` with a method `login` this takes two parameters `username` and `password`. This is a generic login function which will check the database for the user it will return either `'Successfully Logged in!'` if it passes the test or `'Wrong username or password!'` if either the password is wrong or username does not exist.
## Usage
```javascript
var database = new Database();
database.login('Timmy', 'password');
```
```python
database = Database()
database.login('Timmy', 'password')
```
```ruby
database = Database.new;
database.login('Timmy', 'password')
``` | bug_fixes | def validate(username, password):
database = Database()
return database . login(username, password)
| Invalid Login - Bug Fixing #11 | 55e4c52ad58df7509c00007e | [
"Security",
"Debugging"
] | https://www.codewars.com/kata/55e4c52ad58df7509c00007e | 8 kyu |
## Terminal game turn function
You are creating a text-based terminal version of your favorite board game. In the board game, each turn has six steps that must happen in this order: roll the dice, move, combat, get coins, buy more health, and print status.
---
You are using a library (`Game.Logic` in C#) that already has the functions below. Create a function named `doTurn/DoTurn/do_turn` that calls the functions in the proper order as described in the paragraph above.
```javascript
- combat
- buyHealth
- getCoins
- printStatus
- rollDice
- move
```
```ruby
- `combat`
- `buy_health`
- `get_coins`
- `print_status`
- `roll_dice`
- `move`
```
```python
- `combat`
- `buy_health`
- `get_coins`
- `print_status`
- `roll_dice`
- `move`
```
```csharp
- Combat
- BuyHealth
- GetCoins
- PrintStatus
- RollDice
- Move
``` | reference | def do_turn():
roll_dice()
move()
combat()
get_coins()
buy_health()
print_status()
| Grasshopper - Terminal Game Turn Function | 56019d3b2c39ccde76000086 | [
"Fundamentals"
] | https://www.codewars.com/kata/56019d3b2c39ccde76000086 | 8 kyu |
A variation of determining leap years, assuming only integers are used and years can be negative and positive.
Write a function which will return the days in the year and the year entered in a string. For example:
````if:javascript
```javascript
yearDays(2000) returns "2000 has 366 days"
```
````
````if-not:javascript
```
year_days(2000) returns "2000 has 366 days"
```
````
There are a few assumptions we will accept the year 0, even though there is no year 0 in the Gregorian Calendar.
Also the basic rule for validating a leap year are as follows
Most years that can be divided evenly by 4 are leap years.
Exception: Century years are NOT leap years UNLESS they can be evenly divided by 400.
So the years 0, -64 and 2016 will return 366 days.
Whilst 1974, -10 and 666 will return 365 days.
| reference | def year_days(year):
days = 365
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
days += 1
return "%d has %d days" % (year, days)
| Days in the year | 56d6c333c9ae3fc32800070f | [
"Date Time",
"Fundamentals"
] | https://www.codewars.com/kata/56d6c333c9ae3fc32800070f | 8 kyu |
You should get and parse the html of the [codewars leaderboard page](https://www.codewars.com/users/leaderboard).
You can use `Nokogiri`(Ruby) or `BeautifulSoup`(Python) or `CheerioJS`(Javascript).
For Javascript: Return a Promise resolved with your 'Leaderboard' Object!
----
### Note: Use the Overall leaderboard table.
#### Return a 'Leaderboard' object with a position property.
```
Leaderboard#position should contain 500 'User' objects.
Leaderboard#position[i] should return the ith ranked User(1 based index).
```
#### Each User should have the following properties
```
User#name # => the user's username, not their real name
User#clan # => the user's clan, empty string if empty clan field
User#honor # => the user's honor points as an integer
```
#### Ex:
```
an_alien = leaderboard.position[3] # => #<User:0x3124da0 @name="myjinxin2015", @clan="China Changyuan", @honor=21446>
an_alien.name # => "myjinxin2015"
an_alien.clan # => "China Changyuan"
an_alien.honor # => 21446
```
| reference | from bs4 import BeautifulSoup
import requests
URL = 'https://www.codewars.com/users/leaderboard'
class solution:
class user:
def __init__(self, name, clan, honor):
self . name = name
self . clan = clan
self . honor = honor
class FuckYourIndex (list):
def __init__(self, L):
super(). __init__(L)
def __getitem__(self, i):
return list . __getitem__(self, i - 1)
def __init__(self):
SOURCE = requests . get(URL). text
soup = BeautifulSoup(SOURCE, 'html.parser')
self . position = self . FuckYourIndex(
[solution . get_user(user) for user in soup . find("tr"). next_siblings])
@ classmethod
def get_user(cls, user):
name = user['data-username']
clan, honor = (tag . text for tag in user . find(
"td", {"class", "is-big"}). next_siblings)
return cls . user(name, clan, int(honor . replace(',', '')))
| Scraping: Codewars Top 500 Users | 581c06b95cfa838603000435 | [
"Fundamentals"
] | https://www.codewars.com/kata/581c06b95cfa838603000435 | 5 kyu |
A [pernicious number](https://en.wikipedia.org/wiki/Pernicious_number) is a positive integer whose binary digit sum (or [Hamming weight](https://en.wikipedia.org/wiki/Hamming_weight)) is a prime number.
```
25 = 11001 --> digit sum = 3 --> 3 is prime --> therefore 25 is a pernicious number
75 = 1001011 --> digit sum = 4 --> 4 is not prime --> therefore 75 is not a pernicious number
```
#Task
Your job is to create a function that will list all of the pernicious numbers up to the given value (inclusive). The values given will increase in size, meaning the list will be very large.
For example:
```pernicious(5) should return [3, 5]```
```pernicious(12) should return [3, 5, 6, 7, 9, 10, 11, 12]```
If there are no pernicious numbers in the given range, your function should return "No pernicious numbers". This means when given a negative value, it should still recieve this output.
```pernicious(0) should return "No pernicious numbers"```
```pernicious(-1) should return "No pernicious numbers"```
Also, if given a floating point number, return the list of pernicious numbers with the number **floored** (rounded down).
```pernicious(17.546456) should return [3, 5, 6, 7, 9, 10, 11, 12, 13, 14, 17]```
**You will only be given integers and floats.**
Remember:
```1``` is not a prime number and ```2``` is a prime number.
| algorithms | def pernicious(n):
return [x for x in range(int(n) + 1) if bin(x). count("1") in [2, 3, 5, 7, 11, 13]] or "No pernicious numbers"
| Pernicious Numbers | 56e195d02bb22479e50016af | [
"Arrays",
"Binary",
"Algorithms"
] | https://www.codewars.com/kata/56e195d02bb22479e50016af | 7 kyu |
Who knows the nursery rhyme <a href="https://www.youtube.com/watch?v=Ak7kedzR8bg">Ten Green Bottles</a>?
Lyrics:
```
Ten green bottles hanging on the wall,
Ten green bottles hanging on the wall,
And if one green bottle should accidentally fall,
There'll be nine green bottles hanging on the wall.
Nine green bottles hanging on the wall,
Nine green bottles hanging on the wall,
And if one green bottle should accidentally fall,
There'll be eight green bottles hanging on the wall.
Eight green bottles hanging on the wall...
Seven green bottles hanging on the wall...
...
One green bottle hanging on the wall,
One green bottle hanging on the wall,
If that one green bottle should accidentally fall,
There'll be no green bottles hanging on the wall.
```
# Task
Write some amazing code to reproduce the above lyrics starting from ```n``` green bottles!
<hr>
* parameter ```n``` is 1 to 10
* newline terminates every line (including the last)
* don't forget the blank lines between the verses | algorithms | def ten_green_bottles(n):
numbers = {10: 'ten', 9: 'nine', 8: 'eight', 7: 'seven', 6: 'six', 5: 'five',
4: 'four', 3: 'three', 2: 'two', 1: 'one', 0: 'no'}
res = []
for x in range(n, 0, - 1):
s = f""" { numbers [ x ]. capitalize ()} green bottle { 's' if x > 1 else '' } hanging on the wall,
{ numbers [ x ]. capitalize ()} green bottle { 's' if x > 1 else '' } hanging on the wall,
{ 'And if' if x > 1 else "If that" } one green bottle should accidentally fall,
There'll be { numbers [ x - 1 ]} green bottle { '' if x - 1 == 1 else 's' } hanging on the wall.
"""
res . append(s)
return '\n' . join(res)
| Ten Green Bottles | 5838e2978bbc04b7cd000008 | [
"Algorithms"
] | https://www.codewars.com/kata/5838e2978bbc04b7cd000008 | 7 kyu |
Imagine you are in a universe where you can just perform the following arithematic operations. Addition(+), Subtraction(-), Multiplication(\*), Division(/). You are given given a postfix expression. Postfix expression is where operands come after operator. Each operator and operand are seperated by a space. You need to evaluate the expression.
For example: 25 45 + is equivalent of 25 + 45, hence the answer would be 70. Instead if you are given 20 40 + 60 \*, it is equivalent of (20+40) \* 60, hence the answer should be 3600. 20 40 60 + \* is equivalent of 20 \* (40 + 60) = 2000.
Create a method 'evaluate' that takes a string as input and returns a long resulted in the evaluation.
Just concentrate on happy paths.
Assume that expression is always valid and division is always an integer division.
| algorithms | def postfix_evaluator(expr):
stack = []
operators = "- + * //" . split()
for i in expr . replace("/", "//"). split():
if i in operators:
y, x = stack . pop(), stack . pop()
i = str(eval(x + i + y))
stack . append(i)
return int(stack[0])
| Evaluate a postfix expression | 577e9095d648a15b800000d4 | [
"Algorithms"
] | https://www.codewars.com/kata/577e9095d648a15b800000d4 | 5 kyu |
We define a special score for a word (ssw) as follows. We multiply the corresponding 10 - base ascii code for each letter of the word by its respective frequency of this letter in the word, we collect these addens and we sum them up.
For example for the word, ```investigation``` we have the respective ascci codes and frequencies for each letter:
```
Letter Ascii decimal code Letter Frequency (in "investigation")
i 105 3
n 110 2
t 116 2
a 97 1
e 101 1
g 103 1
o 111 1
s 115 1
v 118 1
```
So the ```ssw``` for this word will be:
```
ssw = 3 * 105 + 2 * 110 + 2 * 116 + 97 * 1 + 101 * 1 + 103 * 1 + 111 * 1 + 115 * 1 + 118 * 1 = 1412
```
We need a function ```find_word()``` (Javascript: ```findWord()```) that receives two arguments, number of letters, ```num_let``` (Javascript: ```numLet```) and a maximum special score```max_ssw``` (Javascript: ```maxSsw```) for the word.
The function will output a word from a data base of 2000 words that have the highest possible ```ssw``` of the given number of letters but smaller or equal than the given ```max_ssw```. If we have more than one word with the same number of letters, ```num_let```, and the same special score, ```ssw```, it will be chosen the last word of the list of words sorted.
You were provided with a list of 2000 words of the Oxford Dictionary Of English (U.K. English), named ```WORD_LIST``` for python, ```$word_list``` for ruby, ```wordList``` for javascript.
```python
Let's see some cases:
num_let = 8
max_ssw = 888
find_word(num_let, max_ssw) == 'southern'
/// There are three words with 8 letters and with ssw == 888
'question', 'security' and 'southern'
The list of these words sorted withe its respespective ssw is [(888, 'question'),
(888, 'security'), (888, 'southern')], 'southern' should be chosen
num_let = 9
max_ssw = 500
find_word(num_let, max_ssw) == None # in Ruby nil, in Javascript null
/// the word of 9 letters with minimum ssw is 'candidate' with ssw = 925
There are no word of 9 letters less than 500
```
We may have the case when the all the words of certain number of letters are bellow ```max_ssw```
```python
num_let = 7
max_ssw = 1412
find_word(num_let, max_ssw) == 'support'
///'support' is the word of 7 letters with highest ssw (797)
```
Enjoy it!
| reference | import itertools as it
def score(word):
return sum(ord(c) for c in word)
WORDS = sorted(sorted(WORD_LIST, key=score), key=len)
WORDS = {l: [(s, list(ws)) for s, ws in it . groupby(g, key=score)]
for l, g in it . groupby(WORDS, key=len)}
def find_word(length, max_ssw):
try:
return [words for ssw, words in WORDS[length] if ssw <= max_ssw][- 1][- 1]
except IndexError:
return None
| Special Scores For Words | 563c9f8073ccb1464d0000ae | [
"Fundamentals",
"Data Structures",
"Algorithms",
"Memoization"
] | https://www.codewars.com/kata/563c9f8073ccb1464d0000ae | 6 kyu |
The central dogma of molecular biology is that DNA is transcribed into RNA, which is then tranlsated into protein. RNA, like DNA, is a long strand of nucleic acids held together by a sugar backbone (ribose in this case). Each segment of three bases is called a <i>codon</i>. Molecular machines called ribosomes translate the RNA codons into amino acid chains, called polypeptides which are then folded into a protein.
Protein sequences are easily visualized in much the same way that DNA and RNA are, as large strings of letters. An important thing to note is that the 'Stop' codons do not encode for a specific amino acid. Their only function is to stop translation of the protein, as such they are not incorporated into the polypeptide chain. 'Stop' codons should not be in the final protein sequence. To save a you a lot of unnecessary (and boring) typing the keys and values for your amino acid dictionary are provided.
Given a string of RNA, create a funciton which translates the RNA into its protein sequence. Note: the test cases will always produce a valid string.
```python
protein('UGCGAUGAAUGGGCUCGCUCC') returns 'CDEWARS'
```
```ruby
protein('UGCGAUGAAUGGGCUCGCUCC') returns 'CDEWARS'
```
```javascript
protein('UGCGAUGAAUGGGCUCGCUCC') returns 'CDEWARS'
```
Included as test cases is a real world example! The last example test case encodes for a protein called green fluorescent protein; once spliced into the genome of another organism, proteins like GFP allow biologists to visualize cellular processes!
Amino Acid Dictionary
----------------------
```ruby
# Phenylalanine
'UUC'=>'F', 'UUU'=>'F',
# Leucine
'UUA'=>'L', 'UUG'=>'L', 'CUU'=>'L', 'CUC'=>'L','CUA'=>'L','CUG'=>'L',
# Isoleucine
'AUU'=>'I', 'AUC'=>'I', 'AUA'=>'I',
# Methionine
'AUG'=>'M',
# Valine
'GUU'=>'V', 'GUC'=>'V', 'GUA'=>'V', 'GUG'=>'V',
# Serine
'UCU'=>'S', 'UCC'=>'S', 'UCA'=>'S', 'UCG'=>'S', 'AGU'=>'S', 'AGC'=>'S',
# Proline
'CCU'=>'P', 'CCC'=>'P', 'CCA'=>'P', 'CCG'=>'P',
# Threonine
'ACU'=>'T', 'ACC'=>'T', 'ACA'=>'T', 'ACG'=>'T',
# Alanine
'GCU'=>'A', 'GCC'=>'A', 'GCA'=>'A', 'GCG'=>'A',
# Tyrosine
'UAU'=>'Y', 'UAC'=>'Y',
# Histidine
'CAU'=>'H', 'CAC'=>'H',
# Glutamine
'CAA'=>'Q', 'CAG'=>'Q',
# Asparagine
'AAU'=>'N', 'AAC'=>'N',
# Lysine
'AAA'=>'K', 'AAG'=>'K',
# Aspartic Acid
'GAU'=>'D', 'GAC'=>'D',
# Glutamic Acid
'GAA'=>'E', 'GAG'=>'E',
# Cystine
'UGU'=>'C', 'UGC'=>'C',
# Tryptophan
'UGG'=>'W',
# Arginine
'CGU'=>'R', 'CGC'=>'R', 'CGA'=>'R', 'CGG'=>'R', 'AGA'=>'R', 'AGG'=>'R',
# Glycine
'GGU'=>'G', 'GGC'=>'G', 'GGA'=>'G', 'GGG'=>'G',
# Stop codon
'UAA'=>'Stop', 'UGA'=>'Stop', 'UAG'=>'Stop'
```
```python
# Your dictionary is provided as PROTEIN_DICT
PROTEIN_DICT = {
# Phenylalanine
'UUC': 'F', 'UUU': 'F',
# Leucine
'UUA': 'L', 'UUG': 'L', 'CUU': 'L', 'CUC': 'L', 'CUA': 'L', 'CUG': 'L',
# Isoleucine
'AUU': 'I', 'AUC': 'I', 'AUA': 'I',
# Methionine
'AUG': 'M',
# Valine
'GUU': 'V', 'GUC': 'V', 'GUA': 'V', 'GUG': 'V',
# Serine
'UCU': 'S', 'UCC': 'S', 'UCA': 'S', 'UCG': 'S', 'AGU': 'S', 'AGC': 'S',
# Proline
'CCU': 'P', 'CCC': 'P', 'CCA': 'P', 'CCG': 'P',
# Threonine
'ACU': 'T', 'ACC': 'T', 'ACA': 'T', 'ACG': 'T',
# Alanine
'GCU': 'A', 'GCC': 'A', 'GCA': 'A', 'GCG': 'A',
# Tyrosine
'UAU': 'Y', 'UAC': 'Y',
# Histidine
'CAU': 'H', 'CAC': 'H',
# Glutamine
'CAA': 'Q', 'CAG': 'Q',
# Asparagine
'AAU': 'N', 'AAC': 'N',
# Lysine
'AAA': 'K', 'AAG': 'K',
# Aspartic Acid
'GAU': 'D', 'GAC': 'D',
# Glutamic Acid
'GAA': 'E', 'GAG': 'E',
# Cystine
'UGU': 'C', 'UGC': 'C',
# Tryptophan
'UGG': 'W',
# Arginine
'CGU': 'R', 'CGC': 'R', 'CGA': 'R', 'CGG': 'R', 'AGA': 'R', 'AGG': 'R',
# Glycine
'GGU': 'G', 'GGC': 'G', 'GGA': 'G', 'GGG': 'G',
# Stop codon
'UAA': 'Stop', 'UGA': 'Stop', 'UAG': 'Stop'
}
```
```javascript
// Phenylalanine
'UUC':'F', 'UUU':'F',
// Leucine
'UUA':'L', 'UUG':'L', 'CUU':'L', 'CUC':'L','CUA':'L','CUG':'L',
// Isoleucine
'AUU':'I', 'AUC':'I', 'AUA':'I',
// Methionine
'AUG':'M',
// Valine
'GUU':'V', 'GUC':'V', 'GUA':'V', 'GUG':'V',
// Serine
'UCU':'S', 'UCC':'S', 'UCA':'S', 'UCG':'S', 'AGU':'S', 'AGC':'S',
// Proline
'CCU':'P', 'CCC':'P', 'CCA':'P', 'CCG':'P',
// Threonine
'ACU':'T', 'ACC':'T', 'ACA':'T', 'ACG':'T',
// Alanine
'GCU':'A', 'GCC':'A', 'GCA':'A', 'GCG':'A',
// Tyrosine
'UAU':'Y', 'UAC':'Y',
// Histidine
'CAU':'H', 'CAC':'H',
// Glutamine
'CAA':'Q', 'CAG':'Q',
// Asparagine
'AAU':'N', 'AAC':'N',
// Lysine
'AAA':'K', 'AAG':'K',
// Aspartic Acid
'GAU':'D', 'GAC':'D',
// Glutamic Acid
'GAA':'E', 'GAG':'E',
// Cystine
'UGU':'C', 'UGC':'C',
// Tryptophan
'UGG':'W',
// Arginine
'CGU':'R', 'CGC':'R', 'CGA':'R', 'CGG':'R', 'AGA':'R', 'AGG':'R',
// Glycine
'GGU':'G', 'GGC':'G', 'GGA':'G', 'GGG':'G',
// Stop codon
'UAA':'Stop', 'UGA':'Stop', 'UAG':'Stop',
```
| reference | from itertools import takewhile
AMINO_ACID = {
# Phenylalanine
'UUC': 'F', 'UUU': 'F',
# Leucine
'UUA': 'L', 'UUG': 'L', 'CUU': 'L', 'CUC': 'L', 'CUA': 'L', 'CUG': 'L',
# Isoleucine
'AUU': 'I', 'AUC': 'I', 'AUA': 'I',
# Methionine
'AUG': 'M',
# Valine
'GUU': 'V', 'GUC': 'V', 'GUA': 'V', 'GUG': 'V',
# Serine
'UCU': 'S', 'UCC': 'S', 'UCA': 'S', 'UCG': 'S', 'AGU': 'S', 'AGC': 'S',
# Proline
'CCU': 'P', 'CCC': 'P', 'CCA': 'P', 'CCG': 'P',
# Threonine
'ACU': 'T', 'ACC': 'T', 'ACA': 'T', 'ACG': 'T',
# Alanine
'GCU': 'A', 'GCC': 'A', 'GCA': 'A', 'GCG': 'A',
# Tyrosine
'UAU': 'Y', 'UAC': 'Y',
# Histidine
'CAU': 'H', 'CAC': 'H',
# Glutamine
'CAA': 'Q', 'CAG': 'Q',
# Asparagine
'AAU': 'N', 'AAC': 'N',
# Lysine
'AAA': 'K', 'AAG': 'K',
# Aspartic Acid
'GAU': 'D', 'GAC': 'D',
# Glutamic Acid
'GAA': 'E', 'GAG': 'E',
# Cystine
'UGU': 'C', 'UGC': 'C',
# Tryptophan
'UGG': 'W',
# Arginine
'CGU': 'R', 'CGC': 'R', 'CGA': 'R', 'CGG': 'R', 'AGA': 'R', 'AGG': 'R',
# Glycine
'GGU': 'G', 'GGC': 'G', 'GGA': 'G', 'GGG': 'G',
# Stop codon
'UAA': 'Stop', 'UGA': 'Stop', 'UAG': 'Stop'
}
def protein(rna):
xs = (AMINO_ACID[rna[i: i + 3]] for i in range(0, len(rna), 3))
xs = takewhile(lambda x: x != 'Stop', xs)
return '' . join(xs)
| RNA to Protein Sequence Translation | 555a03f259e2d1788c000077 | [
"Fundamentals"
] | https://www.codewars.com/kata/555a03f259e2d1788c000077 | 6 kyu |
Base on the fairy tale [Diamonds and Toads](https://en.wikipedia.org/wiki/Diamonds_and_Toads) from Charles Perrault. In this kata you will have to complete a function that take 2 arguments:
- A string, that correspond to what the daugther says.
- A string, that tell you wich fairy the girl have met, this one can be `good` or `evil`.
The function should return the following count as a hash:
- If the girl have met the `good` fairy:
- count 1 `ruby` everytime you see a `r` and 2 everytime you see a `R`
- count 1 `crystal` everytime you see a `c` and 2 everytime you see a `C`
- If the girl have met the `evil` fairy:
- count 1 `python` everytime you see a `p` and 2 everytime uou see a `P`
- count 1 `squirrel` everytime you see a `s` and 2 everytime you see a `S`
**Note**: For this kata I decided to remplace the normal `Diamonds` and `Toads` by some programming languages. And just discover that [Squirrel](https://en.wikipedia.org/wiki/Squirrel_(programming_language) is a programming language. | reference | from collections import Counter
def diamonds_and_toads(sentence, fairy):
c = Counter(sentence)
d = {'good': ['ruby', 'crystal'], 'evil': ['python', 'squirrel']}
return {s: c[s[0]] + 2 * c[s[0]. upper()] for s in d[fairy]}
| Diamonds and Toads | 57fa537f8b0760c7da000407 | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/57fa537f8b0760c7da000407 | 6 kyu |
In genetics a reading frame is a way to divide a sequence of nucleotides (DNA bases) into a set of consecutive non-overlapping triplets (also called codon). Each of this triplets is translated into an amino-acid during a translation process to create proteins.
In a single strand of DNA you find 3 Reading frames, for example the following sequence:
```
AGGTGACACCGCAAGCCTTATATTAGC
```
will be decompose in:
```
Frame 1: AGG·TGA·CAC·CGC·AAG·CCT·TAT·ATT·AGC
Frame 2: A·GGT·GAC·ACC·GCA·AGC·CTT·ATA·TTA·GC
Frame 3: AG·GTG·ACA·CCG·CAA·GCC·TTA·TAT·TAG·C
```
In a double strand DNA you find 3 more Reading frames base on the reverse complement-strand, given the previous DNA sequence, in the reverse complement ( A-->T, G-->C, T-->A, C-->G).
Due to the splicing of DNA strands and the fixed reading direction of a nucleotide strand, the reverse complement gets read from right to left
```
AGGTGACACCGCAAGCCTTATATTAGC
Reverse complement: TCCACTGTGGCGTTCGGAATATAATCG
reversed reverse frame: GCTAATATAAGGCTTGCGGTGTCACCT
```
You have:
```
Reverse Frame 1: GCT AAT ATA AGG CTT GCG GTG TCA CCT
reverse Frame 2: G CTA ATA TAA GGC TTG CGG TGT CAC CT
reverse Frame 3: GC TAA TAT AAG GCT TGC GGT GTC ACC T
```
You can find more information about the Open Reading frame in wikipedia just [here] (https://en.wikipedia.org/wiki/Reading_frame)
Given the [standard table of genetic code](http://www.ncbi.nlm.nih.gov/Taxonomy/Utils/wprintgc.cgi#SG1):
```
AAs = FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG
Base1 = TTTTTTTTTTTTTTTTCCCCCCCCCCCCCCCCAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGG
Base2 = TTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGG
Base3 = TCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAG
```
The tri-nucleotide TTT = F, TTC = F, TTA = L...
So our 6 frames will be translate as:
```
Frame 1: AGG·TGA·CAC·CGC·AAG·CCT·TAT·ATT·AGC
R * H R K P Y I S
Frame 2: A·GGT·GAC·ACC·GCA·AGC·CTT·ATA·TTA·GC
G D T A S L I L
Frame 3: AG·GTG·ACA·CCG·CAA·GCC·TTA·TAT·TAG·C
V T P Q A L Y *
Reverse Frame 1: GCT AAT ATA AGG CTT GCG GTG TCA CCT
A N I R L A V S P
Reverse Frame 2: G CTA ATA TAA GGC TTG CGG TGT CAC CT
L I * G L R C H
Reverse Frame 3: GC TAA TAT AAG GCT TGC GGT GTC ACC T
* Y K A C G V T
```
In this kata you should create a function that translates DNA on all 6 frames, this function takes 2 arguments.
The first one is the DNA sequence the second one is an array of frame number for example if we want to translate in Frame 1 and Reverse 1 this array will be [1,-1]. Valid frames are 1, 2, 3 and -1, -2, -3.
The translation hash is available for you under a translation hash `$codons` [Ruby] or `codon` [other languages] (for example to access value of 'TTT' you should call $codons['TTT'] => 'F').
The function should return an array with all translation asked for, by default the function do the translation on all 6 frames. | algorithms | from preloaded import codons
def translate_with_frame(dna, frames=[1, 2, 3, - 1, - 2, - 3]):
rdna = dna . translate(str . maketrans('AGTC', 'TCAG'))[:: - 1]
return ['' . join(codons . get([rdna, dna][fr > 0][k: k + 3], '') for k in range(abs(fr) - 1, len(dna), 3)) for fr in frames]
| Translate DNA in 6 frames | 5708ef48fe2d018413000776 | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/5708ef48fe2d018413000776 | 5 kyu |
## Task
Give you two strings: ```s1``` and ```s2```. If they are opposite, return `true`; otherwise, return `false`. Note: The result should be a boolean value, instead of a string.
The ```opposite``` means: All letters of the two strings are the same, but the case is opposite. you can assume that the string only contains letters or it's a empty string. Also take note of the edge case - if both strings are empty then you should return `false`/`False`.
## Examples (input -> output)
```
"ab","AB" -> true
"aB","Ab" -> true
"aBcd","AbCD" -> true
"AB","Ab" -> false
"","" -> false
```
| games | def is_opposite(s1, s2):
return False if not (s1 or s2) else s1 . swapcase() == s2
| They say that only the name is long enough to attract attention. They also said that only a simple Kata will have someone to solve it. This is a sadly story #1: Are they opposite? | 574b1916a3ebd6e4fa0012e7 | [
"Puzzles",
"Games"
] | https://www.codewars.com/kata/574b1916a3ebd6e4fa0012e7 | 8 kyu |
# Task
You are given an array of integers that you want distribute between several groups. The first group should contain numbers from 1 to 10<sup>4</sup>, the second should contain those from 10<sup>4</sup> + 1 to 2 x 10<sup>4</sup>, ..., the 100<sup>th</sup> one should contain numbers from 99 x 10<sup>4</sup> + 1 to 10<sup>6</sup> and so on.
All the numbers will then be written down in groups to the text file in such a way that:
```
the groups go one after another;
each non-empty group has a header which occupies one line;
each number in a group occupies one line.
```
Calculate how many lines the resulting text file will have.
# Example
For `a = [20000, 239, 10001, 999999, 10000, 20566, 29999]`,
the output should be `11`.
The numbers can be divided into 4 groups:
239 and 10000 go to the 1st group (1 ... 10<sup>4</sup>);
10001 and 20000 go to the second 2nd (10<sup>4</sup> + 1 ... 2 x 10<sup>4</sup>);
20566 and 29999 go to the 3rd group (2 x 10<sup>4</sup> + 1 ... 3 x 10<sup>4</sup>);
groups from 4 to 99 are empty;
999999 goes to the 100<sup>th</sup> group (99 * 10<sup>4</sup> + 1 ... 10<sup>6</sup>).
Thus, there will be 4 groups (i.e. four headers) and 7 numbers,
so the file will occupy 4 + 7 = 11 lines.
The file like this:
```
1-10000:
239
10000
10001-20000:
10001
20000
20001-30000:
20566
29999
990001-1000000:
999999
```
# Input/Output
- `[input]` integer array `a`
Constraints: 1 ≤ a.length ≤ 10<sup>4</sup>, 1 ≤ a[i] ≤ 10<sup>6</sup>.
- `[output]` an integer
The number of lines needed to store the grouped numbers. | games | def numbers_grouping(a):
return len(set((n - 1) / / 10000 for n in a)) + len(a)
| Simple Fun #34: Numbers Grouping | 588711735ea0b4649e000001 | [
"Puzzles"
] | https://www.codewars.com/kata/588711735ea0b4649e000001 | 7 kyu |
# Task
`N` candles are placed in a row, some of them are initially lit. For each candle from the 1st to the Nth the following algorithm is applied: if the observed candle is lit then states of this candle and all candles before it are changed to the opposite. Which candles will remain lit after applying the algorithm to all candles in the order they are placed in the line?
# Example
For `a = [1, 1, 1, 1, 1]`, the output should be `[0, 1, 0, 1, 0].`
Check out the image below for better understanding:
<div style="background-color: white">
![](https://codefightsuserpics.s3.amazonaws.com/tasks/switchLights/img/example.png?_tm=1484040239470)
</div>
For `a = [0, 0]`, the output should be `[0, 0].`
The candles are not initially lit, so their states are not altered by the algorithm.
# Input/Output
- `[input]` integer array `a`
Initial situation - array of zeros and ones of length N, 1 means that the corresponding candle is lit.
Constraints: `2 ≤ a.length ≤ 5000.`
- `[output]` an integer array
Situation after applying the algorithm - array in the same format as input with the same length. | games | def switch_lights(initial_states):
states = list(initial_states)
parity = 0
for i in reversed(range(len(states))):
parity ^= initial_states[i]
states[i] ^= parity
return states
| Simple Fun #39: Switch Lights | 5888145122fe8620950000f0 | [
"Puzzles"
] | https://www.codewars.com/kata/5888145122fe8620950000f0 | 7 kyu |
The pair of integer numbers `(m, n)`, such that `10 > m > n > 0`, (below 10), that its sum, `(m + n)`, and rest, `(m - n)`, are perfect squares, is (5, 4).
Let's see what we have explained with numbers.
```
5 + 4 = 9 = 3²
5 - 4 = 1 = 1²
(10 > 5 > 4 > 0)
```
The pair of numbers `(m, n)`, closest to and below 50, having the property described above is `(45, 36)`.
```
45 + 36 = 81 = 9²
45 - 36 = 9 = 3²
(50 > 45 > 36 > 0)
```
With the function `closest_pair_tonum()`, that receives a number `upper_limit`, as an upper limit, we should be able to obtain the closest pair to `upper_limit`, that fulfills the property described above.
The function should return the largest pair of numbers `(m, n)`, satisfying `upper_limit > m > n > 0`. Note that we say pair A `(a0, a1)` is larger than pair B `(b0, b1)` when `a0 > b0` or `a0 == b0 and
a1 > b1`.
Let's see some cases:
```python
closest_pair_tonum(10) == (5, 4) # (m = 5, n = 4)
closest_pair_tonum(30) == (29, 20)
closest_pair_tonum(50) == (45, 36)
```
```javascript
closestPairTonum(10) == [5, 4] // (m = 5, n = 4)
closestPairTonum(30) == [29, 20]
closestPairTonum(50) == [45, 36]
```
```ruby
closest_pair_tonum(10) == [5, 4] # (m = 5, n = 4)
closest_pair_tonum(30) == [29, 20]
closest_pair_tonum(50) == [45, 36]
```
Happy coding and enjoy it!!
(We will be having a second part of a similar exercise (in some days) that will need a faster algorithm for values of `upper_limit` < 1000)
| reference | def closest_pair_tonum(uLim):
return next((a, b) for a in reversed(range(1, uLim)) for b in reversed(range(1, a))
if not (a + b) * * .5 % 1 and not (a - b) * * .5 % 1)
| The Sum and The Rest of Certain Pairs of Numbers have to be Perfect Squares | 561e1e2e6b2e78407d000011 | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/561e1e2e6b2e78407d000011 | 7 kyu |
Santa is coming to town and he needs your help finding out who's been naughty or nice. You will be given an entire year of JSON data following this format:
```javascript
{
January: {
'1': 'Naughty','2': 'Naughty', ..., '31': 'Nice'
},
February: {
'1': 'Nice','2': 'Naughty', ..., '28': 'Nice'
},
...
December: {
'1': 'Nice','2': 'Nice', ..., '31': 'Naughty'
}
}
```
Your function should return `"Naughty!"` or `"Nice!"` depending on the total number of occurrences in a given year (whichever one is greater). If both are equal, return `"Nice!"` | reference | def naughty_or_nice(data):
nice = 0
for month in data:
for day in data[month]:
nice += 1 if data[month][day] == "Nice" else - 1
return "Nice!" if nice >= 0 else "Naughty!"
| Naughty or Nice | 5662b14e0a1fb8320a00005c | [
"JSON",
"Fundamentals"
] | https://www.codewars.com/kata/5662b14e0a1fb8320a00005c | 7 kyu |
There are many word games that can help to make our minds more agile.
Many TV programs, in different countries, use them as entertainment for the audience.
Lorraine had tried to win one of them many times but she was not successful in her attempts. The TV contest is as follows:
- The TV show host gives a random caller a scrambled word (that is incomprehensible) and by rearranging those letters they have to discover a word that is in the Oxford English Dictionary.
- They have only 25 seconds to discover the word.
Her friend Bruce obtained the list of 2000, frequently used, English words used by the TV show.
Help Lorraine by making a function that will give her a list of all valid words that may be obtained by rearranging the scrambled word.
There always be at least one valid word for each test case.
Let's see some test cases:
```python
unscramble("shi") == ['his']
unscramble("nowk") == ['know']
unscramble("amle") == ['male', 'meal']
```
The list of words that Bruce obtained (keep the secret!) is named ```word_list```, in ruby ```$word_list``` and javascript ```wordList```.
For words with more than six letters we have a challenge with speed.
Try to create a suitable memoized data structure for fast hashing using the provided ```word_list```.
Remember that all the words will correspond to U.K. English (Oxford Dictionary). | reference | def unscramble(scramble):
return [i for i in word_list if sorted(i) == sorted(scramble)]
| Lorraine Wants to Win the TV Contest | 562dbaf65d4ab6685c0000ed | [
"Fundamentals",
"Algorithms",
"Data Structures"
] | https://www.codewars.com/kata/562dbaf65d4ab6685c0000ed | 7 kyu |
Your task is to write a function that takes two or more objects and returns a new object which combines all the input objects.
All input object properties will have only numeric values. Objects are combined together so that the values of matching keys are added together.
An example:
```javascript
const objA = { a: 10, b: 20, c: 30 }
const objB = { a: 3, c: 6, d: 3 }
combine(objA, objB) // Returns { a: 13, b: 20, c: 36, d: 3 }
```
```python
objA = { 'a': 10, 'b': 20, 'c': 30 }
objB = { 'a': 3, 'c': 6, 'd': 3 }
combine(objA, objB) # Returns { a: 13, b: 20, c: 36, d: 3 }
```
```ruby
objA = { 'a' => 10, 'b' => 20, 'c' => 30 }
objB = { 'a' => 3, 'c' => 6, 'd' => 3 }
combine(objA, objB) # Returns { a => 13, b => 20, c => 36, d => 3 }
```
The combine function should be a good citizen, so should not mutate the input objects. | reference | def combine(* bs):
c = {}
for b in bs:
for k, v in b . items():
c[k] = v + c . get(k, 0)
return c
| Combine objects | 56bd9e4b0d0b64eaf5000819 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/56bd9e4b0d0b64eaf5000819 | 7 kyu |
Colour plays an important role in our lifes. Most of us like this colour better then another. User experience specialists believe that certain colours have certain psychological meanings for us.
You are given a 2D array, composed of a colour and its 'common' association in each array element. The function you will write needs to return the colour as 'key' and association as its 'value'.
For example:
```javascript
var array = [["white", "goodness"], ...] //returns [{white: 'goodness'}, ...]
```
```ruby
array = [["white", "goodness"], ...] #returns [{'white'=>'goodness'}, ...]
```
```python
var array = [["white", "goodness"], ...] returns [{'white': 'goodness'}, ...]
```
| reference | def colour_association(arr):
return [{k: v} for k, v in arr]
| Colour Association | 56d6b7e43e8186c228000637 | [
"Fundamentals"
] | https://www.codewars.com/kata/56d6b7e43e8186c228000637 | 7 kyu |
In genetics 2 differents DNAs sequences can code for the same protein.
This is due to the redundancy of the genetic code, in fact 2 different tri-nucleotide can code for the same amino-acid.
For example the tri-nucleotide 'TTT' and the tri-nucleotide 'TTC' both code for the amino-acid 'F'. For more information you can take a look [here](https://en.wikipedia.org/wiki/DNA_codon_table).
Your goal in this kata is to define if two differents DNAs sequences code for exactly the same protein. Your function take the 2 sequences you should compare.
For some kind of simplicity here the sequences will respect the following rules:
- It is a full protein sequence beginning with a Start codon and finishing by an Stop codon
- It will only contain valid tri-nucleotide.
The translation hash is available for you under a translation hash `$codons` [Ruby] or `codons` [Python and JavaScript].
To better understand this kata you can take a look at this [one](https://www.codewars.com/kata/5708ef48fe2d018413000776), it can help you to start.
| algorithms | def code_for_same_protein(seq1, seq2):
return all(codons[seq1[c: c + 3]] == codons[seq2[c: c + 3]] for c in range(0, len(seq1), 3))
| 2 DNAs sequences, coding for same protein? | 57cbb9e240e3024aae000b26 | [
"Strings",
"Algorithms",
"Arrays"
] | https://www.codewars.com/kata/57cbb9e240e3024aae000b26 | 7 kyu |
Complete the method that takes a sequence of objects with two keys each: country or state, and capital. Keys may be symbols or strings.
The method should return an array of sentences declaring the state or country and its capital.
## Examples
```ruby
state_capitals = [{state: 'Maine', capital: 'Augusta'}]
capital(state_capitals)[0] # returns "The capital of Maine is Augusta"
country_capitals = [{'country' => 'Spain', 'capital' => 'Madrid'}]
capital(country_capitals)[0] # returns "The capital of Spain is Madrid"
mixed_capitals: [{"state" => 'Maine', capital: 'Augusta'}, {country: 'Spain', "capital" => "Madrid"}]
capital(mixed_capitals)[0] # returns "The capital of Maine is Augusta"
```
```javascript
state_capitals = [{state: 'Maine', capital: 'Augusta'}]
capital(state_capitals)[0] // returns "The capital of Maine is Augusta"
country_capitals = [{'country' : 'Spain', 'capital' : 'Madrid'}]
capital(country_capitals)[0] // returns "The capital of Spain is Madrid"
mixed_capitals: [{"state" : 'Maine', capital: 'Augusta'}, {country: 'Spain', "capital" : "Madrid"}]
capital(mixed_capitals)[1] // returns "The capital of Spain is Madrid"
```
```python
[{'state': 'Maine', 'capital': 'Augusta'}] --> ["The capital of Maine is Augusta"]
[{'country' : 'Spain', 'capital' : 'Madrid'}] --> ["The capital of Spain is Madrid"]
[{"state" : 'Maine', 'capital': 'Augusta'}, {'country': 'Spain', "capital" : "Madrid"}] --> ["The capital of Maine is Augusta", "The capital of Spain is Madrid"]
```
```rust
&[Capital { country: None, state: Some("Maine"), capital: "Augusta" }] -> vec!["The capital of Maine is Augusta".to_string()]
&[Capital { country: Some("Spain"), state: None, capital: "Madrid" }] -> vec!["The capital of Spain is Madrid".to_string()]
&[Capital { country: None, state: Some("Maine"), capital: "Augusta" }, Capital { country: Some("Spain"), state: None, capital: "Madrid" }] -> vec!["The capital of Maine is Augusta".to_string(), "The capital of Spain is Madrid".to_string()]
``` | reference | def capital(capitals):
return [f"The capital of { c . get ( 'state' ) or c [ 'country' ]} is { c [ 'capital' ]} " for c in capitals]
| Find the Capitals | 53573877d5493b4d6e00050c | [
"Fundamentals"
] | https://www.codewars.com/kata/53573877d5493b4d6e00050c | 7 kyu |
<p>In this finite version of <a href="http://en.wikipedia.org/wiki/Conway's_Game_of_Life">Conway's Game of Life</a> (here is an excerpt of the rules) ... </p>
<p>
<i>
The universe of the Game of Life is an infinite two-dimensional orthogonal grid of square cells, each of which is in one of two possible states, alive or dead.
Every cell interacts with its eight neighbours, which are the cells that are horizontally, vertically, or diagonally adjacent. At each step in time, the following transitions occur:
<ul>
<li>Any live cell with fewer than two live neighbours dies, as if caused by under-population.</li>
<li>Any live cell with two or three live neighbours lives on to the next generation.</li>
<li>Any live cell with more than three live neighbours dies, as if by overcrowding.</li>
<li>Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.</li>
</ul>
The initial pattern constitutes the seed of the system. The first generation is created by applying the above rules simultaneously to every cell in the seed—births and deaths occur simultaneously, and the discrete moment at which this happens is sometimes called a tick (in other words, each generation is a pure function of the preceding one)
</i>
</p>
...implement your own method which will take the initial state as an NxM array of 0's (dead cell) and 1's (living cell) and return an equally sized array representing the next generation. Cells outside the array must be considered dead.
Cells that would born out of the array boundaries should be ignored (universe never grows beyond the initial NxM grid).<br/> N.B.: for illustration purposes, 0 and 1 will be represented as ░ and ▓ blocks (PHP: basic black and white squares) respectively. You can take advantage of the 'htmlize' function to get a text representation of the universe:<br/>eg:
```javascript
console.log(htmlize(cells));
```
```python
print htmlize(cells)
```
```ruby
puts htmlize(cells)
```
```php
echo htmlize($cells) . "\r\n";
```
```julia
print(htmlize(cells))
``` | games | def next_gen(cells):
ng = Life(cells)
return ng . process(1)
class Life:
def __init__(self, cells):
self . cells = cells
self . neighbor = [(- 1, - 1), (- 1, 1), (1, 1), (1, - 1),
(0, 1), (0, - 1), (1, 0), (- 1, 0)]
self . _forLife = lambda x, y: self . _express(x, y) in (2, 3)
self . _forDead = lambda x, y: self . _express(x, y) == 3
@ property
def core(self):
return {(x, y): c for x, e in enumerate(self . cells) for y, c in enumerate(e)}
def _express(self, xc, yc):
core = self . core
return sum(self . cells[(x + xc)][(y + yc)] for x, y in self . neighbor if core . get(((x + xc), (y + yc))) != None)
def process(self, gen):
for _ in range(gen):
nextG = [e[::] for e in self . cells]
for (x, y), c in self . core . items():
nextG[x][y] = {0: self . _forDead, 1: self . _forLife}. get(c)(x, y)
self . cells = nextG
return self . cells
| Conway's Game of Life | 525fbff0594da0665c0003a3 | [
"Games",
"Graphics",
"Puzzles",
"Cellular Automata"
] | https://www.codewars.com/kata/525fbff0594da0665c0003a3 | 5 kyu |
Your task is to implement a function that calculates an election winner from a list of voter selections using an [Instant Runoff Voting](http://en.wikipedia.org/wiki/Instant-runoff_voting) algorithm. If you haven't heard of IRV, here's a basic overview (slightly altered for this kata):
- Each voter selects several candidates in order of preference.
- The votes are tallied from the each voter's first choice.
- If the first-place candidate has more than half the total votes, they win.
- Otherwise, find the candidate who got the least votes and remove them from each person's voting list.
- In case of a tie for least, remove all of the tying candidates.
- In case of a complete tie between every candidate, return nil(Ruby)/None(Python)/undefined(JS).
- Start over.
- Continue until somebody has more than half the votes; they are the winner.
Your function will be given a list of voter ballots; each ballot will be a list of candidates (symbols) in descending order of preference. You should return the symbol corresponding to the winning candidate. See the default test for an example! | algorithms | from collections import Counter
def runoff(voters):
while voters[0]:
poll = Counter(ballot[0] for ballot in voters)
winner, maxscore = max(poll . items(), key=lambda x: x[1])
minscore = min(poll . values())
if maxscore * 2 > len(voters):
return winner
voters = [[c for c in voter if poll[c] > minscore] for voter in voters]
| Instant Runoff Voting | 52996b5c99fdcb5f20000004 | [
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/52996b5c99fdcb5f20000004 | 4 kyu |
<img src=http://upload.wikimedia.org/wikipedia/commons/thumb/f/f0/Chickpea_Cakes_-_Kolkata_2011-03-24_2015.JPG/320px-Chickpea_Cakes_-_Kolkata_2011-03-24_2015.JPG>
Welcome Warrior! Let's play a game!
You've gotten challenged by a lot of kata, now it's time for you to challenge the kata!
In a room is a table with a pile of cakes. One of these cakes is poisoned. Every turn, we will take cakes from this pile and eat them, leaving the last one to be the poisoned cake. Whoever eats the poisoned cake will die. The poisoned cake is clearly marked, so you do not have to guess. Rather you need to rely on logic to save you.
<h2>The rules are simple:</h2>
1. Do not eat the last cake. It's obivious that the poisoned cake will be the last to be eaten, so, **DON'T EAT THE LAST CAKE**. Try to make your opponent eat it.
2. When it is your turn, you can only take **one**, **two** or **three** cakes. The same rules apply to your opponent on their turn. You cannot skip your move, so choose wisely how many cakes to eat. Both opponents will be able to see how many cakes the other eats on each turn.
3. You **cannot copy** your opponent's previous move; likewise they cannot copy yours. If your opponent takes one cake, next move you can only choose between two and three. If you take three cakes, your opponent can only choose one or two. This doesn't effect the first move, only subsequent ones.
4. If one of the players has no valid moves (ie. one cake left and previous move was one cake), that player will **skip** their turn. Then the **other** player will be forced to eat the last cake. This is the **ONLY** case of turn skipping.
5. You can choose whether or not to go first. This decision is key to victory, so don't hurry, choose wisely!
<h2>Task of this kata:</h2>
To solve this kata, you should write class called ``Player``. This class has one constructor and two other functions:
```javascript
class Player {
// called at the beginning of each game. Parameter: a number of cakes on the table
constructor(cakes) {
}
// called after the constructor. Must return true if you want to move first, false is you want to move after your opponent
// Parameter: number of cakes on the table left (same as in constructor)
firstmove(cakes) {
}
// called before each of your moves. First parameter: number of cakes left on the table. Second parameter: amount of cakes took by your opponent last move. Must return 1, 2 or 3 depending of how much cakes you want to take.
move(cakes, last) {
}
}
```
```typescript
class Player {
// called at the beginning of each game. Parameter: a number of cakes on the table
constructor(cakes: number) {
}
// called after the constructor. Must return true if you want to move first, false is you want to move after your opponent
// Parameter: number of cakes on the table left (same as in constructor)
firstmove(cakes: number): boolean {
}
// called before each of your moves. First parameter: number of cakes left on the table. Second parameter: amount of cakes took by your opponent last move. Must return 1, 2 or 3 depending of how much cakes you want to take.
move(cakes: number, last: number): number {
}
}
```
```coffeescript
class Player
# called at the beginning of each game. Parameter: a number of cakes on the table.
constructor: (cakes) ->
# called after the constructor.
# Parameter: number of cakes on the table left (same as in constructor).
# Must return true if you want to move first, false is you want to move after your opponent.
firstmove: (cakes) ->
# called before each of your moves.
# First parameter: number of cakes left on the table.
# Second parameter: amount of cakes took by your opponent last move.
# Must return 1, 2 or 3 depending of how much cakes you want to take.
move: (cakes, last) ->
```
```ruby
class Player
# called at the beginning of each game. Parameter: a number of cakes on the table.
def initialize(cakes)
end
# called after the constructor.
# Parameter: number of cakes on the table left (same as in constructor).
# Must return true if you want to move first, false is you want to move after your opponent.
def firstmove(cakes)
end
# called before each of your moves.
# First parameter: number of cakes left on the table.
# Second parameter: amount of cakes took by your opponent last move.
# Must return 1, 2 or 3 depending of how much cakes you want to take.
def move(cakes, last)
last == 1 ? 2 : 1 # I'm not greedy
end
end
```
```python
class Player:
# called at the beginning of each game. Parameter: a number of cakes on the table.
def __init__(self, cakes):
# called after the constructor.
# Parameter: number of cakes on the table left (same as in constructor).
# Must return true if you want to move first, false is you want to move after your opponent.
def firstmove(self, cakes):
# called before each of your moves.
# First parameter: number of cakes left on the table.
# Second parameter: amount of cakes took by your opponent last move.
# Must return 1, 2 or 3 depending of how much cakes you want to take.
def move(self, cakes, last):
```
```php
<?php
class Player
{
// Called at the beginning of each game.
// Parameter: a number of cakes on the table.
function __construct(int $cakes)
{
}
// Called after the constructor.
// Parameter: number of cakes on the table left (same as in constructor).
// Must return true if you want to move first, false is you want to move after your opponent.
public function firstmove(int $cakes): bool
{
}
// Called before each of your moves.
// First parameter: number of cakes left on the table.
// Second parameter: amount of cakes took by your opponent last move.
// Must return 1, 2 or 3 depending of how much cakes you want to take.
public function move(int $cakes, int $last): int
{
}
}
```
```java
public class Player {
Player(int cakes) {
// called at the beginning of each game. Parameter: a number of cakes on the table
}
boolean firstMove(int cakes){
// called after the constructor.
// Parameter: number of cakes on the table left (same as in constructor)
// Must return true if you want to move first, false is you want to move after your opponent
}
int move(int cakes, int last){
// called before each of your moves.
// First parameter: number of cakes left on the table.
// Second parameter: amount of cakes took by your opponent last move.
// Must return 1, 2 or 3 depending of how much cakes you want to take.
}
}
```
```haskell
-- actually, forget that class, it's useless. just define
firstMove :: Int -> Bool -- Must return True if you want to move first, False if you want to move after your opponent
-- Parameter: number of cakes initially on the table
move :: Int -> Int -> Int -- Must return 1, 2 or 3 depending on how many cakes you want to take
-- First parameter: number of cakes currently on the table
-- Second parameter: number of cakes your opponent took last move ( or 0, only for the very first move of any game )
```
Each test is a different game and different instance of the `Player` class. You should not worry about calling functions, you should only watch the number of cakes on the table and decide on every move how many to take, and decide who moves first.
Write your ``Player`` class and beat your opponent! You must figure out a strategy that can guarantee you a victory.
Your implementation should not crash or do invalid moves if used as the second player (without an option to choose the fisrt move). If you are forced to lose, do it with dignity.
<h2>Example:</h2>
```javascript
class Player {
constructor(cakes) {
// Not sure if you need one
}
// Decide who moves first - player or opponent (true if player)
firstmove(cakes) {
// I wish to move first
return true;
}
// Decide your next move
move(cakes, last) {
// I'm not greedy
return last == 1 ? 2 : 1;
}
}
```
```typescript
export class Player {
constructor(cakes: number) {
// Not sure if you need one
}
// Decide who moves first - player or opponent (true if player)
firstmove(cakes: number): boolean {
// I wish to move first
return true;
}
// Decide your next move
move(cakes: number, last: number): number {
// I'm not greedy
return last == 1 ? 2 : 1;
}
}
```
```coffeescript
class Player
constructor: (cakes) ->
# Decide who moves first - player or opponent (return true if player)
firstmove: (cakes) ->
true # I want to move first
# Decide your next move (return 1, 2 or 3)
move: (cakes, last) ->
if last is 1 then 2 else 1 # I'm not greedy
```
```ruby
class Player
# Constructor
def initialize(cakes)
end
# Decide who moves first - player or opponent (return true if player)
def firstmove(cakes)
true # I want to move first
end
# Decide your next move (return 1, 2 or 3)
def move(cakes, last)
last == 1 ? 2 : 1 # I'm not greedy
end
end
```
```python
class Player:
# Constructor
def __init__(self, cakes):
pass
# Decide who moves first
def firstmove(self, cakes):
# I wish to move first
return True
# Decide your next move
def move(self, cakes, last):
#I'm not greedy
return 1 if last != 1 else 2
```
```php
<?php
class Player
{
// Class constructor
function __construct(int $cakes)
{
// Not sure if you need one
}
// Decide who moves first - player or opponent (true if player)
public function firstmove(int $cakes): bool
{
// I wish to move first
return true;
}
// Decide your next move
public function move(int $cakes, int $last): int
{
// I'm not greedy
return $last == 1 ? 2 : 1;
}
}
```
```java
public class Player {
Player(int cakes) {
}
// Decide who moves first - player or opponent (return true if player)
boolean firstMove(int cakes) {
// I wish to move first
return true;
}
// Decide your next move (return 1, 2 or 3)
int move(int cakes, int last) {
// I'm not greedy
return last == 1 ? 2 : 1;
}
}
```
```haskell
-- Decide who moves first - player or opponent (return True if player)
firstMove :: Int -> Bool
firstMove cakes = True -- I wish to move first
-- Decide your next move (return 1, 2 or 3)
move :: Int -> Int -> Int
move cakes 1 = 2
move cakes last = 1 -- I'm not greedy
```
<h2>Example of game:</h2>
12 cakes on the table. You decide to move first.
You eat 1 cake, 11 cakes left.
Opponent eats 3 cakes, 8 cakes left.
You eat 2 cakes, 6 cakes left.
Opponent eats 1 cake, 5 cakes left.
You eat 3 cakes, 2 cakes left.
Opponent has no winning choice. If he eats 2 cakes, he will lose. If he eats 1 cake, you will be left in stalemate situation, and he will again eat 1 cake and lose.
You win. | games | from heapq import heapify, heappop, heappush
class Player:
def __init__(self, cakes):
# We will compute and store all possible states for the game
# The boolean value indicates if a victory is possible
self . states = {(1, 1): True, (1, 2): False, (1, 3): False, (2, 1): False}
# Using a heap we compute the possible states starting with final states
h = [(1, 1), (1, 2), (1, 3), (2, 1)]
heapify(h)
while h:
c, l = heappop(h)
for p in (3, 2, 1):
if p != l and c + l <= cakes:
self . states[(c + l, p)] = (not self . states[(c, l)]
) or self . states . get((c + l, p), False)
if (c + l, p) not in h:
heappush(h, (c + l, p))
# Decide who moves first
def firstmove(self, cakes):
# We move first if there is (at least) one move that makes the adversary lose
return not all([self . states[(cakes - i, i)] for i in (1, 2, 3) if cakes - i > 0])
# Decide your next move
def move(self, cakes, last):
for next in (3, 2, 1):
if next == last or cakes - next <= 0:
continue # We can't return last, nor eat the cake !
if not self . states[(cakes - next, next)]:
return next
# I'm not greedy
return 1 if last != 1 else 2
| Don't Eat the Last Cake! | 5384df88aa6fc164bb000e7d | [
"Puzzles"
] | https://www.codewars.com/kata/5384df88aa6fc164bb000e7d | 5 kyu |
Steve and Josh are bored and want to play something. They don't want to think too much, so they come up with a really simple game. Write a function called winner and figure out who is going to win.
They are dealt the same number of cards. They both flip the card on the top of their deck. Whoever has a card with higher value wins the round and gets one point (if the cards are of the same value, neither of them gets a point). After this, the two cards are discarded and they flip another card from the top of their deck. They do this until they have no cards left.
`deckSteve` and `deckJosh` are arrays representing their decks. They are filled with *cards*, represented by a single character. The card rank is as follows (from lowest to highest):
```
'2','3','4','5','6','7','8','9','T','J','Q','K','A'
```
Every card may appear in the deck more than once. Figure out who is going to win and return who wins and with what score:
* `"Steve wins x to y"` if Steve wins; where `x` is Steve's score, `y` is Josh's score;
* `"Josh wins x to y"` if Josh wins; where `x` is Josh's score, `y` is Steve's score;
* `"Tie"` if the score is tied at the end of the game.
## Example
* Steve is dealt: `['A','7','8']`
* Josh is dealt: `['K','5','9']`
1. In the first round, ace beats king and Steve gets one point.
2. In the second round, 7 beats 5 and Steve gets his second point.
3. In the third round, 9 beats 8 and Josh gets one point.
So you should return: `"Steve wins 2 to 1"`
| algorithms | def winner(deck_Steve, deck_Josh):
deck = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A']
Steve = 0
Josh = 0
for i in range(len(deck_Steve)):
if deck . index(deck_Steve[i]) > deck . index(deck_Josh[i]):
Steve += 1
elif deck . index(deck_Steve[i]) < deck . index(deck_Josh[i]):
Josh += 1
else:
continue
if Steve > Josh:
return "Steve wins " + str(Steve) + " to " + str(Josh)
elif Josh > Steve:
return "Josh wins " + str(Josh) + " to " + str(Steve)
else:
return "Tie"
| Simple card game | 53417de006654f4171000587 | [
"Arrays",
"Games",
"Algorithms"
] | https://www.codewars.com/kata/53417de006654f4171000587 | 6 kyu |
Complete the function that determines the score of a hand in the card game [Blackjack](https://en.wikipedia.org/wiki/Blackjack) (aka 21).
The function receives an array of strings that represent each card in the hand (`"2"`, `"3",` ..., `"10"`, `"J"`, `"Q"`, `"K"` or `"A"`) and should return the score of the hand (integer).
~~~if:c
Note: in C the function receives a character array with the card `10` represented by the character `T`.
~~~
### Scoring rules:
Number cards count as their face value (2 through 10). Jack, Queen and King count as 10. An Ace can be counted as either 1 or 11.
Return the highest score of the cards that is less than or equal to 21. If there is no score less than or equal to 21 return the smallest score more than 21.
## Examples
```
["A"] ==> 11
["A", "J"] ==> 21
["A", "10", "A"] ==> 12
["5", "3", "7"] ==> 15
["5", "4", "3", "2", "A", "K"] ==> 25
```
| algorithms | def score_hand(a):
n = sum(11 if x == "A" else 10 if x in "JQK" else int(x) for x in a)
for _ in range(a . count("A")):
if n > 21:
n -= 10
return n
| Blackjack Scorer | 534ffb35edb1241eda0015fe | [
"Games",
"Algorithms"
] | https://www.codewars.com/kata/534ffb35edb1241eda0015fe | 5 kyu |
Your task is to create a function that will take an integer and return the result of the look-and-say function on that integer. This should be a general function that takes as input any positive integer, and returns an integer; inputs are not limited to the sequence which starts with "1".
Conway's Look-and-say sequence goes like this:
- Start with a number.
- *Look* at the number, and group consecutive digits together.
- For each digit group, *say* the number of digits, then the digit itself.
This can be repeated on its result to generate the sequence.
For example:
- Start with ``1``.
- There is one ``1`` --> ``11``
- Start with ``11``. There are two ``1`` digits --> ``21``
- Start with ``21``. There is one ``2`` and one ``1`` --> ``1211``
- Start with ``1211``. There is one ``1``, one ``2``, and two ``1``s --> ``111221``
Sample inputs and outputs::
- `0` --> `10`
- `2014` --> `12101114`
- `9000` --> `1930`
- `22322` --> `221322`
- `222222222222` --> `122` | algorithms | from itertools import groupby
def look_say(n):
return int("" . join(f' { len ( list ( v ))}{ k } ' for k, v in groupby(str(n))))
| Conway's Look and Say - Generalized | 530045e3c7c0f4d3420001af | [
"Algorithms"
] | https://www.codewars.com/kata/530045e3c7c0f4d3420001af | 5 kyu |
The Western Suburbs Croquet Club has two categories of membership, Senior and Open. They would like your help with an application form that will tell prospective members which category they will be placed.
To be a senior, a member must be at least 55 years old and have a handicap greater than 7. In this croquet club, handicaps range from -2 to +26; the better the player the lower the handicap.
## Input
Input will consist of a list of pairs. Each pair contains information for a single potential member. Information consists of an integer for the person's age and an integer for the person's handicap.
## Output
Output will consist of a list of string values (in Haskell and C: `Open` or `Senior`) stating whether the respective member is to be placed in the senior or open category.
### Example
```
input = [[18, 20], [45, 2], [61, 12], [37, 6], [21, 21], [78, 9]]
output = ["Open", "Open", "Senior", "Open", "Open", "Senior"]
```
| reference | def openOrSenior(data):
return ["Senior" if age >= 55 and handicap >= 8 else "Open" for (age, handicap) in data]
| Categorize New Member | 5502c9e7b3216ec63c0001aa | [
"Fundamentals"
] | https://www.codewars.com/kata/5502c9e7b3216ec63c0001aa | 7 kyu |
## An identifier is simply a name...
Can you amend this object so that its properties comprise only vaild identifiers? | bug_fixes | Person = {
'1stname': "John",
'second-name': "Doe",
'email@ddress': "[email protected]",
'male.female': "M"
}
| What's wrong with these identifiers? | 56bb01de0e8b29de50000b19 | [
"Bugs",
"Fundamentals",
"Rules",
"Language Syntax"
] | https://www.codewars.com/kata/56bb01de0e8b29de50000b19 | 8 kyu |
In Haskell, _Monads_ are simple containers, or even 'box-like' datastructures, of which lists are included, which can respond to certain functions, which are defined in the Monad typeclass. (To put it simply!)
In this kata, you must implement the __Bind__ function for lists, or arrays. In haskell, the function is represented by `>>=`, but we'll just call it `bind`.
Essentially, `bind` should map the array with the function given, and then flatten it one time. Don't manipulate the original array; make you function _pure_: without side-effects, so that no variables are edited whilst the function is carried out. In dynamically typed languages, you should throw an error if the given function does not return a list.
Here's how it should work:
```coffeescript
bind( [1,2,3], (a) -> [a+1] )
=> [2,3,4]
bind( [1,2,3], (a) -> [[a]] )
=> [[1],[2],[3]]
bind( [1,2,3], (a) -> a )
=> # ERROR! The returned value is not a list!
```
```javascript
bind( [1,2,3], function(a){ return [a+1] } )
=> [2,3,4]
bind( [1,2,3], function(a){ return [[a]] } )
=> [[1],[2],[3]]
bind( [1,2,3], function(a){ return a } )
=> # ERROR! The returned value is not a list!
```
```python
bind( [1,2,3], lambda a: [a+1] )
=> [2,3,4]
bind( [1,2,3], lambda a: [[a]] )
=> [[1],[2],[3]]
bind( [1,2,3], lambda a: a )
=> # ERROR! The returned value is not a list!
```
```ruby
bind( [1,2,3] ) {|a| [a+1] }
=> [2,3,4]
bind( [1,2,3] ) {|a| [[a]] }
=> [[1],[2],[3]]
bind( [1,2,3] ) {|a| a }
=> # ERROR! The returned value is not a list!
```
```clojure
(bind [1 2 3] #(do [(+ % 1)]) )
=> [2,3,4]
(bind [1 2 3] #(do [[ % ]]) )
=> [[1],[2],[3]]
(bind [1 2 3] #(do %) )
=> # ERROR! The returned value is not a list!
```
```java
bind(Arrays.asList(1,2,3), i -> Arrays.asList((int)i + 1))
//=> [2,3,4]
bind(Arrays.asList(1,2,3), i -> Arrays.asList(Arrays.asList(i)));
//=> [[1],[2],[3]]
bind(Arrays.asList(3,4,5), i -> i);
//=> # ERROR! Java does this on its own! You can't even compile! Strong typing FTW!
```
As per usual, the ruby function will be passed a Proc or Lambda. Remember that the function still takes two arguments!
| algorithms | def bind(lst, func):
return [y for x in lst for y in func(x)]
| Binding within the List Monad | 546e416c8e3b6bf82f0002f2 | [
"Monads",
"Lists",
"Algorithms"
] | https://www.codewars.com/kata/546e416c8e3b6bf82f0002f2 | 6 kyu |
## Prologue
You're part of a team porting MS Paint into the browser and currently working on a new UI component that allows user to control the canvas zoom level.
According to the wireframes delivered to you in PowerPoint format the user should be able to *cycle* through specified zoom levels by clicking a button in the UI repeatedly. The reverse direction should work with shift key held.
A new function is needed to support this behavior, so you alt-tab to Visual Studio and get to work.
---
## Instructions
Implement a function which when given the arguments
1. Direction to which to cycle the current value
2. List of values
3. Current value
returns the value next to current value in the specified direction.
The function should pick the next value from the other side of the list in case there are no values in the given direction.
## Examples
``` haskell
cycleList R [1,2,3] 1 -- => Just 2
cycleList L [1,2,3] 1 -- => Just 3
cycleList R [1,2,3] 0 -- => Nothing
cycleList L ["foo", "bar", "xyz"] "bar" -- => Just "foo"
```
``` javascript
cycle(1, [1,2,3], 1) // => 2
// Given the direction 1, returns the value next to 1 on the right
cycle(-1, [1,2,3], 1) // => 3
// Given the direction -1 and value 1, wraps around list returning the last element
cycle(1, [1,2,3], 0) // => null
// 0 does not exist in the list, returns null
cycle(1, [1,2,2,3], 2) // => 2
// Corner case: multiple instances of given value, picks next relative to first occurrence
```
``` coffeescript
# Given the direction 1, returns the value next to 1 on the right
cycle(1, [1,2,3], 1) # => 2
# Given the direction -1 and value 1, wraps around list returning the last element
cycle(-1, [1,2,3], 1) # => 3
# 0 does not exist in the list, returns null
cycle(1, [1,2,3], 0) # => null
# Corner case: multiple instances of given value, picks next relative to first occurrence
cycle(1, [1,2,2,3], 2) # => 2
```
``` python
# Given the direction 1, returns the value next to 1 on the right
cycle(1, [1,2,3], 1) # => 2
# Given the direction -1 and value 1, wraps around list returning the last element
cycle(-1, [1,2,3], 1) # => 3
# 0 does not exist in the list, returns null
cycle(1, [1,2,3], 0) # => null
# Corner case: multiple instances of given value, picks next relative to first occurrence
cycle(1, [1,2,2,3], 2) # => 2
``` | algorithms | from typing import List, Optional
def cycle(d: int, v: List[int], c: int) - > Optional[int]:
try:
return v[v . index(c) + d]
except ValueError:
return
except IndexError:
return v[0]
| Cycle a list of values | 5456812629ccbf311b000078 | [
"Algorithms"
] | https://www.codewars.com/kata/5456812629ccbf311b000078 | 6 kyu |
This is a hard version of <a href = 'http://www.codewars.com/kata/56a1c074f87bc2201200002e'>How many are smaller than me?</a>. If you have troubles solving this one, have a look at the easier kata first.
Write
```javascript
function smaller(arr)
```
```rust
fn smaller(arr: &[i32]) -> Vec<usize>
```
that given an array ```arr```, you have to return the amount of numbers that are smaller than ```arr[i]``` to the right.
For example:
```javascript
smaller([5, 4, 3, 2, 1]) === [4, 3, 2, 1, 0]
smaller([1, 2, 0]) === [1, 1, 0]
```
```rust
smaller(&[5, 4, 3, 2, 1]) == [4, 3, 2, 1, 0];
smaller(&[1, 2, 0]) == [1, 1, 0];
```
~~~if:python
### Note
Your solution will be tested against inputs with up to 120_000 elements
~~~
~~~if:rust
### Note
Your solution will be tested against inputs with up to 150_000 elements
~~~
~~~if:javascript
### Note
Your solution will be tested against inputs with up to 100_000 elements
~~~ | algorithms | class Tree:
''' v,r,l: value, left, right,
n: number of occurrences of v
lt: number of numbers lower than v (in the left subtree only)
'''
def __init__(self, v):
self . v, self . l, self . r, self . n, self . lt = v, None, None, 1, 0
def insert(tree, v):
if not tree:
return Tree(v), 0
if v < tree . v:
tree . lt += 1
tree . l, n = insert(tree . l, v)
elif v == tree . v:
tree . n += 1
n = tree . lt
else:
tree . r, n = insert(tree . r, v)
n += tree . n + tree . lt
return tree, n
def smaller(arr):
out, tree = [], None
for v in reversed(arr):
tree, n = insert(tree, v)
out . append(n)
return out[:: - 1]
| How many are smaller than me II? | 56a1c63f3bc6827e13000006 | [
"Algorithms",
"Performance"
] | https://www.codewars.com/kata/56a1c63f3bc6827e13000006 | 3 kyu |
Write a function that given, an array ```arr```, returns an array containing at each index ```i``` the amount of numbers that are smaller than ```arr[i]``` to the right.
For example:
```
* Input [5, 4, 3, 2, 1] => Output [4, 3, 2, 1, 0]
* Input [1, 2, 0] => Output [1, 1, 0]
```
If you've completed this one and you feel like testing your performance tuning of this same kata, head over to the much tougher version <a href = 'http://www.codewars.com/kata/56a1c63f3bc6827e13000006'>How many are smaller than me II?</a>
| algorithms | def smaller(arr):
# Good Luck!
return [len([a for a in arr[i:] if a < arr[i]]) for i in range(0, len(arr))]
| How many are smaller than me? | 56a1c074f87bc2201200002e | [
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/56a1c074f87bc2201200002e | 7 kyu |
General Patron is faced with a problem , his intelligence has intercepted some secret messages from the enemy but they are all encrypted.
Those messages are crucial to getting the jump on the enemy and winning the war. Luckily intelligence also captured an encoding device as well.
However even the smartest programmers weren't able to crack it though. So the general is asking you , his most odd but brilliant programmer.
You can call the encoder like this.
```javascript
console.log (device.encode ('What the hell')) ;
```
```coffeescript
console.log device.encode('What the hell')
```
```cpp
std::cout << Encoder::encode("Hello World!");
```
```python
encode("Hello World!")
```
```ruby
encode("Hello World!")
```
```csharp
Console.WriteLine(Encoder.Encode("Hello World!"));
```
Our cryptoanalysts kept poking at it and found some interesting patterns.
```javascript
console.log (device.encode ('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')) ;
console.log (device.encode ('bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb')) ;
console.log (device.encode ('!@#$%^&*()_+-')) ;
console.log ('abcdefghijklmnopqrstuvwxyz') ;
console.log ('abcdefghijklmnopqrstuvwxyz'.split ('').map (function (a) {
return device.encode (a) ;
}).join ('')) ;
console.log ('abcdefghijklmnopqrstuvwxyz'.split ('').map (function (a) {
return device.encode ('_'+a)[1] ;
}).join ('')) ;
console.log ('abcdefghijklmnopqrstuvwxyz'.split ('').map (function (a) {
return device.encode ('__'+a)[2] ;
}).join ('')) ;
```
```coffeescript
console.log device.encode('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
console.log device.encode('bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb')
console.log device.encode('!@#$%^&*()_+')
console.log 'abcdefghijklmnopqrstuvwxyz'
console.log 'abcdefghijklmnopqrstuvwxyz'.split('').map((a) ->
device.encode a
).join('')
console.log 'abcdefghijklmnopqrstuvwxyz'.split('').map((a) ->
device.encode('_' + a)[1]
).join('')
console.log 'abcdefghijklmnopqrstuvwxyz'.split('').map((a) ->
device.encode('__' + a)[2]
).join('')
```
```cpp
std::cout << (Encoder::encode ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")) << "\n" ;
std::cout << (Encoder::encode ("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")) << "\n" ;
std::cout << (Encoder::encode ("!@#$%^&*()_+-")) << "\n" ;
std::string a, b, c;
for (const auto& w : std::string("abcdefghijklmnopqrstuvwxyz")) {
a += Encoder::encode (std::string( "") + w)[0];
b += Encoder::encode (std::string( "_") + w)[1];
c += Encoder::encode (std::string("__") + w)[2];
}
std::cout << a << "\n";
std::cout << b << "\n";
std::cout << c << "\n";
```
```python
print(
encode("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"))
print(
encode("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"))
print(encode("!@#$%^&*()_+-"))
a,b,c = "", "", ""
for w in "abcdefghijklmnopqrstuvwxyz":
a += encode( "" + w)[0]
b += encode( "_" + w)[1]
c += encode("__" + w)[2]
print(a)
print(b)
print(c)
```
```ruby
puts encode("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
puts encode("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")
puts encode("!@#$%^&*()_+-")
a,b,c = ["", "", ""]
('a'..'z').each do |l|
a += encode( "" + l)[0]
b += encode( "_" + l)[1]
c += encode("__" + l)[2]
end
puts a
puts b
puts c
```
```csharp
Console.WriteLine(Encoder.Encode ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
Console.WriteLine(Encoder.Encode ("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"));
Console.WriteLine(Encoder.Encode ("!@#$%^&*()_+-"));
StringBuilder a = new StringBuilder();
StringBuilder b = new StringBuilder();
StringBuilder c = new StringBuilder();
foreach (char w in "abcdefghijklmnopqrstuvwxyz") {
a.Append(Encoder.Encode ( "" + w)[0]);
b.Append(Encoder.Encode ( "_" + w)[1]);
c.Append(Encoder.Encode ("__" + w)[2]);
}
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
```
We think if you keep on this trail you should be able to crack the code!
You are expected to fill in the
```javascript
device.decode
```
```coffeescript
device.decode
```
```cpp
std::string Decoder::decode(const std::string&)
```
```python
decode
```
```ruby
decode
```
```csharp
public static string Decode(string p_what)
```
function.
Good luck ! General Patron is counting on you!
| games | def decode(s):
decrypted_message = ''
i = 0
key = "bdhpF,82QsLirJejtNmzZKgnB3SwTyXG ?.6YIcflxVC5WE94UA1OoD70MkvRuPqHa"
for char in s:
i += 1
if char not in key:
decrypted_message += char
continue
idx = (key . index(char) - i) % 66
decrypted_message += key[idx]
return decrypted_message
| Help the general decode secret enemy messages. | 52cf02cd825aef67070008fa | [
"Puzzles"
] | https://www.codewars.com/kata/52cf02cd825aef67070008fa | 3 kyu |
For encrypting strings this region of chars is given (in this order!):
* all letters (ascending, first all UpperCase, then all LowerCase)
* all digits (ascending)
* the following chars: `.,:;-?! '()$%&"`
These are 77 chars! (This region is zero-based.)<br/>
Write two methods: <br/>
```csharp
string Encrypt(string text)
string Decrypt(string encryptedText)
```
```javascript
function encrypt(text)
function decrypt(encryptedText)
```
```typescript
export function encrypt(text:string):string
export function decrypt(encryptedText:string):string
```
```python
def encrypt(text)
def decrypt(encrypted_text)
```
```cpp
std::string encrypt(std::string text)
std::string decrypt(std::string text)
```
```clojure
(encrypt (text))
(decrypt (text))
```
Prechecks:<br>
1. If the input-string has chars, that are not in the region, throw an Exception(C#, Python) or Error(JavaScript).<br>
2. If the input-string is null or empty return exactly this value!<br>
For building the encrypted string:<br>
1. For every second char do a switch of the case.<br>
2. For every char take the index from the region. Take the difference from the region-index of the char before (from the input text! Not from the fresh encrypted char before!). (Char2 = Char1-Char2)<br>
Replace the original char by the char of the difference-value from the region. In this step the first letter of the text is unchanged.<br>
3. Replace the first char by the mirror in the given region. (`'A' -> '"'`, `'B' -> '&'`, ...)
Simple example:
* Input: `"Business"`
* Step 1: `"BUsInEsS"`
* Step 2: `"B61kujla"`
* `B -> U`
* `B (1) - U (20) = -19`
* `-19 + 77 = 58`
* `Region[58] = "6"`
* `U -> s`
* `U (20) - s (44) = -24`
* `-24 + 77 = 53`
* `Region[53] = "1"`
* Step 3: `"&61kujla"`
This kata is part of the Simple Encryption Series:<br>
<a href="https://www.codewars.com/kata/simple-encryption-number-1-alternating-split" taget=_blank>Simple Encryption #1 - Alternating Split</a><br>
<a href="https://www.codewars.com/kata/simple-encryption-number-2-index-difference" taget=_blank>Simple Encryption #2 - Index-Difference</a><br>
<a href="https://www.codewars.com/kata/simple-encryption-number-3-turn-the-bits-around" taget=_blank>Simple Encryption #3 - Turn The Bits Around</a><br>
<a href="https://www.codewars.com/kata/simple-encryption-number-4-qwerty" taget=_blank>Simple Encryption #4 - Qwerty</a><br>
Have fun coding it and please don't forget to vote and rank this kata! :-) | algorithms | region = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;-?! '()$%&" + '"'
def decrypt(encrypted_text):
if not encrypted_text:
return encrypted_text
letters = list(encrypted_text)
letters[0] = region[- (region . index(letters[0]) + 1)]
for i in range(1, len(letters)):
letters[i] = region[region . index(
letters[i - 1]) - region . index(letters[i])]
for i in range(1, len(letters), 2):
letters[i] = letters[i]. swapcase()
return "" . join(letters)
def encrypt(text):
if not text:
return text
letters = list(text)
for i in range(1, len(letters), 2):
letters[i] = text[i]. swapcase()
swapped = letters[:]
for i in range(1, len(letters)):
letters[i] = region[region . index(
swapped[i - 1]) - region . index(swapped[i])]
letters[0] = region[- (region . index(swapped[0]) + 1)]
return "" . join(letters)
| Simple Encryption #2 - Index-Difference | 5782b5ad202c0ef42f0012cb | [
"Fundamentals",
"Cryptography",
"Security",
"Strings",
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/5782b5ad202c0ef42f0012cb | 5 kyu |
The Vigenère cipher is a classic cipher originally developed by Italian cryptographer Giovan Battista Bellaso and published in 1553. It is named after a later French cryptographer Blaise de Vigenère, who had developed a stronger autokey cipher (a cipher that incorporates the message of the text into the key).
The cipher is easy to understand and implement, but survived three centuries of attempts to break it, earning it the nickname "le chiffre indéchiffrable" or "the indecipherable cipher."
[From Wikipedia](https://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher):
> The Vigenère cipher is a method of encrypting alphabetic text by using a series of different Caesar ciphers based on the letters of a keyword. It is a simple form of polyalphabetic substitution.
>
> . . .
>
> In a Caesar cipher, each letter of the alphabet is shifted along some number of places; for example, in a Caesar cipher of shift `3`, `A` would become `D`, `B` would become `E`, `Y` would become `B` and so on. The Vigenère cipher consists of several Caesar ciphers in sequence with different shift values.
Assume the key is repeated for the length of the text, character by character. Note that some implementations repeat the key over characters only if they are part of the alphabet -- **this is not the case here.**
The shift is derived by applying a Caesar shift to a character with the corresponding index of the key in the alphabet.
Visual representation:
```javascript
"my secret code i want to secure" // message
"passwordpasswordpasswordpasswor" // key
```
Write a class that, when given a key and an alphabet, can be used to encode and decode from the cipher.
## Example
```javascript
var alphabet = 'abcdefghijklmnopqrstuvwxyz';
var key = 'password';
// creates a cipher helper with each letter substituted
// by the corresponding character in the key
var c = new VigenèreCipher(key, alphabet);
c.encode('codewars'); // returns 'rovwsoiv'
c.decode('laxxhsj'); // returns 'waffles'
```
Any character not in the alphabet must be left as is. For example (following from above):
```javascript
c.encode('CODEWARS'); // returns 'CODEWARS'
``` | algorithms | class VigenereCipher (object):
def __init__(self, key: str, alphabet: str):
self . alphabet = list(alphabet)
self . key = [alphabet . index(i) for i in key]
def encode(self, text):
return "" . join([self . alphabet[(self . alphabet . index(text[i]) + self . key[i % len(self . key)]) % len(self . alphabet)]
if text[i] in self . alphabet else text[i] for i in range(len(text))])
def decode(self, text):
return "" . join([self . alphabet[(self . alphabet . index(text[i]) - self . key[i % len(self . key)]) % len(self . alphabet)]
if text[i] in self . alphabet else text[i] for i in range(len(text))])
| Vigenère Cipher Helper | 52d1bd3694d26f8d6e0000d3 | [
"Algorithms",
"Ciphers",
"Security",
"Object-oriented Programming",
"Strings"
] | https://www.codewars.com/kata/52d1bd3694d26f8d6e0000d3 | 4 kyu |
You have to write two methods to *encrypt* and *decrypt* strings.
Both methods have two parameters:
```
1. The string to encrypt/decrypt
2. The Qwerty-Encryption-Key (000-999)
```
The rules are very easy:
```
The crypting-regions are these 3 lines from your keyboard:
1. "qwertyuiop"
2. "asdfghjkl"
3. "zxcvbnm,."
If a char of the string is not in any of these regions, take the char direct in the output.
If a char of the string is in one of these regions: Move it by the part of the key in the
region and take this char at the position from the region.
If the movement is over the length of the region, continue at the beginning.
The encrypted char must have the same case like the decrypted char!
So for upperCase-chars the regions are the same, but with pressed "SHIFT"!
The Encryption-Key is an integer number from 000 to 999. E.g.: 127
The first digit of the key (e.g. 1) is the movement for the first line.
The second digit of the key (e.g. 2) is the movement for the second line.
The third digit of the key (e.g. 7) is the movement for the third line.
(Consider that the key is an integer! When you got a 0 this would mean 000. A 1 would mean 001. And so on.)
```
You do not need to do any prechecks. The strings will always be not null
and will always have a length > 0. You do not have to throw any exceptions.
An Example:
```
Encrypt "Ball" with key 134
1. "B" is in the third region line. Move per 4 places in the region. -> ">" (Also "upperCase"!)
2. "a" is in the second region line. Move per 3 places in the region. -> "f"
3. "l" is in the second region line. Move per 3 places in the region. -> "d"
4. "l" is in the second region line. Move per 3 places in the region. -> "d"
--> Output would be ">fdd"
```
*Hint: Don't forget: The regions are from an US-Keyboard!<br>*
*In doubt google for "US Keyboard."*
<br><br>
This kata is part of the Simple Encryption Series:<br>
<a href="https://www.codewars.com/kata/simple-encryption-number-1-alternating-split" taget=_blank>Simple Encryption #1 - Alternating Split</a><br>
<a href="https://www.codewars.com/kata/simple-encryption-number-2-index-difference" taget=_blank>Simple Encryption #2 - Index-Difference</a><br>
<a href="https://www.codewars.com/kata/simple-encryption-number-3-turn-the-bits-around" taget=_blank>Simple Encryption #3 - Turn The Bits Around</a><br>
<a href="https://www.codewars.com/kata/simple-encryption-number-4-qwerty" taget=_blank>Simple Encryption #4 - Qwerty</a><br>
Have fun coding it and please don't forget to vote and rank this kata! :-) | algorithms | from collections import deque
KEYBOARD = ['zxcvbnm,.', 'ZXCVBNM<>', 'asdfghjkl',
'ASDFGHJKL', 'qwertyuiop', 'QWERTYUIOP']
def encrypt(text, encryptKey): return converter(text, encryptKey, 1)
def decrypt(text, encryptKey): return converter(text, encryptKey, - 1)
def converter(text, encryptKey, sens):
deques = list(map(deque, KEYBOARD))
for i, deq in enumerate(deques):
deq . rotate(- sens * (encryptKey / / 10 * * (i / / 2) % 10))
return text . translate(str . maketrans('' . join(KEYBOARD), '' . join('' . join(deq) for deq in deques)))
| Simple Encryption #4 - Qwerty | 57f14afa5f2f226d7d0000f4 | [
"Cryptography",
"Security",
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/57f14afa5f2f226d7d0000f4 | 5 kyu |
[Rotation ciphers](http://en.wikipedia.org/wiki/Caesar_cipher) are very vulnerable to brute force attacks. There are only 25 possible ways to decrypt the message.
Example Encoded Message:````ymjxvznwwjqnxhzyj````
Possible Decoded Messages:
```
znkywaoxxkroyiazk, aolzxbpyylspzjbal, bpmaycqzzmtqakcbm,
cqnbzdraanurbldcn, drocaesbbovscmedo, espdbftccpwtdnfep,
ftqecguddqxueogfq, gurfdhveeryvfphgr, hvsgeiwffszwgqihs,
iwthfjxggtaxhrjit, jxuigkyhhubyiskju, kyvjhlziivczjtlkv,
lzwkimajjwdakumlw, maxljnbkkxeblvnmx, nbymkocllyfcmwony,
ocznlpdmmzgdnxpoz, pdaomqennaheoyqpa, qebpnrfoobifpzrqb,
rfcqosgppcjgqasrc, sgdrpthqqdkhrbtsd, thesquirreliscute,
uiftrvjssfmjtdvuf, vjguswkttgnkuewvg, wkhvtxluuholvfxwh,
xliwuymvvipmwgyxi
```
If you scan through the list you will see only a few that contain an english word longer than two characters. ````thesquirreliscute```` is the only one that could be completely seperated into english words to form the message "the squirrel is cute".
Your job for this kata is to make a function that will give all possible decoded messages given the encoded message and suspected contents.
UPDATE: the original unshifted alphabet should also be tested for, making it a total of 26 possible ways to decrypt the message. Returned results are to be sorted as well. See last line below for an example:
```python
decode('ymjxvznwwjqnxhzyj','squirrel') # returns ['thesquirreliscute']
decode('lzwespnsdmwakafxafalq','max') # returns ['maxftqotenxblbgybgbmr', 'themaxvalueisinfinity']
decode('pumy','um') # returns ['pumy']
```
```ruby
decode('ymjxvznwwjqnxhzyj','squirrel') # returns ['thesquirreliscute']
decode('lzwespnsdmwakafxafalq','max') # returns ['maxftqotenxblbgybgbmr', 'themaxvalueisinfinity']
decode('pumy','um') # returns ['pumy']
```
```javascript
decode('ymjxvznwwjqnxhzyj','squirrel') // returns ['thesquirreliscute']
decode('lzwespnsdmwakafxafalq','max') // returns ['maxftqotenxblbgybgbmr', 'themaxvalueisinfinity']
decode('pumy','um') // returns ['pumy']
``` | games | def rotation(string, n): return '' . join(chr(ord(c) + n - 26 * (ord(c) + n > 122))
for c in string)
def decode(message, contents): return [rotation(message, n)
for n in range(26)
if contents in rotation(message, n)]
| Rotation Cipher Cracker | 54729e48e1d2a369e00000d3 | [
"Ciphers",
"Cryptography",
"Algorithms",
"Security",
"Puzzles"
] | https://www.codewars.com/kata/54729e48e1d2a369e00000d3 | 6 kyu |
Implement the [Polybius square cipher](http://en.wikipedia.org/wiki/Polybius_square).
Replace every letter with a two digit number. The first digit is the row number, and the second digit is the column number of following square. Letters `'I'` and `'J'` are both 24 in this cipher:
<style>
table#polybius-square {width: 100px;}
table#polybius-square td {background-color: #2f2f2f;}
table#polybius-square th {background-color: #3f3f3f;}
</style>
<table id="polybius-square">
<tbody><tr><th></th><th>1</th><th>2</th><th>3</th><th>4</th><th>5</th></tr>
<tr><th>1</th><td>A</td><td>B</td><td>C</td><td>D</td><td>E</td></tr>
<tr><th>2</th><td>F</td><td>G</td><td>H</td><td>I/J</td><td>K</td></tr>
<tr><th>3</th><td>L</td><td>M</td><td>N</td><td>O</td><td>P</td></tr>
<tr><th>4</th><td>Q</td><td>R</td><td>S</td><td>T</td><td>U</td></tr>
<tr><th>5</th><td>V</td><td>W</td><td>X</td><td>Y</td><td>Z</td></tr>
</tbody></table>
Input will be valid (only spaces and uppercase letters from A to Z), so no need to validate them.
## Examples
```javascript
polybius('A') // "11"
polybius('IJ') // "2424"
polybius('CODEWARS') // "1334141552114243"
polybius('POLYBIUS SQUARE CIPHER') // "3534315412244543 434145114215 132435231542"
```
```python
polybius('A') # "11"
polybius('IJ') # "2424"
polybius('CODEWARS') # "1334141552114243"
polybius('POLYBIUS SQUARE CIPHER') # "3534315412244543 434145114215 132435231542"
```
```ruby
polybius('A') # "11"
polybius('IJ') # "2424"
polybius('CODEWARS') # "1334141552114243"
polybius('POLYBIUS SQUARE CIPHER') # "3534315412244543 434145114215 132435231542"
```
```java
Solution.polybius("A") // "11"
Solution.polybius("IJ") // "2424"
Solution.polybius("CODEWARS") // "1334141552114243"
Solution.polybius("POLYBIUS SQUARE CIPHER") // "3534315412244543 434145114215 132435231542"
``` | algorithms | def polybius(text):
letmap = {"A": "11", "B": "12", "C": "13", "D": "14", "E": "15",
"F": "21", "G": "22", "H": "23", "I": "24", "J": "24", "K": "25",
"L": "31", "M": "32", "N": "33", "O": "34", "P": "35",
"Q": "41", "R": "42", "S": "43", "T": "44", "U": "45",
"V": "51", "W": "52", "X": "53", "Y": "54", "Z": "55", " ": " "}
enc = ""
for i in range ( 0 , len ( text )):
enc = enc + letmap [ text [ i ]. upper ()]
return enc | Polybius square cipher - encode | 542a823c909c97da4500055e | [
"Cryptography",
"Ciphers",
"Algorithms"
] | https://www.codewars.com/kata/542a823c909c97da4500055e | 6 kyu |
A simple substitution cipher replaces one character from an alphabet with a character from an alternate alphabet, where each character's position in an alphabet is mapped to the alternate alphabet for encoding or decoding.
E.g.
```javascript
var abc1 = "abcdefghijklmnopqrstuvwxyz";
var abc2 = "etaoinshrdlucmfwypvbgkjqxz";
var sub = new SubstitutionCipher(abc1, abc2);
sub.encode("abc") // => "eta"
sub.encode("xyz") // => "qxz"
sub.encode("aeiou") // => "eirfg"
sub.decode("eta") // => "abc"
sub.decode("qxz") // => "xyz"
sub.decode("eirfg") // => "aeiou"
```
```python
map1 = "abcdefghijklmnopqrstuvwxyz";
map2 = "etaoinshrdlucmfwypvbgkjqxz";
cipher = Cipher(map1, map2);
cipher.encode("abc") # => "eta"
cipher.encode("xyz") # => "qxz"
cipher.encode("aeiou") # => "eirfg"
cipher.decode("eta") # => "abc"
cipher.decode("qxz") # => "xyz"
cipher.decode("eirfg") # => "aeiou"
```
```rust
let map1 = "abcdefghijklmnopqrstuvwxyz";
let map2 = "etaoinshrdlucmfwypvbgkjqxz";
let cipher = Cipher::new(map1, map2);
cipher.encode("abc") // => "eta"
cipher.encode("xyz") // => "qxz"
cipher.encode("aeiou") // => "eirfg"
cipher.decode("eta") // => "abc"
cipher.decode("qxz") // => "xyz"
cipher.decode("eirfg") // => "aeiou"
```
If a character provided is not in the opposing alphabet, simply leave it as be. | algorithms | class Cipher (object):
def __init__(self, map1, map2):
self . enc_key = str . maketrans(map1, map2)
self . dec_key = str . maketrans(map2, map1)
def encode(self, stg):
return stg . translate(self . enc_key)
def decode(self, stg):
return stg . translate(self . dec_key)
| Simple Substitution Cipher Helper | 52eb114b2d55f0e69800078d | [
"Ciphers",
"Security",
"Object-oriented Programming",
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/52eb114b2d55f0e69800078d | 6 kyu |
You are given a secret message you need to decipher. Here are the things you need to know to decipher it:
For each word:
- the second and the last letter is switched (e.g. `Hello` becomes `Holle`)
- the first letter is replaced by its character code (e.g. `H` becomes `72`)
* there are no special characters used, only letters and spaces
* words are separated by a single space
* there are no leading or trailing spaces
Examples
```
'72olle 103doo 100ya' --> 'Hello good day'
'82yade 115te 103o' --> 'Ready set go'
```
| reference | def decipher_word(word):
i = sum(map(str . isdigit, word))
decoded = chr(int(word[: i]))
if len(word) > i + 1:
decoded += word[- 1]
if len(word) > i:
decoded += word[i + 1: - 1] + word[i: i + 1]
return decoded
def decipher_this(string):
return ' ' . join(map(decipher_word, string . split()))
| Decipher this! | 581e014b55f2c52bb00000f8 | [
"Strings",
"Arrays",
"Ciphers",
"Fundamentals"
] | https://www.codewars.com/kata/581e014b55f2c52bb00000f8 | 6 kyu |
You have been recruited by an unknown organization for your cipher encrypting/decrypting skills.
Being new to the organization they decide to test your skills.
Your first test is to write an algorithm that encrypts the given string in the following steps.
1. The first step of the encryption is a standard ROT13 cipher.
This is a special case of the caesar cipher where the letter is encrypted with its key that is thirteen letters down the alphabet,
i.e. `A => N, B => O, C => P, etc..`
1. Part two of the encryption is to take the ROT13 output and replace each letter with its exact opposite. `A => Z, B => Y, C => X`.
The return value of this should be the encrypted message.
Do not worry about capitalization or punctuation. All encrypted messages should be lower case and punctuation free.
As an example, the string `"welcome to our organization"` should return `"qibkyai ty ysv yvgmzenmteyz"`.
Good luck, and congratulations on the new position.
| algorithms | def encrypter(strng):
return '' . join(c if c == ' ' else chr(122 - ((ord(c) - 97) + 13) % 26) for c in strng)
| ROT13 variant cipher | 56fb3cde26cc99c2fd000009 | [
"Cryptography",
"Security",
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/56fb3cde26cc99c2fd000009 | 6 kyu |
Let’s get to know our hero: Agent #134 - Mr. Slayer.
He was sent by his CSV agency to Ancient Rome in order to resolve some important national issues. However, something incredible has happened - the enemies have taken Julius Caesar as a prisoner!!!
Caesar, not a simple man as you know, managed to send cryptic message with coordinates of his location hoping that somebody would break the code. Here our agent of the secret service comes to the stage.
But he needs your help!
**Mission:**
You have to implement the function “Encode” of CaesarCrypto class that codes or decodes text based on Caesar’s algorithm.<br><ul><li>the function receives 2 parameters: an original text of any length of type “string” and a number of type “int” that represents shifts;</li><li>only letters in both cases must be encrypted;</li><li>alphabet contains only letters in this range: a-zA-Z;</li><li>by encryption the letter can change the case;</li><li>shift could be either positive or negative (for left shift);</li><li>If the input text is empty, null or includes only whitespaces, return an empty string.</li></ul>
Time's ticking away. The life of Caesar is on the chopping block! Go for it!
| algorithms | from string import ascii_letters as az
def caesar_crypto_encode(text, shift):
if not text:
return ''
sh = shift % 52
return str . translate(text, str . maketrans(az, az[sh:] + az[: sh])). strip()
| Cryptography #1 - Viva Cesare | 576fac714bc84c312c0000b7 | [
"Fundamentals",
"Cryptography",
"Algorithms"
] | https://www.codewars.com/kata/576fac714bc84c312c0000b7 | 6 kyu |
A keyword cipher is a monoalphabetic cipher which uses a "keyword" to provide encryption. It is somewhat similar to a Caesar cipher.
In a keyword cipher, repeats of letters in the keyword are removed and the alphabet is reordered such that the letters in the keyword appear first, followed by the rest of the letters in the alphabet in their otherwise usual order.
E.g. for an uppercase latin alphabet with keyword of "KEYWORD":
`A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z`
becomes:
`K|E|Y|W|O|R|D|A|B|C|F|G|H|I|J|L|M|N|P|Q|S|T|U|V|X|Z`
such that:
```javascript
cipher.encode('ABCHIJ') == 'KEYABC'
cipher.decode('KEYABC') == 'ABCHIJ'
```
All letters in the keyword will also be in the alphabet. For the purpose of this kata, only the first occurence of a letter in a keyword should be used. Any characters not provided in the alphabet should be left in situ when encoding or decoding.
| refactoring | from string import maketrans
class keyword_cipher (object):
def __init__(self, abc, keyword):
key_abc = '' . join(sorted(set(keyword), key=keyword . index)) + \
'' . join(c for c in abc if c not in keyword)
self . e_tab = maketrans(abc, key_abc)
self . d_tab = maketrans(key_abc, abc)
def encode(self, str):
return str . translate(self . e_tab)
def decode(self, str):
return str . translate(self . d_tab)
| Keyword Cipher Helper | 535c1c80cdbf5011e600030f | [
"Cryptography",
"Ciphers",
"Security",
"Object-oriented Programming",
"Strings"
] | https://www.codewars.com/kata/535c1c80cdbf5011e600030f | 6 kyu |
# Number encrypting: cypher
## Part I of Number encrypting Katas
***
## Introduction
Back then when the internet was coming up, most search functionalities simply looked for keywords in text to show relevant documents. Hackers weren't very keen on having their information displayed on websites, bulletin boards, newsgroups or any other place, so they started to replace certain letters in words. It started out with simple vowel substitutions like a 4 instead of an A, or a 3 instead of an E. This meant that topics like cracking or hacking remained undetected.
Here we will use a reduced version of the *Leet Speak alphabet*, but you can find more information [here](http://www.gamehouse.com/blog/leet-speak-cheat-sheet/) or at [Wikipedia](https://en.wikipedia.org/wiki/Leet).
## Task
You will receive a string composed by English words, `string`. You will have to return a cyphered version of that string.
The numbers corresponding to each letter are represented at the table below. Notice that different letters can share the same number. In those cases, one letter will be upper case and the other one lower case.
<style>
.cell {
border: 1px solid white;
text-align: center;
width: 7%;
}
.title {
border: 1px solid white;
border-bottom: 1px solid white;
text-align: center;
min-width: 11em;
}
.no-border {border: none}
table {
margin-bottom: 10px
}
</style>
<pre>
<table>
<tr >
<td class="no-border"></td>
<td class="cell">1</td>
<td class="cell">2</td>
<td class="cell">3</td>
<td class="cell">4</td>
<td class="cell">5</td>
<td class="cell">6</td>
<td class="cell">7</td>
<td class="cell">8</td>
<td class="cell">9</td>
<td class="cell">0</td>
</tr>
<tr >
<td class="title">Upper case</td>
<td class="cell">I</td>
<td class="cell">R</td>
<td class="cell">E</td>
<td class="cell">A</td>
<td class="cell">S</td>
<td class="cell">G</td>
<td class="cell">T</td>
<td class="cell">B</td>
<td class="cell"></td>
<td class="cell">O</td>
</tr>
<tr >
<td class="title">Lower case</td>
<td class="cell">l</td>
<td class="cell">z</td>
<td class="cell">e</td>
<td class="cell">a</td>
<td class="cell">s</td>
<td class="cell">b</td>
<td class="cell">t</td>
<td class="cell"></td>
<td class="cell">g</td>
<td class="cell">o</td>
</tr>
<tr></tr>
</table>
</pre>
Any character that is not at the table, does not change when cyphered.
## Examples
* **Input:** "Hello World". **Output**: "H3110 W0r1d"
* **Input:** "I am your father". **Output**: "1 4m y0ur f47h3r"
* **Input:** "I do not know what else I can test. Be cool. Good luck". **Output**: "1 d0 n07 kn0w wh47 3153 1 c4n 7357. 83 c001. 600d 1uck"
## Part II
If you liked this Kata, you can find the [part II: *Number encrypting: decypher*](https://www.codewars.com/kata/number-encrypting-decypher), where your goal is to decypher the strings.
| reference | def cypher(s):
return s . translate(str . maketrans('IREASGTBlzeasbtgoO', '123456781234567900'))
| Number encrypting: cypher | 57aa3927e298a757820000a8 | [
"Fundamentals",
"Strings",
"Ciphers",
"Cryptography"
] | https://www.codewars.com/kata/57aa3927e298a757820000a8 | 7 kyu |
When you sign up for an account somewhere, some websites do not actually store your password in their databases. Instead, they will transform your password into something else using a cryptographic hashing algorithm.
After the password is transformed, it is then called a *password hash*. Whenever you try to login, the website will transform the password you tried using the same hashing algorithm and simply see if the password hashes are the same.
-----
Create the function that converts a given string into an `md5` hash. The return value should be encoded in `hexadecimal`.
```if:javascript
Remember that you can include the builtin `require()` function to include external modules (you're not expected to implement MD5 hash algorithm yourself, there are many modules that can do that for you).
If you're not familiar with modules, see [this kata](https://www.codewars.com/kata/541db50c259d9c55c00007b9).
NodeJS documentation [here](https://nodejs.org/api/).
```
## Code Examples
```
passHash("password") // --> "5f4dcc3b5aa765d61d8327deb882cf99"
passHash("abc123") // --> "e99a18c428cb38d5f260853678922e03"
```
If you want to externally test a string, [look at this website](http://www.md5hasher.net/).
-----
As a side note, `md5` can be exploited, so never use it for anything secure. The reason I used it in this kata is simply because it is a very common hashing algorithm and many people will recognize the name. | reference | from hashlib import md5
def pass_hash(str):
return md5(str . encode()). hexdigest()
| Password Hashes | 54207f9677730acd490000d1 | [
"Security",
"Fundamentals"
] | https://www.codewars.com/kata/54207f9677730acd490000d1 | 7 kyu |
You have managed to intercept an important message and you are trying to read it.
You realise that the message has been encoded and can be decoded by switching each letter with a corresponding letter.
You also notice that each letter is paired with the letter that it coincides with when the alphabet is reversed.
For example: "a" is encoded with "z", "b" with "y", "c" with "x", etc
You read the first sentence:
```
"r slkv mlylwb wvxlwvh gsrh nvhhztv"
```
After a few minutes you manage to decode it:
```
"i hope nobody decodes this message"
```
Create a function that will instantly decode any of these messages
You can assume no punctuation or capitals, only lower case letters, but remember spaces! | games | from string import ascii_lowercase as alphabet
def decode(message):
return message . translate(str . maketrans(alphabet, alphabet[:: - 1]))
| Decoding a message | 565b9d6f8139573819000056 | [
"Puzzles",
"Algorithms",
"Cryptography",
"Security",
"Games"
] | https://www.codewars.com/kata/565b9d6f8139573819000056 | 7 kyu |
Fans of The Wire will appreciate this one.
For those that haven't seen the show, the Barksdale Organization has a simple method for encoding telephone numbers exchanged via pagers: "Jump to the other side of the 5 on the keypad, and swap 5's and 0's."
Here's a keypad for visualization.
```
┌───┬───┬───┐
│ 1 │ 2 │ 3 │
├───┼───┼───┤
│ 4 │ 5 │ 6 │
├───┼───┼───┤
│ 7 │ 8 │ 9 │
└───┼───┼───┘
│ 0 │
└───┘
```
Detective, we're hot on their trail! We have a big pile of encoded messages here to use as evidence, but it would take way too long to decode by hand. Could you write a program to do this for us?
Write a function called decode(). Given an encoded string of exactly `10` digits, return the actual phone number in string form. Don't worry about input validation, parenthesis, or hyphens.
| games | def decode(s):
return s . translate(str . maketrans("1234567890", "9876043215"))
| The Barksdale Code | 573d498eb90ccf20a000002a | [
"Cryptography",
"Puzzles"
] | https://www.codewars.com/kata/573d498eb90ccf20a000002a | 7 kyu |
The most basic encryption method is to map a char to another char by a certain math rule.
Because every char has an ASCII value, we can manipulate this value with a simple math expression.
For example 'a' + 1 would give us 'b', because 'a' value is 97 and 'b' value is 98.
You will need to write a method which does exactly that -
get a string as text and an int as the rule of manipulation, and should return encrypted text.
for example:
encrypt("a",1) = "b"
*Full ascii table is used on our question (256 chars) - so 0-255 are the valid values.*
If the value exceeds 255, it should 'wrap'. ie. if the value is 345 it should wrap to 89.
Good luck. | games | def encrypt(text, rule):
return "" . join(chr((ord(i) + rule) % 256) for i in text)
| Basic Encryption | 5862fb364f7ab46270000078 | [
"Mathematics",
"Strings",
"Ciphers"
] | https://www.codewars.com/kata/5862fb364f7ab46270000078 | 6 kyu |
Third day at your new cryptoanalyst job and you come across your toughest assignment yet. Your job is to implement a simple keyword cipher. A keyword cipher is a type of monoalphabetic substitution where two parameters are provided as such (string, keyword). The string is encrypted by taking the keyword, dropping any letters that appear more than once. The rest of the letters of the alphabet that aren't used are then appended to the end of the keyword.
For example, if your string was "hello" and your keyword was "wednesday", your encryption key would be 'wednsaybcfghijklmopqrtuvxz'.
To encrypt 'hello' you'd substitute as follows,
```
abcdefghijklmnopqrstuvwxyz
hello ==> |||||||||||||||||||||||||| ==> bshhk
wednsaybcfghijklmopqrtuvxz
```
hello encrypts into bshhk with the keyword wednesday. This cipher also uses lower case letters only.
Good Luck.
| algorithms | abc = "abcdefghijklmnopqrstuvwxyz"
def keyword_cipher(s, keyword, key=""):
for c in keyword + abc:
if c not in key:
key += c
return s . lower(). translate(str . maketrans(abc, key))
| Keyword Cipher | 57241cafef90082e270012d8 | [
"Cryptography",
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/57241cafef90082e270012d8 | 6 kyu |
Help Suzuki count his vegetables....
Suzuki is the master monk of his monastery so it is up to him to ensure the kitchen is operating at full capacity to feed his students and the villagers that come for lunch on a daily basis.
This week there was a problem with his deliveries and all the vegetables became mixed up. There are two important aspects of cooking in his kitchen, it must be done in harmony and nothing can be wasted. Since the monks are a record keeping people the first order of business is to sort the mixed up vegetables and then count them to ensure there is enough to feed all the students and villagers.
You will be given a string with the following vegetables:
```
"cabbage", "carrot", "celery", "cucumber", "mushroom", "onion", "pepper", "potato", "tofu", "turnip"
```
Return a list of objects (tuple in Python, array in JavaScript, table in COBOL) with the count of each vegetable in descending order. If there are any non vegetables mixed in discard them. If the count of two vegetables is the same sort in reverse alphabetical order (Z->A).
```
(119, "pepper"),
(114, "carrot"),
(113, "turnip"),
(102, "onion"),
(101, "tofu"),
(100, "cabbage"),
(93, "mushroom"),
(90, "cucumber"),
(88, "potato"),
(80, "celery")
```
Please also try the other Kata in this series..
* [Help Suzuki purchase his Tofu!](https://www.codewars.com/kata/57d4ecb8164a67b97c00003c)
* [Help Suzuki pack his coal basket!](https://www.codewars.com/kata/57f09d0bcedb892791000255)
* [Help Suzuki rake his garden!](https://www.codewars.com/kata/571c1e847beb0a8f8900153d)
* [Suzuki needs help lining up his students!](https://www.codewars.com/kata/5701800886306a876a001031)
* [How many stairs will Suzuki climb in 20 years?](https://www.codewars.com/kata/56fc55cd1f5a93d68a001d4e) | reference | def count_vegetables(s):
items = s . split()
veggies = ['cabbage', 'carrot', 'celery', 'cucumber',
'mushroom', 'onion', 'pepper', 'potato', 'tofu', 'turnip']
return sorted([(items . count(v), v) for v in veggies], reverse=True)
| Help Suzuki count his vegetables.... | 56ff1667cc08cacf4b00171b | [
"Fundamentals"
] | https://www.codewars.com/kata/56ff1667cc08cacf4b00171b | 7 kyu |
Suzuki is a monk who climbs a large staircase to the monastery as part of a ritual. Some days he climbs more stairs than others depending on the number of students he must train in the morning. He is curious how many stairs might be climbed over the next 20 years and has spent a year marking down his daily progress.
The sum of all the stairs logged in a year will be used for estimating the number he might climb in 20.
<u>20_year_estimate = one_year_total * 20</u>
You will receive the following data structure representing the stairs Suzuki logged in a year. You will have all data for the entire year so regardless of how it is logged the problem should be simple to solve.
```
stairs = [sunday,monday,tuesday,wednesday,thursday,friday,saturday]
```
Make sure your solution takes into account all of the nesting within the stairs array.
Each weekday in the stairs array is an array.
```
sunday = [6737, 7244, 5776, 9826, 7057, 9247, 5842, 5484, 6543, 5153, 6832, 8274, 7148, 6152, 5940, 8040, 9174, 7555, 7682, 5252, 8793, 8837, 7320, 8478, 6063, 5751, 9716, 5085, 7315, 7859, 6628, 5425, 6331, 7097, 6249, 8381, 5936, 8496, 6934, 8347, 7036, 6421, 6510, 5821, 8602, 5312, 7836, 8032, 9871, 5990, 6309, 7825]
```
Your function should return the 20 year estimate of the stairs climbed using the formula above.
Please also try the other Kata in this series..
* [Help Suzuki count his vegetables...](https://www.codewars.com/kata/56ff1667cc08cacf4b00171b)
* [Help Suzuki purchase his Tofu!](https://www.codewars.com/kata/57d4ecb8164a67b97c00003c)
* [Help Suzuki pack his coal basket!](https://www.codewars.com/kata/57f09d0bcedb892791000255)
* [Help Suzuki rake his garden!](https://www.codewars.com/kata/571c1e847beb0a8f8900153d)
* [Suzuki needs help lining up his students!](https://www.codewars.com/kata/5701800886306a876a001031)
| reference | def stairs_in_20(stairs):
return sum(sum(day) for day in stairs) * 20
| How many stairs will Suzuki climb in 20 years? | 56fc55cd1f5a93d68a001d4e | [
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/56fc55cd1f5a93d68a001d4e | 8 kyu |
Suzuki needs help lining up his students!
Today Suzuki will be interviewing his students to ensure they are progressing in their training. He decided to schedule the interviews based on the length of the students name in descending order. The students will line up and wait for their turn.
You will be given a string of student names. Sort them and return a list of names in descending order.
Here is an example input:
```python
string = 'Tadashi Takahiro Takao Takashi Takayuki Takehiko Takeo Takeshi Takeshi'
```
Here is an example return from your function:
```python
lst = ['Takehiko',
'Takayuki',
'Takahiro',
'Takeshi',
'Takeshi',
'Takashi',
'Tadashi',
'Takeo',
'Takao']
```
Names of equal length will be returned in reverse alphabetical order (Z->A) such that:
```python
string = "xxa xxb xxc xxd xa xb xc xd"
```
Returns
```python
['xxd', 'xxc', 'xxb', 'xxa', 'xd', 'xc', 'xb', 'xa']
```
Please also try the other Kata in this series..
* [Help Suzuki count his vegetables...](https://www.codewars.com/kata/56ff1667cc08cacf4b00171b)
* [Help Suzuki purchase his Tofu!](https://www.codewars.com/kata/57d4ecb8164a67b97c00003c)
* [Help Suzuki pack his coal basket!](https://www.codewars.com/kata/57f09d0bcedb892791000255)
* [Help Suzuki rake his garden!](https://www.codewars.com/kata/571c1e847beb0a8f8900153d)
* [How many stairs will Suzuki climb in 20 years?](https://www.codewars.com/kata/56fc55cd1f5a93d68a001d4e) | reference | def lineup_students(s):
return sorted(s . split(), key=lambda i: (len(i), i), reverse=True)
| Suzuki needs help lining up his students! | 5701800886306a876a001031 | [
"Strings",
"Sorting",
"Fundamentals"
] | https://www.codewars.com/kata/5701800886306a876a001031 | 7 kyu |
Help Suzuki rake his garden!
The monastery has a magnificent Zen garden made of white gravel and rocks and it is raked diligently everyday by the monks. Suzuki having a keen eye is always on the lookout for anything creeping into the garden that must be removed during the daily raking such as insects or moss.
You will be given a string representing the garden such as:
```
garden = 'gravel gravel gravel gravel gravel gravel gravel gravel gravel rock slug ant gravel gravel snail rock gravel gravel gravel gravel gravel gravel gravel slug gravel ant gravel gravel gravel gravel rock slug gravel gravel gravel gravel gravel snail gravel gravel rock gravel snail slug gravel gravel spider gravel gravel gravel gravel gravel gravel gravel gravel moss gravel gravel gravel snail gravel gravel gravel ant gravel gravel moss gravel gravel gravel gravel snail gravel gravel gravel gravel slug gravel rock gravel gravel rock gravel gravel gravel gravel snail gravel gravel rock gravel gravel gravel gravel gravel spider gravel rock gravel gravel'
```
Rake out any items that are not a rock or gravel and replace them with gravel such that:
```
garden = 'slug spider rock gravel gravel gravel gravel gravel gravel gravel'
```
Returns a string with all items except a rock or gravel replaced with gravel:
```
garden = 'gravel gravel rock gravel gravel gravel gravel gravel gravel gravel'
```
Please also try the other Kata in this series..
* [Help Suzuki count his vegetables...](https://www.codewars.com/kata/56ff1667cc08cacf4b00171b)
* [Help Suzuki purchase his Tofu!](https://www.codewars.com/kata/57d4ecb8164a67b97c00003c)
* [Help Suzuki pack his coal basket!](https://www.codewars.com/kata/57f09d0bcedb892791000255)
* [Suzuki needs help lining up his students!](https://www.codewars.com/kata/5701800886306a876a001031)
* [How many stairs will Suzuki climb in 20 years?](https://www.codewars.com/kata/56fc55cd1f5a93d68a001d4e) | reference | VALID = {'gravel', 'rock'}
def rake_garden(garden):
return ' ' . join(a if a in VALID else 'gravel' for a in garden . split())
| Help Suzuki rake his garden! | 571c1e847beb0a8f8900153d | [
"Fundamentals"
] | https://www.codewars.com/kata/571c1e847beb0a8f8900153d | 7 kyu |
Help Suzuki purchase his Tofu!
Suzuki has sent a lay steward to market who will purchase some items not produced in the monastary gardens for the monks. The stewart has with him a large box full of change from donations earlier in the day mixed in with some personal items. You will be given a string of items representing the box.
Sort through the items in the box finding the coins and putting aside anything else.
You will be given a data structure similar to the one below.
```
box = 'mon mon mon mon mon apple mon mon mon mon mon mon mon monme mon mon monme mon mon mon mon cloth monme mon mon mon mon mon mon mon mon cloth mon mon monme mon mon mon mon monme mon mon mon mon mon mon mon mon mon mon mon mon mon'
Return the following in your solution.
[count of mon coins in box, count of monme coins in box,sum of all coins value in box, minimum number of coins needed for Tofu]
100 ≤ cost ≤ 1000
cost = 124
returns
[45, 5, 345, 6]
```
The coins have the following values:
monme = 60
mon = 1
Determine the minimum number of coins to pay for tofu. You must pay with exact change and if you do not have the correct change return “leaving the market”.
If the cost of tofu is higher than your total amount of money also return “leaving the market”
Please also try the other Kata in this series..
* [Help Suzuki count his vegetables...](https://www.codewars.com/kata/56ff1667cc08cacf4b00171b)
* [Help Suzuki pack his coal basket!](https://www.codewars.com/kata/57f09d0bcedb892791000255)
* [Help Suzuki rake his garden!](https://www.codewars.com/kata/571c1e847beb0a8f8900153d)
* [Suzuki needs help lining up his students!](https://www.codewars.com/kata/5701800886306a876a001031)
* [How many stairs will Suzuki climb in 20 years?](https://www.codewars.com/kata/56fc55cd1f5a93d68a001d4e)
| reference | def buy_tofu(cost, box):
box = box . split()
M, m = box . count('monme'), box . count('mon')
total = 60 * M + m
C, c = divmod(cost, 60)
change = min(C, M)
if 60 * change + m < cost:
return 'leaving the market'
return [m, M, total, change + (C - change) * 60 + c]
| Help Suzuki purchase his Tofu! | 57d4ecb8164a67b97c00003c | [
"Algorithms",
"Data Structures",
"Fundamentals"
] | https://www.codewars.com/kata/57d4ecb8164a67b97c00003c | 6 kyu |
__Function composition__ is a mathematical operation that mainly presents itself in lambda calculus and computability. It is explained well [here](http://www.mathsisfun.com/sets/functions-composition.html), but this is my explanation, in simple mathematical notation:
```
f3 = compose( f1 f2 )
Is equivalent to...
f3(a) = f1( f2( a ) )
```
~~~if-not:lambdacalc,ruby
Your task is to create a `compose` function to carry out this task, which will be passed two functions or lambdas. Ruby functions will be passed, and should return, either a proc or a lambda. Remember that the resulting composed function may be passed multiple arguments!
~~~
~~~if:ruby
Your task is to create a `compose` function to carry out this task, which will be passed two functions, and should return either a proc or a lambda. Remember that the resulting composed function may be passed multiple arguments!
~~~
~~~if:lambdacalc
Your task is to create a `compose` function to carry out this task.
~~~
```javascript
compose(f , g)(x)
=> f( g( x ) )
```
```ruby
compose(f , g).(x)
=> f.( g.( x ) )
```
```coffeescript
compose(f , g)(x)
=> f( g( x ) )
```
```clojure
((compose f g) x)
=> (f (g x) )
```
```python
compose(f , g)(x)
=> f( g( x ) )
```
```lambdacalc
h = compose f g
h x # f (g x)
```
This kata is not available in haskell; that would be too easy! | reference | def compose(f, g):
return lambda * x: f(g(* x))
| Function Composition | 5421c6a2dda52688f6000af8 | [
"Functional Programming",
"Fundamentals"
] | https://www.codewars.com/kata/5421c6a2dda52688f6000af8 | 6 kyu |
You will be given an array of objects representing data about developers who have signed up to attend the next coding meetup that you are organising.
Your task is to return an **object which includes the count of food options selected by the developers on the meetup sign-up form.**.
For example, given the following input array:
```javascript
var list1 = [
{ firstName: 'Noah', lastName: 'M.', country: 'Switzerland', continent: 'Europe', age: 19, language: 'C',
meal: 'vegetarian' },
{ firstName: 'Anna', lastName: 'R.', country: 'Liechtenstein', continent: 'Europe', age: 52, language: 'JavaScript',
meal: 'standard' },
{ firstName: 'Ramona', lastName: 'R.', country: 'Paraguay', continent: 'Americas', age: 29, language: 'Ruby',
meal: 'vegan' },
{ firstName: 'George', lastName: 'B.', country: 'England', continent: 'Europe', age: 81, language: 'C',
meal: 'vegetarian' },
];
```
```python
list1 = [
{ 'firstName': 'Noah', 'lastName': 'M.', 'country': 'Switzerland', 'continent': 'Europe', 'age': 19, 'language': 'C', 'meal': 'vegetarian' },
{ 'firstName': 'Anna', 'lastName': 'R.', 'country': 'Liechtenstein', 'continent': 'Europe', 'age': 52, 'language': 'JavaScript', 'meal': 'standard' },
{ 'firstName': 'Ramona', 'lastName': 'R.', 'country': 'Paraguay', 'continent': 'Americas', 'age': 29, 'language': 'Ruby', 'meal': 'vegan' },
{ 'firstName': 'George', 'lastName': 'B.', 'country': 'England', 'continent': 'Europe', 'age': 81, 'language': 'C', 'meal': 'vegetarian' },
]
```
```cobol
01 List.
03 ListLength pic 9(2) value 4.
03 dev1.
05 FirstName pic a(9) value 'Noah'.
05 LastName pic x(2) value 'M.'.
05 Country pic a(24) value 'Switzerland'.
05 Continent pic a(8) value 'Europe'.
05 Age pic 9(3) value 19.
05 Language pic a(10) value 'C'.
05 Meal pic a(17) value 'vegetarian'.
03 dev2.
05 FirstName pic a(9) value 'Anna'.
05 LastName pic x(2) value 'R.'.
05 Country pic a(24) value 'Liechtenstein'.
05 Continent pic a(8) value 'Europe'.
05 Age pic 9(3) value 52.
05 Language pic a(10) value 'JavaScript'.
05 Meal pic a(17) value 'standard'.
03 dev3.
05 FirstName pic a(9) value 'Ramona'.
05 LastName pic x(2) value 'R.'.
05 Country pic a(24) value 'Paraguay'.
05 Continent pic a(8) value 'Americas'.
05 Age pic 9(3) value 29.
05 Language pic a(10) value 'Ruby'.
05 Meal pic a(17) value 'vegan'.
03 dev4.
05 FirstName pic a(9) value 'George'.
05 LastName pic x(2) value 'B.'.
05 Country pic a(24) value 'England'.
05 Continent pic a(8) value 'Europe'.
05 Age pic 9(3) value 81.
05 Language pic a(10) value 'C'.
05 Meal pic a(17) value 'vegetarian'.
```
your function should return the following object (the order of properties does not matter):
```javascript
{ vegetarian: 2, standard: 1, vegan: 1 }
```
```python
{ 'vegetarian': 2, 'standard': 1, 'vegan': 1 }
```
```cobol
[['vegetarian', 2], ['standard', 1], ['vegan', 1]]
```
Notes:
- The order of the meals count in the object does not matter.
- The count value should be a valid number.
- The input array will always be valid and formatted as in the example above.
- there are 5 possible meal options and the strings representing the selected meal option will always be formatted in the same way, as follows: `'standard'`, `'vegetarian'`, `'vegan'`, `'diabetic'`, `'gluten-intolerant'`.
<br>
<br>
<br>
<br>
<br>
This kata is part of the **Coding Meetup** series which includes a number of short and easy to follow katas which have been designed to allow mastering the use of higher-order functions. In JavaScript this includes methods like: `forEach, filter, map, reduce, some, every, find, findIndex`. Other approaches to solving the katas are of course possible.
Here is the full list of the katas in the **Coding Meetup** series:
<a href="http://www.codewars.com/kata/coding-meetup-number-1-higher-order-functions-series-count-the-number-of-javascript-developers-coming-from-europe">Coding Meetup #1 - Higher-Order Functions Series - Count the number of JavaScript developers coming from Europe</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-2-higher-order-functions-series-greet-developers">Coding Meetup #2 - Higher-Order Functions Series - Greet developers</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-3-higher-order-functions-series-is-ruby-coming">Coding Meetup #3 - Higher-Order Functions Series - Is Ruby coming?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-4-higher-order-functions-series-find-the-first-python-developer">Coding Meetup #4 - Higher-Order Functions Series - Find the first Python developer</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-5-higher-order-functions-series-prepare-the-count-of-languages">Coding Meetup #5 - Higher-Order Functions Series - Prepare the count of languages</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-6-higher-order-functions-series-can-they-code-in-the-same-language">Coding Meetup #6 - Higher-Order Functions Series - Can they code in the same language?</a>
<a href="http://www.codewars.com/kata/coding-meetup-number-7-higher-order-functions-series-find-the-most-senior-developer">Coding Meetup #7 - Higher-Order Functions Series - Find the most senior developer</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-8-higher-order-functions-series-will-all-continents-be-represented">Coding Meetup #8 - Higher-Order Functions Series - Will all continents be represented?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-9-higher-order-functions-series-is-the-meetup-age-diverse">Coding Meetup #9 - Higher-Order Functions Series - Is the meetup age-diverse?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-10-higher-order-functions-series-create-usernames">Coding Meetup #10 - Higher-Order Functions Series - Create usernames</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-11-higher-order-functions-series-find-the-average-age">Coding Meetup #11 - Higher-Order Functions Series - Find the average age</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-12-higher-order-functions-series-find-github-admins">Coding Meetup #12 - Higher-Order Functions Series - Find GitHub admins</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-13-higher-order-functions-series-is-the-meetup-language-diverse">Coding Meetup #13 - Higher-Order Functions Series - Is the meetup language-diverse?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-14-higher-order-functions-series-order-the-food">Coding Meetup #14 - Higher-Order Functions Series - Order the food</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-15-higher-order-functions-series-find-the-odd-names">Coding Meetup #15 - Higher-Order Functions Series - Find the odd names</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-16-higher-order-functions-series-ask-for-missing-details">Coding Meetup #16 - Higher-Order Functions Series - Ask for missing details</a> | reference | from collections import Counter
def order_food(lst):
return Counter(dev['meal'] for dev in lst)
| Coding Meetup #14 - Higher-Order Functions Series - Order the food | 583952fbc23341c7180002fd | [
"Functional Programming",
"Data Structures",
"Arrays",
"Fundamentals",
"Algorithms",
"Strings"
] | https://www.codewars.com/kata/583952fbc23341c7180002fd | 7 kyu |
You will be given an array of objects representing data about developers who have signed up to attend the next coding meetup that you are organising.
Given the following input array:
```javascript
var list1 = [
{ firstName: 'Aba', lastName: 'N.', country: 'Ghana', continent: 'Africa', age: 21, language: 'Python' },
{ firstName: 'Abb', lastName: 'O.', country: 'Israel', continent: 'Asia', age: 39, language: 'Java' }
];
```
```cobol
01 list1.
03 ListLength pic 9(2) value 2.
03 dev1.
05 FirstName pic a(9) value 'Aba'.
05 LastName pic x(2) value 'N.'.
05 Country pic a(24) value 'Ghana'.
05 Continent pic a(8) value 'Africa'.
05 Age pic 9(3) value 21.
05 Language pic a(10) value 'Python'.
03 dev2.
05 FirstName pic a(9) value 'Abb'.
05 LastName pic x(2) value 'O.'.
05 Country pic a(24) value 'Israel'.
05 Continent pic a(8) value 'Asia'.
05 Age pic 9(3) value 39.
05 Language pic a(10) value 'Java'.
```
write a function that when executed as `findOddNames(list1)` returns only the developers where **if you add the ASCII representation of all characters in their first names, the result will be an odd number**:
```javascript
[
{ firstName: 'Abb', lastName: 'O.', country: 'Israel', continent: 'Asia', age: 39, language: 'Java' }
]
```
```cobol
01 result.
03 ResLength pic 9(2) value 1.
03 .
05 FirstName pic a(9) value 'Abb'.
05 LastName pic x(2) value 'O.'.
05 Country pic a(24) value 'Israel'.
05 Continent pic a(8) value 'Asia'.
05 Age pic 9(3) value 39.
05 Language pic a(10) value 'Java'.
```
Explanation of the above:
- Sum of ASCII codes of letters in `'Aba'` is: `65 + 98 + 97 = 260` which is an even number
- Sum of ASCII codes of letters in `'Abb'` is: `65 + 98 + 98 = 261` which is an **odd number**
Notes:
- Preserve the order of the original list.
- Return an empty array `[]` if there is no developer with an "odd" name.
- The input array and first names will always be valid and formatted as in the example above.
<br>
<br>
<br>
<br>
<br>
This kata is part of the **Coding Meetup** series which includes a number of short and easy to follow katas which have been designed to allow mastering the use of higher-order functions. In JavaScript this includes methods like: `forEach, filter, map, reduce, some, every, find, findIndex`. Other approaches to solving the katas are of course possible.
Here is the full list of the katas in the **Coding Meetup** series:
<a href="http://www.codewars.com/kata/coding-meetup-number-1-higher-order-functions-series-count-the-number-of-javascript-developers-coming-from-europe">Coding Meetup #1 - Higher-Order Functions Series - Count the number of JavaScript developers coming from Europe</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-2-higher-order-functions-series-greet-developers">Coding Meetup #2 - Higher-Order Functions Series - Greet developers</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-3-higher-order-functions-series-is-ruby-coming">Coding Meetup #3 - Higher-Order Functions Series - Is Ruby coming?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-4-higher-order-functions-series-find-the-first-python-developer">Coding Meetup #4 - Higher-Order Functions Series - Find the first Python developer</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-5-higher-order-functions-series-prepare-the-count-of-languages">Coding Meetup #5 - Higher-Order Functions Series - Prepare the count of languages</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-6-higher-order-functions-series-can-they-code-in-the-same-language">Coding Meetup #6 - Higher-Order Functions Series - Can they code in the same language?</a>
<a href="http://www.codewars.com/kata/coding-meetup-number-7-higher-order-functions-series-find-the-most-senior-developer">Coding Meetup #7 - Higher-Order Functions Series - Find the most senior developer</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-8-higher-order-functions-series-will-all-continents-be-represented">Coding Meetup #8 - Higher-Order Functions Series - Will all continents be represented?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-9-higher-order-functions-series-is-the-meetup-age-diverse">Coding Meetup #9 - Higher-Order Functions Series - Is the meetup age-diverse?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-10-higher-order-functions-series-create-usernames">Coding Meetup #10 - Higher-Order Functions Series - Create usernames</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-11-higher-order-functions-series-find-the-average-age">Coding Meetup #11 - Higher-Order Functions Series - Find the average age</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-12-higher-order-functions-series-find-github-admins">Coding Meetup #12 - Higher-Order Functions Series - Find GitHub admins</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-13-higher-order-functions-series-is-the-meetup-language-diverse">Coding Meetup #13 - Higher-Order Functions Series - Is the meetup language-diverse?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-14-higher-order-functions-series-order-the-food">Coding Meetup #14 - Higher-Order Functions Series - Order the food</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-15-higher-order-functions-series-find-the-odd-names">Coding Meetup #15 - Higher-Order Functions Series - Find the odd names</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-16-higher-order-functions-series-ask-for-missing-details">Coding Meetup #16 - Higher-Order Functions Series - Ask for missing details</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-17-higher-order-functions-series-sort-by-programming-language">Coding Meetup #17 - Higher-Order Functions Series - Sort by programming language</a> | reference | def find_odd_names(lst):
return [x for x in lst if sum(map(ord, x["firstName"])) % 2]
| Coding Meetup #15 - Higher-Order Functions Series - Find the odd names | 583a8bde28019d615a000035 | [
"Functional Programming",
"Data Structures",
"Arrays",
"Fundamentals",
"Algorithms",
"Strings"
] | https://www.codewars.com/kata/583a8bde28019d615a000035 | 6 kyu |
You will be given an array of objects representing data about developers who have signed up to attend the next coding meetup that you are organising.
Given the following input array:
```javascript
var list1 = [
{ firstName: 'Harry', lastName: 'K.', country: 'Brazil', continent: 'Americas', age: 22, language: 'JavaScript', githubAdmin: 'yes' },
{ firstName: 'Kseniya', lastName: 'T.', country: 'Belarus', continent: 'Europe', age: 49, language: 'Ruby', githubAdmin: 'no' },
{ firstName: 'Jing', lastName: 'X.', country: 'China', continent: 'Asia', age: 34, language: 'JavaScript', githubAdmin: 'yes' },
{ firstName: 'Piotr', lastName: 'B.', country: 'Poland', continent: 'Europe', age: 128, language: 'JavaScript', githubAdmin: 'no' }
];
```
```python
list1 = [
{ 'firstName': 'Harry', 'lastName': 'K.', 'country': 'Brazil', 'continent': 'Americas', 'age': 22, 'language': 'JavaScript', 'githubAdmin': 'yes' },
{ 'firstName': 'Kseniya', 'lastName': 'T.', 'country': 'Belarus', 'continent': 'Europe', 'age': 49, 'language': 'Ruby', 'githubAdmin': 'no' },
{ 'firstName': 'Jing', 'lastName': 'X.', 'country': 'China', 'continent': 'Asia', 'age': 34, 'language': 'JavaScript', 'githubAdmin': 'yes' },
{ 'firstName': 'Piotr', 'lastName': 'B.', 'country': 'Poland', 'continent': 'Europe', 'age': 128, 'language': 'JavaScript', 'githubAdmin': 'no' }
]
```
```cobol
01 list1.
03 ListLength pic 9(2) value 4.
03 dev1.
05 FirstName pic a(9) value 'Harry'.
05 LastName pic x(2) value 'K.'.
05 Country pic a(24) value 'Brazil'.
05 Continent pic a(8) value 'Americas'.
05 Age pic 9(3) value 22.
05 Language pic a(10) value 'JavaScript'.
05 GithubAdmin pic a(3) value 'yes'.
03 dev2.
05 FirstName pic a(9) value 'Kseniya'.
05 LastName pic x(2) value 'T.'.
05 Country pic a(24) value 'Belarus'.
05 Continent pic a(8) value 'Europe'.
05 Age pic 9(3) value 49.
05 Language pic a(10) value 'Ruby'.
05 GithubAdmin pic a(3) value 'no'.
03 dev3.
05 FirstName pic a(9) value 'Jing'.
05 LastName pic x(2) value 'X.'.
05 Country pic a(24) value 'China'.
05 Continent pic a(8) value 'Asia'.
05 Age pic 9(3) value 34.
05 Language pic a(10) value 'JavaScript'.
05 GithubAdmin pic a(3) value 'yes'.
03 dev4.
05 FirstName pic a(9) value 'Piotr'.
05 LastName pic x(2) value 'B.'.
05 Country pic a(24) value 'Poland'.
05 Continent pic a(8) value 'Europe'.
05 Age pic 9(3) value 128.
05 Language pic a(10) value 'JavaScript'.
05 GithubAdmin pic a(3) value 'no'.
```
write a function that when executed as `findAdmin(list1, 'JavaScript')` returns only the JavaScript developers who are GitHub admins:
```javascript
[
{ firstName: 'Harry', lastName: 'K.', country: 'Brazil', continent: 'Americas', age: 22, language: 'JavaScript', githubAdmin: 'yes' },
{ firstName: 'Jing', lastName: 'X.', country: 'China', continent: 'Asia', age: 34, language: 'JavaScript', githubAdmin: 'yes' }
]
```
```python
[
{ 'firstName': 'Harry', 'lastName': 'K.', 'country': 'Brazil', 'continent': 'Americas', 'age': 22, 'language': 'JavaScript', 'githubAdmin': 'yes' },
{ 'firstName': 'Jing', 'lastName': 'X.', 'country': 'China', 'continent': 'Asia', 'age': 34, 'language': 'JavaScript', 'githubAdmin': 'yes' }
]
```
```cobol
01 result.
03 ResLength pic 9(2) value 2.
03 .
05 FirstName pic a(9) value 'Harry'.
05 LastName pic x(2) value 'K.'.
05 Country pic a(24) value 'Brazil'.
05 Continent pic a(8) value 'Americas'.
05 Age pic 9(3) value 22.
05 Language pic a(10) value 'JavaScript'.
05 GithubAdmin pic a(4) value 'yes'.
03 .
05 FirstName pic a(9) value 'Jing'.
05 LastName pic x(2) value 'X.'.
05 Country pic a(24) value 'China'.
05 Continent pic a(8) value 'Asia'.
05 Age pic 9(3) value 34.
05 Language pic a(10) value 'JavaScript'.
05 GithubAdmin pic a(4) value 'yes'.
```
Notes:
- The original order should be preserved.
- If there are no GitHub admin developers in a given language then return an empty array `[]`.
- The input array will always be valid and formatted as in the example above.
- The strings representing whether someone is a GitHub admin will always be formatted as `'yes'` and `'no'` (all lower-case).
- The strings representing a given language will always be formatted in the same way (e.g. `'JavaScript'` will always be formatted with upper-case 'J' and 'S'.
<br>
<br>
<br>
<br>
<br>
This kata is part of the **Coding Meetup** series which includes a number of short and easy to follow katas which have been designed to allow mastering the use of higher-order functions. In JavaScript this includes methods like: `forEach, filter, map, reduce, some, every, find, findIndex`. Other approaches to solving the katas are of course possible.
Here is the full list of the katas in the **Coding Meetup** series:
<a href="http://www.codewars.com/kata/coding-meetup-number-1-higher-order-functions-series-count-the-number-of-javascript-developers-coming-from-europe">Coding Meetup #1 - Higher-Order Functions Series - Count the number of JavaScript developers coming from Europe</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-2-higher-order-functions-series-greet-developers">Coding Meetup #2 - Higher-Order Functions Series - Greet developers</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-3-higher-order-functions-series-is-ruby-coming">Coding Meetup #3 - Higher-Order Functions Series - Is Ruby coming?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-4-higher-order-functions-series-find-the-first-python-developer">Coding Meetup #4 - Higher-Order Functions Series - Find the first Python developer</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-5-higher-order-functions-series-prepare-the-count-of-languages">Coding Meetup #5 - Higher-Order Functions Series - Prepare the count of languages</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-6-higher-order-functions-series-can-they-code-in-the-same-language">Coding Meetup #6 - Higher-Order Functions Series - Can they code in the same language?</a>
<a href="http://www.codewars.com/kata/coding-meetup-number-7-higher-order-functions-series-find-the-most-senior-developer">Coding Meetup #7 - Higher-Order Functions Series - Find the most senior developer</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-8-higher-order-functions-series-will-all-continents-be-represented">Coding Meetup #8 - Higher-Order Functions Series - Will all continents be represented?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-9-higher-order-functions-series-is-the-meetup-age-diverse">Coding Meetup #9 - Higher-Order Functions Series - Is the meetup age-diverse?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-10-higher-order-functions-series-create-usernames">Coding Meetup #10 - Higher-Order Functions Series - Create usernames</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-11-higher-order-functions-series-find-the-average-age">Coding Meetup #11 - Higher-Order Functions Series - Find the average age</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-12-higher-order-functions-series-find-github-admins">Coding Meetup #12 - Higher-Order Functions Series - Find GitHub admins</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-13-higher-order-functions-series-is-the-meetup-language-diverse">Coding Meetup #13 - Higher-Order Functions Series - Is the meetup language-diverse?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-14-higher-order-functions-series-order-the-food">Coding Meetup #14 - Higher-Order Functions Series - Order the food</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-15-higher-order-functions-series-find-the-odd-names">Coding Meetup #15 - Higher-Order Functions Series - Find the odd names</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-16-higher-order-functions-series-ask-for-missing-details">Coding Meetup #16 - Higher-Order Functions Series - Ask for missing details</a> | reference | def find_admin(lst, lang):
return [i for i in lst if i['language'] == lang and i['githubAdmin'] == 'yes']
| Coding Meetup #12 - Higher-Order Functions Series - Find GitHub admins | 582dace555a1f4d859000058 | [
"Functional Programming",
"Data Structures",
"Arrays",
"Fundamentals",
"Algorithms",
"Strings"
] | https://www.codewars.com/kata/582dace555a1f4d859000058 | 7 kyu |
You will be given a sequence of objects representing data about developers who have signed up to attend the next coding meetup that you are organising.
Given the following input array:
```javascript
var list1 = [
{ firstName: 'Maria', lastName: 'Y.', country: 'Cyprus', continent: 'Europe', age: 30, language: 'Java' },
{ firstName: 'Victoria', lastName: 'T.', country: 'Puerto Rico', continent: 'Americas', age: 70, language: 'Python' },
];
```
```python
list1 = [
{ 'firstName': 'Maria', 'lastName': 'Y.', 'country': 'Cyprus', 'continent': 'Europe', 'age': 30, 'language': 'Java' },
{ 'firstName': 'Victoria', 'lastName': 'T.', 'country': 'Puerto Rico', 'continent': 'Americas', 'age': 70, 'language': 'Python' },
]
```
```cobol
01 List.
03 dev1.
05 FirstName pic a(9) value 'Maria'.
05 LastName pic x(2) value 'Y.'.
05 Country pic a(22) value 'Cyprus'.
05 Continent pic a(8) value 'Europe'.
05 Age pic 9(3) value 30.
05 Language pic a(10) value 'Java'.
03 dev2.
05 FirstName pic a(9) value 'Victoria'.
05 LastName pic x(2) value 'T.'.
05 Country pic a(22) value 'Puerto Rico'.
05 Continent pic a(8) value 'Americas'.
05 Age pic 9(3) value 70.
05 Language pic a(10) value 'Python'.
```
write a function that returns the average age of developers (rounded to the nearest integer). In the example above your function should return `50` (number).
Notes:
- The input array will always be valid and formatted as in the example above.
- Age is represented by a number which can be any positive integer.
<br>
<br>
<br>
<br>
<br>
This kata is part of the **Coding Meetup** series which includes a number of short and easy to follow katas which have been designed to allow mastering the use of higher-order functions. In JavaScript this includes methods like: `forEach, filter, map, reduce, some, every, find, findIndex`. Other approaches to solving the katas are of course possible.
Here is the full list of the katas in the **Coding Meetup** series:
<a href="http://www.codewars.com/kata/coding-meetup-number-1-higher-order-functions-series-count-the-number-of-javascript-developers-coming-from-europe">Coding Meetup #1 - Higher-Order Functions Series - Count the number of JavaScript developers coming from Europe</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-2-higher-order-functions-series-greet-developers">Coding Meetup #2 - Higher-Order Functions Series - Greet developers</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-3-higher-order-functions-series-is-ruby-coming">Coding Meetup #3 - Higher-Order Functions Series - Is Ruby coming?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-4-higher-order-functions-series-find-the-first-python-developer">Coding Meetup #4 - Higher-Order Functions Series - Find the first Python developer</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-5-higher-order-functions-series-prepare-the-count-of-languages">Coding Meetup #5 - Higher-Order Functions Series - Prepare the count of languages</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-6-higher-order-functions-series-can-they-code-in-the-same-language">Coding Meetup #6 - Higher-Order Functions Series - Can they code in the same language?</a>
<a href="http://www.codewars.com/kata/coding-meetup-number-7-higher-order-functions-series-find-the-most-senior-developer">Coding Meetup #7 - Higher-Order Functions Series - Find the most senior developer</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-8-higher-order-functions-series-will-all-continents-be-represented">Coding Meetup #8 - Higher-Order Functions Series - Will all continents be represented?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-9-higher-order-functions-series-is-the-meetup-age-diverse">Coding Meetup #9 - Higher-Order Functions Series - Is the meetup age-diverse?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-10-higher-order-functions-series-create-usernames">Coding Meetup #10 - Higher-Order Functions Series - Create usernames</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-11-higher-order-functions-series-find-the-average-age">Coding Meetup #11 - Higher-Order Functions Series - Find the average age</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-12-higher-order-functions-series-find-github-admins">Coding Meetup #12 - Higher-Order Functions Series - Find GitHub admins</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-13-higher-order-functions-series-is-the-meetup-language-diverse">Coding Meetup #13 - Higher-Order Functions Series - Is the meetup language-diverse?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-14-higher-order-functions-series-order-the-food">Coding Meetup #14 - Higher-Order Functions Series - Order the food</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-15-higher-order-functions-series-find-the-odd-names">Coding Meetup #15 - Higher-Order Functions Series - Find the odd names</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-16-higher-order-functions-series-ask-for-missing-details">Coding Meetup #16 - Higher-Order Functions Series - Ask for missing details</a> | algorithms | def get_average(lst):
return round(sum(x["age"] for x in lst) / len(lst))
| Coding Meetup #11 - Higher-Order Functions Series - Find the average age | 582ba36cc1901399a70005fc | [
"Functional Programming",
"Data Structures",
"Arrays",
"Fundamentals",
"Algorithms",
"Strings"
] | https://www.codewars.com/kata/582ba36cc1901399a70005fc | 7 kyu |
You will be given an array of objects (associative arrays in PHP) representing data about developers who have signed up to attend the next coding meetup that you are organising.
Your task is to return:
- `true` if developers from all of the following age groups have signed up: teens, twenties, thirties, forties, fifties, sixties, seventies, eighties, nineties, centenarian (at least 100 years young).
- `false` otherwise.
For example, given the following input array:
```javascript
var list1 = [
{ firstName: 'Harry', lastName: 'K.', country: 'Brazil', continent: 'Americas', age: 19, language: 'Python' },
{ firstName: 'Kseniya', lastName: 'T.', country: 'Belarus', continent: 'Europe', age: 29, language: 'JavaScript' },
{ firstName: 'Jing', lastName: 'X.', country: 'China', continent: 'Asia', age: 39, language: 'Ruby' },
{ firstName: 'Noa', lastName: 'A.', country: 'Israel', continent: 'Asia', age: 40, language: 'Ruby' },
{ firstName: 'Andrei', lastName: 'E.', country: 'Romania', continent: 'Europe', age: 59, language: 'C' },
{ firstName: 'Maria', lastName: 'S.', country: 'Peru', continent: 'Americas', age: 60, language: 'C' },
{ firstName: 'Lukas', lastName: 'X.', country: 'Croatia', continent: 'Europe', age: 75, language: 'Python' },
{ firstName: 'Chloe', lastName: 'K.', country: 'Guernsey', continent: 'Europe', age: 88, language: 'Ruby' },
{ firstName: 'Viktoria', lastName: 'W.', country: 'Bulgaria', continent: 'Europe', age: 98, language: 'PHP' },
{ firstName: 'Piotr', lastName: 'B.', country: 'Poland', continent: 'Europe', age: 128, language: 'JavaScript' }
];
```
```php
$list1 = [
[
"first_name" => "Harry",
"last_name" => "K.",
"country" => "Brazil",
"continent" => "Americas",
"age" => 19,
"language" => "Python"
],
[
"first_name" => "Kseniya",
"last_name" => "T.",
"country" => "Belarus",
"continent" => "Europe",
"age" => 29,
"language" => "JavaScript"
],
[
"first_name" => "Jing",
"last_name" => "X.",
"country" => "China",
"continent" => "Asia",
"age" => 39,
"language" => "Ruby"
],
[
"first_name" => "Noa",
"last_name" => "A.",
"country" => "Israel",
"continent" => "Asia",
"age" => 40,
"language" => "Ruby"
],
[
"first_name" => "Andrei",
"last_name" => "E.",
"country" => "Romania",
"continent" => "Europe",
"age" => 59,
"language" => "C"
],
[
"first_name" => "Maria",
"last_name" => "S.",
"country" => "Peru",
"continent" => "Americas",
"age" => 60,
"language" => "C"
],
[
"first_name" => "Lukas",
"last_name" => "X.",
"country" => "Croatia",
"continent" => "Europe",
"age" => 75,
"language" => "Python"
],
[
"first_name" => "Chloe",
"last_name" => "K.",
"country" => "Guernsey",
"continent" => "Europe",
"age" => 88,
"language" => "Ruby"
],
[
"first_name" => "Viktoria",
"last_name" => "W.",
"country" => "Bulgaria",
"continent" => "Europe",
"age" => 98,
"language" => "PHP"
],
[
"first_name" => "Piotr",
"last_name" => "B.",
"country" => "Poland",
"continent" => "Europe",
"age" => 128,
"language" => "JavaScript"
]
];
```
```python
list1 = [
{ 'firstName': 'Harry', 'lastName': 'K.', 'country': 'Brazil', 'continent': 'Americas', 'age': 19, 'language': 'Python' },
{ 'firstName': 'Kseniya', 'lastName': 'T.', 'country': 'Belarus', 'continent': 'Europe', 'age': 29, 'language': 'JavaScript' },
{ 'firstName': 'Jing', 'lastName': 'X.', 'country': 'China', 'continent': 'Asia', 'age': 39, 'language': 'Ruby' },
{ 'firstName': 'Noa', 'lastName': 'A.', 'country': 'Israel', 'continent': 'Asia', 'age': 40, 'language': 'Ruby' },
{ 'firstName': 'Andrei', 'lastName': 'E.', 'country': 'Romania', 'continent': 'Europe', 'age': 59, 'language': 'C' },
{ 'firstName': 'Maria', 'lastName': 'S.', 'country': 'Peru', 'continent': 'Americas', 'age': 60, 'language': 'C' },
{ 'firstName': 'Lukas', 'lastName': 'X.', 'country': 'Croatia', 'continent': 'Europe', 'age': 75, 'language': 'Python' },
{ 'firstName': 'Chloe', 'lastName': 'K.', 'country': 'Guernsey', 'continent': 'Europe', 'age': 88, 'language': 'Ruby' },
{ 'firstName': 'Viktoria', 'lastName': 'W.', 'country': 'Bulgaria', 'continent': 'Europe', 'age': 98, 'language': 'PHP' },
{ 'firstName': 'Piotr', 'lastName': 'B.', 'country': 'Poland', 'continent': 'Europe', 'age': 128, 'language': 'JavaScript' }
]
```
```cobol
01 List.
03 ListLength pic 9(2) value 10.
03 dev1.
05 FirstName pic a(9) value 'Harry'.
05 LastName pic x(2) value 'K.'.
05 Country pic a(24) value 'Brazil'.
05 Continent pic a(8) value 'Americas'.
05 Age pic 9(3) value 19.
05 Language pic a(10) value 'Python'.
03 dev2.
05 FirstName pic a(9) value 'Kseniya'.
05 LastName pic x(2) value 'T.'.
05 Country pic a(24) value 'Belarus'.
05 Continent pic a(8) value 'Europe'.
05 Age pic 9(3) value 29.
05 Language pic a(10) value 'JavaScript'.
03 dev3.
05 FirstName pic a(9) value 'Jing'.
05 LastName pic x(2) value 'X.'.
05 Country pic a(24) value 'China'.
05 Continent pic a(8) value 'Asia'.
05 Age pic 9(3) value 39.
05 Language pic a(10) value 'Ruby'.
03 dev4.
05 FirstName pic a(9) value 'Noa'.
05 LastName pic x(2) value 'A.'.
05 Country pic a(24) value 'Israel'.
05 Continent pic a(8) value 'Asia'.
05 Age pic 9(3) value 40.
05 Language pic a(10) value 'Ruby'.
03 dev5.
05 FirstName pic a(9) value 'Andrei'.
05 LastName pic x(2) value 'E.'.
05 Country pic a(24) value 'Romania'.
05 Continent pic a(8) value 'Europe'.
05 Age pic 9(3) value 59.
05 Language pic a(10) value 'C'.
03 dev6.
05 FirstName pic a(9) value 'Maria'.
05 LastName pic x(2) value 'S.'.
05 Country pic a(24) value 'Peru'.
05 Continent pic a(8) value 'Americas'.
05 Age pic 9(3) value 60.
05 Language pic a(10) value 'C'.
03 dev7.
05 FirstName pic a(9) value 'Lukas'.
05 LastName pic x(2) value 'X.'.
05 Country pic a(24) value 'Croatia'.
05 Continent pic a(8) value 'Europe'.
05 Age pic 9(3) value 75.
05 Language pic a(10) value 'Python'.
03 dev8.
05 FirstName pic a(9) value 'Chloe'.
05 LastName pic x(2) value 'K.'.
05 Country pic a(24) value 'Guernsey'.
05 Continent pic a(8) value 'Europe'.
05 Age pic 9(3) value 88.
05 Language pic a(10) value 'Ruby'.
03 dev9.
05 FirstName pic a(9) value 'Viktoria'.
05 LastName pic x(2) value 'W.'.
05 Country pic a(24) value 'Bulgaria'.
05 Continent pic a(8) value 'Europe'.
05 Age pic 9(3) value 98.
05 Language pic a(10) value 'PHP'.
03 dev10.
05 FirstName pic a(9) value 'Piotr'.
05 LastName pic x(2) value 'B.'.
05 Country pic a(24) value 'Poland'.
05 Continent pic a(8) value 'Europe'.
05 Age pic 9(3) value 128.
05 Language pic a(10) value 'JavaScript'.
```
your function should return `true` as there is at least one developer from each age group.
Notes:
- The input array will always be valid and formatted as in the example above.
- Age is represented by a number which can be any positive integer up to 199.
<br>
<br>
<br>
<br>
<br>
This kata is part of the **Coding Meetup** series which includes a number of short and easy to follow katas which have been designed to allow mastering the use of higher-order functions. In JavaScript this includes methods like: `forEach, filter, map, reduce, some, every, find, findIndex`. Other approaches to solving the katas are of course possible.
Here is the full list of the katas in the **Coding Meetup** series:
<a href="http://www.codewars.com/kata/coding-meetup-number-1-higher-order-functions-series-count-the-number-of-javascript-developers-coming-from-europe">Coding Meetup #1 - Higher-Order Functions Series - Count the number of JavaScript developers coming from Europe</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-2-higher-order-functions-series-greet-developers">Coding Meetup #2 - Higher-Order Functions Series - Greet developers</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-3-higher-order-functions-series-is-ruby-coming">Coding Meetup #3 - Higher-Order Functions Series - Is Ruby coming?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-4-higher-order-functions-series-find-the-first-python-developer">Coding Meetup #4 - Higher-Order Functions Series - Find the first Python developer</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-5-higher-order-functions-series-prepare-the-count-of-languages">Coding Meetup #5 - Higher-Order Functions Series - Prepare the count of languages</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-6-higher-order-functions-series-can-they-code-in-the-same-language">Coding Meetup #6 - Higher-Order Functions Series - Can they code in the same language?</a>
<a href="http://www.codewars.com/kata/coding-meetup-number-7-higher-order-functions-series-find-the-most-senior-developer">Coding Meetup #7 - Higher-Order Functions Series - Find the most senior developer</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-8-higher-order-functions-series-will-all-continents-be-represented">Coding Meetup #8 - Higher-Order Functions Series - Will all continents be represented?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-9-higher-order-functions-series-is-the-meetup-age-diverse">Coding Meetup #9 - Higher-Order Functions Series - Is the meetup age-diverse?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-10-higher-order-functions-series-create-usernames">Coding Meetup #10 - Higher-Order Functions Series - Create usernames</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-11-higher-order-functions-series-find-the-average-age">Coding Meetup #11 - Higher-Order Functions Series - Find the average age</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-12-higher-order-functions-series-find-github-admins">Coding Meetup #12 - Higher-Order Functions Series - Find GitHub admins</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-13-higher-order-functions-series-is-the-meetup-language-diverse">Coding Meetup #13 - Higher-Order Functions Series - Is the meetup language-diverse?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-14-higher-order-functions-series-order-the-food">Coding Meetup #14 - Higher-Order Functions Series - Order the food</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-15-higher-order-functions-series-find-the-odd-names">Coding Meetup #15 - Higher-Order Functions Series - Find the odd names</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-16-higher-order-functions-series-ask-for-missing-details">Coding Meetup #16 - Higher-Order Functions Series - Ask for missing details</a> | algorithms | def is_age_diverse(lst):
arr = list(map(lambda x: x["age"] / / 10, lst))
return any(x >= 10 for x in arr) and all(i in arr for i in range(1, 10))
| Coding Meetup #9 - Higher-Order Functions Series - Is the meetup age-diverse? | 5829ca646d02cd1a65000284 | [
"Functional Programming",
"Data Structures",
"Arrays",
"Fundamentals",
"Algorithms",
"Strings"
] | https://www.codewars.com/kata/5829ca646d02cd1a65000284 | 6 kyu |
You will be given a sequence of objects (associative arrays in PHP) representing data about developers who have signed up to attend the next coding meetup that you are organising.
Your task is to return:
- `true` if all of the following continents / geographic zones will be represented by at least one developer: 'Africa', 'Americas', 'Asia', 'Europe', 'Oceania'.
- `false` otherwise.
For example, given the following input array:
```javascript
var list1 = [
{ firstName: 'Fatima', lastName: 'A.', country: 'Algeria', continent: 'Africa', age: 25, language: 'JavaScript' },
{ firstName: 'Agustín', lastName: 'M.', country: 'Chile', continent: 'Americas', age: 37, language: 'C' },
{ firstName: 'Jing', lastName: 'X.', country: 'China', continent: 'Asia', age: 39, language: 'Ruby' },
{ firstName: 'Laia', lastName: 'P.', country: 'Andorra', continent: 'Europe', age: 55, language: 'Ruby' },
{ firstName: 'Oliver', lastName: 'Q.', country: 'Australia', continent: 'Oceania', age: 65, language: 'PHP' },
];
```
```php
$list1 = [
[
"first_name" => "Fatima",
"last_name" => "A.",
"country" => "Algeria",
"continent" => "Africa",
"age" => 25,
"language" => "JavaScript"
],
[
"first_name" => "Agustin",
"last_name" => "M.",
"country" => "Chile",
"continent" => "Americas",
"age" => 37,
"language" => "C"
],
[
"first_name" => "Jing",
"last_name" => "X",
"country" => "China",
"continent" => "Asia",
"age" => 39,
"language" => "Ruby"
],
[
"first_name" => "Laia",
"last_name" => "P.",
"country" => "Andorra",
"continent" => "Europe",
"age" => 55,
"language" => "Ruby"
],
[
"first_name" => "Oliver",
"last_name" => "Q.",
"country" => "Australia",
"continent" => "Oceania",
"age" => 65,
"language" => "PHP"
]
];
```
```python
list1 = [
{ 'firstName': 'Fatima', 'lastName': 'A.', 'country': 'Algeria', 'continent': 'Africa', 'age': 25, 'language': 'JavaScript' },
{ 'firstName': 'Agustín', 'lastName': 'M.', 'country': 'Chile', 'continent': 'Americas', 'age': 37, 'language': 'C' },
{ 'firstName': 'Jing', 'lastName': 'X.', 'country': 'China', 'continent': 'Asia', 'age': 39, 'language': 'Ruby' },
{ 'firstName': 'Laia', 'lastName': 'P.', 'country': 'Andorra', 'continent': 'Europe', 'age': 55, 'language': 'Ruby' },
{ 'firstName': 'Oliver', 'lastName': 'Q.', 'country': 'Australia', 'continent': 'Oceania', 'age': 65, 'language': 'PHP' }
]
```
```cobol
01 List.
03 ListLength pic 9(2) value 5.
03 dev1.
05 FirstName pic a(9) value 'Fatima'.
05 LastName pic x(2) value 'A.'.
05 Country pic a(24) value 'Algeria'.
05 Continent pic a(8) value 'Africa'.
05 Age pic 9(3) value 25.
05 Language pic a(10) value 'JavaScript'.
03 dev2.
05 FirstName pic a(9) value 'Agustin'.
05 LastName pic x(2) value 'M.'.
05 Country pic a(24) value 'Chile'.
05 Continent pic a(8) value 'Americas'.
05 Age pic 9(3) value 37.
05 Language pic a(10) value 'C'.
03 dev3.
05 FirstName pic a(9) value 'Jing'.
05 LastName pic x(2) value 'X.'.
05 Country pic a(24) value 'China'.
05 Continent pic a(8) value 'Asia'.
05 Age pic 9(3) value 39.
05 Language pic a(10) value 'Ruby'.
03 dev4.
05 FirstName pic a(9) value 'Laia'.
05 LastName pic x(2) value 'P.'.
05 Country pic a(24) value 'Andorra'.
05 Continent pic a(8) value 'Europe'.
05 Age pic 9(3) value 55.
05 Language pic a(10) value 'Ruby'.
03 dev5.
05 FirstName pic a(9) value 'Oliver'.
05 LastName pic x(2) value 'Q.'.
05 Country pic a(24) value 'Australia'.
05 Continent pic a(8) value 'Oceania'.
05 Age pic 9(3) value 69.
05 Language pic a(10) value 'PHP'.
```
your function should return `true` as there is at least one developer from the required 5 geographic zones.
Notes:
- The input array and continent names will always be valid and formatted as in the list above for example 'Africa' will always start with upper-case 'A'.
<br>
<br>
<br>
<br>
<br>
This kata is part of the **Coding Meetup** series which includes a number of short and easy to follow katas which have been designed to allow mastering the use of higher-order functions. In JavaScript this includes methods like: `forEach, filter, map, reduce, some, every, find, findIndex`. Other approaches to solving the katas are of course possible.
Here is the full list of the katas in the **Coding Meetup** series:
<a href="http://www.codewars.com/kata/coding-meetup-number-1-higher-order-functions-series-count-the-number-of-javascript-developers-coming-from-europe">Coding Meetup #1 - Higher-Order Functions Series - Count the number of JavaScript developers coming from Europe</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-2-higher-order-functions-series-greet-developers">Coding Meetup #2 - Higher-Order Functions Series - Greet developers</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-3-higher-order-functions-series-is-ruby-coming">Coding Meetup #3 - Higher-Order Functions Series - Is Ruby coming?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-4-higher-order-functions-series-find-the-first-python-developer">Coding Meetup #4 - Higher-Order Functions Series - Find the first Python developer</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-5-higher-order-functions-series-prepare-the-count-of-languages">Coding Meetup #5 - Higher-Order Functions Series - Prepare the count of languages</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-6-higher-order-functions-series-can-they-code-in-the-same-language">Coding Meetup #6 - Higher-Order Functions Series - Can they code in the same language?</a>
<a href="http://www.codewars.com/kata/coding-meetup-number-7-higher-order-functions-series-find-the-most-senior-developer">Coding Meetup #7 - Higher-Order Functions Series - Find the most senior developer</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-8-higher-order-functions-series-will-all-continents-be-represented">Coding Meetup #8 - Higher-Order Functions Series - Will all continents be represented?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-9-higher-order-functions-series-is-the-meetup-age-diverse">Coding Meetup #9 - Higher-Order Functions Series - Is the meetup age-diverse?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-10-higher-order-functions-series-create-usernames">Coding Meetup #10 - Higher-Order Functions Series - Create usernames</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-11-higher-order-functions-series-find-the-average-age">Coding Meetup #11 - Higher-Order Functions Series - Find the average age</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-12-higher-order-functions-series-find-github-admins">Coding Meetup #12 - Higher-Order Functions Series - Find GitHub admins</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-13-higher-order-functions-series-is-the-meetup-language-diverse">Coding Meetup #13 - Higher-Order Functions Series - Is the meetup language-diverse?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-14-higher-order-functions-series-order-the-food">Coding Meetup #14 - Higher-Order Functions Series - Order the food</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-15-higher-order-functions-series-find-the-odd-names">Coding Meetup #15 - Higher-Order Functions Series - Find the odd names</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-16-higher-order-functions-series-ask-for-missing-details">Coding Meetup #16 - Higher-Order Functions Series - Ask for missing details</a> | algorithms | def all_continents(lst):
return len(set(x["continent"] for x in lst)) == 5
| Coding Meetup #8 - Higher-Order Functions Series - Will all continents be represented? | 58291fea7ff3f640980000f9 | [
"Functional Programming",
"Data Structures",
"Arrays",
"Fundamentals",
"Algorithms",
"Strings"
] | https://www.codewars.com/kata/58291fea7ff3f640980000f9 | 6 kyu |
You will be given a sequence of objects representing data about developers who have signed up to attend the next coding meetup that you are organising.
Your task is to return a sequence which includes the developer who is the oldest. In case of a tie, include all same-age senior developers listed in the same order as they appeared in the original input array.
For example, given the following input array:
```javascript
var list1 = [
{ firstName: 'Gabriel', lastName: 'X.', country: 'Monaco', continent: 'Europe', age: 49, language: 'PHP' },
{ firstName: 'Odval', lastName: 'F.', country: 'Mongolia', continent: 'Asia', age: 38, language: 'Python' },
{ firstName: 'Emilija', lastName: 'S.', country: 'Lithuania', continent: 'Europe', age: 19, language: 'Python' },
{ firstName: 'Sou', lastName: 'B.', country: 'Japan', continent: 'Asia', age: 49, language: 'PHP' },
];
```
```python
list1 = [
{ 'firstName': 'Gabriel', 'lastName': 'X.', 'country': 'Monaco', 'continent': 'Europe', 'age': 49, 'language': 'PHP' },
{ 'firstName': 'Odval', 'lastName': 'F.', 'country': 'Mongolia', 'continent': 'Asia', 'age': 38, 'language': 'Python' },
{ 'firstName': 'Emilija', 'lastName': 'S.', 'country': 'Lithuania', 'continent': 'Europe', 'age': 19, 'language': 'Python' },
{ 'firstName': 'Sou', 'lastName': 'B.', 'country': 'Japan', 'continent': 'Asia', 'age': 49, 'language': 'PHP' },
]
```
```cobol
01 List.
03 ListLength pic 9(2) value 4.
03 dev1.
05 FirstName pic a(9) value 'Gabriel'.
05 LastName pic x(2) value 'X.'.
05 Country pic a(24) value 'Monaco'.
05 Continent pic a(8) value 'Europe'.
05 Age pic 9(3) value 49.
05 Language pic a(10) value 'PHP'.
03 dev2.
05 FirstName pic a(9) value 'Odval'.
05 LastName pic x(2) value 'F.'.
05 Country pic a(24) value 'Mongolia'.
05 Continent pic a(8) value 'Asia'.
05 Age pic 9(3) value 38.
05 Language pic a(10) value 'Python'.
03 dev3.
05 FirstName pic a(9) value 'Emilija'.
05 LastName pic x(2) value 'S.'.
05 Country pic a(24) value 'Lithuania'.
05 Continent pic a(8) value 'Europe'.
05 Age pic 9(3) value 19.
05 Language pic a(10) value 'Python'.
03 dev4.
05 FirstName pic a(9) value 'Sou'.
05 LastName pic x(2) value 'B.'.
05 Country pic a(24) value 'Japan'.
05 Continent pic a(8) value 'Asia'.
05 Age pic 9(3) value 49.
05 Language pic a(10) value 'PHP'.
```
your function should return the following array:
```javascript
[
{ firstName: 'Gabriel', lastName: 'X.', country: 'Monaco', continent: 'Europe', age: 49, language: 'PHP' },
{ firstName: 'Sou', lastName: 'B.', country: 'Japan', continent: 'Asia', age: 49, language: 'PHP' },
]
```
```python
[
{ 'firstName': 'Gabriel', 'lastName': 'X.', 'country': 'Monaco', 'continent': 'Europe', 'age': 49, 'language': 'PHP' },
{ 'firstName': 'Sou', 'lastName': 'B.', 'country': 'Japan', 'continent': 'Asia', 'age': 49, 'language': 'PHP' },
]
```
```cobol
01 result.
03 res-length pic 9(2) value 2.
03 .
05 FirstName pic a(9) value 'Gabriel'.
05 LastName pic x(2) value 'X.'.
05 Country pic a(24) value 'Monaco'.
05 Continent pic a(8) value 'Europe'.
05 Age pic 9(3) value 49.
05 Language pic a(10) value 'PHP'.
03 .
05 FirstName pic a(9) value 'Sou'.
05 LastName pic x(2) value 'B.'.
05 Country pic a(24) value 'Japan'.
05 Continent pic a(8) value 'Asia'.
05 Age pic 9(3) value 49.
05 Language pic a(10) value 'PHP'.
```
Notes:
- The input array will always be valid and formatted as in the example above and will never be empty.
<br>
<br>
<br>
<br>
<br>
This kata is part of the **Coding Meetup** series which includes a number of short and easy to follow katas which have been designed to allow mastering the use of higher-order functions. In JavaScript this includes methods like: `forEach, filter, map, reduce, some, every, find, findIndex`. Other approaches to solving the katas are of course possible.
Here is the full list of the katas in the **Coding Meetup** series:
<a href="http://www.codewars.com/kata/coding-meetup-number-1-higher-order-functions-series-count-the-number-of-javascript-developers-coming-from-europe">Coding Meetup #1 - Higher-Order Functions Series - Count the number of JavaScript developers coming from Europe</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-2-higher-order-functions-series-greet-developers">Coding Meetup #2 - Higher-Order Functions Series - Greet developers</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-3-higher-order-functions-series-is-ruby-coming">Coding Meetup #3 - Higher-Order Functions Series - Is Ruby coming?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-4-higher-order-functions-series-find-the-first-python-developer">Coding Meetup #4 - Higher-Order Functions Series - Find the first Python developer</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-5-higher-order-functions-series-prepare-the-count-of-languages">Coding Meetup #5 - Higher-Order Functions Series - Prepare the count of languages</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-6-higher-order-functions-series-can-they-code-in-the-same-language">Coding Meetup #6 - Higher-Order Functions Series - Can they code in the same language?</a>
<a href="http://www.codewars.com/kata/coding-meetup-number-7-higher-order-functions-series-find-the-most-senior-developer">Coding Meetup #7 - Higher-Order Functions Series - Find the most senior developer</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-8-higher-order-functions-series-will-all-continents-be-represented">Coding Meetup #8 - Higher-Order Functions Series - Will all continents be represented?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-9-higher-order-functions-series-is-the-meetup-age-diverse">Coding Meetup #9 - Higher-Order Functions Series - Is the meetup age-diverse?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-10-higher-order-functions-series-create-usernames">Coding Meetup #10 - Higher-Order Functions Series - Create usernames</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-11-higher-order-functions-series-find-the-average-age">Coding Meetup #11 - Higher-Order Functions Series - Find the average age</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-12-higher-order-functions-series-find-github-admins">Coding Meetup #12 - Higher-Order Functions Series - Find GitHub admins</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-13-higher-order-functions-series-is-the-meetup-language-diverse">Coding Meetup #13 - Higher-Order Functions Series - Is the meetup language-diverse?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-14-higher-order-functions-series-order-the-food">Coding Meetup #14 - Higher-Order Functions Series - Order the food</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-15-higher-order-functions-series-find-the-odd-names">Coding Meetup #15 - Higher-Order Functions Series - Find the odd names</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-16-higher-order-functions-series-ask-for-missing-details">Coding Meetup #16 - Higher-Order Functions Series - Ask for missing details</a> | algorithms | def find_senior(lst):
mage = max(a['age'] for a in lst)
return [a for a in lst if a['age'] == mage]
| Coding Meetup #7 - Higher-Order Functions Series - Find the most senior developer | 582887f7d04efdaae3000090 | [
"Functional Programming",
"Data Structures",
"Arrays",
"Fundamentals",
"Algorithms",
"Strings"
] | https://www.codewars.com/kata/582887f7d04efdaae3000090 | 6 kyu |
You will be given an array of objects (associative arrays in PHP, tables in COBOL) representing data about developers who have signed up to attend the next coding meetup that you are organising.
Your task is to return either:
- `true` if all developers in the list code in the same language; or
- `false` otherwise.
For example, given the following input array:
```javascript
var list1 = [
{ firstName: 'Daniel', lastName: 'J.', country: 'Aruba', continent: 'Americas', age: 42, language: 'JavaScript' },
{ firstName: 'Kseniya', lastName: 'T.', country: 'Belarus', continent: 'Europe', age: 22, language: 'JavaScript' },
{ firstName: 'Hanna', lastName: 'L.', country: 'Hungary', continent: 'Europe', age: 65, language: 'JavaScript' },
];
```
```php
$list1 = [
[
"first_name" => "Daniel",
"last_name" => "J.",
"country" => "Aruba",
"continent" => "Americas",
"age" => 42,
"language" => "JavaScript"
],
[
"first_name" => "Kseniya",
"last_name" => "T.",
"country" => "Belarus",
"continent" => "Europe",
"age" => 22,
"language" => "JavaScript"
],
[
"first_name" => "Hanna",
"last_name" => "L.",
"country" => "Hungary",
"continent" => "Europe",
"age" => 65,
"language" => "JavaScript"
]
];
```
```python
list1 = [
{ 'firstName': 'Daniel', 'lastName': 'J.', 'country': 'Aruba', 'continent': 'Americas', 'age': 42, 'language': 'JavaScript' },
{ 'firstName': 'Kseniya', 'lastName': 'T.', 'country': 'Belarus', 'continent': 'Europe', 'age': 22, 'language': 'JavaScript' },
{ 'firstName': 'Hanna', 'lastName': 'L.', 'country': 'Hungary', 'continent': 'Europe', 'age': 65, 'language': 'JavaScript' },
]
```
```cobol
01 List.
03 ListLength pic 9 value 3.
03 dev1.
05 FirstName pic a(9) value 'Daniel'.
05 LastName pic x(2) value 'J.'.
05 Country pic a(24) value 'Aruba'.
05 Continent pic a(8) value 'Americas'.
05 Age pic 9(3) value 42.
05 Language pic a(10) value 'JavaScript'.
03 dev2.
05 FirstName pic a(9) value 'Kseniya'.
05 LastName pic x(2) value 'T.'.
05 Country pic a(24) value 'Belarus'.
05 Continent pic a(8) value 'Europe'.
05 Age pic 9(3) value 29.
05 Language pic a(10) value 'JavaScript'.
03 dev3.
05 FirstName pic a(9) value 'Hanna'.
05 LastName pic x(2) value 'L.'.
05 Country pic a(24) value 'Hungary'.
05 Continent pic a(8) value 'Europe'.
05 Age pic 9(3) value 29.
05 Language pic a(10) value 'JavaScript'.
```
your function should return `true`.
Notes:
- The strings representing a given language will always be formatted in the same way (e.g. 'JavaScript' will always be formatted will upper-case 'J' and 'S'
- The input array will always be valid and formatted as in the example above.
<br>
<br>
<br>
<br>
<br>
This kata is part of the **Coding Meetup** series which includes a number of short and easy to follow katas which have been designed to allow mastering the use of higher-order functions. In JavaScript this includes methods like: `forEach, filter, map, reduce, some, every, find, findIndex`. Other approaches to solving the katas are of course possible.
Here is the full list of the katas in the **Coding Meetup** series:
<a href="http://www.codewars.com/kata/coding-meetup-number-1-higher-order-functions-series-count-the-number-of-javascript-developers-coming-from-europe">Coding Meetup #1 - Higher-Order Functions Series - Count the number of JavaScript developers coming from Europe</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-2-higher-order-functions-series-greet-developers">Coding Meetup #2 - Higher-Order Functions Series - Greet developers</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-3-higher-order-functions-series-is-ruby-coming">Coding Meetup #3 - Higher-Order Functions Series - Is Ruby coming?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-4-higher-order-functions-series-find-the-first-python-developer">Coding Meetup #4 - Higher-Order Functions Series - Find the first Python developer</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-5-higher-order-functions-series-prepare-the-count-of-languages">Coding Meetup #5 - Higher-Order Functions Series - Prepare the count of languages</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-6-higher-order-functions-series-can-they-code-in-the-same-language">Coding Meetup #6 - Higher-Order Functions Series - Can they code in the same language?</a>
<a href="http://www.codewars.com/kata/coding-meetup-number-7-higher-order-functions-series-find-the-most-senior-developer">Coding Meetup #7 - Higher-Order Functions Series - Find the most senior developer</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-8-higher-order-functions-series-will-all-continents-be-represented">Coding Meetup #8 - Higher-Order Functions Series - Will all continents be represented?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-9-higher-order-functions-series-is-the-meetup-age-diverse">Coding Meetup #9 - Higher-Order Functions Series - Is the meetup age-diverse?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-10-higher-order-functions-series-create-usernames">Coding Meetup #10 - Higher-Order Functions Series - Create usernames</a>
<<<<<<< mine
<a href="https://www.codewars.com/kata/coding-meetup-number-11-higher-order-functions-series-find-the-average-age">Coding Meetup #11 - Higher-Order Functions Series - Find the average age</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-12-higher-order-functions-series-find-github-admins">Coding Meetup #12 - Higher-Order Functions Series - Find GitHub admins</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-13-higher-order-functions-series-is-the-meetup-language-diverse">Coding Meetup #13 - Higher-Order Functions Series - Is the meetup language-diverse?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-14-higher-order-functions-series-order-the-food">Coding Meetup #14 - Higher-Order Functions Series - Order the food</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-15-higher-order-functions-series-find-the-odd-names">Coding Meetup #15 - Higher-Order Functions Series - Find the odd names</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-16-higher-order-functions-series-ask-for-missing-details">Coding Meetup #16 - Higher-Order Functions Series - Ask for missing details</a>
| algorithms | def is_same_language(lst):
return len(set(i["language"] for i in lst)) == 1
| Coding Meetup #6 - Higher-Order Functions Series - Can they code in the same language? | 58287977ef8d4451f90001a0 | [
"Functional Programming",
"Data Structures",
"Arrays",
"Fundamentals",
"Algorithms",
"Strings"
] | https://www.codewars.com/kata/58287977ef8d4451f90001a0 | 7 kyu |
You will be given an array of objects (associative arrays in PHP, table in COBOL) representing data about developers who have signed up to attend the next coding meetup that you are organising.
Your task is to return an **object (associative array in PHP, table in COBOL) which includes the count of each coding language represented at the meetup**.
For example, given the following input array:
```javascript
var list1 = [
{ firstName: 'Noah', lastName: 'M.', country: 'Switzerland', continent: 'Europe', age: 19, language: 'C' },
{ firstName: 'Anna', lastName: 'R.', country: 'Liechtenstein', continent: 'Europe', age: 52, language: 'JavaScript' },
{ firstName: 'Ramon', lastName: 'R.', country: 'Paraguay', continent: 'Americas', age: 29, language: 'Ruby' },
{ firstName: 'George', lastName: 'B.', country: 'England', continent: 'Europe', age: 81, language: 'C' },
];
```
```python
list1 = [
{ 'firstName': 'Noah', 'lastName': 'M.', 'country': 'Switzerland', 'continent': 'Europe', 'age': 19, 'language': 'C' },
{ 'firstName': 'Anna', 'lastName': 'R.', 'country': 'Liechtenstein', 'continent': 'Europe', 'age': 52, 'language': 'JavaScript' },
{ 'firstName': 'Ramon', 'lastName': 'R.', 'country': 'Paraguay', 'continent': 'Americas', 'age': 29, 'language': 'Ruby' },
{ 'firstName': 'George', 'lastName': 'B.', 'country': 'England', 'continent': 'Europe', 'age': 81, 'language': 'C' },
]
```
```php
$list1 = [
[
"first_name" => "Noah",
"last_name" => "M.",
"country" => "Switzerland",
"continent" => "Europe",
"age" => 19,
"language" => "C"
],
[
"first_name" => "Anna",
"last_name" => "R.",
"country" => "Liechtenstein",
"continent" => "Europe",
"age" => 52,
"language" => "JavaScript"
],
[
"first_name" => "Ramon",
"last_name" => "R.",
"country" => "Paraguay",
"continent" => "Americas",
"age" => 29,
"language" => "Ruby"
],
[
"first_name" => "George",
"last_name" => "B.",
"country" => "England",
"continent" => "Europe",
"age" => 81,
"language" => "C"
]
];
```
```cobol
01 List.
03 ListLength pic 9(3) value 4.
03 dev1.
05 FirstName pic a(9) value 'Noah'.
05 LastName pic x(2) value 'M.'.
05 Country pic a(24) value 'Switzerland'.
05 Continent pic a(8) value 'Europe'.
05 Age pic 9(3) value 19.
05 Language pic a(10) value 'C'.
03 dev2.
05 FirstName pic a(9) value 'Anna'.
05 LastName pic x(2) value 'R.'.
05 Country pic a(24) value 'Liechtenstein'.
05 Continent pic a(8) value 'Europe'.
05 Age pic 9(3) value 32.
05 Language pic a(10) value 'JavaScript'.
03 dev3.
05 FirstName pic a(9) value 'Ramon'.
05 LastName pic x(2) value 'R.'.
05 Country pic a(24) value 'Paraguay'.
05 Continent pic a(8) value 'Americas'.
05 Age pic 9(3) value 99.
05 Language pic a(10) value 'Ruby'.
03 dev4.
05 FirstName pic a(9) value 'George'.
05 LastName pic x(2) value 'B.'.
05 Country pic a(24) value 'England'.
05 Continent pic a(8) value 'Europe'.
05 Age pic 9(3) value 21.
05 Language pic a(10) value 'C'.
```
your function should return the following object (associative array in PHP, table in COBOL):
```javascript
{ C: 2, JavaScript: 1, Ruby: 1 }
```
```python
{ 'C': 2, 'JavaScript': 1, 'Ruby': 1 }
```
```php
[
"C" => 2,
"JavaScript" => 1,
"Ruby" => 1
]
```
```cobol
[['C', 2], ['JavaScript': 1], ['Ruby': 1]]
```
Notes:
- The order of the languages in the object does not matter.
- The count value should be a valid number.
- The input array will always be valid and formatted as in the example above.
<br>
<br>
<br>
<br>
<br>
This kata is part of the **Coding Meetup** series which includes a number of short and easy to follow katas which have been designed to allow mastering the use of higher-order functions. In JavaScript this includes methods like: `forEach, filter, map, reduce, some, every, find, findIndex`. Other approaches to solving the katas are of course possible.
Here is the full list of the katas in the **Coding Meetup** series:
<a href="http://www.codewars.com/kata/coding-meetup-number-1-higher-order-functions-series-count-the-number-of-javascript-developers-coming-from-europe">Coding Meetup #1 - Higher-Order Functions Series - Count the number of JavaScript developers coming from Europe</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-2-higher-order-functions-series-greet-developers">Coding Meetup #2 - Higher-Order Functions Series - Greet developers</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-3-higher-order-functions-series-is-ruby-coming">Coding Meetup #3 - Higher-Order Functions Series - Is Ruby coming?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-4-higher-order-functions-series-find-the-first-python-developer">Coding Meetup #4 - Higher-Order Functions Series - Find the first Python developer</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-5-higher-order-functions-series-prepare-the-count-of-languages">Coding Meetup #5 - Higher-Order Functions Series - Prepare the count of languages</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-6-higher-order-functions-series-can-they-code-in-the-same-language">Coding Meetup #6 - Higher-Order Functions Series - Can they code in the same language?</a>
<a href="http://www.codewars.com/kata/coding-meetup-number-7-higher-order-functions-series-find-the-most-senior-developer">Coding Meetup #7 - Higher-Order Functions Series - Find the most senior developer</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-8-higher-order-functions-series-will-all-continents-be-represented">Coding Meetup #8 - Higher-Order Functions Series - Will all continents be represented?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-9-higher-order-functions-series-is-the-meetup-age-diverse">Coding Meetup #9 - Higher-Order Functions Series - Is the meetup age-diverse?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-10-higher-order-functions-series-create-usernames">Coding Meetup #10 - Higher-Order Functions Series - Create usernames</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-11-higher-order-functions-series-find-the-average-age">Coding Meetup #11 - Higher-Order Functions Series - Find the average age</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-12-higher-order-functions-series-find-github-admins">Coding Meetup #12 - Higher-Order Functions Series - Find GitHub admins</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-13-higher-order-functions-series-is-the-meetup-language-diverse">Coding Meetup #13 - Higher-Order Functions Series - Is the meetup language-diverse?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-14-higher-order-functions-series-order-the-food">Coding Meetup #14 - Higher-Order Functions Series - Order the food</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-15-higher-order-functions-series-find-the-odd-names">Coding Meetup #15 - Higher-Order Functions Series - Find the odd names</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-16-higher-order-functions-series-ask-for-missing-details">Coding Meetup #16 - Higher-Order Functions Series - Ask for missing details</a> | algorithms | from collections import Counter
def count_languages(lst):
return Counter([d['language'] for d in lst])
| Coding Meetup #5 - Higher-Order Functions Series - Prepare the count of languages | 5828713ed04efde70e000346 | [
"Functional Programming",
"Data Structures",
"Arrays",
"Fundamentals",
"Algorithms"
] | https://www.codewars.com/kata/5828713ed04efde70e000346 | 7 kyu |
You will be given an array of objects (associative arrays in PHP, tables in COBOL) representing data about developers who have signed up to attend the next coding meetup that you are organising.
Your task is to **return an array where each object will have a new property 'greeting' with the following string value:**
**Hi < firstName here >, what do you like the most about < language here >?**
For example, given the following input array:
```javascript
var list1 = [
{ firstName: 'Sofia', lastName: 'I.', country: 'Argentina', continent: 'Americas', age: 35, language: 'Java' },
{ firstName: 'Lukas', lastName: 'X.', country: 'Croatia', continent: 'Europe', age: 35, language: 'Python' },
{ firstName: 'Madison', lastName: 'U.', country: 'United States', continent: 'Americas', age: 32, language: 'Ruby' }
];
```
```ruby
list1 = [
{ firstName: 'Sofia', lastName: 'I.', country: 'Argentina', continent: 'Americas', age: 35, language: 'Java' },
{ firstName: 'Lukas', lastName: 'X.', country: 'Croatia', continent: 'Europe', age: 35, language: 'Python' },
{ firstName: 'Madison', lastName: 'U.', country: 'United States', continent: 'Americas', age: 32, language: 'Ruby' }
]
```
```php
$list1 = [
[
"first_name" => "Sofia",
"last_name" => "I.",
"country" => "Argentina",
"continent" => "Americas",
"age" => 35,
"language" => "Java"
],
[
"first_name" => "Lukas",
"last_name" => "X.",
"country" => "Croatia",
"continent" => "Europe",
"age" => 35,
"language" => "Python"
],
[
"first_name" => "Madison",
"last_name" => "U.",
"country" => "United States",
"continent" => "Americas",
"age" => 32,
"language" => "Ruby"
]
];
```
```python
list1 = [
{ 'firstName': 'Sofia', 'lastName': 'I.', 'country': 'Argentina', 'continent': 'Americas', 'age': 35, 'language': 'Java' },
{ 'firstName': 'Lukas', 'lastName': 'X.', 'country': 'Croatia', 'continent': 'Europe', 'age': 35, 'language': 'Python' },
{ 'firstName': 'Madison', 'lastName': 'U.', 'country': 'United States', 'continent': 'Americas', 'age': 32, 'language': 'Ruby' }
]
```
```cobol
01 List.
03 ListLength pic 9(3) value 3.
03 dev1.
05 FirstName pic a(9) value 'Sofia'.
05 LastName pic x(2) value 'I.'.
05 Country pic a(24) value 'Argentina'.
05 Continent pic a(8) value 'Americas'.
05 Age pic 9(3) value 35.
05 Language pic a(10) value 'Java'.
03 dev2.
05 FirstName pic a(9) value 'Lukas'.
05 LastName pic x(2) value 'X.'.
05 Country pic a(24) value 'Croatia'.
05 Continent pic a(8) value 'Europe'.
05 Age pic 9(3) value 75.
05 Language pic a(10) value 'Python'.
03 dev3.
05 FirstName pic a(9) value 'Madison'.
05 LastName pic x(2) value 'U.'.
05 Country pic a(24)
value 'United States of America'.
05 Continent pic a(8) value 'Americas'.
05 Age pic 9(3) value 32.
05 Language pic a(10) value 'Ruby'.
```
your function should return the following array:
```javascript
[
{ firstName: 'Sofia', lastName: 'I.', country: 'Argentina', continent: 'Americas', age: 35, language: 'Java',
greeting: 'Hi Sofia, what do you like the most about Java?'
},
{ firstName: 'Lukas', lastName: 'X.', country: 'Croatia', continent: 'Europe', age: 35, language: 'Python',
greeting: 'Hi Lukas, what do you like the most about Python?'
},
{ firstName: 'Madison', lastName: 'U.', country: 'United States', continent: 'Americas', age: 32, language: 'Ruby',
greeting: 'Hi Madison, what do you like the most about Ruby?'
}
];
```
```ruby
[
{ firstName: 'Sofia', lastName: 'I.', country: 'Argentina', continent: 'Americas', age: 35, language: 'Java',
greeting: 'Hi Sofia, what do you like the most about Java?'
},
{ firstName: 'Lukas', lastName: 'X.', country: 'Croatia', continent: 'Europe', age: 35, language: 'Python',
greeting: 'Hi Lukas, what do you like the most about Python?'
},
{ firstName: 'Madison', lastName: 'U.', country: 'United States', continent: 'Americas', age: 32, language: 'Ruby',
greeting: 'Hi Madison, what do you like the most about Ruby?'
}
]
```
```php
[
[
"first_name" => "Sofia",
"last_name" => "I.",
"country" => "Argentina",
"continent" => "Americas",
"age" => 35,
"language" => "Java",
"greeting" => "Hi Sofia, what do you like the most about Java?"
],
[
"first_name" => "Lukas",
"last_name" => "X.",
"country" => "Croatia",
"continent" => "Europe",
"age" => 35,
"language" => "Python",
"greeting" => "Hi Lukas, what do you like the most about Python?"
],
[
"first_name" => "Madison",
"last_name" => "U.",
"country" => "United States",
"continent" => "Americas",
"age" => 32,
"language" => "Ruby",
"greeting" => "Hi Madison, what do you like the most about Ruby?"
]
]
```
```python
[
{ 'firstName': 'Sofia', 'lastName': 'I.', 'country': 'Argentina', 'continent': 'Americas', 'age': 35, 'language': 'Java',
'greeting': 'Hi Sofia, what do you like the most about Java?'
},
{ 'firstName': 'Lukas', 'lastName': 'X.', 'country': 'Croatia', 'continent': 'Europe', 'age': 35, 'language': 'Python',
'greeting': 'Hi Lukas, what do you like the most about Python?'
},
{ 'firstName': 'Madison', 'lastName': 'U.', 'country': 'United States', 'continent': 'Americas', 'age': 32, 'language': 'Ruby',
'greeting': 'Hi Madison, what do you like the most about Ruby?'
}
]
```
```cobol
01 List.
03 ListLength pic 9(3) value 3.
03 dev1.
05 FirstName pic a(9) value 'Sofia'.
05 LastName pic x(2) value 'I.'.
05 Country pic a(24) value 'Argentina'.
05 Continent pic a(8) value 'Americas'.
05 Age pic 9(3) value 35.
05 Language pic a(10) value 'Java'.
05 Greeting pic x(55) value
'Hi Sofia, what do you like the most about Java?'.
03 dev2.
05 FirstName pic a(9) value 'Lukas'.
05 LastName pic x(2) value 'X.'.
05 Country pic a(24) value 'Croatia'.
05 Continent pic a(8) value 'Europe'.
05 Age pic 9(3) value 75.
05 Language pic a(10) value 'Python'.
05 Greeting pic x(55) value
'Hi Lukas, what do you like the most about Python?'.
03 dev3.
05 FirstName pic a(9) value 'Madison'.
05 LastName pic x(2) value 'U.'.
05 Country pic a(24)
value 'United States of America'.
05 Continent pic a(8) value 'Americas'.
05 Age pic 9(3) value 32.
05 Language pic a(10) value 'Ruby'.
05 Greeting pic x(55) value
'Hi Madison, what do you like the most about Ruby?'.
```
Notes:
- The order of the properties in the objects does not matter (except in COBOL).
- The input array will always be valid and formatted as in the example above.
<br>
<br>
<br>
<br>
<br>
This kata is part of the **Coding Meetup** series which includes a number of short and easy to follow katas which have been designed to allow mastering the use of higher-order functions. In JavaScript this includes methods like: `forEach, filter, map, reduce, some, every, find, findIndex`. Other approaches to solving the katas are of course possible.
Here is the full list of the katas in the **Coding Meetup** series:
<a href="http://www.codewars.com/kata/coding-meetup-number-1-higher-order-functions-series-count-the-number-of-javascript-developers-coming-from-europe">Coding Meetup #1 - Higher-Order Functions Series - Count the number of JavaScript developers coming from Europe</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-2-higher-order-functions-series-greet-developers">Coding Meetup #2 - Higher-Order Functions Series - Greet developers</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-3-higher-order-functions-series-is-ruby-coming">Coding Meetup #3 - Higher-Order Functions Series - Is Ruby coming?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-4-higher-order-functions-series-find-the-first-python-developer">Coding Meetup #4 - Higher-Order Functions Series - Find the first Python developer</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-5-higher-order-functions-series-prepare-the-count-of-languages">Coding Meetup #5 - Higher-Order Functions Series - Prepare the count of languages</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-6-higher-order-functions-series-can-they-code-in-the-same-language">Coding Meetup #6 - Higher-Order Functions Series - Can they code in the same language?</a>
<a href="http://www.codewars.com/kata/coding-meetup-number-7-higher-order-functions-series-find-the-most-senior-developer">Coding Meetup #7 - Higher-Order Functions Series - Find the most senior developer</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-8-higher-order-functions-series-will-all-continents-be-represented">Coding Meetup #8 - Higher-Order Functions Series - Will all continents be represented?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-9-higher-order-functions-series-is-the-meetup-age-diverse">Coding Meetup #9 - Higher-Order Functions Series - Is the meetup age-diverse?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-10-higher-order-functions-series-create-usernames">Coding Meetup #10 - Higher-Order Functions Series - Create usernames</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-11-higher-order-functions-series-find-the-average-age">Coding Meetup #11 - Higher-Order Functions Series - Find the average age</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-12-higher-order-functions-series-find-github-admins">Coding Meetup #12 - Higher-Order Functions Series - Find GitHub admins</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-13-higher-order-functions-series-is-the-meetup-language-diverse">Coding Meetup #13 - Higher-Order Functions Series - Is the meetup language-diverse?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-14-higher-order-functions-series-order-the-food">Coding Meetup #14 - Higher-Order Functions Series - Order the food</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-15-higher-order-functions-series-find-the-odd-names">Coding Meetup #15 - Higher-Order Functions Series - Find the odd names</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-16-higher-order-functions-series-ask-for-missing-details">Coding Meetup #16 - Higher-Order Functions Series - Ask for missing details</a> | algorithms | def greet_developers(lst):
for x in lst:
x["greeting"] = f"Hi { x [ 'firstName' ]} , what do you like the most about { x [ 'language' ]} ?"
return lst
| Coding Meetup #2 - Higher-Order Functions Series - Greet developers | 58279e13c983ca4a2a00002a | [
"Data Structures",
"Fundamentals",
"Algorithms",
"Strings",
"Regular Expressions",
"Arrays",
"Functional Programming"
] | https://www.codewars.com/kata/58279e13c983ca4a2a00002a | 7 kyu |
You will be given an array of objects (associative arrays in PHP) representing data about developers who have signed up to attend the next coding meetup that you are organising. The list is ordered according to who signed up first.
Your task is to return one of the following strings:
- `< firstName here >, < country here >` of the first Python developer who has signed up; or
- `There will be no Python developers` if no Python developer has signed up.
For example, given the following input array:
```javascript
var list1 = [
{ firstName: 'Mark', lastName: 'G.', country: 'Scotland', continent: 'Europe', age: 22, language: 'JavaScript' },
{ firstName: 'Victoria', lastName: 'T.', country: 'Puerto Rico', continent: 'Americas', age: 30, language: 'Python' },
{ firstName: 'Emma', lastName: 'B.', country: 'Norway', continent: 'Europe', age: 19, language: 'Clojure' }
];
```
```php
$list1 = [
[
"first_name" => "Mark",
"last_name" => "G.",
"country" => "Scotland",
"continent" => "Europe",
"age" => 22,
"language" => "JavaScript"
],
[
"first_name" => "Victoria",
"last_name" => "T.",
"country" => "Puerto Rico",
"continent" => "Americas",
"age" => 30,
"language" => "Python"
],
[
"first_name" => "Emma",
"last_name" => "B.",
"country" => "Norway",
"continent" => "Europe",
"age" => 19,
"language" => "Clojure"
]
];
```
```python
list1 = [
{ "first_name": "Mark", "last_name": "G.", "country": "Scotland", "continent": "Europe", "age": 22, "language": "JavaScript" },
{ "first_name": "Victoria", "last_name": "T.", "country": "Puerto Rico", "continent": "Americas", "age": 30, "language": "Python" },
{ "first_name": "Emma", "last_name": "B.", "country": "Norway", "continent": "Europe", "age": 19, "language": "Clojure" }
]
```
```cobol
01 List.
03 ListLength pic 9(3) value 3.
03 dev1.
05 FirstName pic a(9) value 'Mark'.
05 LastName pic x(2) value 'G.'.
05 Country pic a(24) value 'Scotland'.
05 Continent pic a(8) value 'Europe'.
05 Age pic 9(3) value 52.
05 Language pic a(10) value 'JavaScript'.
03 dev2.
05 FirstName pic a(9) value 'Victoria'.
05 LastName pic x(2) value 'T.'.
05 Country pic a(24) value 'Puerto Rico'.
05 Continent pic a(8) value 'Americas'.
05 Age pic 9(3) value 70.
05 Language pic a(10) value 'Python'.
03 dev3.
05 FirstName pic a(9) value 'Emma'.
05 LastName pic x(2) value 'B.'.
05 Country pic a(24) value 'Norway'.
05 Continent pic a(8) value 'Europe'.
05 Age pic 9(3) value 19.
05 Language pic a(10) value 'Clojure'.
```
your function should return `Victoria, Puerto Rico`.
Notes:
- The input array will always be valid and formatted as in the example above.
<br>
<br>
<br>
<br>
<br>
This kata is part of the **Coding Meetup** series which includes a number of short and easy to follow katas which have been designed to allow mastering the use of higher-order functions. In JavaScript this includes methods like: `forEach, filter, map, reduce, some, every, find, findIndex`. Other approaches to solving the katas are of course possible.
Here is the full list of the katas in the **Coding Meetup** series:
<a href="http://www.codewars.com/kata/coding-meetup-number-1-higher-order-functions-series-count-the-number-of-javascript-developers-coming-from-europe">Coding Meetup #1 - Higher-Order Functions Series - Count the number of JavaScript developers coming from Europe</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-2-higher-order-functions-series-greet-developers">Coding Meetup #2 - Higher-Order Functions Series - Greet developers</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-3-higher-order-functions-series-is-ruby-coming">Coding Meetup #3 - Higher-Order Functions Series - Is Ruby coming?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-4-higher-order-functions-series-find-the-first-python-developer">Coding Meetup #4 - Higher-Order Functions Series - Find the first Python developer</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-5-higher-order-functions-series-prepare-the-count-of-languages">Coding Meetup #5 - Higher-Order Functions Series - Prepare the count of languages</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-6-higher-order-functions-series-can-they-code-in-the-same-language">Coding Meetup #6 - Higher-Order Functions Series - Can they code in the same language?</a>
<a href="http://www.codewars.com/kata/coding-meetup-number-7-higher-order-functions-series-find-the-most-senior-developer">Coding Meetup #7 - Higher-Order Functions Series - Find the most senior developer</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-8-higher-order-functions-series-will-all-continents-be-represented">Coding Meetup #8 - Higher-Order Functions Series - Will all continents be represented?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-9-higher-order-functions-series-is-the-meetup-age-diverse">Coding Meetup #9 - Higher-Order Functions Series - Is the meetup age-diverse?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-10-higher-order-functions-series-create-usernames">Coding Meetup #10 - Higher-Order Functions Series - Create usernames</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-11-higher-order-functions-series-find-the-average-age">Coding Meetup #11 - Higher-Order Functions Series - Find the average age</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-12-higher-order-functions-series-find-github-admins">Coding Meetup #12 - Higher-Order Functions Series - Find GitHub admins</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-13-higher-order-functions-series-is-the-meetup-language-diverse">Coding Meetup #13 - Higher-Order Functions Series - Is the meetup language-diverse?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-14-higher-order-functions-series-order-the-food">Coding Meetup #14 - Higher-Order Functions Series - Order the food</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-15-higher-order-functions-series-find-the-odd-names">Coding Meetup #15 - Higher-Order Functions Series - Find the odd names</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-16-higher-order-functions-series-ask-for-missing-details">Coding Meetup #16 - Higher-Order Functions Series - Ask for missing details</a>
| algorithms | def get_first_python(users):
for data in users:
if data['language'] == 'Python':
return f' { data [ "first_name" ]} , { data [ "country" ]} '
return 'There will be no Python developers'
| Coding Meetup #4 - Higher-Order Functions Series - Find the first Python developer | 5827bc50f524dd029d0005f2 | [
"Functional Programming",
"Data Structures",
"Arrays",
"Fundamentals",
"Algorithms",
"Strings",
"Regular Expressions"
] | https://www.codewars.com/kata/5827bc50f524dd029d0005f2 | 7 kyu |
You will be given an array of objects (associative arrays in PHP) representing data about developers who have signed up to attend the next coding meetup that you are organising.
Your task is to return:
- `true` if at least one Ruby developer has signed up; or
- `false` if there will be no Ruby developers.
For example, given the following input array:
```python
list1 = [
{ 'firstName': 'Sofia', 'lastName': 'I.', 'country': 'Argentina', 'continent': 'Americas', 'age': 35, 'language': 'Java' },
{ 'firstName': 'Lukas', 'lastName': 'X.', 'country': 'Croatia', 'continent': 'Europe', 'age': 35, 'language': 'Python' },
{ 'firstName': 'Madison', 'lastName': 'U.', 'country': 'United States', 'continent': 'Americas', 'age': 32, 'language': 'Ruby' }
]
```
```javascript
var list1 = [
{ firstName: 'Emma', lastName: 'Z.', country: 'Netherlands', continent: 'Europe', age: 29, language: 'Ruby' },
{ firstName: 'Piotr', lastName: 'B.', country: 'Poland', continent: 'Europe', age: 128, language: 'Javascript' },
{ firstName: 'Jayden', lastName: 'P.', country: 'Jamaica', continent: 'Americas', age: 42, language: 'JavaScript' }
];
```
```php
$list1 = [
[
"first_name" => "Emma",
"last_name" => "Z.",
"country" => "Netherlands",
"continent" => "Europe",
"age" => 29,
"language" => "Ruby"
],
[
"first_name" => "Piotr",
"last_name" => "B.",
"country" => "Poland",
"continent" => "Europe",
"age" => 128,
"language" => "JavaScript"
],
[
"first_name" => "Jayden",
"last_name" => "P.",
"country" => "Jamaica",
"continent" => "Americas",
"age" => 42,
"language" => "JavaScript"
]
];
```
```ruby
list1 = [
{ first_name: 'Emma', last_name: 'Z.', country: 'Netherlands', continent: 'Europe', age: 29, language: 'Ruby' },
{ first_name: 'Piotr', last_name: 'B.', country: 'Poland', continent: 'Europe', age: 128, language: 'Javascript' },
{ first_name: 'Jayden', last_name: 'P.', country: 'Jamaica', continent: 'Americas', age: 42, language: 'JavaScript' }
]
```
```crystal
list1 = [
{ first_name: 'Emma', last_name: 'Z.', country: 'Netherlands', continent: 'Europe', age: 29, language: 'Ruby' },
{ first_name: 'Piotr', last_name: 'B.', country: 'Poland', continent: 'Europe', age: 128, language: 'Javascript' },
{ first_name: 'Jayden', last_name: 'P.', country: 'Jamaica', continent: 'Americas', age: 42, language: 'JavaScript' }
]
```
```cobol
01 List.
03 ListLength pic 9 value 3.
03 dev1.
05 FirstName pic a(9) value 'Emma'.
05 LastName pic x(2) value 'Z.'.
05 Country pic a(24) value 'Netherlands'.
05 Continent pic a(8) value 'Europe'.
05 Age pic 9(3) value 29.
05 Language pic a(10) value 'Ruby'.
03 dev2.
05 FirstName pic a(9) value 'Piotr'.
05 LastName pic x(2) value 'B.'.
05 Country pic a(24) value 'Poland'.
05 Continent pic a(8) value 'Europe'.
05 Age pic 9(3) value 128.
05 Language pic a(10) value 'JavaScript'.
03 dev3.
05 FirstName pic a(9) value 'Jayden'.
05 LastName pic x(2) value 'P.'.
05 Country pic a(24) value 'Jamaica'.
05 Continent pic a(8) value 'Americas'.
05 Age pic 9(3) value 42.
05 Language pic a(10) value 'JavaScript'.
```
your function should return `true`.
Notes:
- The input array will always be valid and formatted as in the example above.
<br>
<br>
<br>
<br>
<br>
This kata is part of the **Coding Meetup** series which includes a number of short and easy to follow katas which have been designed to allow mastering the use of higher-order functions. In JavaScript this includes methods like: `forEach, filter, map, reduce, some, every, find, findIndex`. Other approaches to solving the katas are of course possible.
Here is the full list of the katas in the **Coding Meetup** series:
<a href="http://www.codewars.com/kata/coding-meetup-number-1-higher-order-functions-series-count-the-number-of-javascript-developers-coming-from-europe">Coding Meetup #1 - Higher-Order Functions Series - Count the number of JavaScript developers coming from Europe</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-2-higher-order-functions-series-greet-developers">Coding Meetup #2 - Higher-Order Functions Series - Greet developers</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-3-higher-order-functions-series-is-ruby-coming">Coding Meetup #3 - Higher-Order Functions Series - Is Ruby coming?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-4-higher-order-functions-series-find-the-first-python-developer">Coding Meetup #4 - Higher-Order Functions Series - Find the first Python developer</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-5-higher-order-functions-series-prepare-the-count-of-languages">Coding Meetup #5 - Higher-Order Functions Series - Prepare the count of languages</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-6-higher-order-functions-series-can-they-code-in-the-same-language">Coding Meetup #6 - Higher-Order Functions Series - Can they code in the same language?</a>
<a href="http://www.codewars.com/kata/coding-meetup-number-7-higher-order-functions-series-find-the-most-senior-developer">Coding Meetup #7 - Higher-Order Functions Series - Find the most senior developer</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-8-higher-order-functions-series-will-all-continents-be-represented">Coding Meetup #8 - Higher-Order Functions Series - Will all continents be represented?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-9-higher-order-functions-series-is-the-meetup-age-diverse">Coding Meetup #9 - Higher-Order Functions Series - Is the meetup age-diverse?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-10-higher-order-functions-series-create-usernames">Coding Meetup #10 - Higher-Order Functions Series - Create usernames</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-11-higher-order-functions-series-find-the-average-age">Coding Meetup #11 - Higher-Order Functions Series - Find the average age</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-12-higher-order-functions-series-find-github-admins">Coding Meetup #12 - Higher-Order Functions Series - Find GitHub admins</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-13-higher-order-functions-series-is-the-meetup-language-diverse">Coding Meetup #13 - Higher-Order Functions Series - Is the meetup language-diverse?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-14-higher-order-functions-series-order-the-food">Coding Meetup #14 - Higher-Order Functions Series - Order the food</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-15-higher-order-functions-series-find-the-odd-names">Coding Meetup #15 - Higher-Order Functions Series - Find the odd names</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-16-higher-order-functions-series-ask-for-missing-details">Coding Meetup #16 - Higher-Order Functions Series - Ask for missing details</a> | algorithms | def is_ruby_coming(lst):
return any(x["language"] == "Ruby" for x in lst)
| Coding Meetup #3 - Higher-Order Functions Series - Is Ruby coming? | 5827acd5f524dd029d0005a4 | [
"Data Structures",
"Fundamentals",
"Algorithms",
"Strings",
"Regular Expressions",
"Arrays",
"Functional Programming"
] | https://www.codewars.com/kata/5827acd5f524dd029d0005a4 | 7 kyu |
You will be given an array of objects (hashes in ruby) representing data about developers who have signed up to attend the coding meetup that you are organising for the first time.
Your task is to **return the number of JavaScript developers coming from Europe**.
For example, given the following list:
```javascript
var list1 = [
{ firstName: 'Noah', lastName: 'M.', country: 'Switzerland', continent: 'Europe', age: 19, language: 'JavaScript' },
{ firstName: 'Maia', lastName: 'S.', country: 'Tahiti', continent: 'Oceania', age: 28, language: 'JavaScript' },
{ firstName: 'Shufen', lastName: 'L.', country: 'Taiwan', continent: 'Asia', age: 35, language: 'HTML' },
{ firstName: 'Sumayah', lastName: 'M.', country: 'Tajikistan', continent: 'Asia', age: 30, language: 'CSS' }
];
```
```python
lst1 = [
{ 'firstName': 'Noah', 'lastName': 'M.', 'country': 'Switzerland', 'continent': 'Europe', 'age': 19, 'language': 'JavaScript' },
{ 'firstName': 'Maia', 'lastName': 'S.', 'country': 'Tahiti', 'continent': 'Oceania', 'age': 28, 'language': 'JavaScript' },
{ 'firstName': 'Shufen', 'lastName': 'L.', 'country': 'Taiwan', 'continent': 'Asia', 'age': 35, 'language': 'HTML' },
{ 'firstName': 'Sumayah', 'lastName': 'M.', 'country': 'Tajikistan', 'continent': 'Asia', 'age': 30, 'language': 'CSS' }
]
```
```ruby
list1 = [
{ first_name: 'Noah', last_name: 'M.', country: 'Switzerland', continent: 'Europe', age: 19, language: 'JavaScript' },
{ first_name: 'Maia', last_name: 'S.', country: 'Tahiti', continent: 'Oceania', age: 28, language: 'JavaScript' },
{ first_name: 'Shufen', last_name: 'L.', country: 'Taiwan', continent: 'Asia', age: 35, language: 'HTML' },
{ first_name: 'Sumayah', last_name: 'M.', country: 'Tajikistan', continent: 'Asia', age: 30, language: 'CSS' }
]
```
```cobol
01 List.
03 ListLength pic 9(3) value 4.
03 dev1.
05 FirstName pic a(9) value 'Noah'.
05 LastName pic x(2) value 'M.'.
05 Country pic a(24) value 'Switzerland'.
05 Continent pic a(8) value 'Europe'.
05 Age pic 9(3) value 19.
05 Language pic a(10) value 'JavaScript'.
03 dev2.
05 FirstName pic a(9) value 'Maia'.
05 LastName pic x(2) value 'S.'.
05 Country pic a(24) value 'Tahiti'.
05 Continent pic a(8) value 'Oceania'.
05 Age pic 9(3) value 28.
05 Language pic a(10) value 'Clojure'.
03 dev3.
05 FirstName pic a(9) value 'Shufen'.
05 LastName pic x(2) value 'L.'.
05 Country pic a(24) value 'Taiwan'.
05 Continent pic a(8) value 'Asia'.
05 Age pic 9(3) value 35.
05 Language pic a(10) value 'PHP'.
03 dev4.
05 FirstName pic a(9) value 'Sumayah'.
05 LastName pic x(2) value 'M.'.
05 Country pic a(24) value 'Tajikistan'.
05 Continent pic a(8) value 'Asia'.
05 Age pic 9(3) value 30.
05 Language pic a(10) value 'CSS'.
```
your function should return number `1`.
If, there are no JavaScript developers from Europe then your function should return `0`.
Notes:
- The format of the strings will always be `Europe` and `JavaScript`.
- All data will always be valid and uniform as in the example above.
<br>
<br>
<br>
<br>
<br>
This kata is part of the **Coding Meetup** series which includes a number of short and easy to follow katas which have been designed to allow mastering the use of higher-order functions. In JavaScript this includes methods like: `forEach, filter, map, reduce, some, every, find, findIndex`. Other approaches to solving the katas are of course possible.
Here is the full list of the katas in the **Coding Meetup** series:
<a href="http://www.codewars.com/kata/coding-meetup-number-1-higher-order-functions-series-count-the-number-of-javascript-developers-coming-from-europe">Coding Meetup #1 - Higher-Order Functions Series - Count the number of JavaScript developers coming from Europe</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-2-higher-order-functions-series-greet-developers">Coding Meetup #2 - Higher-Order Functions Series - Greet developers</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-3-higher-order-functions-series-is-ruby-coming">Coding Meetup #3 - Higher-Order Functions Series - Is Ruby coming?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-4-higher-order-functions-series-find-the-first-python-developer">Coding Meetup #4 - Higher-Order Functions Series - Find the first Python developer</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-5-higher-order-functions-series-prepare-the-count-of-languages">Coding Meetup #5 - Higher-Order Functions Series - Prepare the count of languages</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-6-higher-order-functions-series-can-they-code-in-the-same-language">Coding Meetup #6 - Higher-Order Functions Series - Can they code in the same language?</a>
<a href="http://www.codewars.com/kata/coding-meetup-number-7-higher-order-functions-series-find-the-most-senior-developer">Coding Meetup #7 - Higher-Order Functions Series - Find the most senior developer</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-8-higher-order-functions-series-will-all-continents-be-represented">Coding Meetup #8 - Higher-Order Functions Series - Will all continents be represented?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-9-higher-order-functions-series-is-the-meetup-age-diverse">Coding Meetup #9 - Higher-Order Functions Series - Is the meetup age-diverse?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-10-higher-order-functions-series-create-usernames">Coding Meetup #10 - Higher-Order Functions Series - Create usernames</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-11-higher-order-functions-series-find-the-average-age">Coding Meetup #11 - Higher-Order Functions Series - Find the average age</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-12-higher-order-functions-series-find-github-admins">Coding Meetup #12 - Higher-Order Functions Series - Find GitHub admins</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-13-higher-order-functions-series-is-the-meetup-language-diverse">Coding Meetup #13 - Higher-Order Functions Series - Is the meetup language-diverse?</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-14-higher-order-functions-series-order-the-food">Coding Meetup #14 - Higher-Order Functions Series - Order the food</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-15-higher-order-functions-series-find-the-odd-names">Coding Meetup #15 - Higher-Order Functions Series - Find the odd names</a>
<a href="https://www.codewars.com/kata/coding-meetup-number-16-higher-order-functions-series-ask-for-missing-details">Coding Meetup #16 - Higher-Order Functions Series - Ask for missing details</a> | algorithms | def count_developers(lst):
return sum(x["language"] == "JavaScript" and x["continent"] == "Europe" for x in lst)
| Coding Meetup #1 - Higher-Order Functions Series - Count the number of JavaScript developers coming from Europe | 582746fa14b3892727000c4f | [
"Data Structures",
"Fundamentals",
"Algorithms",
"Strings",
"Regular Expressions",
"Arrays",
"Functional Programming"
] | https://www.codewars.com/kata/582746fa14b3892727000c4f | 7 kyu |
You must create a function, `spread`, that takes a function and a list of arguments to be applied to that function. You must make this function return the result of calling the given function/lambda with the given arguments.
eg:
```javascript
spread(someFunction, [1, true, "Foo", "bar"] )
// is the same as...
someFunction(1, true, "Foo", "bar")
```
```clojure
(spread someFunction [1 true "Foo" "bar"] )
; is the same as...
(someFunction 1 true "Foo" "bar")
```
```coffeescript
spread someFunction, [1, true, "Foo", "bar"]
# is the same as...
someFunction 1, true, "Foo", "bar"
```
```python
spread(someFunction, [1, true, "Foo", "bar"] )
# is the same as...
someFunction(1, true, "Foo", "bar")
```
```ruby
spread someFunction, [1, true, "Foo", "bar"]
# is the same as...
someFunction.(1, true, "Foo", "bar")
``` | reference | def spread(func, args):
return func(* args)
| Unpacking Arguments | 540de1f0716ab384b4000828 | [
"Functional Programming",
"Fundamentals"
] | https://www.codewars.com/kata/540de1f0716ab384b4000828 | 7 kyu |
Write a function `reverse` which reverses a list (or in clojure's case, any list-like data structure)
(the dedicated builtin(s) functionalities are deactivated) | reference | def reverse(lst):
out = list()
for i in range(len(lst) - 1, - 1, - 1):
out . append(lst[i])
return out
| esreveR | 5413759479ba273f8100003d | [
"Functional Programming",
"Fundamentals"
] | https://www.codewars.com/kata/5413759479ba273f8100003d | 7 kyu |
Implement two methods `anyMatch` and `allMatch` which take the head of a linked list and a predicate function, and return:
* anyMatch: whether the predicate is true for *any* of the list's elements.
* allMatch: whether the predicate is true for *all* of the list's elements.
For example:
Given the list: `1 -> 2 -> 3`, and the predicate `x => x > 1`, **anyMatch** / `any_match` should return true (both 2 & 3 are valid for this predicate), and **allMatch** / `all_match` should return false (1 is not valid for this predicate)
The linked list is defined as follows:
```c
struct Node {
struct Node *next;
int data;
};
```
```javascript
function Node(data, next = null) {
this.data = data;
this.next = next;
}
```
```java
class Node<T> {
public T data;
public Node<T> next;
Node(T data, Node next) {
this.data = data;
this.next = next;
}
Node(T data) {
this(data, null);
}
}
```
```php
class Node {
public $data, $next;
public function __construct($data, $next = NULL) {
$this->data = $data;
$this->next = $next;
}
}
```
```python
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
```
Note: the list may be null and can hold any type of value.
Good luck!
This kata is part of [fun with lists](https://www.codewars.com/collections/fun-with-lists) series:
* [Fun with lists: length](https://www.codewars.com/kata/581e476d5f59408553000a4b)
* [Fun with lists: indexOf](https://www.codewars.com/kata/581c6b075cfa83852700021f)
* [Fun with lists: lastIndexOf](https://www.codewars.com/kata/581c867a33b9fe732e000076)
* [Fun with lists: countIf](https://www.codewars.com/kata/5819081d056d4bdd410004f8)
* [Fun with lists: anyMatch + allMatch](https://www.codewars.com/kata/581e50555f59405743001813)
* [Fun with lists: filter](https://www.codewars.com/kata/582041237df353e01d000084)
* [Fun with lists: map](https://www.codewars.com/kata/58259d9062cfb45e1a00006b)
* [Fun with lists: reduce](https://www.codewars.com/kata/58319f37aeb69a89a00000c7) | reference | from typing import Callable
def any_match(head: Node, pred: Callable[[any], bool]) - > bool:
while head:
if pred(head . data):
return True
head = head . next
return False
def all_match(head: Node, pred: Callable[[all], bool]) - > bool:
while head:
if not pred(head . data):
return False
head = head . next
return True
| Fun with lists: anyMatch + allMatch | 581e50555f59405743001813 | [
"Lists",
"Functional Programming",
"Fundamentals"
] | https://www.codewars.com/kata/581e50555f59405743001813 | 7 kyu |
Implement the method **countIf** (`count_if` in PHP and Python), which accepts a linked list (head) and a predicate function, and returns the number of elements which apply to the given predicate.
For example:
Given the list: `1 -> 2 -> 3`, and the predicate `x => x >= 2`, **countIf** / `count_if` should return 2, since `x >= 2` applies to both 2 and 3.
The linked list is defined as follows:
```javascript
function Node(data, next = null) {
this.data = data;
this.next = next;
}
```
```java
class Node<T> {
public T data;
public Node<T> next;
Node(T data, Node next) {
this.data = data;
this.next = next;
}
Node(T data) {
this(data, null);
}
}
```
```php
class Node {
public $data, $next;
public function __construct($data, $next = NULL) {
$this->data = $data;
$this->next = $next;
}
}
```
```c
struct Node {
struct Node *next;
int data;
};
```
```python
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
```
Note: the list may be null and can hold any type of value.
Good luck!
This kata is part of [fun with lists](https://www.codewars.com/collections/fun-with-lists) series:
* [Fun with lists: length](https://www.codewars.com/kata/581e476d5f59408553000a4b)
* [Fun with lists: indexOf](https://www.codewars.com/kata/581c6b075cfa83852700021f)
* [Fun with lists: lastIndexOf](https://www.codewars.com/kata/581c867a33b9fe732e000076)
* [Fun with lists: countIf](https://www.codewars.com/kata/5819081d056d4bdd410004f8)
* [Fun with lists: anyMatch + allMatch](https://www.codewars.com/kata/581e50555f59405743001813)
* [Fun with lists: filter](https://www.codewars.com/kata/582041237df353e01d000084)
* [Fun with lists: map](https://www.codewars.com/kata/58259d9062cfb45e1a00006b)
* [Fun with lists: reduce](https://www.codewars.com/kata/58319f37aeb69a89a00000c7) | reference | def count_if(head, func):
counter = 0
while head:
counter += func(head . data)
head = head . next
return counter
| Fun with lists: countIf | 5819081d056d4bdd410004f8 | [
"Lists",
"Functional Programming",
"Fundamentals"
] | https://www.codewars.com/kata/5819081d056d4bdd410004f8 | 6 kyu |
Implement the method **lastIndexOf** (`last_index_of` in PHP and Python), which accepts a linked list (head) and a value, and returns the index (zero based) of the *last* occurrence of that value if exists, or -1 otherwise.
For example:
Given the list: `1 -> 2 -> 3 -> 3`, and the value 3, **lastIndexOf** / `last_index_of` should return 3.
The linked list is defined as follows:
```c
struct List {
struct List *next;
int data;
};
```
```javascript
function Node(data, next = null) {
this.data = data;
this.next = next;
}
```
```java
class Node {
public Object data;
public Node next;
Node(T data, Node next) {
this.data = data;
this.next = next;
}
Node(T data) {
this(data, null);
}
}
```
```php
class Node {
public $data, $next;
public function __construct($data, $next = NULL) {
$this->data = $data;
$this->next = $next;
}
}
```
```kotlin
data class Node(val data: Any?, val next: Node?=null)
```
```python
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
```
Note: the list may be `null`/`None` and can hold any type of value.
Good luck!
This kata is part of [fun with lists](https://www.codewars.com/collections/fun-with-lists) series:
* [Fun with lists: length](https://www.codewars.com/kata/581e476d5f59408553000a4b)
* [Fun with lists: indexOf](https://www.codewars.com/kata/581c6b075cfa83852700021f)
* [Fun with lists: lastIndexOf](https://www.codewars.com/kata/581c867a33b9fe732e000076)
* [Fun with lists: countIf](https://www.codewars.com/kata/5819081d056d4bdd410004f8)
* [Fun with lists: anyMatch + allMatch](https://www.codewars.com/kata/581e50555f59405743001813)
* [Fun with lists: filter](https://www.codewars.com/kata/582041237df353e01d000084)
* [Fun with lists: map](https://www.codewars.com/kata/58259d9062cfb45e1a00006b)
* [Fun with lists: reduce](https://www.codewars.com/kata/58319f37aeb69a89a00000c7) | reference | def last_index_of(head, search_val):
i = 0
last = - 1
while head:
value = head . data
if value == search_val:
last = i
head = head . next
i += 1
return last
| Fun with lists: lastIndexOf | 581c867a33b9fe732e000076 | [
"Lists",
"Fundamentals"
] | https://www.codewars.com/kata/581c867a33b9fe732e000076 | 7 kyu |
Implement the method **indexOf** (`index_of` in PHP), which accepts a linked list (head) and a value, and returns the index (zero based) of the *first* occurrence of that value if exists, or -1 otherwise.
For example:
Given the list: `1 -> 2 -> 3 -> 3`, and the value 3, **indexOf** / `index_of` should return 2.
The linked list is defined as follows:
```c
struct Node {
struct Node *next;
int data;
};
```
```javascript
function Node(data, next = null) {
this.data = data;
this.next = next;
}
```
```java
class Node {
public Object data;
public Node next;
Node(T data, Node next) {
this.data = data;
this.next = next;
}
Node(T data) {
this(data, null);
}
}
```
```php
class Node {
public $data, $next;
public function __construct($data, $next = NULL) {
$this->data = $data;
$this->next = $next;
}
}
```
```python
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
```
Note: the list may be null and can hold any type of value.
Good luck!
This kata is part of [fun with lists](https://www.codewars.com/collections/fun-with-lists) series:
* [Fun with lists: length](https://www.codewars.com/kata/581e476d5f59408553000a4b)
* [Fun with lists: indexOf](https://www.codewars.com/kata/581c6b075cfa83852700021f)
* [Fun with lists: lastIndexOf](https://www.codewars.com/kata/581c867a33b9fe732e000076)
* [Fun with lists: countIf](https://www.codewars.com/kata/5819081d056d4bdd410004f8)
* [Fun with lists: anyMatch + allMatch](https://www.codewars.com/kata/581e50555f59405743001813)
* [Fun with lists: filter](https://www.codewars.com/kata/582041237df353e01d000084)
* [Fun with lists: map](https://www.codewars.com/kata/58259d9062cfb45e1a00006b)
* [Fun with lists: reduce](https://www.codewars.com/kata/58319f37aeb69a89a00000c7)
| reference | def index_of(head, value, idx=0):
if head is None:
return - 1
if head . data == value:
return idx
return index_of(head . next, value, idx + 1)
| Fun with lists: indexOf | 581c6b075cfa83852700021f | [
"Lists",
"Fundamentals"
] | https://www.codewars.com/kata/581c6b075cfa83852700021f | 7 kyu |
### Context and Definitions
You are in charge of developing a new cool JavaScript library that provides functionality similar to that of [Underscore.js](http://underscorejs.org/).
You have started by adding a new **list data type** to your library. You came up with a design of a data structure that represents an [algebraic data type](http://en.wikipedia.org/wiki/Algebraic_data_type) as a pair of elements:
```javascript
function Cons(head,tail){
this.head = head;
this.tail = tail;
}
```
```python
class Cons:
def __init__(self, head, tail):
self.head = head
self.tail = tail
```
```rust
#[derive(Debug, PartialEq, Eq)]
enum Cons<T: Clone> {
Cons(T, Box<Cons<T>>),
Null
}
impl<T: Clone> Cons<T> {
pub fn new(head: T, tail: Self) -> Self {
Cons::Cons(head, Box::new(tail))
}
}
```
You are pretty smart, because using this new data type, we can easily build a list of elements. For instance, a list of numbers:
```javascript
var numbers = new Cons(1, new Cons(2, new Cons(3, new Cons(4, new Cons(5, null)))));
```
```python
numbers = Cons(1, Cons(2, Cons(3, Cons(4, Cons(5, None)))))
```
```rust
let numbers = Cons::new(1, Cons::new(2, Cons::new(3, Cons::new(4, Cons::new(5, Cons::Null)))));
```
In a code review with your boss, you explained him how every *cons cell* contains a "value" in its head, and in its tail it contains either another cons cell or null. We know we have reached the end of the data structure when the tail is null.
So, your boss is pretty excited about this new data structure and wants to know if you will be able to build some more functionality around it. In a demo you did this week for the rest of your team, in order to illustrate how this works, you showed them a method to transform a list of items of your list data type into a JavaScript array:
```javascript
function toArray(list) {
if(list){
var more = list.tail;
return [list.head].concat(more? toArray(more) : []);
}
return [];
}
Cons.prototype.toArray = function(){ return toArray(this); };
```
```python
# added to the class implementation:
def to_array(self):
tail = self.tail
new_tail = (tail.to_array() if tail is not None else [])
return [self.head] + new_tail
```
```rust
impl<T: Clone> Cons<T> {
pub fn to_vec(&self) -> Vec<T> {
match self {
&Cons::Null => vec![],
&Cons::Cons(ref head, ref tail) => {
let mut head = vec![head.clone()];
head.extend(tail.to_vec());
head
}
}
}
}
```
And they were amazed when you simply did this:
```javascript
console.log(numbers.toArray()); // yields [1,2,3,4,5]
```
```python
print(numbers.to_array()) # yields [1,2,3,4,5]
```
```rust
println!("{:?}", numbers.to_vec()); // yields [1,2,3,4,5]
```
### The New Requirements
Now, the team is convinced that this is the way to go and they would like to build the library around this cool new data type, but they want you to provide a few more features for them so that they can start using this type in solving some real world problems.
You have been reading about a technique called [applicative programming](http://quod.lib.umich.edu/s/spobooks/bbv9810.0001.001/1:15?rgn=div1;view=fulltext) which basically consists in applying a function to every element in a list. So, you gave it some thought and you have decided to start adding features like **filter**, **map** and **reduce**. Basically you want to provide equivalent functionality to that of JavaScript arrays and in the future even more.
So, you will now add:
- [filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FArray%2Ffilter): create a new algebraic list containing only the elements that satisfy a predicate function.
- [map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FArray%2Ffilter) : create a new list in which every element is the result of applying a function provided as argument.
- fromArray: a convenient complementary method that creates a list out of a JavaScript array.
For this Kata, the definition of `Cons` and the prototypal/class method `toArray`/`to_array`/`into_vec` are already loaded in your environment.
### Examples of Usage
```javascript
var numbers = Cons.fromArray([1,2,3,4,5]);
numbers.filter(function(n){ return n % 2 === 0; }).toArray(); //yields [2,4]
numbers.map( function(n){ return n * n; }).toArray(); //yields [1,4,9,16,25]
var digits = Cons.fromArray(["1","2","3","4","5"]);
var integers = digits.map(function(s){return parseInt(s);})
.filter(function(n){ return n > 3;})
.toArray(); //yields [4,5]
```
```python
numbers = Cons.from_array([1,2,3,4,5])
numbers.filter(lambda x: x % 2 == 0).to_array() # yields [2,4]
numbers.map(lambda x: x * x).to_array() # yields [1,4,9,16,25]
digits = Cons.from_array(["1","2","3","4","5"])
integers = digits.map(int) \
.filter(lambda n: n > 3) \
.to_array() # yields [4,5]
```
```rust
let numbers = Cons::from_iter(vec![1,2,3,4,5]);
numbers.filter(|x| x % 2 == 0).into_vec(); // yields [2,4]
numbers.map(|x| x * x).into_vec(); // yields [1,4,9,16,25]
let digits = Cons::from_iter(vec!["1","2","3","4","5"]);
let ints = digits.map(str::parse::<i32>)
.map(Result::unwrap)
.filter(|&n| n > 3)
.into_vec() // yields [4,5]
```
In other words:
- The static method `Cons.fromArray` (or `from_array`, `from_iter`) produces `Cons(1, Cons(2, Cons(3, Cons 4, Cons 5, null)))))`.
- Above filter creates a new list: `Cons(2, Cons(4, null))`.
- So does above map: `Cons(1, Cos(4, Cons(9, Cons(16, Cons(25, null)))))`.
| algorithms | class Cons:
def __init__(self, value, tail):
self . value = value
self . tail = tail
def to_array(self, lst=None):
if lst is None:
lst = []
lst . append(self . value)
if self . tail is not None:
self . tail . to_array(lst)
return lst
@ classmethod
def from_array(cls, arr):
head = None
for x in reversed(arr):
head = Cons(x, head)
return head
def filter(self, fn):
if fn(self . value):
return Cons(self . value, self . tail and self . tail . filter(fn))
else:
return self . tail and self . tail . filter(fn)
def map(self, fn):
return Cons(fn(self . value), self . tail and self . tail . map(fn))
| Algebraic Lists | 529a92d9aba78c356b000353 | [
"Lists",
"Algebra",
"Algorithms"
] | https://www.codewars.com/kata/529a92d9aba78c356b000353 | 4 kyu |