description
stringlengths
38
154k
category
stringclasses
5 values
solutions
stringlengths
13
289k
name
stringlengths
3
179
id
stringlengths
24
24
tags
listlengths
0
13
url
stringlengths
54
54
rank_name
stringclasses
8 values
<h2>Story:</h2> Alex is a great fan of Snooker and he likes recording the results of his favorite players by recording the balls that fall into the pockets of the table. He asks you to help him with a program that calculates the points a player scored in a given set using his notes. Unfortunatly his notes are quiet a mess ... <h2>Task:</h2> Given his short hand notation as string, calculate the points a player scored in a set. He codes the ball colors with letters: - R = red (1 point) - Y = yellow (2 points) - G = green (3 points) - Bn = brown (4 points) - Be = blue (5 points) - P = pink (6 points) - Bk = black (7 points) - W = white (no points because it's a foul) The color may be followed by a number 'R12' would stand for 12 red balls pocketed. If there is no number given, the ball was pocketed once.<br> <code>"R15P3G1Bk4Y1Bn1Be3" or "R13Bk14YRGBnBkRBePBk1"</code> Sometimes Alex forgets that he already wrote down a color and records it multiple times. For your convenience the points for each color are provided as hash / dictionary with the name 'blz'. If the string include white ball("W"-symbol) - return <code>'Foul'</code><br> for example: <code>"G9G11P9Bn2Bn1Be10G7<b>W</b>Bn10G3"</code><br> If the total score is more than 147 - <code>'invalid data'</code><br> for example: <code>"Bn14Bn14Bn8P9"</code>
games
import re def frame(balls): if 'W' in balls: return 'Foul' list = re . findall('[A-Z][a-z]*[0-9]*', balls) sum = 0 for ball in list: num = re . findall('[0-9]+', ball) color = ball . rstrip(num[0]) if num else ball n = int(num[0]) if num else 1 sum += n * int(blz[color]) return sum if sum < 148 else 'invalid data'
Alex & snooker: points earned.
58b96d99404be9187c000003
[ "Strings", "Arrays" ]
https://www.codewars.com/kata/58b96d99404be9187c000003
6 kyu
Given a list of lists containing only 1s and 0s, return a new list that differs from list 1 in its first element, list 2 in its second element, list 3 in its 3rd element, and so on. ``` cantor([[0,0,0], [1,1,1], [0,1,0]]) = [1,0,1] cantor([[1,0,0], [0,1,0], [0,0,1]]) = [0,0,0] ``` The nested list will always be perfectly square. Your solution should be a list containing only 1s and 0s. See [Wikipedia](https://en.wikipedia.org/wiki/Cantor%27s_diagonal_argument) for background (if you're interested; it won't help you solve the kata). Obviously this kata is not the same because the lists are not infinite so it doesn't really prove anything -- consider it a tribute... ~~~if:lambdacalc ### Encodings purity: `LetRec` numEncoding: `Church` export constructors `nil, cons` and deconstructor `foldl` for your `List` encoding ~~~
reference
def cantor(nested_list): return [not (line[i]) for i, line in enumerate(nested_list)]
Cantor's Diagonals
5a5e4f5f118dd1b407000028
[ "Fundamentals" ]
https://www.codewars.com/kata/5a5e4f5f118dd1b407000028
7 kyu
In the world of birding there are four-letter codes for the common names of birds. These codes are created by some simple rules: * If the bird's name has only one word, the code takes the first four letters of that word. * If the name is made up of two words, the code takes the first two letters of each word. * If the name is made up of three words, the code is created by taking the first letter from the first two words and the first two letters from the third word. * If the name is four words long, the code uses the first letter from all the words. *(There are other ways that codes are created, but this Kata will only use the four rules listed above)* Complete the function that takes an array of strings of common bird names from North America, and create the codes for those names based on the rules above. The function should return an array of the codes in the same order in which the input names were presented. Additional considertations: * The four-letter codes in the returned array should be in UPPER CASE. * If a common name has a hyphen/dash, it should be considered a space. ## Example If the input array is: `["Black-Capped Chickadee", "Common Tern"]` The return array would be: `["BCCH", "COTE"]`
reference
import re SPLITTER = re . compile(r"[\s-]") def birdify(lst): return '' . join(x[: 4 / / len(lst)] for x in lst) + ('' if len(lst) != 3 else lst[- 1][1]) def bird_code(arr): return [birdify(SPLITTER . split(name)). upper() for name in arr]
Create Four Letter Birding Codes from Bird Names
5a580064e6be38fd34000147
[ "Arrays", "Regular Expressions", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5a580064e6be38fd34000147
6 kyu
# Task: We define the "self reversed power sequence" as one shown below: <img src="http://i.imgur.com/5PwwTaz.jpg"> Implement a function that takes 2 arguments (`ord max` and `num dig`), and finds the smallest term of the sequence whose index is less than or equal to `ord max`, and has exactly `num dig` number of digits. If there is a number with correct amount of digits, the result should be an array in the form: ```javascript [true, smallest found term] [false, -1] ``` ```python [True, smallest found term] [False, -1] ``` ```ruby [true, smallest found term] [false, -1] ``` ## Input range: ```javascript ordMax <= 500 ``` ```python ord_max <= 1000 ``` ```ruby ord_max <= 1000 ``` ___ ## Examples: ```javascript minLengthNum(5, 10) === [true, 10] // 10th term has 5 digits minLengthNum(7, 11) === [false, -1] // no terms before the 13th one have 7 digits minLengthNum(7, 14) === [true, 13] // 13th term is the first one which has 7 digits ``` ```python min_length_num(5, 10) == [True, 10] # 10th term has 5 digits min_length_num(7, 11) == [False, -1] # no terms before the 13th one have 7 digits min_length_num(7, 14) == [True, 13] # 13th term is the first one which has 7 digits ``` ```ruby min_length_num(5, 10) == [true, 10] # 10th term has 5 digits min_length_num(7, 11) == [false, -1] # no terms before the 13th one have 7 digits min_length_num(7, 14) == [true, 13] # 13th term is the first one which has 7 digits ``` Which you can see in the table below: ``` n-th Term Term Value 1 0 2 1 3 3 4 8 5 22 6 65 7 209 8 732 9 2780 10 11377 11 49863 12 232768 13 1151914 14 6018785 ``` ___ Enjoy it and happy coding!!
reference
# precalculate results results = {} n, digits = 1, 0 while digits <= 1000: digits = len(str(sum(x * * (n - x + 1) for x in range(1, n)))) if digits not in results: results[digits] = n n += 1 def min_length_num(digits, max_num): n = results . get(digits, 0) return [True, n + 1] if n and n < max_num else [False, - 1]
Reversed Self Power
560248d6ba06815d6f000098
[ "Fundamentals", "Mathematics", "Algorithms", "Performance" ]
https://www.codewars.com/kata/560248d6ba06815d6f000098
5 kyu
First order Chebyshew polynomials are defined by: T{0}( v ) = 1 T{1}( v ) = v T{n+1}( v ) = 2 * v * T{n}( v ) - T{n-1}( v ) Calculate `T{n}( v )` for given values of `v` and `n`. You don't have to round your results but you should expect large values.
algorithms
def chebyshev(n, v): t0, t1 = 1, v for _ in range(n): t0, t1 = t1, 2 * v * t1 - t0 return t0
First order Chebyshev polynomials
58a2ff40e7841f82b600010a
[ "Algorithms" ]
https://www.codewars.com/kata/58a2ff40e7841f82b600010a
6 kyu
This is a simple string decoding algorithm. The idea is to take a string of characters and decode it into an array. Each character is a single element in the result unless a backslash followed by a positive number is encountered. When a backslash followed by a positive number is found, the number indicates how many of the next characters are grouped together as one element. Example: ``` "abc\5defghi\2jkl" => [ "a", "b", "c", "defgh", "i", "jk", "l" ] ``` If the number is larger than the count of remaining characters, treat it as reading the remaining characters. If you are reading characters, and you find an escape inside a string, they should be tallied into the string: ``` "\5ab\3cde" => [ "ab\3c", "d", "e" ] ```
algorithms
from itertools import islice def decode(s): def f(): it = iter(s) for c in it: if c == "\\": digits = next(it) while True: c = next(it) if not c . isdigit(): break digits += c c += "" . join(islice(it, int(digits) - 1)) yield c return list(f())
Decoded String by the Numbers
562c3b54746f50d28d000027
[ "Algorithms" ]
https://www.codewars.com/kata/562c3b54746f50d28d000027
6 kyu
In the wake of the npm's `left-pad` debacle, you decide to write a new super padding method that superceds the functionality of `left-pad`. Your version will provide the same functionality, but will additionally add right, and justified padding of string -- the `super_pad`. Your function `super_pad` should take three arguments: the string `string`, the width of the final string `width`, and a fill character `fill`. However, the fill character can be enriched with a format string resulting in different padding strategies. If `fill` begins with `'<'` the string is padded on the left with the remaining fill string and if `fill` begins with `'>'` the string is padded on the right. Finally, if `fill` begins with `'^'` the string is padded on the left and the right, where the left padding is always greater or equal to the right padding. The `fill` string can contain more than a single char, of course. Some examples to clarify the inner workings: - `super_pad("test", 10)` returns <code>"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;test"</code> - `super_pad("test", 10, "x")` returns `"xxxxxxtest"` - `super_pad("test", 10, "xO")` returns `"xOxOxOtest"` - `super_pad("test", 10, "xO-")` returns `"xO-xO-test"` - `super_pad("some other test", 10, "nope")` returns `"other test"` - `super_pad("some other test", 10, "> ")` returns `"some other"` - `super_pad("test", 7, ">nope")` returns `"testnop"` - `super_pad("test", 7, "^more complex")` returns `"motestm"` - `super_pad("test", 7, "")` returns `"test"` The `super_pad` method always returns a string of length `width` if possible. We expect the `width` to be positive (including 0) and the fill could be also an empty string.
algorithms
def super_pad(string, width, fill=" "): if fill . startswith('>'): return (string + width * fill[1:])[: width] elif fill . startswith('^'): pad = (width * fill[1:])[: max(0, width - len(string) + 1) / / 2] return (pad + string + pad)[: width] else: if fill . startswith('<'): fill = fill[1:] return (width * fill)[: max(0, width - len(string))] + string[max(0, len(string) - width):]
Next level string padding
56f3ca069821793533000a3a
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/56f3ca069821793533000a3a
6 kyu
# Task You are given a function that should insert an asterisk (`*`) between every pair of **even digits** in the given input, and return it as a string. If the input is a sequence, concat the elements first as a string. ## Input The input can be an integer, a string of digits or a sequence containing integers only. ## Output Return a string. ## Examples ``` 5312708 --> "531270*8" "0000" --> "0*0*0*0" [1, 4, 64] --> "14*6*4" ``` Have fun!
algorithms
import re def asterisc_it(s): if isinstance(s, int): s = str(s) elif isinstance(s, list): s = '' . join(map(str, s)) return re . sub(r'(?<=[02468])(?=[02468])', '*', s)
Asterisk it
5888cba35194f7f5a800008b
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/5888cba35194f7f5a800008b
7 kyu
You need to play around with the provided string (s). Move consonants forward 9 places through the alphabet. If they pass 'z', start again at 'a'. Move vowels back 5 places through the alphabet. If they pass 'a', start again at 'z'. For our Polish friends this kata does not count 'y' as a vowel. Exceptions: If the character is 'c' or 'o', move it back 1 place. For 'd' move it back 3, and for 'e', move it back 4. If a moved letter becomes 'c', 'o', 'd' or 'e', revert it back to it's original value. Provided string will always be lower case, won't be empty and will have no special characters.
algorithms
def vowel_back(st): return st . translate(str . maketrans("abcdefghijklmnopqrstuvwxyz", "vkbaafpqistuvwnyzabtpvfghi"))
Vowels Back
57cfd92c05c1864df2001563
[ "Fundamentals", "Strings", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/57cfd92c05c1864df2001563
6 kyu
John is developing a system to report fuel usage but needs help with the coding. First, he needs you to write a function that, given the actual consumption (in l/100 km) and remaining amount of petrol (in l), will give you how many kilometers you'll be able to drive. Second, he needs you to write a function that, given a distance (in km), a consumption (in l/100 km), and an amount of petrol (in l), will return one of the following: If you can't make the distance without refueling, it should return the message "You will need to refuel". If you can make the distance, the function will check every 100 km and produce an array with [1:kilometers already driven. 2: kilometers till end. 3: remaining amount of petrol] and return all the arrays inside another array ([[after 100km], [after 200km], [after 300km]...]) PLEASE NOTE: any of the values with decimals that you return should be rounded to 2 decimals.
games
def total_kilometers(cons, petrol): return round(100 * petrol / cons, 2) def check_distance(dist, cons, petrol): return ("You will need to refuel" if dist > total_kilometers(cons, petrol) else [[n * 100, dist - 100 * n, round(petrol - cons * n, 2)] for n in range(dist / / 100 + 1)])
Fuel usage reporting
55cb8b5ddd6a67fef7000070
[ "Fundamentals", "Games", "Puzzles" ]
https://www.codewars.com/kata/55cb8b5ddd6a67fef7000070
6 kyu
Create a decorator ```expected_type()``` that checks if what the decorated function returns is of expected type. An ```UnexpectedTypeException``` should be raised if the type returned by the decorated function doesn't match the ones expected. Requirements: * ```expected_type()``` should accept a tuple of many types that may be valid * ```UnexpectedTypeException``` should be raised if decorated function returns object of type that wasn't defined in ```expected_type()```'s arguments (you have to implement that class) * ```return_something``` will be decorated with ```expected_type``` in the tests and will look exactly like in the example below Example: ``` @expected_type((str,)) def return_something(input): # do stuff here with the input... return something >>> return_something('The quick brown fox jumps over the lazy dog.') 'The quick brown fox jumps over the lazy dog.' >>> return_something('The quick brown fox jumps over the lazy dog.') 'Maybe you'll output another string...' >>> return_something(None) UnexpectedTypeException: Was expecting instance of: str <<< if the returned type isn't one of the expected ones. ```
reference
class UnexpectedTypeException (Exception): pass def expected_type(return_types): def decor(func): def wrapper(* args, * * kwargs): ans = func(* args, * * kwargs) if not isinstance(ans, return_types): raise UnexpectedTypeException() return ans return wrapper return decor
Expected Type Decorator
56f411dc9821795fd90011d9
[ "Fundamentals", "Design Patterns", "Object-oriented Programming" ]
https://www.codewars.com/kata/56f411dc9821795fd90011d9
6 kyu
The cat wants to lay down on the table, but the problem is that we don't know where it is in the room! You'll get in input: - the cat coordinates as a list of length 2, with the row on the map and the column on the map. - the map of the room as a list of lists where every element can be 0 if empty or 1 if is the table (there can be only one 1 in the room / lists will never be empty). # Task: You'll need to return the route to the table, beginning from the cat's starting coordinates, as a String. The route must be a sequence of letters U, D, R, L that means Up, Down, Right, Left. The order of the letters in the output isn't important. # Outputs: * The route for the cat to reach the table, as a string * If there isn't a table in the room you must return "NoTable" * if the cat is outside of the room you must return "NoCat" (this output has the precedence on the above one). * If the cat is alredy on the table, you can return an empty String. # Example: ``` cat = [0,1] room =[[0,0,0], [0,0,0], [0,0,1]] The route will be "RDD", or "DRD" or "DDR" ```
reference
from itertools import chain def putTheCatOnTheTable(cat, map): lX, lY = len(map), len(map[0]) x, y = cat if not (0 <= x < lX and 0 <= y < lY): return 'NoCat' try: table = divmod(list(chain . from_iterable(map)). index(1), lY) except ValueError: return "NoTable" return '' . join(['UD', 'LR'][i][d > 0] * abs(d) for i, d in enumerate([b - a for a, b in zip(cat, table)]))
Put the cat on the table
560030c3ab9f805455000098
[ "Fundamentals" ]
https://www.codewars.com/kata/560030c3ab9f805455000098
6 kyu
The number 1089 is the smallest one, non palindromic, that has the same prime factors that its reversal. Thus, ```python prime factorization of 1089 with 3, 3, 11, 11 -------> 3, 11 prime factorization of 9801 with 3, 3, 3, 3, 11, 11 -------> 3, 11 ``` The task for this kata is to create a function same_factRev(), that receives a nMax, to find all the numbers with the above property, bellow nMax. the function same_factRev(), will output a sorted list with the found numbers bellow nMax Let'se some cases ```python same_factRev(1100) -----> [1089] same_factRev(2500) -----> [1089, 2178] ``` (Palindromic numbers are like: 171, 454, 4224, these ones should be discarded) Happy coding!! (The sequence of these kind of numbers is registered in OEIS as A110819)
reference
from bisect import bisect A110819 = [1089, 2178, 4356, 6534, 8712, 9801, 10989, 21978, 24024, 26208, 42042, 43956, 48048] def same_factRev(nMax): return A110819[: bisect(A110819, nMax)]
Numbers and its Reversal Having Same Prime Factors.
55ea170313b76622b3000014
[ "Fundamentals", "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/55ea170313b76622b3000014
5 kyu
Write a function that reverses the bits in an integer. For example, the number `417` is `110100001` in binary. Reversing the binary is `100001011` which is `267`. You can assume that the number is not negative.
reference
def reverse_bits(n): return int(bin(n)[: 1: - 1], 2)
Reverse the bits in an integer
5959ec605595565f5c00002b
[ "Bits", "Fundamentals" ]
https://www.codewars.com/kata/5959ec605595565f5c00002b
7 kyu
A group of friends (n >= 2) have reunited for a get-together after a very long time. They agree that they will make presentations on holiday destinations or expeditions they have been to only if it satisfies **one simple rule**: > the holiday/journey being presented must have been visited _only_ by the presenter and no one else from the audience. Write a program to output the presentation agenda, including the presenter and their respective presentation titles. --- ### EXAMPLES ```python presentation_agenda([ {'person': 'Abe', 'dest': ['London', 'Dubai']}, {'person': 'Bond', 'dest': ['Melbourne', 'Dubai']} ]) == [{'person': 'Abe', 'dest': ['London']}, {'person': 'Bond', 'dest': ['Melbourne']}] presentation_agenda([ {'person': 'Abe', 'dest': ['Dubai']}, {'person': 'Brad', 'dest': ['Dubai']} ]) == [] presentation_agenda([ {'person': 'Abe', 'dest': ['London', 'Dubai']}, {'person': 'Bond', 'dest': ['Melbourne', 'Dubai']}, {'person': 'Carrie', 'dest': ['Melbourne']}, {'person': 'Damu', 'dest': ['Melbourne', 'Dubai', 'Paris']} ]) == [{'person': 'Abe', 'dest': ['London']}, {'person': 'Damu', 'dest': ['Paris']}] ``` ```javascript presentationAgenda([ {'person': 'Abe', 'dest': ['London', 'Dubai']}, {'person': 'Bond', 'dest': ['Melbourne', 'Dubai']} ]) == [{'person': 'Abe', 'dest': ['London']}, {'person': 'Bond', 'dest': ['Melbourne']}] presentationAgenda([ {'person': 'Abe', 'dest': ['Dubai']}, {'person': 'Brad', 'dest': ['Dubai']} ]) == [] presentationAgenda([ {'person': 'Abe', 'dest': ['London', 'Dubai']}, {'person': 'Bond', 'dest': ['Melbourne', 'Dubai']}, {'person': 'Carrie', 'dest': ['Melbourne']}, {'person': 'Damu', 'dest': ['Melbourne', 'Dubai', 'Paris']} ]) == [{'person': 'Abe', 'dest': ['London']}, {'person': 'Damu', 'dest': ['Paris']}] ```
algorithms
from collections import Counter def presentation_agenda(friend_list): uniqueDest = {d for d, c in Counter( d for p in friend_list for d in p['dest']). items() if c == 1} pFilteredDest = tuple( (p['person'], [d for d in p['dest'] if d in uniqueDest]) for p in friend_list) return [{'person': name, 'dest': lst} for name, lst in pFilteredDest if lst]
Exclusive presentations
57dd8c78eb0537722f0006bd
[ "Sets", "Algorithms" ]
https://www.codewars.com/kata/57dd8c78eb0537722f0006bd
6 kyu
Following the trails of your lost master - Λoile - who you inherited your mad programming skills from, you have finally caught a lead and begin your adventure into the dungeon where progress can be made. To pass the first cave, you need to **crack the code** on the podium sitting in front of the gate, blocking you from moving onwards. ![](https://i.imgur.com/80QfkdF.jpg) Fortunately, you have access to the internet, make good use of it. To pass, implement the function in your language based on the code as given. Good luck! :345**/.87vv98,:<> v/*52:,+2*<>**- | >6%.:52*%.1+:25*^@
games
# Top portion is adapted from my solution for a different kata about this language # Removing the instructions that aren't used.to not fully spoiler the other kata. from enum import Enum D = Enum('Direction', ['U', 'D', 'L', 'R']) def interpret(code): instructions = tuple(l for l in code . split('\n')) output = "" ip = [0, 0] direction = D . R op = instructions[ip[1]][ip[0]] stack = [] def pop(): return stack . pop() if stack else 0 def div(a, b): return b / / a if a != 0 else 0 def mod(a, b): return b % a if a != 0 else 0 def sub(a, b): return b - a while op != '@': if op == '^': direction = D . U elif op == '<': direction = D . L elif op == '>': direction = D . R elif op == 'v': direction = D . D elif op == '|': direction = D . U if pop() else D . D elif op == ':': stack . append(stack[- 1] if stack else 0) elif op == '$': pop() elif op == '.': output += str(pop()) elif op == ',': output += chr(pop()) elif op == ' ': pass elif op == '+': stack . append(pop() + pop()) elif op == '-': stack . append(sub(pop(), pop())) elif op == '*': stack . append(pop() * pop()) elif op == '/': stack . append(div(pop(), pop())) elif op == '%': stack . append(mod(pop(), pop())) elif op . isdigit(): stack . append(int(op)) # Move to next instruction if direction == D . L: ip[0] = (ip[0] - 1) % len(instructions[ip[1]]) elif direction == D . R: ip[0] = (ip[0] + 1) % len(instructions[ip[1]]) elif direction == D . U: ip[1] = (ip[1] - 1) % len(instructions) elif direction == D . D: ip[1] = (ip[1] + 1) % len(instructions) op = instructions[ip[1]][ip[0]] return output def podium_code(): return interpret(':345**/.87vv98,:<>\nv/*52:,+2*<>**- |\n>6%.:52*%.1+:25*^@')
Cryptic Cave: Episode 1
5a5c5a1ab3bfa8728d00008d
[ "Reverse Engineering", "Games", "Esoteric Languages", "Puzzles" ]
https://www.codewars.com/kata/5a5c5a1ab3bfa8728d00008d
5 kyu
All of sudden you and Stripes find yourselves in a sticky situation. Your paper drop business has grown to the point where it's too much for just Stripes and you to handle. Simply, there are just too many houses and not enough of you. Since your job is to make sure the business runs smoothly, it's up to you to find a solution. Create a method that returns how many paperboys you need to hire to get the job done in the set amount of time. Remember you and Stripes are already a team of two so you need to return how many extra hands are needed. You'll be passed four arguments. A neighbourhood, the number of houses to deliver to in that neighbourhood, the amount of time it takes one paperboy to deliver to 50 houses (in minutes), and the time in hours to complete the job. In this example you have 400 houses to deliver to in Brooklyn Heights. It takes one paperboy (or papergirl) 30 minutes to deliver to 50 houses and you have one hour to complete the job. ```javascript var route1 = new Route("Brooklyn Heights", 400, 30, 1); route1.paperboysNeeded() //should return "2 paperboys needed for Brooklyn Heights" ``` In this example you have 100 houses in Highland Park, it takes you 15 minutes to deliver to 50 houses and you have 15 minutes to complete the job. ```javascript var route14 = new Route("Highland Park", 100, 15, .25); route14.paperboysNeeded() //should return "You and Stripes can handle the work yourselves" ``` Note: if a paper delivery cannot reach the next house, he does not drop any fraction of a paper for that house.
algorithms
from math import ceil class Route: def __init__(self, soc, h, m, t): c = ceil(h / int((t * 60) * 50 / m)) self . paperboys_needed = lambda: f" { c - 2 } paperboy {[ '' , 's' ][ c > 3 ]} needed for { soc } " if c > 2 else "You and Stripes can handle the work yourselves"
Paperboy 2
56fa467e0ba33b8b1100064a
[ "Algorithms" ]
https://www.codewars.com/kata/56fa467e0ba33b8b1100064a
6 kyu
Write a function ```unpack()``` that unpacks a ```list``` of elements that can contain objects(`int`, `str`, `list`, `tuple`, `dict`, `set`) within each other without any predefined depth, meaning that there can be many levels of elements contained in one another. Example: ```python unpack([None, [1, ({2, 3}, {'foo': 'bar'})]]) == [None, 1, 2, 3, 'foo', 'bar'] ``` Note: you don't have to bother about the order of the elements, especially when unpacking a `dict` or a `set`. Just unpack all the elements.
reference
from collections import Iterable def unpack(iterable): lst = [] for x in iterable: if isinstance(x, dict): x = unpack(x . items()) elif isinstance(x, str): x = [x] elif isinstance(x, Iterable): x = unpack(x) else: x = [x] lst . extend(x) return lst
Unpack
56ee74e7fd6a2c3c7800037e
[ "Fundamentals", "Algorithms", "Lists", "Recursion" ]
https://www.codewars.com/kata/56ee74e7fd6a2c3c7800037e
6 kyu
In logic, an implication (or material conditional) states that > If `p` is true, `q` should be true too. We can express the result of any implication of two statements as a logical table: ``` q T F p T T F F T T ``` In this kata, we will take that further. Given an array, assume that from first to last item in the array, each implies the next (for example, in an array of three items `p`, `q`, and `r`: `(p -> q) -> r`). Return the boolean answer. If the array is empty, return `None`, `null` or a similar empty value. There will be no more than `8` variables in the array, and the array will contain only boolean values.
algorithms
from functools import reduce def mult_implication(lst): return reduce(lambda p, q: not p or q, lst) if lst else None
Multiple implications
58f671ee5522a9c33800009b
[ "Algorithms" ]
https://www.codewars.com/kata/58f671ee5522a9c33800009b
7 kyu
## Prologue In this kata. We assume that you know what [BrainFuck](http://en.wikipedia.org/wiki/Brainfuck) is. And it would be better if you were able to recite all 8 basic operators to solve this kata. ## Background Have you ever coded BrainFuck by hand ? Have you ever counted the operators again and again to make sure that the pointer points to the correct cell ? Is it fun ? Of course it is fun, especially when you produce a super short code abusing every cells while having the same functionality as long long codes. But is it always that fun ? We know what to do if we are not 100 percent satisfied with an existing language. Stop using it, or create another language and transpile to it. ## Requirement You are given a `code` follows the following specification, and are going to transpile it to BrainFuck. ## Specification ### Lexical Syntax The syntax for lexical parsing is described in an EBNF like syntax. Literal strings are enclosed in pairs of ' or " characters below, using Unicode escapes. ```txt EOL -> 'U+000A' CommentPrefix -> '//' | '--' | '#' Comment -> CommentPrefix <all characters until EOL or EOF> VarPrefix -> '$' | '_' | 'a' | 'b' | ... | 'z' | 'A' | 'B' | ... | 'Z' VarSuffix -> VarPrefix | Digit CharElement -> <any characters other than ', ", or \> | '\\' | "\'" | '\"' | '\n' | '\r' | '\t' CharQuote -> "'" Char -> CharQuote CharElement CharQuote StringQuote -> '"' String -> StringQuote CharElement* StringQuote Digit -> '0' | '1' | ... | '9' Number -> '-' Digit+ | Digit+ | Char ``` ### Grammar The language grammar for parsing is described in an EBNF like syntax. Literal strings are enclosed in pairs of ' or " characters below. ```txt Program -> [ Statement ] [ Comment ] [ EOL Program ] VarName -> VarPrefix VarSuffix* VarNameOrNumber -> VarName | Number VarNameOrString -> VarName | String VarSingle -> VarName | ListName '[' Number ']' Statement -> "var" VarSingle+ | "set" VarName VarNameOrNumber | "inc" VarName VarNameOrNumber | "dec" VarName VarNameOrNumber | "add" VarNameOrNumber VarNameOrNumber VarName | "sub" VarNameOrNumber VarNameOrNumber VarName | "mul" VarNameOrNumber VarNameOrNumber VarName | "divmod" VarNameOrNumber VarNameOrNumber VarName VarName | "div" VarNameOrNumber VarNameOrNumber VarName | "mod" VarNameOrNumber VarNameOrNumber VarName | "cmp" VarNameOrNumber VarNameOrNumber VarName | "a2b" VarNameOrNumber VarNameOrNumber VarNameOrNumber VarName | "b2a" VarNameOrNumber VarName VarName VarName | "lset" ListName VarNameOrNumber VarNameOrNumber | "lget" ListName VarNameOrNumber VarName | "ifeq" VarName VarNameOrNumber | "ifneq" VarName VarNameOrNumber | "wneq" VarName VarNameOrNumber | "proc" ProcedureName ProcedureParameter* | "end" | "call" ProcedureName ProcedureParameter* | "read" VarName | "msg" VarNameOrString+ | "rem" <all characters until EOL or EOF> ListName -> VarName ProcedureName -> VarName ProcedureParameter -> VarName ``` Note + One or more whitespace characters are used to separate non-terminals in the grammar (except for 'Comment'). + Instruction names and variable names are case insensitive, i.e. lookup ignores case. + Character literals should be translated to their ASCII encoded numeral (eg. `'z' -> 122`). + If a number is not in range [0,255] wrap it into this range . (eg. `450 -> 194`, `-450 -> 62`) ### Instruction #### Variable `var VarSingle+`. Define one or more variables, some could be lists. The length of a list will always be in range [1,256]. eg. `var A B C[100] D` defines variable `A`, `B`, `C` and `D` where `C` represent a 100-length list (or you call it an array). `var X [ 80 ]` is also acceptable. All variables and all list slots are initialized to `0`. `set a b`. Set value of variable `a` to `b`. Examples : `set X 30`, `set X Y`. **Note** Variables can be defined everywhere except inside a `procedure`, and they are all global variables, cannot be used before defined. #### Arithmetic `inc a b`. Increase the value of `a` as `b`. Equivalent to C : `a += b`. Examples : `inc X 10`, `inc X Y`. `dec a b`. Decrease the value of `a` as `b`. Equivalent to C : `a -= b`. Examples : `dec Y 10`, `dec X Y`. `add a b c`. Add `a` and `b` then store the result into `c`. Equivalent to C : `c = a + b`. Examples : `add 10 X Y`, `add X Y X` `sub a b c`. Subtract `b` from `a` then store the result into `c`. Equivalent to C : `c = a - b`. Examples : `sub X 20 Y`, `sub X Y Y` `mul a b c`. Multiply `a` and `b` then store the result into `c`. Equivalent to C : `c = a * b`. Examples : `mul 10 20 X`, `mul X 10 X` `divmod a b c d`. Divide `a` and `b` then store the quotient into `c` and the remainder into `d`. Equivalent to C : `c = floor(a / b), d = a % b`. Examples : `divmod 20 10 X Y`, `divmod X Y X Y`, `divmod X 10 Y X`. `div a b c`. Divide `a` and `b` then store the quotient into `c`. Equivalent to C : `c = floor(a / b)`. Examples : `div 10 X X`, `div X X X` `mod a b c`. Divide `a` and `b` then store the remainder into `c`. Equivalent to C : `c = a % b`. Examples : `mod 10 X X`, `mod X X Y` **Note** The behavior when divisor is 0 is not defined, and will not be tested. `cmp a b c`. Compare `a` and `b`. If `a` < `b` store -1(255) into `c`. If `a` == `b` store 0 into `c`. If `a` > `b` store 1 into `c`. Examples : `cmp 10 10 X`, `cmp X X X`, `cmp X 20 Y` `a2b a b c d`. ASCII To Byte. Treat `a`, `b` and `c` as ASCII digits and store the number represents those digits into `d`. Equivalent to C : `d = 100 * (a - 48) + 10 * (b - 48) + (c - 48)`. Examples : `a2b '1' '5' '9' X`, `a2b '0' X Y X` `b2a a b c d`. Byte To ASCII. The reverse operation of `a2b`. Equivalent to C : `b = 48 + floor(a / 100), c = 48 + floor(a / 10 % 10), d = 48 + (a % 10)`. Examples : `b2a 159 X Y Z`, `b2a 'z' X Y Z`, `b2a X X Y Z` #### List `lset a b c`. Set `c` into index `b` of list `a`. Equivalent to C : `a[b] = c`. Examples : `lset X 0 20`, `lset X Y Z` `lget a b c`. Read index `b` of list `a` into `c`. Equivalent to C : `c = a[b]`. Examples : `lget X 0 X`, `lget X Y Z` **Note** The behavior of accessing invalid index (negative or too big) is not defined, and will not be tested. #### Control Flow `ifeq a b`. Execute the block when `a` equals to `b`. Equivalent to C : `if (a == b) {` `ifneq a b`. Execute the block when `a` not equals to `b`. Equivalent to C : `if (a != b) {` `wneq a b`. Execute the block repeatly while `a` not equals to `b`. Equivalent to C : `while (a != b) {` `proc procedureName procedureParameter`. Begin a procedure block. `end`. The end of `ifeq`, `ifneq`, `wneq` and `proc`. Equivalent to C : `}` `call procedureName argument`. Invoke a procedure. Notes + `ifeq`, `ifneq` and `wneq` can be nested, can appear inside a `proc`. + `proc` can not be nested. + `call` can invoke a `proc` before it is defined. + `call` can be inside a `proc`. + Procedures can not be directly or indirectly recursive. + Arguments are passed to a procedure by reference, which means procedures are kind of marco. + Procedure paramaters can have same name with global variables, in which case its content refers to the parameter instead of global variables. #### Interactive `read a`. Read into `a`, using the BF ',' operator. `msg`. Print message, using the BF '.' operator. String arguments can separate other arguments, no whitespace is needed there. Examples : `msg "a is " a`, `msg"b ""is"b"\n"`, `msg a b c` #### Comment `rem`. Used for whole line comments. ## Error Handling A complete transpiler would not only accept valid input but also tells the errors in an invalid input. If any situation mentioned below occured, generate an error on the first occurrence. There will not be any other invalid forms appears in the final tests. (eg. `msg 20` does not suit the specification but will not be tested) Also, there will not exist procedures that are not being used. + Unknown instructions. `whatever a b c` + Number of arguments for an instruction does not match the expectation. `add 20`, `div 20 20 c d` + Undefined var names. `var Q\nadd Q Q S` + Duplicate var names. `var Q q`, `var Q\nvar Q[20]` + Define variables inside a procedure. `proc whatever\nvar Q\nend` + Unclosed `[]` pair. `var Q[ 20 S` + Expect a variable but got something else. `set 20 20`, `inc "a" 5` + Expect a variable but got a list. `var A B[20]\nlset B B 20` + Expect a list but got a variable. `var A B[20]\nlset A 0 20` + Unclosed `''` pair. `add '0 '1' a` + Unclosed `""` pair. `msg "abc` + Nested procedures. `proc pa\nproc pb\nend\nend` + Duplicate procedure names. `proc a\nend\nproc a\nend` + Duplicate parameter names. `proc a Q q\nend` + End before beginning a block. `end` + Unclosed blocks. `var a\nifeq a 0` + Undefined procedure. `call whatever` + The length of arguments does not match the length of parameters. `proc a b c\nend\ncall a x` + Recursive call. ```txt var A set a 20 call Wrap a proc Say x msg "It is "x call Wrap X end Proc Wrap X call Say x eNd ``` ## What should the code be transpiled like Any valid BrainFuck code with the same functionality. If you stuck on some instructions, you can check the following links. [Brainfuck algorithms](https://esolangs.org/wiki/Brainfuck_algorithms) [INSHAME: Brainfuck](http://www.inshame.com/search/label/Brainfuck) Actually this kata is inspired by the project `FBF` on INSHAME site. ## Example ```javascript var code = kcuf(` var q w e read q read w add q w e msg q " " w " " e `) runBF(Code,'A!') === 'A ! b' ``` Checkout more in example tests. ## About the BrainFuck interpreter The interpreter used here + Accept and ignore characters other than `+-<>,.[]`. + Has *infinity* cells. + Cells value are wrapped into [0,255]. + Throws an error when accessing negative indexes. The following situations will be optimized + Continous `+`s. + Continous `-`s. + Continous `<`s. + Continous `>`s. + Loops that only contain `+-<>`, return back to be begining position at the end, and totally increasing 1 or decreasing 1 to the begining position. (eg. `[-]`, `[>+<-<+>]`. Not `[>]`, `[->]`, `[>[-]]`) ## Note + You do not need to concentrate on the size and performance of the output code, but you may need to be careful if the algorithm you used to transpile an instruction is too slow. + If you are sure that my implementation of BrainFuck interpreter includes a bug that fails your solution. Please feel free to raise an issue. + If the description above is not clear enough. Please feel free to question me. Have Fun. O_o
reference
import re from abc import ABC from collections import ChainMap from collections.abc import Iterable, Iterator, MutableMapping from contextlib import AbstractContextManager from dataclasses import asdict, dataclass, fields, replace from enum import Enum from itertools import islice, tee from typing import Any, Literal, overload # I try to be pedantic and avoid undefined behaviour, # so I also raise this in all cases that are said to be never tested. # Except for division by zero and out-of-bound lset/lget, # which are impossible to check at compile time. class KcufError(Exception): '''Any possible error in the program source code.''' pass # ----------------------------------------------------------------------------- # Lexer # # Splits the source code into a stream of tokens. # Works like a filter, doesn't hold more than 1 token in memory. # ----------------------------------------------------------------------------- _CHAR_ELEMENT_PATTERN = r'''(?:[^'"\n\\]|[\\][\\'"nrt])''' class TokenType(Enum): COMMENT = r'(?:^[ \t]*[Rr][Ee][Mm]\b|//|--|#).*?$' VAR_NAME = r'[A-Za-z$_][A-Za-z$_0-9]*' BRACKET = r'[\[\]]' NUMBER = r'-?[0-9]+' CHAR = f"'{_CHAR_ELEMENT_PATTERN}'" STRING = f'"{_CHAR_ELEMENT_PATTERN}*"' EOL = r'\n' WHITESPACE = r'[ \t]+' INVALID_TOKEN = r'.' def __repr__(self) -> str: return f'{self.__class__.__name__}.{self.name}' TT = TokenType _TOKEN_PATTERN = '|'.join(f'({t.value})' for t in TokenType) _TOKEN = re.compile(_TOKEN_PATTERN, re.MULTILINE) @dataclass(repr=False) class Token: type: TokenType value: str def __repr__(self) -> str: return f'{type(self).__name__}({self.type.name}, {repr(self.value)})' def _primary_lex(source: str) -> Iterator[Token]: '''Just split `source` into tokens defined in `TOKEN_CLASSES`.''' for match in _TOKEN.finditer(source): matched_group = match.lastindex assert matched_group is not None, 'Some group should always match' token_type = list(TokenType)[matched_group - 1] token_value = match[matched_group] yield Token(token_type, token_value) def lex(source: str) -> Iterator[Token]: '''Split `source` into tokens which are useful for the parser.''' tokens = _primary_lex(source) for token in tokens: if token.type == TT.INVALID_TOKEN: # Apart from unclosed strings/chars, # this also covers other random gibberish that's never tested. raise KcufError('Invalid token') if token.type in (TT.WHITESPACE, TT.COMMENT): continue yield token # ----------------------------------------------------------------------------- # Parser # # Combines tokens into statements, # verifies the grammar for blocks and procs. # # Works like a filter, doesn't hold more than 1 statement in memory. # ----------------------------------------------------------------------------- def _iter_line(tokens: Iterable[Token]) -> Iterator[Token]: '''Iterate over `tokens` until EOL of EOF.''' for token in tokens: if token.type == TT.EOL: break yield token class String(str): '''A string literal in the program.''' def __repr__(self) -> str: return f'{type(self).__name__}({super().__str__()})' class VarName(str): '''A simple implementation of a case-insensitive string. Represents a variable/list/procedure/parameter name. ''' def __new__(cls, contents: str): if isinstance(contents, VarName): contents = contents._contents # type:ignore self = str.__new__(cls, contents.casefold()) self._contents = contents # type:ignore return self def __repr__(self) -> str: return f'{type(self).__name__}({repr(self._contents)})' # type:ignore class ListName(VarName): pass @dataclass class Constant: value: int VarNameOrNumber = VarName | Constant def _parse_var_name(token: Token) -> VarName: if token.type != TT.VAR_NAME: raise KcufError('Expect a variable but got something else') return VarName(token.value) def _parse_var_name_or_number(token: Token) -> VarNameOrNumber: match token: case Token(TT.VAR_NAME, name): return VarName(name) case Token(TT.NUMBER, value_str): value = int(value_str) % 256 return Constant(value) case Token(TT.CHAR, value_str): value = ord(eval(value_str)) return Constant(value) case _: # This case is never tested. raise KcufError('Expect VarNameOrNumber but got something else') @dataclass class Declaration: name: VarName size: int | None = None @property def is_list(self) -> bool: return self.size is not None class Statement(ABC): '''Abstract base class for all statements.''' @classmethod def parse(cls, args: Iterable[Token]) -> 'Statement': # Default implementation that works for all fixed-size instructions. try: return cls(*cls._parse_fields(args)) except ValueError: raise KcufError('Number of arguments for an instruction ' 'does not match the expectation') @classmethod def _parse_fields(cls, args: Iterable[Token]) -> Iterator[Any]: '''Parse own fields from tokens (`cls` must be a dataclass).''' args = _iter_line(args) for field, token in zip(fields(cls), args, strict=True): if field.type is VarNameOrNumber: yield _parse_var_name_or_number(token) elif field.type is VarName: yield _parse_var_name(token) elif field.type is ListName: yield ListName(_parse_var_name(token)) else: assert False, 'Forgot to add case' @dataclass class Var(Statement): declarations: list[Declaration] @classmethod def parse(cls, args: Iterable[Token]) -> 'Var': declarations = list(cls._parse_declarations(args)) if len(declarations) == 0: raise KcufError('Number of arguments for an instruction ' 'does not match the expectation') return Var(declarations) @staticmethod def _parse_declarations(tokens: Iterable[Token]) -> Iterator[Declaration]: tokens = _iter_line(tokens) # We need to see 4 tokens ahead. window = list(islice(tokens, 4)) # Window becomes empty after we've consumed all tokens. while window: match window: case [Token(TT.VAR_NAME, name), Token(TT.BRACKET, '['), Token(TT.NUMBER, size_str), Token(TT.BRACKET, ']')]: n_consumed = 4 size = int(size_str) if not 1 <= size <= 256: # This case is never tested. raise KcufError('List size must be in range [1,256]') yield Declaration(ListName(name), size) case [Token(TT.VAR_NAME, name), *_]: n_consumed = 1 yield Declaration(VarName(name)) case _: # This covers 'Unclosed [] pair' # and other random gibberish that's never tested. raise KcufError('Expect VarSingle but got something else') # Move the window forward. window = window[n_consumed:] + list(islice(tokens, n_consumed)) @dataclass class Set(Statement): a: VarName b: VarNameOrNumber @dataclass class Inc(Statement): a: VarName b: VarNameOrNumber @dataclass class Dec(Statement): a: VarName b: VarNameOrNumber @dataclass class Add(Statement): a: VarNameOrNumber b: VarNameOrNumber c: VarName @dataclass class Sub(Statement): a: VarNameOrNumber b: VarNameOrNumber c: VarName @dataclass class Mul(Statement): a: VarNameOrNumber b: VarNameOrNumber c: VarName @dataclass class Divmod(Statement): a: VarNameOrNumber b: VarNameOrNumber c: VarName d: VarName @dataclass class Div(Statement): a: VarNameOrNumber b: VarNameOrNumber c: VarName @dataclass class Mod(Statement): a: VarNameOrNumber b: VarNameOrNumber c: VarName @dataclass class Cmp(Statement): a: VarNameOrNumber b: VarNameOrNumber c: VarName @dataclass class A2b(Statement): a: VarNameOrNumber b: VarNameOrNumber c: VarNameOrNumber d: VarName @dataclass class B2a(Statement): a: VarNameOrNumber b: VarName c: VarName d: VarName @dataclass class Lset(Statement): a: ListName b: VarNameOrNumber c: VarNameOrNumber @dataclass class Lget(Statement): a: ListName b: VarNameOrNumber c: VarName @dataclass class Ifeq(Statement): a: VarName b: VarNameOrNumber @dataclass class Ifneq(Statement): a: VarName b: VarNameOrNumber @dataclass class Wneq(Statement): a: VarName b: VarNameOrNumber @dataclass class Proc(Statement): name: VarName params: list[VarName] @classmethod def parse(cls, args: Iterable[Token]) -> 'Proc': args_iter = _iter_line(args) name_arg = next(args_iter, None) if name_arg is None: raise KcufError('Number of arguments for an instruction ' 'does not match the expectation') name = _parse_var_name(name_arg) params = [_parse_var_name(a) for a in args_iter] return Proc(name, params) @dataclass class End(Statement): pass @dataclass class Call(Statement): proc_name: VarName arguments: list[VarName] @classmethod def parse(cls, args: Iterable[Token]) -> 'Call': args_iter = _iter_line(args) name_arg = next(args_iter, None) if name_arg is None: raise KcufError('Number of arguments for an instruction ' 'does not match the expectation') proc_name = _parse_var_name(name_arg) proc_args = [_parse_var_name(a) for a in args_iter] return Call(proc_name, proc_args) @dataclass class Read(Statement): var_name: VarName @dataclass class Msg(Statement): args: list[VarName | String] @classmethod def parse(cls, args: Iterable[Token]) -> 'Msg': msg_args = [cls._parse_var_name_or_string(a) for a in _iter_line(args)] if len(msg_args) == 0: raise KcufError('Number of arguments for an instruction ' 'does not match the expectation') return Msg(msg_args) @staticmethod def _parse_var_name_or_string(token: Token) -> VarName | String: match token.type: case TT.STRING: return String(token.value) case TT.VAR_NAME: return VarName(token.value) case _: # This case is never tested. raise KcufError('Expect VarNameOrString but got somethin else') @dataclass class Rem(Statement): pass def _is_concrete_statement_type(cls: type) -> bool: return issubclass(cls, Statement) and cls is not Statement def _parse_statements(tokens: Iterable[Token]) -> Iterator[Statement]: # A sentinel value that's never seen in the actual lexer output. eof = Token(TT.COMMENT, 'EOF') tokens_iter = iter(tokens) for token in tokens_iter: # Skip empty lines. while token.type == TT.EOL: token = next(tokens_iter, eof) if token is eof: break statement_cls_name = token.value.capitalize() statement_cls = globals_().get(statement_cls_name, None) if not _is_concrete_statement_type(statement_cls): # This also covers non-VarName tokens, which are never tested. raise KcufError('Unknown instructions') yield statement_cls.parse(tokens_iter) def _check_block_grammar(program: Iterable[Statement]) -> Iterator[Statement]: unclosed_proc = False unclosed_blocks = 0 for statement in program: match statement: case Var() if unclosed_proc: raise KcufError('Define variables inside a procedure') case Proc() if unclosed_proc: raise KcufError('Nested procedures') case Proc(): unclosed_proc = True case Ifeq() | Ifneq() | Wneq(): unclosed_blocks += 1 case End() if unclosed_blocks: unclosed_blocks -= 1 case End() if unclosed_proc: unclosed_proc = False case End(): raise KcufError('End before beginning a block') yield statement if unclosed_blocks or unclosed_proc: raise KcufError('Unclosed blocks') def parse(tokens: Iterable[Token]) -> Iterator[Statement]: '''Check for grammatical errors and combine tokens into statements.''' statements = _parse_statements(tokens) return _check_block_grammar(statements) # ----------------------------------------------------------------------------- # Preprocessor # # Checks for semantic errors, # removes proc definitions and inlines proc calls. # ----------------------------------------------------------------------------- @dataclass class _Procedure(): name: VarName params: list[VarName] body: list[Statement] class _Lookup: '''A lookup table for variables and procedures.''' def __init__(self) -> None: self._variables = ChainMap[VarName, Declaration]() self._procedures = dict[VarName, _Procedure]() self._call_stack = list[VarName]() @property def _globals(self) -> MutableMapping[VarName, Declaration]: return self._variables.maps[-1] def add_global(self, var: Declaration) -> None: if var.name in self._globals: raise KcufError('Duplicate var names') self._globals[var.name] = var def add_procedure(self, procedure: _Procedure) -> None: if procedure.name in self._procedures: raise KcufError('Duplicate procedure names') if len(set(procedure.params)) < len(procedure.params): raise KcufError('Duplicate parameter names') self._procedures[procedure.name] = procedure def new_scope(self, proc: _Procedure, arguments: list[VarName] ) -> AbstractContextManager: '''Return a context manager that allows to enter and exit the scope of a procedure, affecting lookup. ''' class ContextManager: def __enter__(self_) -> 'ContextManager': if proc.name in self._call_stack: raise KcufError('Recursive call') self._call_stack.append(proc.name) if len(arguments) != len(proc.params): raise KcufError('The length of arguments does not match ' 'the length of parameters') resolved_args = [self.var(name) for name in arguments] bindings = {p: a for p, a in zip(proc.params, resolved_args)} self._variables.maps.insert(0, bindings) # type:ignore return self_ def __exit__(self_, exc_type, exc_value, exc_traceback) -> None: self._call_stack.pop() self._variables.maps.pop(0) return ContextManager() def proc(self, proc_name: VarName) -> _Procedure: try: return self._procedures[proc_name] except KeyError: raise KcufError('Undefined procedure') def var(self, var_name: VarName) -> Declaration: var = self._var_or_list(var_name) if var.is_list: raise KcufError('Expect a variable but got a list') return var def list(self, name: ListName) -> Declaration: var = self._var_or_list(name) if not var.is_list: raise KcufError('Expect a list but got a variable') return var def _var_or_list(self, var_name: VarName) -> Declaration: if var_name not in self._variables: # This also covers variables used before they are defined, # which currently isn't tested. raise KcufError('Undefined var names') return self._variables[var_name] def _iter_until_matching_end(body: Iterable[Statement]) -> Iterator[Statement]: unclosed_blocks = 1 for statement in body: if isinstance(statement, (Ifeq, Ifneq, Wneq)): unclosed_blocks += 1 elif isinstance(statement, End): unclosed_blocks -= 1 if not unclosed_blocks: break yield statement class _Preprocessor: def __init__(self) -> None: self._lookup: _Lookup self._unused_procs: set[VarName] def preprocess(self, program: Iterable[Statement]) -> Iterator[Statement]: self._lookup = _Lookup() self._unused_procs = set[VarName]() # Make a full pass to register procs and remove definitions from main. main = list(self._remove_procs(program)) # Then work on a stream. return self._expand_main(main) def _remove_procs(self, body: Iterable[Statement]) -> Iterator[Statement]: body_iter = iter(body) for statement in body_iter: if isinstance(statement, Proc): proc_body = list(_iter_until_matching_end(body_iter)) proc = _Procedure(statement.name, statement.params, proc_body) self._lookup.add_procedure(proc) self._unused_procs.add(proc.name) else: yield statement def _expand_main(self, main: Iterable[Statement]) -> Iterator[Statement]: yield from self._expand_calls(main) if self._unused_procs: # This case is never tested. raise KcufError('Unused procedures') def _expand_calls(self, body: Iterable[Statement]) -> Iterator[Statement]: for statement in body: if isinstance(statement, Var): for decl in statement.declarations: self._lookup.add_global(decl) yield statement elif isinstance(statement, Call): procedure = self._lookup.proc(statement.proc_name) with self._lookup.new_scope(procedure, statement.arguments): yield from self._expand_calls(procedure.body) self._unused_procs.discard(procedure.name) else: statement = self._resolve_var_names(statement) yield statement def _resolve_var_names(self, statement: Statement) -> Statement: '''Resolve used parameters (if any) to the gloval vars they point to''' match statement: case Msg(args): # A special case because fields aren't scalar. resolved_args = list(self._resolve_msg_args(args)) return Msg(resolved_args) case _: fields_dict = asdict(statement) updated_fields = { fn: self._resolve_name(fv) for fn, fv in fields_dict.items() if isinstance(fv, VarName) } return replace(statement, **updated_fields) def _resolve_msg_args(self, args: Iterable[VarName | String] ) -> Iterator[VarName | String]: for arg in args: if isinstance(arg, VarName): yield self._resolve_name(arg) else: yield arg def _resolve_name(self, name: VarName) -> VarName: '''If `name` refers to a parameter, resolve it to the gloval variable that it points to. ''' if isinstance(name, ListName): referenced_list = self._lookup.list(name) return referenced_list.name else: referenced_var = self._lookup.var(name) return referenced_var.name def preprocess(program: Iterable[Statement]) -> Iterator[Statement]: '''Check for semantic errors, remove proc definitions and inline calls.''' return _Preprocessor().preprocess(program) # ----------------------------------------------------------------------------- # Backend # # Takes a valid program from the previous step and translates it to BF. # ----------------------------------------------------------------------------- @dataclass class _Variable: address: int @dataclass class _List: HEAD_SIZE = 4 address: int size: int _Rvalue = _Variable | Constant @dataclass(init=False) class _Zeroed: '''A marker for `_Backend._free()` arguments. Indicates that the cleanup is not needed. ''' address: int def __init__(self, var: _Variable) -> None: self.address = var.address @dataclass class _IfBlock: cond_var: _Variable @dataclass class _WhileBlock: a: _Rvalue b: _Rvalue cond_var: _Variable _Block = _IfBlock | _WhileBlock class _Backend: '''Generates BF code, statement by statement.''' # The main idea is to treat the cell array like a stack. # Statements are implemented using algorithms that claim # available cells at the top, use them, and then reset them back to 0. # Common principles for private methods: # - Translate the eponymous concept into BF. # - Write the result into `_buffer` attribute. # - Don't clobber variables that are supposed to be read-only. # (But sometimes, `consume` option is available. When set to `True`, # it produces more optimized BF code and sets the variable to 0.) # - Always handle cases where multiple operands alias the same cell. # Don't push responsibility onto the caller. # - Apply constant folding where it's easy to implement. def __init__(self, *, cleanup_blocks: bool) -> None: '''`cleanup_blocks=False` allows to compile everything in one pass, but this approach leaks one cell per each `ifeq/ifneq/wneq` block, producing a bloated cell layout that's hard to understand and debug. `cleanup_blocks=True` fixes the leak, but one-pass compilation crashes if there are any `vars` defined inside of blocks. That's because everything is stack allocated and these `vars` are allocated on top of the block cell that needs to be cleaned up. My preferred approach is using `cleanup_blocks=True` with two passes: pre-allocating all `vars` in advance and then generating the code. ''' self._cleanup_blocks = cleanup_blocks self._buffer = list[str]() '''Generated BF code goes here.''' self._ptr = 0 '''Points at the current data cell.''' self._stack_ptr = 0 '''Points at the first available cell on the "BF stack". This cell and all cells to the right are always zeroed.''' self._blocks = list[_Block]() '''A stack to keep track of of entered ifeq,ifneq,wneq blocks.''' self._vars = dict[VarName, _Variable]() self._lists = dict[VarName, _List]() def get_full_result(self) -> str: '''Return full contents of the internal buffer.''' return ''.join(self._buffer) def generate(self, statement: Statement) -> None: '''Translate statement to BF code and append it to internal buffer.''' args = self._lookup_args(statement) match statement: case Var(): self._var(*args) case Set(): self._set(*args) case Inc(): self._inc(*args) case Dec(): self._dec(*args) case Add(): self._add(*args) case Sub(): self._sub(*args) case Mul(): self._mul(*args) case Divmod(): self._divmod(*args) case Div(): self._div(*args) case Mod(): self._mod(*args) case Cmp(): self._cmp(*args) case A2b(): self._a2b(*args) case B2a(): self._b2a(*args) case Lset(): self._lset(*args) case Lget(): self._lget(*args) case Ifeq(): self._ifeq(*args) case Ifneq(): self._ifneq(*args) case Wneq(): self._wneq(*args) case Proc(): assert False, 'Should be already removed' case End(): self._end(*args) case Call(): assert False, 'Should be already expanded' case Read(): self._read(*args) case Msg(): self._msg(*args) case Rem(): pass case _: assert False, 'Forgot to add case' def _lookup_args(self, statement: Statement) -> Iterator[Any]: '''Iterate `statement` args, translating variable names to addresses''' args: Iterable[Any] args = (getattr(statement, field.name) for field in fields(statement)) # Special cases when statement fields are not scalar. if isinstance(statement, Var): args = statement.declarations elif isinstance(statement, Msg): args = statement.args for arg in args: match arg: case ListName() as list_name: yield self._lists[list_name] case VarName() as var_name: yield self._vars[var_name] case _: yield arg def _var(self, *declarations: Declaration) -> None: for decl in declarations: if decl.is_list: assert decl.size is not None, 'Lists are always sized' self._lists[decl.name] = self._allocate_list(decl.size) else: self._vars[decl.name] = self._allocate_var() def _set(self, dest: _Variable, source: _Rvalue, *, consume=False) -> None: if isinstance(source, _Variable) and source.address == dest.address: return self._append(dest, '[-]') self._inc(dest, source, consume=consume) def _inc(self, dest: _Variable, source: _Rvalue, *, consume=False) -> None: if isinstance(source, _Variable) and source.address == dest.address: copy = self._allocate_copy(source) self._inc_dec_impl('inc', dest, copy, consume=True) self._free(_Zeroed(copy)) return self._inc_dec_impl('inc', dest, source, consume=consume) def _dec(self, dest: _Variable, source: _Rvalue, *, consume=False) -> None: if isinstance(source, _Variable) and source.address == dest.address: self._append(dest, '[-]') return self._inc_dec_impl('dec', dest, source, consume=consume) def _inc_dec_impl(self, instruction: Literal['inc', 'dec'], dest: _Variable, source: _Rvalue, *, consume=False ) -> None: '''Assumes `source.address != dest.address`!''' op = '+' if instruction == 'inc' else '-' match source: case _Variable() if consume: self._append(source, '[', dest, op, source, '-]') case _Variable(): temp = self._allocate_var() self._append(source, '[', dest, op, temp, '+', source, '-]') self._append(temp, '[', source, '+', temp, '-]') self._free(_Zeroed(temp)) case Constant(): self._append(dest, op * source.value) def _add(self, op1: _Rvalue, op2: _Rvalue, dest: _Variable) -> None: self._set(dest, op1) self._inc(dest, op2) def _sub(self, op1: _Rvalue, op2: _Rvalue, dest: _Variable) -> None: self._set(dest, op1) self._dec(dest, op2) def _mul(self, mul1: _Rvalue, mul2: _Rvalue, dest: _Variable) -> None: self._set(dest, mul1) # Now we can do `dest *= mul2`: temp = self._allocate_var() self._inc(temp, dest, consume=True) self._append(temp, '[') self._inc(dest, mul2) self._append(temp, '-]') self._free(_Zeroed(temp)) def _divmod(self, a: _Rvalue, b: _Rvalue, c: _Variable, d: _Variable) -> None: self._divmod_div_mod_impl('divmod', a, b, c, d) def _div(self, a: _Rvalue, b: _Rvalue, c: _Variable) -> None: self._divmod_div_mod_impl('div', a, b, c) def _mod(self, a: _Rvalue, b: _Rvalue, c: _Variable) -> None: self._divmod_div_mod_impl('mod', a, b, c) def _divmod_div_mod_impl(self, instruction: Literal['divmod', 'div', 'mod'], a: _Rvalue, b: _Rvalue, c: _Variable, d: _Variable | None = None) -> None: # Harcoded algorithm requires x,y,r,q on the top of the stack. x = self._allocate_copy(a) y = self._allocate_copy(b) r = self._allocate_var() q = self._allocate_var() self._append( x, '[->[->+>>]>[<<+>>[-<+>]>+>>]<<<<<]>[>>>]>[[-<+>]>+>>]<<<<<' ) match instruction: case 'div': self._set(c, q, consume=True) self._free(_Zeroed(q), r, y, _Zeroed(x)) case 'mod': self._set(c, r, consume=True) self._free(q, _Zeroed(r), y, _Zeroed(x)) case 'divmod': assert d is not None, "'divmod' requires d" self._set(c, q, consume=True) self._set(d, r, consume=True) self._free(_Zeroed(q), _Zeroed(r), y, _Zeroed(x)) def _cmp(self, x: _Rvalue, y: _Rvalue, dest: _Variable) -> None: # Easy optimization if `x` and `y` are the same constant or cell. if x == y: self._set(dest, Constant(0)) return is_not_equal = self._allocate_var() self._not_equals(x, y, is_not_equal) # Pure speculation. self._set(dest, Constant(0)) # If x != y, this branch will execute and set `dest` to 1 or 255. self._append(is_not_equal, '[') self._cmp_not_equal(x, y, dest) self._append(is_not_equal, '-]') self._free(_Zeroed(is_not_equal)) def _not_equals(self, x: _Rvalue, y: _Rvalue, dest: _Variable) -> None: '''If `x` != `y`, set `dest` to 1. Else, set `dest` to 0.''' # Easy optimization if `x` and `y` are the same constant or cell. if x == y: self._set(dest, Constant(0)) return # The algorithm below writes the result to `x`, # so we put `x` in `dest` and use `dest` instead. self._set(dest, x) # It also needs `y` as a Variable and zeroes it, so we make a copy. # Copy will also protect us if the original `y` aliases `dest`. y = self._allocate_copy(y) diff = self._allocate_var() self._inc(diff, dest, consume=True) self._dec(diff, y, consume=True) self._append(diff, '[', dest, '+', diff, '[-]]') self._free(_Zeroed(diff), _Zeroed(y)) def _cmp_not_equal(self, x: _Rvalue, y: _Rvalue, dest: _Variable) -> None: '''Assumes `x` != `y` and `dest` == 0. Sets `dest` to 255 or 1.''' # The algorithm below writes the result to `x`, # so we need to protect the original. x = self._allocate_copy(x) # Algorithm for `x = x < y`: temp0 = self._allocate_var() temp1 = self._allocate_var() temp2 = self._allocate_var() # In the algrorithm, these are unnamed. temp3 = self._allocate_var() # But they need to be cleaned up. self._append(temp1, '>+<') self._set(temp1, y) self._append(x, '[', temp0, '+', x, '-]+') self._append(temp1, '[>-]> [<', x, '-', temp0, '[-]', temp1, '>->]<+<') self._append(temp0, '[', temp1, '-[>-]>') self._append('[<', x, '-', temp0, '[-]+', temp1, '>->]') self._append('<+<', temp0, '-]') self._free(temp3, temp2, temp1, _Zeroed(temp0)) # Speculatively set `dest` from 0 to 1, assuming that `x > y`. self._append(dest, '+') # If `x < y`, execute the branch that sets `dest` from 1 to 255. self._append(x, '[', dest, '--', x, '-]') self._free(_Zeroed(x)) def _a2b(self, a: _Rvalue, b: _Rvalue, c: _Rvalue, d: _Variable) -> None: term = self._allocate_var() with self._temporary(d) as d: self._sub(a, Constant(48), term) self._mul(term, Constant(100), d) self._sub(b, Constant(48), term) self._mul(term, Constant(10), term) self._inc(d, term, consume=True) self._sub(c, Constant(48), term) self._inc(d, term, consume=True) self._free(_Zeroed(term)) def _b2a(self, a: _Rvalue, b: _Variable, c: _Variable, d: _Variable) -> None: with self._temporary(b, c, d) as (b, c, d): self._div(a, Constant(100), b) self._inc(b, Constant(48)) self._div(a, Constant(10), c) self._mod(c, Constant(10), c) self._inc(c, Constant(48)) self._mod(a, Constant(10), d) self._inc(d, Constant(48)) @overload def _temporary(self, v: _Variable, /) -> AbstractContextManager[_Variable]: ... @overload def _temporary(self, v0: _Variable, v1: _Variable, /, *vn: _Variable, ) -> AbstractContextManager[tuple[_Variable, ...]]: ... def _temporary(self, *vars: _Variable) -> AbstractContextManager: '''Upon entering, return temporaries to be used instead of `vars`. Upon exiting, write back to `vars` (in the order listed) and destroy temporaries. This protects any variables aliased by `vars` from being overwritten before exiting the context. ''' class ContextManager: def __enter__(self_) -> _Variable | tuple[_Variable, ...]: self_._temps = tuple(self._allocate_var() for _ in vars) if len(self_._temps) == 1: return self_._temps[0] return self_._temps def __exit__(self_, exc_type, exc_value, exc_traceback) -> None: temps_and_originals = list(zip(self_._temps, vars)) for temp, original in temps_and_originals: self._set(original, temp, consume=True) # Need to free stack allocated memory in reverse order. for temp, original in reversed(temps_and_originals): self._free(_Zeroed(temp)) return ContextManager() def _lset(self, a: _List, b: _Rvalue, c: _Rvalue) -> None: if isinstance(b, Constant): cell_in_list = self._const_index(a, b) self._set(cell_in_list, c) return space = _Variable(a.address) index1 = _Variable(a.address + 1) index2 = _Variable(a.address + 2) data = _Variable(a.address + 3) self._set(data, c) self._set(index1, b) self._set(index2, b) # lset from `data`: self._append(space, '>[>>>[-<<<<+>>>>]<[->+<]<[->+<]<[->+<]>-]') self._append('>>>[-]<[->+<]<') self._append('[[-<+>]<<<[->>>>+<<<<]>>-]<<') def _lget(self, a: _List, b: _Rvalue, c: _Variable) -> None: if isinstance(b, Constant): cell_in_list = self._const_index(a, b) self._set(c, cell_in_list) return space = _Variable(a.address) index1 = _Variable(a.address + 1) index2 = _Variable(a.address + 2) data = _Variable(a.address + 3) self._set(index1, b) self._set(index2, b) # lget into `data`: self._append(space, '>[>>>[-<<<<+>>>>]<<[->+<]<[->+<]>-]') self._append('>>>[-<+<<+>>>]<<<[->>>+<<<]>') self._append('[[-<+>]>[-<+>]<<<<[->>>>+<<<<]>>-]<<') # Now we only need to: self._set(c, data, consume=True) def _const_index(self, list: _List, index: Constant) -> _Variable: '''Get address of a list cell at compile time.''' if not 0 <= index.value < list.size: # This case is never tested. raise KcufError('Out of bounds list access') return _Variable(list.address + _List.HEAD_SIZE + index.value) def _ifeq(self, a: _Variable, b: _Rvalue) -> None: self._ifeq_ifneq_impl('ifeq', a, b) def _ifneq(self, a: _Variable, b: _Rvalue) -> None: self._ifeq_ifneq_impl('ifneq', a, b) def _ifeq_ifneq_impl(self, statement: Literal['ifeq', 'ifneq'], a: _Variable, b: _Rvalue) -> None: cond_var = self._allocate_var() # Freed after the end of the block. self._not_equals(a, b, cond_var) if statement == 'ifeq': self._unary_not(cond_var) self._append(cond_var, '[-') block = _IfBlock(cond_var) self._blocks.append(block) def _unary_not(self, x: _Variable) -> None: '''If `x` == 0, set `x` to 1. Else, set `x` to 0.''' temp = self._allocate_var() self._append(x, '[', temp, '+', x, '[-]]+') self._append(temp, '[', x, '-', temp, '-]') self._free(_Zeroed(temp)) def _wneq(self, a: _Variable, b: _Rvalue) -> None: cond_var = self._allocate_var() # Freed after the end of the block. self._not_equals(a, b, cond_var) self._append(cond_var, '[') block = _WhileBlock(a, b, cond_var) self._blocks.append(block) def _end(self) -> None: block = self._blocks.pop() if isinstance(block, _WhileBlock): self._not_equals(block.a, block.b, block.cond_var) self._append(block.cond_var, ']') if self._cleanup_blocks: self._free(_Zeroed(block.cond_var)) def _read(self, var: _Variable) -> None: self._append(var, ',') def _msg(self, *args: _Variable | String) -> None: for argument in args: match argument: case _Variable() as var: self._append(var, '.') case String() as string: self._print_string(string) def _print_string(self, string: String) -> None: '''Generate hardcode for printing a string constant.''' self._goto(self._stack_ptr) for byte_value in eval(string).encode(): self._append('+' * byte_value, '.[-]') def _free(self, *variables: _Variable | _Zeroed) -> None: for var in variables: if not isinstance(var, _Zeroed): self._append(var, '[-]') assert var.address == self._stack_ptr - 1, 'Invalid deallocation' self._stack_ptr -= 1 def _allocate_copy(self, rv: _Rvalue) -> _Variable: copy = self._allocate_var() self._set(copy, rv) return copy def _allocate_list(self, size: int) -> _List: address = self._allocate_stack(size + _List.HEAD_SIZE) return _List(address, size) def _allocate_var(self) -> _Variable: address = self._allocate_stack() return _Variable(address) def _allocate_stack(self, size: int = 1) -> int: pre_increment = self._stack_ptr self._stack_ptr += size return pre_increment def _append(self, *args: str | _Variable) -> None: '''For each argument: * If `str`: treat it as BF code and append to the `_buffer` as is. * If `Variable`: generate a jump to that variable. This allows for a nice notation like the followng: ``` A: Variable = ... B: Variable = ... self._append(A, '[-]', B, '[-]') # set A and B to 0 ``` ''' for arg in args: if isinstance(arg, _Variable): self._goto(arg.address) else: self._buffer.append(arg) def _goto(self, addr: int) -> None: '''Generate a jump to the given cell.''' offset = addr - self._ptr if offset > 0: self._buffer.append('>' * offset) elif offset < 0: self._buffer.append('<' * abs(offset)) self._ptr = addr def generate_bf(program: Iterable[Statement]) -> str: '''Translate a valid preprocessed `program` to BF.''' # It's possible to compile everything in one pass: # backend = _Backend(cleanup_blocks=False) # for statement in program: # backend.generate(statement) # return backend.get_full_result() # But I prefer this approach: backend = _Backend(cleanup_blocks=True) pass1, pass2 = tee(program) # Pre-allocate globals. for statement in pass1: if isinstance(statement, Var): backend.generate(statement) # Generate the other instructions. for statement in pass2: if not isinstance(statement, Var): backend.generate(statement) return backend.get_full_result() # ----------------------------------------------------------------------------- # Transpiler # # High-level pipeline of the other components. # ----------------------------------------------------------------------------- def kcuf(code: str) -> str: tokens = lex(code) program = parse(tokens) program = preprocess(program) return generate_bf(program) globals_ = globals '''Weird anti-cheat messes with `globals` after this module is imported.'''
To BrainFuck Transpiler
59f9cad032b8b91e12000035
[ "Esoteric Languages", "Parsing", "Compilers" ]
https://www.codewars.com/kata/59f9cad032b8b91e12000035
1 kyu
You are taking a music class and you need to know what notes are on every fret of the guitar. There are six strings on the guitar and 18 frets. Given the name of the string as a string`"E", "A", "D", "G", "B" or "e"`, as well the fret in integer format (open note is 0), return the note played. We are going to use a music scale with only sharps and regular notes, so the 12 notes to know are: `A, A#, B, C, C#, D, D#, E, F, F#, G, and G#` (notice that `B#` and `E#` do not exist). Moving up one fret moves one note up the scale, so the open note (`0`) on `E` is `E`; the 1st fret note is `F`, and the second fret note is `F#`; etc. You can find a picture of this here: ![](http://takelessons.com/blog/wp-content/uploads/2014/01/guitar-fretboard.jpg) We're not concerned with octaves, so just return the note as a capital letter (`"C#", "B", "D"` etc.) ### Examples ``` "e", 0 --> "E" "D", 5 --> "G" "E", 18 --> "A#" ```
algorithms
notes = "A, A#, B, C, C#, D, D#, E, F, F#, G, G#" . split(', ') def what_note(string, fret): return notes[(notes . index(string . upper()) + fret) % len(notes)]
Figure Out the Notes
5602e85d255e3240c2000024
[ "Algorithms" ]
https://www.codewars.com/kata/5602e85d255e3240c2000024
7 kyu
You are currently in the United States of America. The main currency here is known as the United States Dollar (USD). You are planning to travel to another country for vacation, so you make it today's goal to convert your USD (all bills, no cents) into the appropriate currency. This will help you be more prepared for when you arrive in the country you will be vacationing in. Given an integer (`usd`) representing the amount of dollars you have and a string (`currency`) representing the name of the currency used in another country, it is your task to determine the amount of foreign currency you will receive when you exchange your United States Dollars. However, there is one minor issue to deal with first. The screens and monitors at the Exchange are messed up. Some conversion rates are correctly presented, but other conversion rates are incorrectly presented. For some countries, they are temporarily displaying the standard conversion rate in the form of a number's binary representation! You make some observations. If a country's currency begins with a vowel, then the conversion rate is unaffected by the technical difficulties. If a country's currency begins with a consonant, then the conversion rate has been tampered with. Normally, the display would show 1 USD converting to 111 Japanese Yen. Instead, the display is showing 1 USD converts to 1101111 Japanese Yen. You take it upon yourself to sort this out. By doing so, your 250 USD rightfully becomes 27750 Japanese Yen. ` function(250, "Japanese Yen") => "You now have 27750 of Japanese Yen." ` Normally, the display would show 1 USD converting to 21 Czech Koruna. Instead, the display is showing 1 USD converts to 10101 Czech Koruna. You take it upon yourself to sort this out. By doing so, your 325 USD rightfully becomes 6825 Czech Koruna. ` function(325, "Czech Koruna") => "You now have 6825 of Czech Koruna." ` Using your understanding of converting currencies in conjunction with the preloaded conversion-rates table, properly convert your dollars into the correct amount of foreign currency. ```if:javascript,ruby Note: `CONVERSION_RATES` is frozen. ```
reference
def convert_my_dollars(usd, currency): if currency[0]. lower() in 'aeiou': rate = CONVERSION_RATES[currency] else: rate = int(str(CONVERSION_RATES[currency]), 2) return f'You now have { usd * rate } of { currency } .'
Currency Conversion
5a5c118380eba8a53d0000ce
[ "Fundamentals", "Mathematics", "Algebra" ]
https://www.codewars.com/kata/5a5c118380eba8a53d0000ce
7 kyu
You are a skier (marked below by the `X`). You have made it to the Olympics! Well done. ``` \_\_\_X\_ \*\*\*\*\*\ \*\*\*\*\*\*\ \*\*\*\*\*\*\*\ \*\*\*\*\*\*\*\*\ \*\*\*\*\*\*\*\*\*\\.\_\_\_\_/ ``` Your job in this kata is to calculate the maximum speed you will achieve during your downhill run. The speed is dictated by the height of the mountain. Each element of the array is a layer of the mountain as indicated by the diagram above (and further below). So for this example the mountain has a height of 5 (5 rows of stars). `Speed` is `mountain height * 1.5`. The jump length is calculated by `(mountain height * speed * 9) / 10`. Jump length should be rounded to 2 decimal places. You must return the length of the resulting jump as a string in the following format: * when less than 10 m: `"X metres: He's crap!"` * between 10 and 25 m: `"X metres: He's ok!"` * between 25 and 50 m: `"X metres: He's flying!"` * when more than 50 m: `"X metres: Gold!!"` So in the example case above, the right answer would be `"33.75 metres: He's flying!"` Sadly, it takes a lot of time to make arrays look like mountains, so the tests wont all look so nice. To give an example, the above mountain would look as follows in most cases: ``` [*****, ******, *******, ********, *********] ``` Not as much fun, eh? *p.s. if you think "metre" is incorrect, please [read this](https://en.wikipedia.org/wiki/Metre#Spelling)*
reference
def ski_jump(mountain): height = len(mountain) speed = height * 1.5 jump_length = height * speed * 9 / 10 return ( f" { jump_length : .2 f } metres: He's crap!" if jump_length < 10 else f" { jump_length : .2 f } metres: He's ok!" if jump_length < 25 else f" { jump_length : .2 f } metres: He's flying!" if jump_length < 50 else f" { jump_length : .2 f } metres: Gold!!" )
Ski Jump
57ed7214f670e99f7a000c73
[ "Fundamentals", "Strings", "Arrays", "Mathematics" ]
https://www.codewars.com/kata/57ed7214f670e99f7a000c73
7 kyu
In this kata you have a 20x20 preloaded array of oil saturation in some region. Your task is to answer whether it is efficient to place the well at the given point. A well is efficient if its efficiency is bigger or equal to given threshold. Input parameters in that function are: <ul> <li> <b>x</b> and <b>y</b> integer coordinates of the well (indexes of 2D array); </li> <li> efficiency threshold (float or integer). </li> </ul> Example of oil field: ```python FIELD = [['0.98', '0.65', '0.23', '0.39', '0.99', ...], [...] ...] ``` ```ruby FIELD = [['0.98', '0.65', '0.23', '0.39', '0.99', ...], [...] ...] ``` Examples of usage: ```python is_efficient(10, 10, 3.5) = True is_efficient(7, 3, 4.5) = False ``` ```ruby is_efficient(10, 10, 3.5) = true is_efficient(7, 3, 4.5) = false ``` To calculate the current efficiency of a well, you should sum up all saturations of cells adjacent to the specified cell plus the saturation of the specified cell itself. <a href='http://hostingkartinok.com/show-image.php?id=4d035268b3b0efa8eb048637f27f00dd'><img style="width:20%" src='http://s8.hostingkartinok.com/uploads/images/2015/12/4d035268b3b0efa8eb048637f27f00dd.png' /></a> The efficiency of the marked point with 0.43 is 5.3 (sum of all cells in rectangle). If you need to calculate the efficiency at the edge of the field, you should just take in account only cells in the field.
reference
def is_efficient(x, y, threshold): o = 0 for i in range(x - 1, x + 2): for j in range(y - 1, y + 2): if 0 <= i <= 19 and 0 <= j <= 19: o += float(FIELD[i][j]) return o >= threshold
Well efficiency calculator
5649b9f069dacef88400005e
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5649b9f069dacef88400005e
6 kyu
You are making your very own boardgame. The game is played by two opposing players, featuring a 6 x 6 tile system, with the players taking turns to move their pieces (similar to chess). The design is finished, now it's time to actually write and implement the features. Being the good programmer you are, you carefully plan the procedure and break the program down into smaller managable sections. You decide to start coding the logic for resolving "fights" when two pieces engage in combat on a tile. Your boardgame features four unique pieces: <em>Swordsman, Knight, Archer</em> and <em>Pikeman</em> Each piece has unique movement and has advantages and weaknesses in combat against one of the other pieces. <h2><u>Task</u></h2> You must write a function ```fightResolve``` that takes the defending and attacking piece as input parameters, and returns the winning piece. It may be the case that both the defending and attacking piece belong to the same player, after which you must return an error value to indicate an illegal move. In C++, C and NASM, the pieces will be represented as ```chars```. Values will be case-sensitive to display ownership. Let the following char values represent each piece from their respective player. <b>Player 1: </b> ```p```= Pikeman, ```k```= Knight, ```a```= Archer, ```s```= Swordsman <b>Player 2: </b> ```P```= Pikeman, ```K```= Knight, ```A```= Archer, ```S```= Swordsman The outcome of the fight between two pieces depends on which piece attacks, the type of the attacking piece and the type of the defending piece. <b>Archers</b> always win against <b>swordsmens</b>, <b>swordsmen</b> always win against <b>pikemen</b>, <b>pikemen</b> always win against <b>knights</b> and <b>knights</b> always win against <b>archers</b>. If a matchup occurs that was not previously mentioned (for example Archers vs Pikemen) the attacker will always win. This table represents the winner of each possible engagement between an attacker and a defender. <br> <style> td, th, tr { border: 1px solid #FFFFFF; } </style> <table style=width:48px> <tr> <th>(Attacker→) <br>(Defender↓)</th> <th>Archer</th> <th>Pikeman</th> <th>Swordsman</th> <th>Knight</th> </tr> <tr> <td><b>Knight</b></td> <td>Defender</td> <td>Attacker</td> <td>Attacker</td> <td>Attacker</td> </tr> <tr> <td><b>Swordsman</b></td> <td>Attacker</td> <td>Defender</td> <td>Attacker</td> <td>Attacker</td> </tr> <tr> <td><b>Archer</b></td> <td>Attacker</td> <td>Attacker</td> <td>Defender</td> <td>Attacker</td> </tr> <tr> <td><b>Pikeman</b></td> <td>Attacker</td> <td>Attacker</td> <td>Attacker</td> <td>Defender</td> </tr> </table> <br> If two pieces from the same player engage in combat, i.e <code>P vs S</code> or <code>k vs a</code>, the function must return -1 to signify and illegal move. Otherwise assume that no other illegal values will be passed. <h2><u>Examples</u></h2> Function prototype: <code>fightResolve(defender, attacker)</code> <code>1. fightResolve('a', 'P')</code> outputs <code>'P'</code>. No interaction defined between Pikemen and Archer. Pikemen is the winner here because it is the attacking piece. <code>2. fightResolve('k', 'A')</code> outputs <code>'k'</code>. Knights always defeat archers, even if Archer is the attacking piece here. <code>3. fightResolve('S', 'A')</code> outputs <code>-1</code>. Friendly units don't fight. Return -1 to indicate error. <h2><u>Notes</u></h2> If you find the task too easy, try to solve it in the most elegant and efficient way. There are many solutions. Good luck!
algorithms
def fight_resolve(d, a): return - 1 if d . islower() == a . islower() else d if d . lower() + a . lower() in "ka sp as pk" else a
Boardgame Fight Resolve
58558673b6b0e5a16b000028
[ "Logic", "Algorithms", "Games" ]
https://www.codewars.com/kata/58558673b6b0e5a16b000028
7 kyu
In the board game Talisman, when two players enter combat the outcome is decided by a combat score, equal to the players power plus any modifiers plus the roll of a standard 1-6 dice. The player with the highest combat score wins and the opposing player loses a life. In the case of a tie combat ends with neither player losing a life. For example: ``` Player 1: 5 Power, 0 Modifier Player 2: 3 Power, 2 Modifier Player 1 rolls a 4, Player 2 rolls a 2. (5 + 0 + 4) -> (3 + 2 + 2) Player 1 wins (9 > 7) ``` Your task is to write a method that calculates the required roll for the player to win. The player and enemy stats are given as an array in the format: ```ruby [power, modifier] ``` ```python [power, modifier] ``` ```javascript [power, modifier] ``` For example for the examples used above the stats would be given as: ```ruby get_requirements([5, 0], [3, 2]) # returns 'Random' ``` ```python get_required([5, 0], [3, 2]) # returns 'Random' ``` ```javascript getRequired([5, 0], [3, 2]) // returns 'Random' ``` If the player has at least 6 more power (including modifiers) than the enemy they automatically wins the fight, as the enemy's combat score couldn't possibly exceed the player's. In this instance the method should return "Auto-win". For example: ```ruby get_requirements([9, 0], [2, 1]) # returns 'Auto-win' as the enemy can't possibly win ``` ```python get_required([9, 0], [2, 1]) # returns 'Auto-win' as the enemy can't possibly win ``` ```javascript getRequired([9, 0], [2, 1]) // returns 'Auto-win' as the enemy can't possibly win ``` If the enemy has at least 6 more power (including modifiers) than the player they automatically wins the fight, as the player's combat score couldn't possibly exceed the enemy's. In this instance the method should return "Auto-lose". For example: ```ruby get_requirements([2, 1], [9, 0]) # returns 'Auto-lose' as the player can't possibly win ``` ```python get_required([2, 1], [9, 0]) # returns 'Auto-lose' as the player can't possibly win ``` ```javascript getRequired([2, 1], [9, 0]) // returns 'Auto-lose' as the player can't possibly win ``` If the player and enemy have the same power (including modifiers) the outcome is purely down to the dice roll, and hence would be considered completely random. In this instance the method should return "Random". For example (as above): ```ruby get_requirements([5, 0], [3, 2]) # returns 'Random' as it is purely down to the dice roll ``` ```python get_required([5, 0], [3, 2]) # returns 'Random' as it is purely down to the dice roll ``` ```javascript getRequired([5, 0], [3, 2]) // returns 'Random' as it is purely down to the dice roll ``` If the player has greater power than the enemy (including modifiers) the player could guarantee a win by rolling a high enough number on the dice. In this instance the method should return a range equal to the numbers which would guarantee victory for the player. ```ruby get_requirements([6, 0], [2, 2]) # returns (5..6) as rolling a 5 or 6 would mean the enemy could not win get_requirements([7, 1], [2, 2]) # returns (3..6) as rolling anything 3 through 6 would mean the enemy could not win ``` ```python get_required([6, 0], [2, 2]) # returns '(5..6)' as rolling a 5 or 6 would mean the enemy could not win get_required([7, 1], [2, 2]) # returns '(3..6)' as rolling anything 3 through 6 would mean the enemy could not win ``` ```javascript getRequired([6, 0], [2, 2]) // returns '(5..6)' as rolling a 5 or 6 would mean the enemy could not win getRequired([7, 1], [2, 2]) // returns '(3..6)' as rolling anything 3 through 6 would mean the enemy could not win ``` If the player has less power than the enemy (including modifiers) the player can only win if the enemy rolls a low enough number, providing they then roll a high enough number. In this instance the method should return a range equal to the numbers which would allow the player a chance to win. ```ruby get_requirements([4, 0], [6, 0]) # returns (1..3) as this would be the only outcome for which the player could still win get_requirements([1, 1], [6, 0]) # returns (1..1) as this would be the only outcome for which the player could still win ``` ```python get_required([4, 0], [6, 0]) # returns '(1..3)' as this would be the only outcome for which the player could still win get_required([1, 1], [6, 0]) # returns '(1..1)' as this would be the only outcome for which the player could still win ``` ```javascript getRequired([4, 0], [6, 0]) // returns '(1..3)' as this would be the only outcome for which the player could still win getRequired([1, 1], [6, 0]) // returns '(1..1)' as this would be the only outcome for which the player could still win ``` If the better case scenario for the player is to hope for a tie, then return `"Pray for a tie!"`. ```ruby get_requirements([7, 2], [6, 8]) # returns "Pray for a tie!" ``` ```python get_required([7, 2], [6, 8]) # returns "Pray for a tie!" ``` ```javascript getRequired([7, 2], [6, 8]) // returns "Pray for a tie!" ```
algorithms
def get_required(p, e): p, e = sum(p), sum(e) if p - e >= 6: return "Auto-win" if p - e == 0: return "Random" if p - e <= - 6: return "Auto-lose" if p - e <= - 5: return "Pray for a tie!" if p > e: return f"( { e - p + 7 } ..6)" return f"(1.. { p - e + 5 } )"
Talisman Board Game Combat System Checker
541837036d821665ee0006c2
[ "Games", "Algorithms" ]
https://www.codewars.com/kata/541837036d821665ee0006c2
7 kyu
A crime scene has been discovered, and among the evidence is a list of agents, with no apparent connection. Your job in the records department is to match this list with police records to find an exact match. Your function will receive a list as the first parameter, the stolen record, followed by a list of lists, the database. A match is found only if it contains the same names in the same order, no more, no less. Your code should return None if the first parameter is an empty list. The database will always contain more than one list. A match should return "Match found". If no matches are found, your code should return "No matches". Example: agents(["John", "Sarah"], [["John", "Sarah"], ["Mary", "David"]]) == "Match found"
reference
def agents(list_found, list_records): if list_found: return "Match found" if list_found in list_records else "No matches"
Stolen police records
5a5bef7a5c770d08cd0032fa
[ "Fundamentals" ]
https://www.codewars.com/kata/5a5bef7a5c770d08cd0032fa
7 kyu
Given two integer arrays where the second array is a shuffled duplicate of the first array with one element missing, find the missing element. Please note, there may be duplicates in the arrays, so checking if a numerical value exists in one and not the other is not a valid solution. ``` find_missing([1, 2, 2, 3], [1, 2, 3]) => 2 ``` ``` find_missing([6, 1, 3, 6, 8, 2], [3, 6, 6, 1, 2]) => 8 ``` The first array will always have at least one element.
algorithms
def find_missing(arr1, arr2): return sum(arr1) - sum(arr2)
Find the missing element between two arrays
5a5915b8d39ec5aa18000030
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/5a5915b8d39ec5aa18000030
7 kyu
# Definition A **number** is called **_Automorphic number_** if and only if *its square ends in the same digits as the number itself*. ___ # Task **_Given_** a **number** *determine if it Automorphic or not* . ___ # Warm-up (Highly recommended) # [Playing With Numbers Series](https://www.codewars.com/collections/playing-with-numbers) ___ # Notes * The **_number_** passed to the function is **_positive_** ___ # Input >> Output Examples ``` autoMorphic (25) -->> return "Automorphic" ``` ## **_Explanation_**: * `25` squared is `625` , **_Ends with the same number's digits which are 25_** . ___ ``` autoMorphic (13) -->> return "Not!!" ``` ## **_Explanation_**: * `13` squared is `169` , **_Not ending with the same number's digits which are 69_** . ___ ``` autoMorphic (76) -->> return "Automorphic" ``` ## **_Explanation_**: * `76` squared is `5776` , **_Ends with the same number's digits which are 76_** . ___ ``` autoMorphic (225) -->> return "Not!!" ``` ## **_Explanation_**: * `225` squared is `50625` , **_Not ending with the same number's digits which are 225_** . ___ ``` autoMorphic (625) -->> return "Automorphic" ``` ## **_Explanation_**: * `625` squared is `390625` , **_Ends with the same number's digits which are 625_** . ___ ``` autoMorphic (1) -->> return "Automorphic" ``` ## **_Explanation_**: * `1` squared is `1` , **_Ends with the same number's digits which are 1_** . ___ ``` autoMorphic (6) -->> return "Automorphic" ``` ## **_Explanation_**: * `6` squared is `36` , **_Ends with the same number's digits which are 6_** ___ ___ # [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers) # [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays) # [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored) ___ ## ALL translations are welcomed ## Enjoy Learning !! # Zizou
reference
def automorphic(n): return "Automorphic" if str(n * n). endswith(str(n)) else "Not!!"
Automorphic Number (Special Numbers Series #6)
5a58d889880385c2f40000aa
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/5a58d889880385c2f40000aa
7 kyu
## Task Given a positive integer `n`, calculate the following sum: ``` n + n/2 + n/4 + n/8 + ... ``` All elements of the sum are the results of integer division. ## Example ``` 25 => 25 + 12 + 6 + 3 + 1 = 47 ```
algorithms
def halving_sum(n): s = 0 while n: s += n n >>= 1 return s
Halving Sum
5a58d46cfd56cb4e8600009d
[ "Algorithms" ]
https://www.codewars.com/kata/5a58d46cfd56cb4e8600009d
7 kyu
Write the following function: ```javascript function areaOfPolygonInsideCircle(circleRadius, numberOfSides) ``` ```haskell areaOfPolygonInsideCircle :: Double -> Int -> Double areaOfPolygonInsideCircle circleRadius numberOfSides = undefined ``` ```php function areaOfPolygonInsideCircle($circleRadius, $numberOfSides) ``` ```csharp public static double AreaOfPolygonInsideCircle(double circleRadius, int numberOfSides) ``` ```clojure (defn area-of-polygon-inside-circle [circle-radius number-of-sides] ``` ```python def area_of_inscribed_polygon(circle_radius, number_of_sides): ``` ```elixir def area_of_polygon_inside_circle(circle_radius, number_of_sides) do ``` ```ruby def area_of_polygon_inside_circle(circle_radius, number_of_sides) ``` ```crystal def area_of_polygon_inside_circle(circle_radius, number_of_sides) ``` ```groovy static double areaOfPolygonInsideCircle(circleRadius, numberOfSides) ``` ```cpp double areaOfPolygonInsideCircle (double circleRadius , int numberOfSides) ``` ```swift areaOfPolygonInsideCircle(_ circleRadius: Double, _ numberOfSides: Int) -> Double ``` ```objc double area_of_polygon_inside_circle(double circle_radius, int number_of_sides); ``` ```c double area_of_polygon_inside_circle(double circle_radius, int number_of_sides); ``` ```dart double areaOfPolygonInsideCircle(double circleRadius, int numberOfSides) ``` ```coffeescript areaOfPolygonInsideCircle = (circleRadius, numberOfSides) ``` ```typescript export function areaOfPolygonInsideCircle(circleRadius: number, numberOfSides: number): number ``` ```java public static double areaOfPolygonInsideCircle(double circleRadius, int numberOfSides) ``` ```coffeescript areaOfPolygonInsideCircle = (circleRadius, numberOfSides) ``` ```go func AreaOfPolygonInsideCircle(circleRadius float64, numberOfSides int) float64 ``` ```nasm area_of_polygon_inside_circle(circle_radius, number_of_sides) ``` ```rust fn area_of_polygon_inside_circle(circle_radius: f64, number_of_sides: i32) -> f64 ``` It should calculate the area of a regular polygon of `numberOfSides`, `number-of-sides`, or `number_of_sides` sides inside a circle of radius `circleRadius`, `circle-radius`, or `circle_radius` which passes through all the vertices of the polygon (such circle is called [**circumscribed circle** or **circumcircle**](https://en.wikipedia.org/wiki/Circumscribed_circle)). ```if:javascript,haskell,dart,php,cpp,groovy,csharp,elixir,clojure,objc,c,swift,ruby,crystal,coffeescript,typescript,java,go,nasm The answer should be a number rounded to 3 decimal places. ``` Input :: Output Examples ```javascript areaOfPolygonInsideCircle(3, 3) // returns 11.691 areaOfPolygonInsideCircle(5.8, 7) // returns 92.053 areaOfPolygonInsideCircle(4, 5) // returns 38.042 ``` ```haskell areaOfPolygonInsideCircle 3 3 -- returns 11.691 areaOfPolygonInsideCircle 5.8 7 -- returns 92.053 areaOfPolygonInsideCircle 4 5 -- returns 38.042 ``` ```dart areaOfPolygonInsideCircle(3.0, 3) // returns 11.691 areaOfPolygonInsideCircle(5.8, 7) // returns 92.053 areaOfPolygonInsideCircle(4.0, 5) // returns 38.042 ``` ```php areaOfPolygonInsideCircle(3, 3) // returns 11.691 areaOfPolygonInsideCircle(5.8, 7) // returns 92.053 areaOfPolygonInsideCircle(4, 5) // returns 38.042 ``` ```cpp areaOfPolygonInsideCircle (3, 3) // returns 11.691 areaOfPolygonInsideCircle (5.8, 7) // returns 92.053 areaOfPolygonInsideCircle (4, 5) // returns 38.042 ``` ```groovy areaOfPolygonInsideCircle(3, 3) // returns 11.691 areaOfPolygonInsideCircle(5.8, 7) // returns 92.053 areaOfPolygonInsideCircle(4, 5) // returns 38.042 ``` ```csharp AreaOfPolygonInsideCircle(3, 3) // returns 11.691 AreaOfPolygonInsideCircle(5.8, 7) // returns 92.053 AreaOfPolygonInsideCircle(4, 5) // returns 38.042 ``` ```python area_of_inscribed_polygon(3, 3) # returns 11.691342951089922 area_of_inscribed_polygon(5.8, 7) # returns 92.05283874578583 area_of_inscribed_polygon(4, 5) # returns 38.04226065180614 ``` ```elixir area_of_polygon_inside_circle(3, 3) # returns 11.691 area_of_polygon_inside_circle(5.8, 7) # returns 92.053 area_of_polygon_inside_circle(4, 5) # returns 38.042 ``` ```clojure (area-of-polygon-inside-circle 3 3) ; returns 11.691 (area-of-polygon-inside-circle 5.8 7) ; returns 92.053 (area-of-polygon-inside-circle 4 5) ; returns 38.042 ``` ```objc area_of_polygon_inside_circle(3, 3); // => 11.691 area_of_polygon_inside_circle(5.8, 7); // => 92.053 area_of_polygon_inside_circle(4, 5); // => 38.042 ``` ```c area_of_polygon_inside_circle(3, 3); // => 11.691 area_of_polygon_inside_circle(5.8, 7); // => 92.053 area_of_polygon_inside_circle(4, 5); // => 38.042 ``` ```swift areaOfPolygonInsideCircle(3, 3); // => 11.691 areaOfPolygonInsideCircle(5.8, 7); // => 92.053 areaOfPolygonInsideCircle(4, 5); // => 38.042 ``` ```ruby area_of_polygon_inside_circle(3, 3) # returns 11.691 area_of_polygon_inside_circle(5.8, 7) # returns 92.053 area_of_polygon_inside_circle(4, 5) # returns 38.042 ``` ```crystal area_of_polygon_inside_circle(3, 3) # returns 11.691 area_of_polygon_inside_circle(5.8, 7) # returns 92.053 area_of_polygon_inside_circle(4, 5) # returns 38.042 ``` ```coffeescript areaOfPolygonInsideCircle(3, 3) # returns 11.691 areaOfPolygonInsideCircle(5.8, 7) # returns 92.053 areaOfPolygonInsideCircle(4, 5) # returns 38.042 ``` ```typescript areaOfPolygonInsideCircle(3, 3) // returns 11.691 areaOfPolygonInsideCircle(5.8, 7) // returns 92.053 areaOfPolygonInsideCircle(4, 5) // returns 38.042 ``` ```java areaOfPolygonInsideCircle(3, 3) // returns 11.691 areaOfPolygonInsideCircle(5.8, 7) // returns 92.053 areaOfPolygonInsideCircle(4, 5) // returns 38.042 ``` ```go AreaOfPolygonInsideCircle(3, 3) // returns 11.691 AreaOfPolygonInsideCircle(5.8, 7) // returns 92.053 AreaOfPolygonInsideCircle(4, 5) // returns 38.042 ``` ```nasm area_of_polygon_inside_circle(3, 3) ; returns 11.691 area_of_polygon_inside_circle(2, 4) ; returns 8 area_of_polygon_inside_circle(2.5, 5) ; returns 14.86 ``` ```rust area_of_polygon_inside_circle(3.0, 3) // returns 11.691 area_of_polygon_inside_circle(2.0, 4) // returns 8 area_of_polygon_inside_circle(2.5, 5) // returns 14.86 ``` Note: if you need to use Pi in your code, use the native value of your language unless stated otherwise.
reference
from math import sin, pi def area_of_polygon_inside_circle(r, n): return round(0.5 * n * r * * 2 * sin(2 * pi / n), 3)
Calculate the area of a regular n sides polygon inside a circle of radius r
5a58ca28e626c55ae000018a
[ "Mathematics", "Geometry", "Fundamentals" ]
https://www.codewars.com/kata/5a58ca28e626c55ae000018a
6 kyu
Get the list of integers for Codewars Leaderboard score (aka Honor) in descending order ``` Note: if it was the bad timing, the data could be updated during your test cases. Try several times if you had such experience. ```
reference
import requests from bs4 import BeautifulSoup def get_leaderboard_honor(): soup = BeautifulSoup(requests . get( 'https://www.codewars.com/users/leaderboard'). text) return [ int(tr . find_all('td')[- 1]. text . replace(',', '')) for tr in soup . select('div.leaderboard table tr')[1:] ]
Codewars Leaderboard
5a57d101cadebf03d40000b9
[ "Fundamentals" ]
https://www.codewars.com/kata/5a57d101cadebf03d40000b9
6 kyu
# Introduction The ragbaby cipher is a substitution cipher that encodes/decodes a text using a keyed alphabet and their position in the plaintext word they are a part of. To encrypt the text `This is an example.` with the key `cipher`, first construct a keyed alphabet: ``` c i p h e r a b d f g j k l m n o q s t u v w x y z ``` Then, number the letters in the text as follows: ``` T h i s i s a n e x a m p l e . 1 2 3 4 1 2 1 2 1 2 3 4 5 6 7 ``` To obtain the encoded text, replace each character of the word with the letter in the keyed alphabet the corresponding number of places to the right of it (wrapping if necessary). Non-alphabetic characters are preserved to mark word boundaries. Our ciphertext is then `Urew pu bq rzfsbtj.` # Task Wirate functions `encode` and `decode` which accept 2 parameters: - `text` - string - a text to encode/decode - `key` - string - a key # Notes - handle lower and upper case in `text` string - `key` consists of only lowercase characters
reference
from string import ascii_lowercase as aLow import re def rotateWord(w, alpha, dct, d): lst = [] for i, c in enumerate(w . lower(), 1): transChar = alpha[(dct[c] + i * d) % 26] if w[i - 1]. isupper(): transChar = transChar . upper() lst . append(transChar) return '' . join(lst) def encode(text, key, d=1): remains, alpha = set(aLow), [] for c in key + aLow: if c in remains: remains . remove(c) alpha . append(c) alpha = '' . join(alpha) dct = {c: i for i, c in enumerate(alpha)} return re . sub(r'[a-zA-Z]+', lambda m: rotateWord(m . group(), alpha, dct, d), text) def decode(text, key): return encode(text, key, - 1)
Ragbaby cipher
5a2166f355519e161a000019
[ "Ciphers", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5a2166f355519e161a000019
6 kyu
**Story** On some island lives a chameleon population. Chameleons here can be of only one of three colors - red, green and blue. Whenever two chameleons of different colors meet, they both change their colors to the third one (i.e. when red and blue chameleons meet, they can both become green). There is no other way for chameleons to change their color (in particular, when red and blue chameleons meet, they can't become both red, only third color can be assumed). Chameleons want to become of one certain color. They may plan they meetings to reach that goal. Chameleons want to know, how fast their goal can be achieved (if it can be achieved at all). **Formal problem** *Input:* Color is coded as integer, 0 - red, 1 - green, 2 - blue. Chameleon starting population is given as an array of three integers, with index corresponding to color (i.e. [2, 5, 3] means 2 red, 5 green and 3 blue chameleons). All numbers are non-negative, their sum is between `1` and `int.MaxValue` (maximal possible value for `int` type, in other languages). Desired color is given as an integer from 0 to 2. *Output:* `Kata.Chameleon` should return *minimal* number of meetings required to change all chameleons to a given color, or -1 if it is impossible (for example, if all chameleons are initially of one other color). **Notes and hints** -- Some tests use rather big input values. Be effective. -- There is a strict proof that answer is either -1 or no greater than total number of chameleons (thus, return type `int` is justified). Don't worry about overflow. **Credits** Kata based on "Chameleons" puzzle from braingames.ru: http://www.braingames.ru/?path=comments&puzzle=226 (russian, not translated).
algorithms
def chameleon(chameleons, color): (_, a), (_, b), (_, c) = sorted((i == color, v) for i, v in enumerate(chameleons)) return - 1 if not a and not c or (b - a) % 3 else b
Chameleon unity
553ba31138239b9bc6000037
[ "Algebra", "Logic", "Algorithms" ]
https://www.codewars.com/kata/553ba31138239b9bc6000037
5 kyu
# Ascii Shift Encryption/Decryption The goal of this kata is to create a very simple ASCII encryption and decryption. The encryption algorithm should shift each character's charcode by the character's current index in the string (0-based). The input strings will never require to go outside of the ASCII range. ### Example: ``` p | a | s | s | w | o | r | d # Plaintext + 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 # Shift (add) p | b | u | v | { | t | x | k # Ciphertext ``` The decryption should reverse this: ``` p | b | u | v | { | t | x | k # Ciphertext - 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 # Shift (subtract) p | a | s | s | w | o | r | d # Plaintext ```
algorithms
def ascii_encrypt(plaintext): return '' . join(chr(ord(c) + i) for i, c in enumerate(plaintext)) def ascii_decrypt(plaintext): return '' . join(chr(ord(c) - i) for i, c in enumerate(plaintext))
ASCII Shift Encryption/Decryption
56e9ac87c3e7d512bc001363
[ "Algorithms" ]
https://www.codewars.com/kata/56e9ac87c3e7d512bc001363
7 kyu
The squarefree part of a positive integer is the largest divisor of that integer which itself has no square factors (other than 1). For example, the squareefree part of 12 is 6, since the only larger divisor is 12, and 12 has a square factor (namely, 4). Your challenge, should you choose to accept it, is to implement a `squareFreePart` function which accepts a number `n` and returns the squarefree part of `n`. In the case that `n = 1`, your function should return 1. The input will always be a strictly positive integer. Here are some examples (input ---> output: ``` 2 ---> 2 4 ---> 2 24 ---> 6 (since any larger divisor is divisible by 4, which is a square) ``` Good luck!
algorithms
def square_free_part(n): for i in range(2, int(n * * 0.5) + 1): while n % (i * * 2) == 0: n /= i return n
Squarefree Part of a Number
567cd7da4b9255b96b000022
[ "Mathematics", "Number Theory", "Algorithms" ]
https://www.codewars.com/kata/567cd7da4b9255b96b000022
5 kyu
# Definition A number is a **_Special Number_** *if it’s digits only consist 0, 1, 2, 3, 4 or 5* **_Given_** a number *determine if it special number or not* . # Warm-up (Highly recommended) # [Playing With Numbers Series](https://www.codewars.com/collections/playing-with-numbers) ___ # Notes * **_The number_** passed will be **_positive_** (N > 0) . * All **single-digit numbers** within the interval **_[1:5]_** are considered as **_special number_**. ___ # Input >> Output Examples ``` specialNumber(2) ==> return "Special!!" ``` ## Explanation: It's **_a single-digit number_** within the interval **_[1:5]_** . ``` specialNumber(9) ==> return "NOT!!" ``` ## Explanation: Although, it's a single-digit number but **_Outside the interval [1:5]_** . ``` specialNumber(23) ==> return "Special!!" ``` ## Explanation: All **_the number's digits_** formed from the interval **_[0:5]_** digits . ``` specialNumber(39) ==> return "NOT!!" ``` ## Explanation: Although, *there is a digit (3) Within the interval* **_But_** **_the second digit is not (Must be ALL The Number's Digits )_** . ``` specialNumber(59) ==> return "NOT!!" ``` ## Explanation: Although, *there is a digit (5) Within the interval* **_But_** **_the second digit is not (Must be ALL The Number's Digits )_** . ``` specialNumber(513) ==> return "Special!!" ``` ___ ``` specialNumber(709) ==> return "NOT!!" ``` ___ # [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored) ### ALL translation are welcomed ## Enjoy Learning !! # Zizou
reference
def special_number(n): return "Special!!" if max(str(n)) <= "5" else "NOT!!"
Special Number (Special Numbers Series #5)
5a55f04be6be383a50000187
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/5a55f04be6be383a50000187
7 kyu
Define a class called `Lamp`. It will have a string attribute for `color` and boolean attribute, `on`, that will refer to whether the lamp is on or not. Define your class constructor with a parameter for color and assign `on` as `false` on initialize. ```if:javascript,typescript,groovy Give the lamp an instance method called `toggleSwitch` that will switch the value of the `on` attribute. ``` ```if:python,ruby Give the lamp an instance method called `toggle_switch` that will switch the value of the `on` attribute. ``` Define another instance method called `state` that will return `"The lamp is on."` if it's on and `"The lamp is off."` otherwise.
reference
class Lamp (object): def __init__(self, color=None, on=False): self . color = color self . on = on def toggle_switch(self): self . on = not self . on def state(self): if self . on: s = 'on' else: s = 'off' return f'The lamp is { s } .'
The Lamp: Revisited
570e6e32de4dc8a8340016dd
[ "Fundamentals", "Object-oriented Programming" ]
https://www.codewars.com/kata/570e6e32de4dc8a8340016dd
6 kyu
Jurassic Word is full of wonderful prehistoric creatures...eating a lot. In this kata your task is to take in a lunchtime scene of a dinosaur and their food, and decipher exactly what ate what. Now, there isn't much mystery in what a dino might be eating. It can be one of: ```java String dead_dino = "_C C}>"; // When this case is included in your return string, use "a dead dino" instead of "dead_dino" String flowers = "iii iii"; String leaves = "||| |||"; String something = "... ..."; // for any other food you could encounter (dots being the food, in a regexp notation, all the characters in the middle being the bitemarks) ``` ```python dead_dino = "_C C}>" # When this case is included in your return string, use "a dead dino" instead of "dead_dino" flowers = "iii iii" leaves = "||| |||" something = "... ..." # for any other food you could encounter (dots being the food, in a regexp notation, all the characters in the middle being the bitemarks) ``` ```javascript String dead_dino = "_C C}>"; // When this case is included in your return string, use "a dead dino" instead of "dead_dino" String flowers = "iii iii"; String leaves = "||| |||"; Sting something = "... ..."; // for any other food you could encounter (dots being the food, in a regexp notation, all the characters in the middle being the bitemarks) ``` These empty spaces in the middle of each food are reserved for the bitemarks made by a dinosaur, which will always be 5 characters long. Unfortunately, you don't get to see the action. You have to look at the bite marks made on the leftovers, and make your judgement that way. There are four kinds of dinosaurs in the park that you know of: ```java static String T_Rex = "VvvvV"; // When this case is included in your return string, // use "T-Rex" instead of "T_Rex" static String brachiosaurus = "uuuuu"; static String velociraptor = "vvvvv"; static String triceratops = "uuVuu"; ``` ```python t_rex = "VvvvV"; # When this case is included in your return string, # use "T-Rex" instead of "T_Rex" brachiosaurus = "uuuuu" velociraptor = "vvvvv" triceratops = "uuVuu" ``` ```javascript t_rex = "VvvvV"; // When this case is included in your return string, // use "T-Rex" instead of "T_Rex" brachiosaurus = "uuuuu"; velociraptor = "vvvvv"; triceratops = "uuVuu"; ``` Although a dinosaur will be eating one of the three available foods, some dinosaurs will only eat certain items. For example, both the brachiosaurus and the triceratops are vegetarians and would love to eat flowers, but only the brachiosaurus would be able to reach the leaves. On the other hand, the T-Rex and the velociraptor would only want to eat dead dinos. Thus, if you see their bitemarks on a food that you know they wouldn't be eating, you must be mistaken and something else is feeding...(DUN DUN DUN). This is also true for bitemarks you have never seen before! Here are a few examples of how your program should work: ```java lunchTime("_CVvvvVC}>") // => "A T-Rex is eating a dead dino." lunchTime("_CvvvvvC}>") // => "A velociraptor is eating a dead dino." lunchTime("iiiuuVuuiii") // => "A triceratops is eating flowers." lunchTime("|||uuVuu|||") // => "Something is eating leaves." lunchTime("_CVvVvVC}>") // => "Something is eating a dead dino." ``` ```python lunch_time("_CVvvvVC}>") # => "A T-Rex is eating a dead dino." lunch_time("_CvvvvvC}>") # => "A velociraptor is eating a dead dino." lunch_time("iiiuuVuuiii") # => "A triceratops is eating flowers." lunch_time("|||uuVuu|||") # => "Something is eating leaves." lunch_time("_CVvVvVC}>") # => "Something is eating a dead dino." ``` ```javascript lunchTime("_CVvvvVC}>") // => "A T-Rex is eating a dead dino." lunchTime("_CvvvvvC}>") // => "A velociraptor is eating a dead dino." lunchTime("iiiuuVuuiii") // => "A triceratops is eating flowers." lunchTime("|||uuVuu|||") // => "Something is eating leaves." lunchTime("_CVvVvVC}>") // => "Something is eating a dead dino." ``` NOTE: All of these strings for bitemarks and food are given to you.
algorithms
class JurassicWord (object): TREX, VELO, BRAK, TRIS = "A T-Rex", "A velociraptor", "A brachiosaurus", "A triceratops" MEAT, FLOW, LEAF = "a dead dino", "flowers", "leaves" DEF = "Something" DEF_ = DEF . lower() EATEN = [((MEAT, 2, 3), "_C", "C}>"), ((FLOW, 3, 3), "iii", "iii"), ((LEAF, 3, 3), "|||", "|||")] EATER = [(TREX, "VvvvV", (MEAT,)), (VELO, "vvvvv", (MEAT,)), (BRAK, "uuuuu", (FLOW, LEAF)), (TRIS, "uuVuu", (FLOW,))] def lunch_time(self, scene): what, i, j = next((res for res, s, e in self . EATEN if scene . startswith( s) and scene . endswith(e)), (self . DEF_, 3, 3)) eater = next((res for res, s, reg in self . EATER if scene[i: - j] == s and ( what == self . DEF_ or what in reg)), self . DEF) return "{} is eating {}." . format(eater, what)
Jurassic Word
55709dc15ebd283cc9000007
[ "Algorithms" ]
https://www.codewars.com/kata/55709dc15ebd283cc9000007
6 kyu
Simple enough this one - you will be given an array. The values in the array will either be numbers or strings, or a mix of both. You will not get an empty array, nor a sparse one. Your job is to return a single array that has first the numbers sorted in ascending order, followed by the strings sorted in alphabetic order. The values must maintain their original type. Note that numbers written as strings are strings and must be sorted with the other strings.
reference
def db_sort(arr): return sorted(arr, key=lambda x: (isinstance(x, str), x))
Double Sort
57cc79ec484cf991c900018d
[ "Fundamentals", "Strings", "Arrays", "Sorting" ]
https://www.codewars.com/kata/57cc79ec484cf991c900018d
7 kyu
Mash 2 arrays together so that the returning array has alternating elements of the 2 arrays . Both arrays will always be the same length. eg. [1,2,3] + ['a','b','c'] = [1, 'a', 2, 'b', 3, 'c']
reference
def array_mash(xs, ys): return [z for p in zip(xs, ys) for z in p]
Array Mash
582642b1083e12521f0000da
[ "Arrays", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/582642b1083e12521f0000da
7 kyu
<b>Background</b><br> There is a message that is circulating via public media that claims a reader can easily read a message where the inner letters of each words is scrambled, as long as the first and last letters remain the same and the word contains all the letters. Another example shows that it is quite difficult to read the text where all the letters are reversed rather than scrambled. In this kata we will make a generator that generates text in a similar pattern, but instead of scrambled or reversed, ours will be sorted alphabetically <b>Requirement</b><br> return a string where:<br> 1) the first and last characters remain in original place for each word<br> 2) characters between the first and last characters must be sorted alphabetically<br> 3) punctuation should remain at the same place as it started, for example: shan't -> sahn't<br> <b>Assumptions</b><br> 1) words are seperated by single spaces<br> 2) only spaces separate words, special characters do not, for example: tik-tak -> tai-ktk<br> 3) special characters do not take the position of the non special characters, for example: -dcba -> -dbca<br> 4) for this kata puctuation is limited to 4 characters: hyphen(-), apostrophe('), comma(,) and period(.) <br> 5) ignore capitalisation<br> for reference: http://en.wikipedia.org/wiki/Typoglycemia
reference
import re def scramble_words(words): def sort_letters(match): s = match . group() letters = iter(sorted(filter(str . isalpha, s[1: - 1]))) return s[0] + "" . join(next(letters) if c . isalpha() else c for c in s[1: - 1]) + s[- 1] return re . sub(r'[a-z][^\s]*[a-z]', sort_letters, words)
Typoglycemia Generator
55953e906851cf2441000032
[ "Fundamentals" ]
https://www.codewars.com/kata/55953e906851cf2441000032
5 kyu
Create a class Vector that has simple (3D) vector operators. In your class, you should support the following operations, given Vector ```a``` and Vector ```b```: ```ruby a + b # returns a new Vector that is the resultant of adding them a - b # same, but with subtraction a == b # returns true if they have the same magnitude and direction a.cross(b) # returns a new Vector that is the cross product of a and b a.dot(b) # returns a number that is the dot product of a and b a.to_a # returns an array representation of the vector. a.to_s # returns a string representation of the vector in the form "<a, b, c>" a.magnitude # returns a number that is the magnitude (geometric length) of vector a. a.x # gets x component a.y # gets y component a.z # gets z component Vector.new([a,b,c]) # creates a new Vector from the supplied 3D array. Vector.new(a,b,c) # same as above ``` ```python a + b # returns a new Vector that is the resultant of adding them a - b # same, but with subtraction a == b # returns true if they have the same magnitude and direction a.cross(b) # returns a new Vector that is the cross product of a and b a.dot(b) # returns a number that is the dot product of a and b a.to_tuple() # returns a tuple representation of the vector. str(a) # returns a string representation of the vector in the form "<a, b, c>" a.magnitude # returns a number that is the magnitude (geometric length) of vector a. a.x # gets x component a.y # gets y component a.z # gets z component Vector([a,b,c]) # creates a new Vector from the supplied 3D array. Vector(a,b,c) # same as above ``` The test cases will not mutate the produced Vector objects, so don't worry about that.
reference
import math class VectorInputCoordsValidationError (Exception): """Custom exception class for invalid input args given to the Vector instantiation""" class Vector: # https://www.mathsisfun.com/algebra/vectors.html def __init__(self, * args): try: self . x, self . y, self . z = args if len(args) == 3 else args[0] except ValueError: raise VectorInputCoordsValidationError( 'Either give single iterable of 3 coords or pass them as *args') def __add__(self, other) - > "Vector": return Vector( self . x + other . x, self . y + other . y, self . z + other . z ) def __sub__(self, other) - > "Vector": return Vector( self . x - other . x, self . y - other . y, self . z - other . z ) def __eq__(self, other) - > bool: # https://www.grc.nasa.gov/www/k-12/airplane/vectcomp.html # https://onlinemschool.com/math/library/vector/equality/ return all(( self . x == other . x, self . y == other . y, self . z == other . z )) def cross(self, other) - > "Vector": # https://www.mathsisfun.com/algebra/vectors-cross-product.html return Vector( self . y * other . z - self . z * other . y, self . z * other . x - self . x * other . z, self . x * other . y - self . y * other . x ) def dot(self, other) - > int: # https://www.mathsisfun.com/algebra/vectors-dot-product.html return self . x * other . x + self . y * other . y + self . z * other . z def to_tuple(self) - > tuple: return self . x, self . y, self . z def __str__(self) - > str: return "<{x}, {y}, {z}>" . format(* * self . __dict__) @ property def magnitude(self) - > float: return math . sqrt( sum( ( self . x * * 2, self . y * * 2, self . z * * 2 ) ) )
Vector Class
532a69ee484b0e27120000b6
[ "Fundamentals", "Object-oriented Programming" ]
https://www.codewars.com/kata/532a69ee484b0e27120000b6
5 kyu
## Problem Determine whether a positive integer number is **colorful** or not. `263` is a colorful number because `[2, 6, 3, 2*6, 6*3, 2*6*3]` are all different; whereas `236` is not colorful, because `[2, 3, 6, 2*3, 3*6, 2*3*6]` have `6` twice. So take all consecutive subsets of digits, take their product and ensure all the products are different. ## Examples ```ruby 263 --> true 236 --> false ``` ```pyhton 263 --> true 236 --> false ```
algorithms
def colorful(number): base_result = [] for x in str(number): base_result . append(int(x)) for y in range(len(base_result) - 1): temp = base_result[y] * base_result[y + 1] base_result . append(temp) # Should you really eval the last value ? :shrug: If so, would use eval return len(set(base_result)) == len(base_result)
Colorful Number
5441310626bc6a1e61000f2c
[ "Algorithms" ]
https://www.codewars.com/kata/5441310626bc6a1e61000f2c
6 kyu
``` ************************* * Create a frame! * * __ __ * * / \~~~/ \ * * ,----( .. ) * * / \__ __/ * * /| (\ |( * * ^ \ /___\ /\ | * * |__| |__|-.. * ************************* ``` Given an array of strings and a character to be used as border, output the frame with the content inside. Notes: * Always keep a space between the input string and the left and right borders. * The biggest string inside the array should always fit in the frame. * The input array is never empty. ## Example `frame(['Create', 'a', 'frame'], '+')` Output: ``` ++++++++++ + Create + + a + + frame + ++++++++++ ```
reference
def frame(text, char): n = len(max(text, key=len)) + 4 return "\n" . join([char * n] + ["%s %s %s" % (char, line . ljust(n - 4), char) for line in text] + [char * n])
Create a frame!
5672f4e3404d0609ec00000a
[ "Strings", "Arrays", "ASCII Art", "Fundamentals" ]
https://www.codewars.com/kata/5672f4e3404d0609ec00000a
6 kyu
You've been given a list that states the daily revenue for each day of the week. Unfortunately, the list has been corrupted and contains extraneous characters. Rather than fix the source of the problem, your boss has asked you to create a program that removes any unneccessary characters and return the corrected list. The expected characters are digits, ' $ ', and ' . ' All items in the returned list are expected to be strings. For example: ```python a1 = ['$5.$6.6x.s4', '{$33ae.5(9', '$29..4e9', '%.$9|4d20', 'A$AA$4r R4.94'] remove_char(a1) >>> ['$56.64', '$33.59', '$29.49', '$94.20', '$44.94'] ```
reference
import re def fix(value): digits = re . sub('\D', '', value) return '$' + digits[: - 2] + '.' + digits[- 2:] def remove_char(values): return [fix(v) for v in values]
Remove Unnecessary Characters from Items in List
586d12f0aa042830910001d1
[ "Fundamentals", "Regular Expressions", "Lists", "Strings" ]
https://www.codewars.com/kata/586d12f0aa042830910001d1
7 kyu
Find all files in the current directory where you run your code, then make a dictionary in the following manner. ``` { filename : first line of the file , ...} ```
reference
import os def first_line(path): with open(path) as f: return f . readline() def create_file_dict(): return {k: first_line(k) for k in next(os . walk('.'))[2]}
Find the files then read them
5a552ef7e6be3855270000bd
[ "Fundamentals" ]
https://www.codewars.com/kata/5a552ef7e6be3855270000bd
6 kyu
# Definition **_Jumping number_** is the number that *All adjacent digits in it differ by 1*. ____ # Task **_Given_** a number, **_Find if it is Jumping or not_** . ____ # Warm-up (Highly recommended) # [Playing With Numbers Series](https://www.codewars.com/collections/playing-with-numbers) ___ # Notes * **_Number_** *passed is always* **_Positive_** . * **_Return_** *the result as* **_String_** . * **_The difference between_** *‘9’ and ‘0’* is **_not considered as 1_** . * **_All single digit numbers_** are considered as **_Jumping numbers_**. ___ # Input >> Output Examples ``` jumpingNumber(9) ==> return "Jumping!!" ``` ## **_Explanation_**: * It's **_single-digit number_** ___ ``` jumpingNumber(79) ==> return "Not!!" ``` ## **_Explanation_**: * *Adjacent digits* **_don't differ by 1_** ___ ``` jumpingNumber(23) ==> return "Jumping!!" ``` ## **_Explanation_**: * *Adjacent digits* **_differ by 1_** ___ ``` jumpingNumber(556847) ==> return "Not!!" ``` ## **_Explanation_**: * *Adjacent digits* **_don't differ by 1_** ___ ``` jumpingNumber(4343456) ==> return "Jumping!!" ``` ## **_Explanation_**: * *Adjacent digits* **_differ by 1_** ___ ``` jumpingNumber(89098) ==> return "Not!!" ``` ## **_Explanation_**: * *Adjacent digits* **_don't differ by 1_** ___ ``` jumpingNumber(32) ==> return "Jumping!!" ``` ## **_Explanation_**: * *Adjacent digits* **_differ by 1_** ___ ___ ___ # [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers) # [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays) # [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored) ___ ## ALL translations are welcomed ## Enjoy Learning !! # Zizou
reference
def jumping_number(number): arr = list(map(int, str(number))) return ('Not!!', 'Jumping!!')[all(map(lambda a, b: abs(a - b) == 1, arr, arr[1:]))]
Jumping Number (Special Numbers Series #4)
5a54e796b3bfa8932c0000ed
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/5a54e796b3bfa8932c0000ed
7 kyu
Your friend has invited you to a party, and tells you to meet them in the line to get in. The one problem is it's a masked party. Everyone in line is wearing a colored mask, including your friend. Find which people in line could be your friend. Your friend has told you that he will be wearing a `RED` mask, and has **TWO** other friends with him, both wearing `BLUE` masks. Input to the function will be an array of strings, each representing a colored mask. For example: ```javascript var line = ['blue','blue','red','red','blue','green']; ``` ```python line = ['blue','blue','red','red','blue','green'] ``` The output of the function should be the number of people who could possibly be your friend. ```javascript friendFind(['blue','blue','red','red','blue','green','chipmunk']) // return 1 ``` ```python friend_find(['blue','blue','red','red','blue','green','chipmunk']) # return 1 ```
algorithms
def redWith2Blues(i, line): return any(line[i - 2 + x: i + 1 + x]. count('blue') == 2 for x in range(3)) def friend_find(line): return sum(p == 'red' and redWith2Blues(i, line) for i, p in enumerate(line))
Masquerade Waiting Line
5357edc90d9c5df39a0013bc
[ "Algorithms", "Arrays", "Puzzles" ]
https://www.codewars.com/kata/5357edc90d9c5df39a0013bc
6 kyu
You are back at your newly acquired decrypting job for the secret organization when a new assignment comes in. Apparently the enemy has been communicating using a device they call "The Mirror". It is a rudimentary device with encrypts the message by switching its letter with its mirror opposite (A => Z), (B => Y), (C => X) etc. Your job is to build a method called "mirror" which will decrypt the messages. Resulting messages will be in lowercase. To add more secrecy, you are to accept a second optional parameter, telling you which letters or characters are to be reversed; if it is not given, consider the whole alphabet as a default. To make it a bit more clear: e.g. in case of "abcdefgh" as the second optional parameter, you replace "a" with "h", "b" with "g" etc. . For example: ```javascript mirror("Welcome home"), "dvoxlnv slnv" //whole alphabet mirrored here mirror("hello", "abcdefgh"), "adllo" //notice only "h" and "e" get reversed ``` ```ruby mirror("Welcome home"), "dvoxlnv slnv" #whole alphabet mirrored here mirror("hello", "abcdefgh"), "adllo" #notice only "h" and "e" get reversed ``` ```python mirror("Welcome home"), "dvoxlnv slnv" #whole alphabet mirrored here mirror("hello", "abcdefgh"), "adllo" #notice only "h" and "e" get reversed ```
algorithms
def mirror(code, chars="abcdefghijklmnopqrstuvwxyz"): return code . lower(). translate(str . maketrans(chars, chars[:: - 1]))
Mirroring cipher
571af500196bb01cc70014fa
[ "Strings", "Cryptography", "Security", "Algorithms" ]
https://www.codewars.com/kata/571af500196bb01cc70014fa
7 kyu
The magic sum of 3s is calculated on an array by summing up odd numbers which include the digit `3`. Write a function `magic_sum` which accepts an array of integers and returns the sum. *Example:* `[3, 12, 5, 8, 30, 13]` results in `16` (`3` + `13`) If the sum cannot be calculated, `0` should be returned.
reference
def magic_sum(arr): return arr and sum(x for x in arr if x % 2 and '3' in str(x)) or 0
Magic Sum of 3s
57193a349906afdf67000f50
[ "Fundamentals" ]
https://www.codewars.com/kata/57193a349906afdf67000f50
7 kyu
An ATM has banknotes of nominal values 10, 20, 50, 100, 200 and 500 dollars. You can consider that there is a large enough supply of each of these banknotes. You have to write the ATM's function that determines the minimal number of banknotes needed to honor a withdrawal of `n` dollars, with `1 <= n <= 1500`. Return that number, or `-1` if it is impossible. Good Luck!!!
algorithms
def solve(n): if n % 10: return - 1 c, billet = 0, iter((500, 200, 100, 50, 20, 10)) while n: x, r = divmod(n, next(billet)) c, n = c + x, r return c
ATM
5635e7cb49adc7b54500001c
[ "Fundamentals", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5635e7cb49adc7b54500001c
7 kyu
**An [isogram](https://en.wikipedia.org/wiki/Isogram)** (also known as a "nonpattern word") is a logological term for a word or phrase without a repeating letter. It is also used by some to mean a word or phrase in which each letter appears the same number of times, not necessarily just once. You task is to write a method `isogram?` that takes a string argument and returns true if the string has the properties of being an isogram and false otherwise. Anything that is not a string is not an isogram (ints, nils, etc.) **Properties:** - must be a string - cannot be nil or empty - each letter appears the same number of times (not necessarily just once) - letter case is not important (= case insensitive) - non-letter characters (e.g. hyphens) should be ignored
algorithms
from collections import Counter import re def is_isogram(word): if type(word) is not str or not word: return False return len(set(Counter(re . sub(r'[^a-z]', "", word . lower())). values())) == 1
Is it an isogram?
586d79182e8d9cfaba0000f1
[ "Algorithms", "Strings" ]
https://www.codewars.com/kata/586d79182e8d9cfaba0000f1
6 kyu
It might be déjà vu, or it might be a duplicate day. You’re well trained in the arts of cleaning up duplicates. Someone has hacked your database and injected all kinds of duplicate records into your tables. You don’t have access to modify the data in the tables or restore the tables to a previous time because the DBA’s are gone. You are provided with an array of employees from the server. Your task is to write the findDuplicates function to remove the duplicate records after they are sent down to the client. Employee Class: ```javascript var Employee = function() { this.FirstName = ''; this.LastName = ''; this.UserName = ''; }; ``` ```python class Employee: def __init__(self,f_name,l_name,u_name): self.first_name = f_name self.last_name = l_name self.user_name = u_name ``` ```ruby class Employee attr_reader :first_name attr_reader :last_name attr_reader :user_name def initialize(f_name,l_name,u_name) @first_name = f_name @last_name = l_name @user_name = u_name end end ``` The result of calling the findDuplicates function should be an array of the Employee objects that are the duplicates. findDuplicates should also perform an in place modification of the array it's given (`employees`), removing the duplicate values. Assumptions: 1. You can assume that the `employees` parameter passed in to findDuplicates is always an array. 2. You can also assume that the `employees` array is a flat array.
algorithms
def find_duplicates(emp): dups, out, uniq = [], [], set() for e in emp: if e in uniq: dups . append(e) else: out . append(e) uniq . add(e) emp . clear() emp . extend(out) return dups
Déjà vu Duplicates
547f601b4a437a2048000981
[ "Algorithms" ]
https://www.codewars.com/kata/547f601b4a437a2048000981
6 kyu
Gematria is an Assyro-Babylonian-Greek system of code and numerology later adopted into Jewish culture. The system assigns numerical value to a word or a phrase in the belief that words or phrases with identical numerical values bear some relation to each other or bear some relation to the number itself. While more commonly used on Hebrew words, there is also an English version. Each letter has a value and the gematrian value of a word or a phrase is the sum of those values. The code takes a word or an expression and returns the gematrian value of it. The calculation is case insensitive and counts no spaces. Example: The gematrian value of "love" is 20+50+700+5 = 775 ‎These are the values of the different letters: a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8, i=9, k=10, l=20, m=30, n=40, o=50, p=60, q=70, r=80, s=90, t=100, u=200, x=300, y=400, z=500, j=600, v=700, w=900
reference
TOME = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'k': 10, 'l': 20, 'm': 30, 'n': 40, 'o': 50, 'p': 60, 'q': 70, 'r': 80, 's': 90, 't': 100, 'u': 200, 'x': 300, 'y': 400, 'z': 500, 'j': 600, 'v': 700, 'w': 900} def gematria(s): return sum(TOME . get(c, 0) for c in s . lower())
Gematria for all
573c91c5eaffa3bd350000b0
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/573c91c5eaffa3bd350000b0
7 kyu
# Union of closed disjoint intervals Write a function `interval_insert` which takes as input - a list `myl` of disjoint closed intervals with integer endpoints, sorted by increasing order of left endpoints - an interval `interval` and returns the union of `interval` with the intervals in `myl`, as an array of disjoint closed intervals. ___ ## Terminology A `closed` interval includes its endpoints. For example `[0,5]` means greater than or equal to `0` and less than or equal to `5`. For more, refer to [Wikipedia](http://bit.ly/disjointInterval). Two intervals are said to be `disjoint` if they have no element in common. Equivalently, disjoint intervals are intervals whose intersection is the empty interval. For example, `[1,3]` and `[4,6]` are disjoint `[1,3]` and `[3,5]` are not. ___ ## Examples: ```c [(1, 2)], (3, 4) -> [(1, 2), (3, 4)] [(3, 4)], (1, 2) -> [(1, 2), (3, 4)] [(1, 2), (4, 6)], (1, 4) -> [(1, 6)] [(0, 2), (3, 6), (7, 7), (9, 12)], (1, 8) -> [(0, 8), (9, 12)] ```
reference
from itertools import chain import bisect def merge_intervals(intervals): intervals = iter(intervals) merged = [next(intervals)] for ins in intervals: l, r = merged[- 1] if ins[0] <= r: merged[- 1] = (l, max(r, ins[1])) else: merged . append(ins) return merged def interval_insert(intervals, ins): intervals = list(intervals) bisect . insort(intervals, ins) return merge_intervals(intervals)
Union of Intervals
5495bfa82eced2146100002f
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5495bfa82eced2146100002f
6 kyu
[XKCD 1609]( http://xkcd.com/1609/) provides us with the following fun fact: ![If anyone tries this on you, the best reply is a deadpan "Oh yeah, that's a common potato chip flavor in Canada."](http://imgs.xkcd.com/comics/food_combinations.png) ### Task: Given an array containing a list of good foods, return a string containing the assertion that any two of the individually good foods are really good when combined. eg: `"You know what's actually really good? Pancakes and relish."` ### Examples: ```ruby Good_foods = ["Ice cream", "Ham", "Relish", "Pancakes", "Ketchup", "Cheese", "Eggs", "Cupcakes", "Sour cream", "Hot chocolate", "Avocado", "Skittles"] actually_really_good( Good_foods ) # "You know what's actually really good? Pancakes and relish." actually_really_good( ['Peanut butter'] ) # "You know what's actually really good? Peanut butter and more peanut butter." actually_really_good( [] ) # "You know what's actually really good? Nothing!" ``` ```javascript Good_foods = ["Ice cream", "Ham", "Relish", "Pancakes", "Ketchup", "Cheese", "Eggs", "Cupcakes", "Sour cream", "Hot chocolate", "Avocado", "Skittles"] actuallyReallyGood( Good_foods ) # "You know what's actually really good? Pancakes and relish." actuallyReallyGood( ['Peanut butter'] ) # "You know what's actually really good? Peanut butter and more peanut butter." actuallyReallyGood( [] ) # "You know what's actually really good? Nothing!" ``` ```python Good_foods = ["Ice cream", "Ham", "Relish", "Pancakes", "Ketchup", "Cheese", "Eggs", "Cupcakes", "Sour cream", "Hot chocolate", "Avocado", "Skittles"] actually_really_good( Good_foods ) # "You know what's actually really good? Pancakes and relish." actually_really_good( ['Peanut butter'] ) # "You know what's actually really good? Peanut butter and more peanut butter." actually_really_good( [] ) # "You know what's actually really good? Nothing!" ``` ### Notes: There are many different valid combinations of 2 foods it doesn't matter which one you choose. But there should be 2 different foods listed **unless** there was only one food given in the input array. Capitalization should be correct, the first given food should be capitalized, but the second should not. The input array should not be modified by the method. The test cases for this kata are fairly complicated, see if you can trick them. (Then let me know about it in the discourse.) The original kata language is *Ruby* ### Bonus: If you thought this kata was easy, try this one: [Testing 'Food combinations'](http://www.codewars.com/kata/testing-food-combinations) in which you get to write a method similar to the one the tests here use to check that a result is valid and returns any errors it has.
reference
from random import sample def actually_really_good(foods): question = "You know what's actually really good? " len_foods = len(foods) if len_foods == 0: return question + "Nothing!" elif len_foods == 1: food = foods[0] return question + f" { food . capitalize ()} and more { food . lower ()} ." else: [food1, food2] = sample(foods, 2) return question + f" { food1 . capitalize ()} and { food2 . lower ()} ."
Food combinations
565f448e6e0190b0a40000cc
[ "Arrays", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/565f448e6e0190b0a40000cc
7 kyu
Given an array of arguments, representing system call arguments keys and values, join it into a single, space-delimited string. You don't need to care about the application name -- your task is only about parameters. Each element of the given array can be: * a single string, * a single string array, * an array of two strings In the last case (array of two strings) the first string should have a `"--"` prefix if it is more than one character long; or a `"-"` prefix otherwise; e.g.: * `["foo", "bar"]` becomes `"--foo bar"` * `["f", "bar"]` becomes `"-f bar"` You may assume that all strings are non-empty and have no spaces. ## Examples ```ruby ["foo", "bar"] # "foo bar" [["foo", "bar"]] # "--foo bar" [["f", "bar"]] # "-f bar" [["foo", "bar"], "baz"] # "--foo bar baz" [["foo"], ["bar", "baz"], "qux"] # "foo --bar baz qux" ``` ```python ["foo", "bar"] # "foo bar" [["foo", "bar"]] # "--foo bar" [["f", "bar"]] # "-f bar" [["foo", "bar"], "baz"] # "--foo bar baz" [["foo"], ["bar", "baz"], "qux"] # "foo --bar baz qux" ```
reference
def args_to_string(args): L = [] for arg in args: if isinstance(arg, str): L . append(arg) elif len(arg) == 1: L . append(arg[0]) elif len(arg[0]) == 1: L . append('-' + ' ' . join(arg)) else: L . append('--' + ' ' . join(arg)) return ' ' . join(L)
Command line parameters
53689951c8a5ca91ac000566
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/53689951c8a5ca91ac000566
6 kyu
An anagram is a word, a phrase, or a sentence formed from another by rearranging its letters. An example of this is "angel", which is an anagram of "glean". Write a function that receives an array of words, and returns the total number of distinct pairs of anagramic words inside it. Some examples: - There are 2 anagrams in the array `["dell", "ledl", "abc", "cba"]` - There are 7 anagrams in the array `["dell", "ledl", "abc", "cba", "bca", "bac"]`
algorithms
from collections import Counter def anagram_counter(words): return sum(n * (n - 1) / / 2 for n in Counter('' . join(sorted(x)) for x in words). values())
Number of anagrams in an array of words
587e18b97a25e865530000d8
[ "Algorithms" ]
https://www.codewars.com/kata/587e18b97a25e865530000d8
6 kyu
### Definition **_Disarium number_** is the number that *The sum of its digits powered with their respective positions is equal to the number itself*. ____ ### Task **_Given_** a number, **_Find if it is Disarium or not_** . ____ ### Warm-up (Highly recommended) ### [Playing With Numbers Series](https://www.codewars.com/collections/playing-with-numbers) ___ ### Notes * **_Number_** *passed is always* **_Positive_** . * **_Return_** *the result as* **_String_** ___ ### Input >> Output Examples ``` disariumNumber(89) ==> return "Disarium !!" ``` #### **_Explanation_**: * Since , **_8<sup>1</sup> + 9<sup>2</sup> = 89_** , thus *output* is `"Disarium !!"` ___ ``` disariumNumber(564) ==> return "Not !!" ``` #### **_Explanation_**: Since , **_5<sup>1</sup> + 6<sup>2</sup> + 4<sup>3</sup> = 105 != 564_** , thus *output* is `"Not !!"` ___ ___ ___ ### [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers) ### [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays) ### [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored) ___ ### ALL translations are welcomed ### Enjoy Learning !! ### Zizou
reference
def disarium_number(n): return "Disarium !!" if n == sum(int(d) * * i for i, d in enumerate(str(n), 1)) else "Not !!"
Disarium Number (Special Numbers Series #3)
5a53a17bfd56cb9c14000003
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/5a53a17bfd56cb9c14000003
7 kyu
### **[Mahjong Series](/collections/mahjong)** **Mahjong** is based on draw-and-discard card games that were popular in 18th and 19th century China and some are still popular today. In each deck, there are three different suits numbered `1` to `9`, which are called **Simple tiles**. To simplify the problem, we talk about only one suit of *simple tiles* in this kata (and that's what the term **Pure Hand** means). Note that there are **EXACTLY** 4 identical copies of each kind of tiles in a deck. In each of Mahjong games, each of the 4 players around the table has 13 tiles. They take turns drawing a tile from the tile walls and then discarding one of the tiles from their hands. One wins the game if that player holds a combination of tiles as defined below: A regular winning hand consists of 4 *Melds* and 1 *Pair*. Each *meld* of tiles can be 3 identical or consecutive tiles of a suit, *e.g.* `222` or `456`. <table style="width: 400px"><tr><td> ![t2](https://upload.wikimedia.org/wikipedia/commons/6/61/MJt2.png) ![t2](https://upload.wikimedia.org/wikipedia/commons/6/61/MJt2.png) ![t2](https://upload.wikimedia.org/wikipedia/commons/6/61/MJt2.png) </td><td> ![t4](https://upload.wikimedia.org/wikipedia/commons/7/72/MJt4.png) ![t5](https://upload.wikimedia.org/wikipedia/commons/5/5c/MJt5.png) ![t6](https://upload.wikimedia.org/wikipedia/commons/7/72/MJt6.png) </td></table> Now let's consider a hand of `1113335557779`. <table style="width: 700px"><tr><td> ![t1](https://upload.wikimedia.org/wikipedia/commons/4/4a/MJt1.png)![t1](https://upload.wikimedia.org/wikipedia/commons/4/4a/MJt1.png)![t1](https://upload.wikimedia.org/wikipedia/commons/4/4a/MJt1.png)![t3](https://upload.wikimedia.org/wikipedia/commons/a/a4/MJt3.png)![t3](https://upload.wikimedia.org/wikipedia/commons/a/a4/MJt3.png)![t3](https://upload.wikimedia.org/wikipedia/commons/a/a4/MJt3.png)![t5](https://upload.wikimedia.org/wikipedia/commons/5/5c/MJt5.png)![t5](https://upload.wikimedia.org/wikipedia/commons/5/5c/MJt5.png)![t5](https://upload.wikimedia.org/wikipedia/commons/5/5c/MJt5.png)![t7](https://upload.wikimedia.org/wikipedia/commons/6/6f/MJt7.png)![t7](https://upload.wikimedia.org/wikipedia/commons/6/6f/MJt7.png)![t7](https://upload.wikimedia.org/wikipedia/commons/6/6f/MJt7.png)![t9](https://upload.wikimedia.org/wikipedia/commons/a/a1/MJt9.png) </td></tr></table> In this hand, there are already 4 *melds* (each of 3 identical tiles), leaving a `9` alone. So we need another `9` to form a *pair*. <table style="width: 700px"> <tr><td> ![t1](https://upload.wikimedia.org/wikipedia/commons/4/4a/MJt1.png)![t1](https://upload.wikimedia.org/wikipedia/commons/4/4a/MJt1.png)![t1](https://upload.wikimedia.org/wikipedia/commons/4/4a/MJt1.png) </td><td> ![t3](https://upload.wikimedia.org/wikipedia/commons/a/a4/MJt3.png)![t3](https://upload.wikimedia.org/wikipedia/commons/a/a4/MJt3.png)![t3](https://upload.wikimedia.org/wikipedia/commons/a/a4/MJt3.png) </td><td> ![t5](https://upload.wikimedia.org/wikipedia/commons/5/5c/MJt5.png)![t5](https://upload.wikimedia.org/wikipedia/commons/5/5c/MJt5.png)![t5](https://upload.wikimedia.org/wikipedia/commons/5/5c/MJt5.png) </td><td> ![t7](https://upload.wikimedia.org/wikipedia/commons/6/6f/MJt7.png)![t7](https://upload.wikimedia.org/wikipedia/commons/6/6f/MJt7.png)![t7](https://upload.wikimedia.org/wikipedia/commons/6/6f/MJt7.png) </td><td> ![t9](https://upload.wikimedia.org/wikipedia/commons/a/a1/MJt9.png)![t9](https://upload.wikimedia.org/wikipedia/commons/a/a1/MJt9.png) </td></tr></table> Additionally, there is another option. Regardless of the 3 *melds* ahead (`111`, `333`, `555`), drawing an `8` produces `77789`, which gives a *pair* of `7`'s and a *meld* (`789`). Therefore, the required tiles to win with `1113335557779` are `8` and `9`. <table style="width: 700px"> <tr><td> ![t1](https://upload.wikimedia.org/wikipedia/commons/4/4a/MJt1.png)![t1](https://upload.wikimedia.org/wikipedia/commons/4/4a/MJt1.png)![t1](https://upload.wikimedia.org/wikipedia/commons/4/4a/MJt1.png) </td><td> ![t3](https://upload.wikimedia.org/wikipedia/commons/a/a4/MJt3.png)![t3](https://upload.wikimedia.org/wikipedia/commons/a/a4/MJt3.png)![t3](https://upload.wikimedia.org/wikipedia/commons/a/a4/MJt3.png) </td><td> ![t5](https://upload.wikimedia.org/wikipedia/commons/5/5c/MJt5.png)![t5](https://upload.wikimedia.org/wikipedia/commons/5/5c/MJt5.png)![t5](https://upload.wikimedia.org/wikipedia/commons/5/5c/MJt5.png) </td><td> ![t7](https://upload.wikimedia.org/wikipedia/commons/6/6f/MJt7.png)![t7](https://upload.wikimedia.org/wikipedia/commons/6/6f/MJt7.png) </td><td> ![t7](https://upload.wikimedia.org/wikipedia/commons/6/6f/MJt7.png)![t8](https://upload.wikimedia.org/wikipedia/commons/1/18/MJt8.png)![t9](https://upload.wikimedia.org/wikipedia/commons/a/a1/MJt9.png) </td></tr></table> Now Sakura wonders which tiles will form a hand with 13 tiles of the same suit (**Pure Hand**). Can you help her? ### **Task** Complete a function to work out all the optional tiles to form a regular winning hand with the given tiles. - **Input** - A string of 13 non-zero digits in non-decreasing order, denoting different tiles of a suit. - **Output** - A string of unique non-zero digits in ascending order. ### **Examples** ``` "1335556789999" => "" (None of the tiles in a deck makes up a winning hand) "1113335557779" => "89" ("8" => "111 333 555 77 789", "9" => "111 333 555 777 99") "1223334455678" => "258" ("2" => "123 22 345 345 678", "5" => "123 234 345 55 678", "8" => "123 234 345 678 88") ```
algorithms
from collections import Counter from copy import * # only works for first case def solution(tiles): valid = "" for i in range(1, 10): x = tiles + str(i) c = Counter(x) if c . most_common(1)[0][1] < 5 and is_valid(Counter(x)): valid += str(i) return valid def is_valid(hand, melds=0, pair=0): hand = {k: v for k, v in hand . items() if v} ordered_hand = sorted(hand, key=int) if melds > 5 or pair > 1: return False if len(hand) == 0: return True if hand[ordered_hand[0]] > 1: new_hand = deepcopy(hand) new_hand[ordered_hand[0]] -= 2 if is_valid(new_hand, melds, pair + 1): return True if hand[ordered_hand[0]] > 2: new_hand = deepcopy(hand) new_hand[ordered_hand[0]] -= 3 if is_valid(new_hand, melds + 1, pair): return True if len(ordered_hand) > 2 and int(ordered_hand[0]) + 2 == int(ordered_hand[1]) + 1 == int(ordered_hand[2]): new_hand = deepcopy(hand) new_hand[ordered_hand[0]] -= 1 new_hand[ordered_hand[1]] -= 1 new_hand[ordered_hand[2]] -= 1 if is_valid(new_hand, melds + 1, pair): return True return False
Mahjong - #1 Pure Hand
56ad7a4978b5162445000056
[ "Games", "Logic", "Algorithms" ]
https://www.codewars.com/kata/56ad7a4978b5162445000056
4 kyu
### **[Mahjong Series](/collections/mahjong)** **Mahjong** is based on draw-and-discard card games that were popular in 18th and 19th century China and some are still popular today. In each deck, there are three different suits numbered 1 to 9, which are called **Simple tiles**. They are *Circles* (denoted by `[1-9]p`), *Bamboo* (denoted by `[1-9]s`), and *Characters* (denoted by `[1-9]m`). <table style="width: 500px"> <tr> <td>Circles:</td><td> ![1p](https://upload.wikimedia.org/wikipedia/commons/4/4a/MJt1.png)![2p](https://upload.wikimedia.org/wikipedia/commons/6/61/MJt2.png)![3p](https://upload.wikimedia.org/wikipedia/commons/a/a4/MJt3.png)![4p](https://upload.wikimedia.org/wikipedia/commons/7/72/MJt4.png)![5p](https://upload.wikimedia.org/wikipedia/commons/5/5c/MJt5.png)![6p](https://upload.wikimedia.org/wikipedia/commons/7/72/MJt6.png)![7p](https://upload.wikimedia.org/wikipedia/commons/6/6f/MJt7.png)![8p](https://upload.wikimedia.org/wikipedia/commons/1/18/MJt8.png)![9p](https://upload.wikimedia.org/wikipedia/commons/a/a1/MJt9.png) </td> </tr> <tr> <td>Bamboo:</td><td> ![1s](https://upload.wikimedia.org/wikipedia/commons/3/37/MJs1.png)![2s](https://upload.wikimedia.org/wikipedia/commons/5/5e/MJs2.png)![3s](https://upload.wikimedia.org/wikipedia/commons/a/a7/MJs3.png)![4s](https://upload.wikimedia.org/wikipedia/commons/d/df/MJs4.png)![5s](https://upload.wikimedia.org/wikipedia/commons/b/bf/MJs5.png)![6s](https://upload.wikimedia.org/wikipedia/commons/c/cb/MJs6.png)![7s](https://upload.wikimedia.org/wikipedia/commons/e/ea/MJs7.png)![8s](https://upload.wikimedia.org/wikipedia/commons/9/99/MJs8.png)![9s](https://upload.wikimedia.org/wikipedia/commons/8/80/MJs9.png) </td> </tr> <tr> <td>Characters: </td><td> ![1m](https://upload.wikimedia.org/wikipedia/commons/1/1c/MJw1.png)![2m](https://upload.wikimedia.org/wikipedia/commons/c/c3/MJw2.png)![3m](https://upload.wikimedia.org/wikipedia/commons/9/9e/MJw3.png)![4m](https://upload.wikimedia.org/wikipedia/commons/e/e8/MJw4.png)![5m](https://upload.wikimedia.org/wikipedia/commons/e/ed/MJw5.png)![6m](https://upload.wikimedia.org/wikipedia/commons/5/58/MJw6.png)![7m](https://upload.wikimedia.org/wikipedia/commons/8/8b/MJw7.png)![8m](https://upload.wikimedia.org/wikipedia/commons/e/e1/MJw8.png)![9m](https://upload.wikimedia.org/wikipedia/commons/f/f3/MJw9.png) </td> </tr></table> Moreover, there is another suit named **Honor tiles**. It includes *Wind tiles* (namely East, South, West, North, denoted by `[1-4]z`) and *Dragon tiles* (namely Red, Green, White, denoted by `[5-7]z`). <table style="width: 400px"> <tr><td>East Wind</td><td>South Wind</td><td>West Wind</td><td>North Wind</td><td>Red Dragon</td><td>Green Dragon</td><td>White Dragon</td></tr> <tr><td> ![1z](https://upload.wikimedia.org/wikipedia/commons/7/74/MJf1.png) </td><td> ![2z](https://upload.wikimedia.org/wikipedia/commons/0/08/MJf2.png) </td><td> ![3z](https://upload.wikimedia.org/wikipedia/commons/d/dc/MJf3.png) </td><td> ![4z](https://upload.wikimedia.org/wikipedia/commons/9/96/MJf4.png) </td><td> ![5z](https://upload.wikimedia.org/wikipedia/commons/1/1b/MJd1.png) </td><td> ![6z](https://upload.wikimedia.org/wikipedia/commons/c/c4/MJd2.png) </td><td> ![7z](https://upload.wikimedia.org/wikipedia/commons/5/5a/MJd3.png) </td></tr> </table> Note that there are **EXACTLY** 4 identical copies of each kind of tiles in a deck. In each of Mahjong games, each of the 4 players around the table has 13 tiles. They take turns drawing a tile from the tile walls and then discarding one of the tiles from their hands. One wins the game if that player holds a defined combination of tiles. A regular winning hand consists of 4 *Melds* and 1 *Pair*. Each *meld* of tiles can be 3 identical copies of a tile (*e.g.* `1p 1p 1p`, `2d 2d 2d`) or 3 consecutive tiles of a **Simple** suit (*e.g.* `6m 7m 8m` or `4s 5s 6s`). <table style="width: 300px"> <tr> <td> ![1p](https://upload.wikimedia.org/wikipedia/commons/4/4a/MJt1.png)![1p](https://upload.wikimedia.org/wikipedia/commons/4/4a/MJt1.png)![1p](https://upload.wikimedia.org/wikipedia/commons/4/4a/MJt1.png) </td> <td> ![2d](https://upload.wikimedia.org/wikipedia/commons/c/c4/MJd2.png)![2d](https://upload.wikimedia.org/wikipedia/commons/c/c4/MJd2.png)![2d](https://upload.wikimedia.org/wikipedia/commons/c/c4/MJd2.png) </td> </tr> <tr> <td> ![6m](https://upload.wikimedia.org/wikipedia/commons/5/58/MJw6.png)![7m](https://upload.wikimedia.org/wikipedia/commons/8/8b/MJw7.png)![8m](https://upload.wikimedia.org/wikipedia/commons/e/e1/MJw8.png) </td> <td> ![4s](https://upload.wikimedia.org/wikipedia/commons/d/df/MJs4.png)![5s](https://upload.wikimedia.org/wikipedia/commons/b/bf/MJs5.png)![6s](https://upload.wikimedia.org/wikipedia/commons/c/cb/MJs6.png) </td> </tr> </table> Here is an example of regular winning hands. <table style="width: 700px"> <tr><td> ![3p](https://upload.wikimedia.org/wikipedia/commons/a/a4/MJt3.png)![4p](https://upload.wikimedia.org/wikipedia/commons/7/72/MJt4.png)![4p](https://upload.wikimedia.org/wikipedia/commons/7/72/MJt4.png)![5p](https://upload.wikimedia.org/wikipedia/commons/5/5c/MJt5.png)![5p](https://upload.wikimedia.org/wikipedia/commons/5/5c/MJt5.png)![6p](https://upload.wikimedia.org/wikipedia/commons/7/72/MJt6.png)![7p](https://upload.wikimedia.org/wikipedia/commons/6/6f/MJt7.png)![7p](https://upload.wikimedia.org/wikipedia/commons/6/6f/MJt7.png)![7p](https://upload.wikimedia.org/wikipedia/commons/6/6f/MJt7.png)![9p](https://upload.wikimedia.org/wikipedia/commons/a/a1/MJt9.png)![9p](https://upload.wikimedia.org/wikipedia/commons/a/a1/MJt9.png)![2s](https://upload.wikimedia.org/wikipedia/commons/5/5e/MJs2.png)![3s](https://upload.wikimedia.org/wikipedia/commons/a/a7/MJs3.png)![4s](https://upload.wikimedia.org/wikipedia/commons/d/df/MJs4.png) </td></tr></table> There are some special combinations of tiles that also win you the game. One of them is called **Seven-pairs**. As the name suggests, it consists of 7 pairs, each consisting of 2 tiles with identical patterns. One of winning hands with *Seven-pairs* is like the one shown below. For the current task, we'll use MCR rules, so two pairs formed with the same 4 tiles are allowed (meaning: `4 * 2s == 2 pairs` for example). <table style="width: 700px"> <tr><td> ![2p](https://upload.wikimedia.org/wikipedia/commons/6/61/MJt2.png)![2p](https://upload.wikimedia.org/wikipedia/commons/6/61/MJt2.png)![7p](https://upload.wikimedia.org/wikipedia/commons/6/6f/MJt7.png)![7p](https://upload.wikimedia.org/wikipedia/commons/6/6f/MJt7.png)![1s](https://upload.wikimedia.org/wikipedia/commons/3/37/MJs1.png)![1s](https://upload.wikimedia.org/wikipedia/commons/3/37/MJs1.png)![4m](https://upload.wikimedia.org/wikipedia/commons/e/e8/MJw4.png)![4m](https://upload.wikimedia.org/wikipedia/commons/e/e8/MJw4.png)![7m](https://upload.wikimedia.org/wikipedia/commons/8/8b/MJw7.png)![7m](https://upload.wikimedia.org/wikipedia/commons/8/8b/MJw7.png)![2w](https://upload.wikimedia.org/wikipedia/commons/0/08/MJf2.png)![2w](https://upload.wikimedia.org/wikipedia/commons/0/08/MJf2.png)![3d](https://upload.wikimedia.org/wikipedia/commons/5/5a/MJd3.png)![3d](https://upload.wikimedia.org/wikipedia/commons/5/5a/MJd3.png) </td></tr></table> ### **Task** Work out all tiles that can make up a winning hand with the given 13 tiles. Remember that a winning hand may be regular or in a form of **Seven-pairs**. - **Input** - A string denoting 13 tiles to be computed, in the order of *Circles* (`[1-9]p`), *Bamboo* (`[1-9]s`), *Characters* (`[1-9]m`), and *Honors* (`[1-7]z`). The tiles are space-separated. - **Output** - A string consisting of the tiles that can form a winning hand with given ones, in the order of *Circles* (`[1-9]p`), *Bamboo* (`[1-9]s`), *Characters* (`[1-9]m`), and *Honors* (`[1-7]z`). ### **Example** ``` "2p 2p 3p 3p 4p 4p 5p 5p 7m 7m 8m 8m 8m" => "2p 5p 7m 8m" (2p => (2p 2p 2p) (3p 4p 5p) (3p 4p 5p) (7m 7m) (8m 8m 8m), 5p => (2p 3p 4p) (2p 3p 4p) (5p 5p 5p) (7m 7m) (8m 8m 8m), 7m => (2p 2p) (3p 4p 5p) (3p 4p 5p) (7m 7m 7m) (8m 8m 8m), 8m => (2p 2p) (3p 3p) (4p 4p) (5p 5p) (7m 7m) (8m 8m) (8m 8m) ) ```
algorithms
ranking = 'psmz' def sorted_tiles(tiles): return sorted(tiles, key=lambda x: (ranking . index(x[1]), int(x[0]))) def check_all_three(tiles): s_tiles = sorted_tiles(tiles) while s_tiles: next = s_tiles[0] if s_tiles . count(next) >= 3: for i in range(3): s_tiles . remove(next) continue if next[1] != 'z' and f" { int ( next [ 0 ]) + 1 }{ next [ 1 ]} " in s_tiles and f" { int ( next [ 0 ]) + 2 }{ next [ 1 ]} " in s_tiles: for i in range(3): s_tiles . remove(f" { int ( next [ 0 ]) + i }{ next [ 1 ]} ") else: return False return True def solution(tiles): res = [] tile_list = tiles . split(" ") all_tiles = [str(i) + c for c in ['p', 's', 'm'] for i in range(1, 10)] + [str(i) + 'z' for i in range(1, 8)] for new_tile in [x for x in all_tiles if x]: new_hand = [new_tile] + tile_list counts = [(x, new_hand . count(x)) for x in set(new_hand)] if new_tile in [x[0] for x in counts if x[1] == 5]: continue if all(x[1] % 2 == 0 for x in counts): res . append(new_tile) continue pairs = list(filter(lambda x: x[1] >= 2, counts)) for p in pairs: short = new_hand[:] short . remove(p[0]) short . remove(p[0]) if check_all_three(short): res . append(new_tile) break res = sorted_tiles(list(set(res))) return ' ' . join(res)
Mahjong - #2 Seven-pairs
56a36b618e2548ddb400004d
[ "Games", "Logic", "Algorithms" ]
https://www.codewars.com/kata/56a36b618e2548ddb400004d
3 kyu
## Bezier curves When a shape is described using vector graphics, its outline is often described as a sequence of linear, quadratic, and cubic Bezier curves. You can read about [Bézier curves](https://en.wikipedia.org/wiki/B%C3%A9zier_curve) on Wikipedia. You don't need to know much about Bezier curves to solve this kata. Just know that the equations of the linear, quadratic, and cubic curves are given by (respectively): 1. `P(t) = (1 - t) * P0 + t * P1` 2. `P(t) = (1 - t)**2 * P0 + 2 * (1 - t) * t * P1 + t**2 * P2` 3. `P(t) = (1 - t)**3 * P0 + 3 * (1 - t)**2 * t * P1 + 3 * (1 - t) * t**2 * P2 + t**3 * P3` The points `P0`, `P1`, `P2`, `P3` are called the control points of the curve, and `t` is a variable, which, when taking values from `0` to `1`, will cause `P(t)` to trace the curve. This should suffice to implement the `point_at(t)` method of the classes you are to implement. To implement the `sub_segment(t)` method, see, in particular, the section on Constructing Bézier Curves of the above referenced Wikipedia article. This section shows animations of how the Bézier curves grow. The animations are showing longer and longer subsegments, hence showing how subsegments are constructed. If you look closely at the quad curve animation, you can see how the control points move from starting all at P0 and ending up at P0, P1 and P2 respectively. Now look closely at the animation of the cubic curve. See how the control points of the growing subsection start at P0 and end up at P0, P1, P2, and P3. No need to read anything, just look. At the end of the referenced subsection there is a link to de Casteljau's algorithm, which you might find helpful, but I wouldn't go there. Just look carefully at the animations. In this kata, you are asked to implement a class for each of the linear, quadratic, and cubic Bézier curves. These classes must extend the following abstract base class and implement the abstract methods: ```Python from abc import ABCMeta, abstractmethod class Segment(metaclass=ABCMeta): @property @abstractmethod def control_points(self): pass @abstractmethod def point_at(self, t): pass @abstractmethod def sub_segment(self, t): pass ``` `control_points` is a property that returns the coordinates of the points that define the curve. Since the linear curve has two control points (the start and end of the segment), `control_points` will hold 4 floats, which are the x- and y-coordinates of the first point followed by the x- and y-coordinates of the second point. For the quadratic and cubic curves there are 6 and 8 control points respectively. The method `point_at(t)` should return the point obtained when inserting `t` in the equation for the curve. This method will be tested for values of `t` in the interval `[0, 1]` only (although it's possible to extrapolate the curve). The method `sub_segment(t_0)` should return the curve that starts at the first point and ends at the point returned by `point_at(t_0)` and follows the curve of the object that this method is invoked on otherwise. For example, if `quad` is a quadratic curve, then `quad.sub_segment(t_0)` is a quadratic curve that starts at `quad`'s first point and ends at `quad.point_at(t_0)` and follows `quad`'s curve. More precisely, ``` quad.point_at(t_0 * t) == quad.sub_segment(t_0).point_at(t) ``` for all values of `t` in the interval `[0, 1]`.
reference
class Segment: # Instead of an abstract class, make it the implementation for all three subclasses def __init__(self, * coords): self . control_points = coords # IMHO a getter/setter is overkill here def control_points_at(self, t): # Helper function p = self . control_points result = [] while p: result . extend(p[: 2]) p = [v + (p[i + 2] - v) * t for i, v in enumerate(p[: - 2])] return result def point_at(self, t): return tuple(self . control_points_at(t)[- 2:]) def sub_segment(self, t): return self . __class__(* self . control_points_at(t)) class Line (Segment): pass class Quad (Segment): pass class Cubic (Segment): pass
Bezier Curves
5a47391c80eba865ea00003e
[ "Fundamentals" ]
https://www.codewars.com/kata/5a47391c80eba865ea00003e
4 kyu
# Kata Task Given 3 points `a`, `b`, `c` <pre style='color:red'> c b a </pre> Find the shortest distance from point `c` to a straight line that passes through points `a` and `b` **Notes** * all points are of the form `[x,y]` where x >= 0 and y >= 0 * if `a` and `b` are the same then just return distance between `a` and `c` * use <a href="https://en.wikipedia.org/wiki/Euclidean_distance">Euclidean</a> distance
algorithms
from math import dist def distance_from_line(a, b, c): ca = dist(c, a) cb = dist(c, b) ab = dist(a, b) s = (ca + cb + ab) / 2 area = (s * (s - ca) * (s - cb) * (s - ab)) * * (1 / 2) if a == b: return ca h = (area * 2) / ab return h
Line Safari : Point distance from a line
59c053f070a3b7d19100007e
[ "Geometry", "Algorithms" ]
https://www.codewars.com/kata/59c053f070a3b7d19100007e
6 kyu
# Introduction and Warm-up (Highly recommended) # [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays) ___ # Task **_Given_** an **_array of integers_** , **_Find the minimum sum_** which is obtained *from summing each Two integers product* . ___ # Notes * **_Array/list_** *will contain* **_positives only_** . * **_Array/list_** *will always have* **_even size_** ___ # Input >> Output Examples ``` minSum({5,4,2,3}) ==> return (22) ``` ## **_Explanation_**: * **_The minimum sum_** *obtained from summing each two integers product* , ` 5*2 + 3*4 = 22` ___ ``` minSum({12,6,10,26,3,24}) ==> return (342) ``` ## **_Explanation_**: * **_The minimum sum_** *obtained from summing each two integers product* , ` 26*3 + 24*6 + 12*10 = 342` ___ ``` minSum({9,2,8,7,5,4,0,6}) ==> return (74) ``` ## **_Explanation_**: * **_The minimum sum_** *obtained from summing each two integers product* , ` 9*0 + 8*2 +7*4 +6*5 = 74` ___ ___ ___ ___ # [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers) # [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays) # [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored) ___ ## ALL translations are welcomed ## Enjoy Learning !! # Zizou
reference
def min_sum(arr): arr = sorted(arr) return sum(arr[i] * arr[- i - 1] for i in range(len(arr) / / 2))
Minimize Sum Of Array (Array Series #1)
5a523566b3bfa84c2e00010b
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/5a523566b3bfa84c2e00010b
7 kyu
You're about to go on a trip around the world! On this trip you're bringing your trusted backpack, that anything fits into. The bad news is that the airline has informed you that your luggage cannot exceed a certain amount of weight. To make sure you're bringing your most valuable items on this journey you've decided to give all your items a score that represents how valuable this item is to you. It's your job to pack your bag so that you get the most value out of the items that you decide to bring. Your input will consist of two arrays, one for the scores and one for the weights. Your input will always be valid lists of equal length, so you don't have to worry about verifying your input. You'll also be given a maximum weight. This is the weight that your backpack cannot exceed. For instance, given these inputs: scores = [15, 10, 9, 5] weights = [1, 5, 3, 4] capacity = 8 The maximum score will be `29`. This number comes from bringing items `1, 3 and 4`. Note: Your solution will have to be efficient as the running time of your algorithm will be put to a test.
algorithms
def pack_bagpack(scores, weights, capacity): load = [0] * (capacity + 1) for score, weight in zip(scores, weights): load = [max(l, weight <= w and load[w - weight] + score) for w, l in enumerate(load)] return load[- 1]
Packing your backpack
5a51717fa7ca4d133f001fdf
[ "Algorithms", "Dynamic Programming" ]
https://www.codewars.com/kata/5a51717fa7ca4d133f001fdf
5 kyu
In this kata, the number 0 is infected. You are given a list. Every turn, any item in the list that is adjacent to a 0 becomes infected and transforms into a 0. How many turns will it take for the whole list to become infected? ``` [0,1,1,0] ==> [0,0,0,0] All infected in 1 turn. [1,1,0,1,1] --> [1,0,0,0,1] --> [0,0,0,0,0] All infected in 2 turns [0,1,1,1] --> [0,0,1,1] --> [0,0,0,1] --> [0,0,0,0] All infected in 3 turns. ``` All lists will contain at least one item, and at least one zero, and the only items will be 0s and 1s. Lists may be very very long, so pure brute force approach will not work.
reference
def infected_zeroes(s): m = 0 l = 0 for i, n in enumerate(s): if n == 0: m = i if l == 0 else max(m, (i - l + 1) / / 2) l = i + 1 return max(m, len(s) - l)
Infected Zeroes
5a511db1b3bfa8f45b000098
[ "Fundamentals" ]
https://www.codewars.com/kata/5a511db1b3bfa8f45b000098
6 kyu
The number `23` is special in the sense that all of its digits are prime numbers. Furthermore, it's **a prime itself**. There are 4 such numbers between 10 and 100: `23, 37, 53, 73`. Let's call these numbers "total primes". Complete the function that takes a range (`a, b`) and returns the number of total primes within that range (a <= primes < b). The test ranges go up to 10<sup>7</sup>. ## Examples ```python (10, 100) ==> 4 # 23, 37, 53, 73 (500, 600) ==> 3 # 523, 557, 577 ``` ```ruby (10, 100) ==> 4 # 23, 37, 53, 73 (500, 600) ==> 3 # 523, 557, 577 ``` Happy coding!
algorithms
from itertools import product def isPrime(n): return n == 2 or n % 2 and all(n % p for p in range(3, int(n * * .5) + 1, 2)) def get_total_primes(a, b): low, high = map(len, map(str, (a, b))) return sum(a <= n < b and isPrime(n) for d in range(low, high + 1) for n in map(int, map('' . join, product("2357", repeat=d))))
Total Primes
5a516c2efd56cbd7a8000058
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5a516c2efd56cbd7a8000058
6 kyu
Introduction and warm-up (highly recommended): [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays) ### Task Given an array/list of integers, find the Nth smallest element in the array. ### Notes * Array/list size is at least 3. * Array/list's numbers could be a mixture of positives , negatives and zeros. * Repetition in array/list's numbers could occur, so don't remove duplications. ### Input >> Output Examples ``` arr=[3,1,2] n=2 ==> return 2 arr=[15,20,7,10,4,3] n=3 ==> return 7 arr=[2,169,13,-5,0,-1] n=4 ==> return 2 arr=[2,1,3,3,1,2], n=3 ==> return 2 ``` [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers) [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays) [More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored) ### Enjoy Learning !!
reference
def nth_smallest(arr, pos): return sorted(arr)[pos - 1]
Nth Smallest Element (Array Series #4)
5a512f6a80eba857280000fc
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/5a512f6a80eba857280000fc
7 kyu
Suppose I have two vectors: `(a1, a2, a3, ..., aN)` and `(b1, b2, b3, ..., bN)`. The dot product between these two vectors is defined as: ``` a1*b1 + a2*b2 + a3*b3 + ... + aN*bN ``` The vectors are classified as orthogonal if the dot product equals zero. Complete the function that accepts two sequences as inputs and returns `true` if the vectors are orthogonal, and `false` if they are not. The sequences will always be correctly formatted and of the same length, so there is no need to check them first. ## Examples ``` [1, 1, 1], [2, 5, 7] --> false [1, 0, 0, 1], [0, 1, 1, 0] --> true ```
algorithms
def is_orthogonal(u, v): return sum(i * j for i, j in zip(u, v)) == 0
Orthogonal Vectors
53670c5867e9f2222f000225
[ "Physics", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/53670c5867e9f2222f000225
7 kyu
The story of the famous Disney-Pixar animated movie "Up" is based on the main character Carl Fredricksen journey in his home equipped with balloons. But can this happen for real? What kind of objects can you lift with helium balloons? How many balloons do you need? In this kata you will create a class ``Journey(object, crew, balloons)`` so anyone can create objects like ``var gravityFalls = new Journey(house, 2, 20622)`` which means starting a new journey to Gravity Falls in a house with 2 members of crew (Carl and Russel). But is this journey possible? Will the ``house`` float? Is it enough to have 20622 helium balloons (the number used by Pixar animators in liftoff scene)? Your ``Journey`` class should have a public method ``isPossible()`` that returns ``true`` or ``false`` based on these rules: 1). Every ``object`` (dictionary in Python) passed to ``Journey`` will have its ``weight`` property like ``var house = {"weight": 45000};`` (we will use metric system in this kata, 45 000 kg is about 100 000 pounds). 2). Each member of the crew weighs 80 kg. 3). We use regular sized party balloons filled with helium. Each balloon lifts 4.8 grams + its own weight. Can you lift a tiny 95 kg(~200 pound) push cart with 50 balloons like in one of the starting scenes of the movie? Can one balloon actually carry a message on a single letter-sized paper sheet sent by Carl to his dying wife Ellie in the other scene? Can the story I heard about man flying in his lawn chair equipped with 1000 balloons be true? Your coding mastery will reveal answers to these and many other important questions in the tests. Let the journey begin!
reference
class Journey: def __init__(self, object, crew, balloons): self . base_weight = object['weight'] self . crew_weight = crew * 80 self . balloons_lifts = balloons * 0.0048 def isPossible(self): return self . balloons_lifts >= self . base_weight + self . crew_weight
Can this object fly? Balloons in "Up" and in real life
59ea2a532a7accf2510000ce
[ "Object-oriented Programming", "Fundamentals" ]
https://www.codewars.com/kata/59ea2a532a7accf2510000ce
7 kyu
**How many elephants can the spider web hold?** Imagine a spider web that is defined by two variables: - strength, measured as the weight in kilograms that the web holds. Strength + 1 elephant will break the web - length, measured as the number of elephants that fit one after the other on the web :) Paraphrasing the song "One elephant went out to play", **how many elephants will the web hold if we put them one after the other, without breaking?** You must take into account two things: - elephants like to create super high pyramids, so, on each level of the structure fits one elephant less than in the previous one. - elephants sitting on the first row weight 1000 kg, the ones sitting on the second row weight 2000 kg, and so on. When rows are full of elephants, next elephants go up one level, and weight 1000 kg more than the previous ones. Visualy represented: Width: 3 Strength: 10000 - 3000Kg: E6 - 2000Kg: E4 E5 - 1000Kg: E1 E2 E3 The elephants weight 10000Kg. Since the web can hold 10000Kg (strength), the solution is 6 elephants. Have fun! Notes: - check all the possible values for the input parameters, even absurd ones :D
algorithms
def breakTheWeb(strength, width): res = total = 0 for i in range(width): for _ in range(width - i): total += (i + 1) * 1000 if total > strength: return res res += 1 return res
How many elephants can the spider web hold?
5830e55fa317216de000001b
[ "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/5830e55fa317216de000001b
6 kyu
The description is rather long but you are given all needed formulas (almost:-) John has bought a bike but before going moutain biking he wants us to do a few simulations. He gathered information: - His trip will consist of an ascent of `dTot` kilometers with an average slope of `slope` *percent* - We suppose that: there is no wind, John's mass is constant `MASS = 80 (kg)`, his power (generated at time `t` by pedaling and measured in watts) at the start of the trip is `WATTS0 = 225 (watts)` - We don't take account of the rolling resistance - When he starts climbing at t = 0 his initial speed (pushed start) is `v0 (km/h)` - His initial acceleration `gamma` is 0. `gamma` is in `km/h/min` at time `t`. It is the number of kilometers per hour he gains or loses in the next *minute*. - Our time step is `DELTA_T = 1.0 / 60.0` (in minutes) Furthermore (constants in uppercase are given below): - Because of tiredness, he *loses* D_WATTS * DELTA_T of power at each DELTA_T. - calcul of acceleration: Acceleration has three components: - 1) on an ascent where the slope is `slope` the effect of earth gravity is given by: `- GRAVITY_ACC * function(slope)` (Beware: here the `slope`is a percentage, it is not an angle. You have to determine `function(slope)`). Some help for `function(slope)`: a) Slope: <https://en.wikipedia.org/wiki/Grade_(slope)> b) Earth gravity: https://en.wikipedia.org/wiki/Gravity_of_Earth - 2) air drag is `- DRAG * abs(v) * abs(v) / MASS` where `v` is his current speed - 3) if his power and his speed are both strictly positive we add the thrust (by pedaling) which is: `+ G_THRUST * watts / (v * MASS)` where `watts` is his current power - 4) if his total `acceleration is <= 1e-5` we set acceleration to 0 - If `v - 3.0 <= 1e-2` John gives up ``` Constants: GRAVITY_ACC = 9.81 * 3.6 * 60.0 // gravity acceleration DRAG = 60.0 * 0.3 / 3.6 // force applied by air on the cyclist DELTA_T = 1.0 / 60.0 // in minutes G_THRUST = 60 * 3.6 * 3.6 // pedaling thrust MASS = 80.0 // biker's mass WATTS0 = 225.0 // initial biker's power D_WATTS = 0.5 // loss of power in W/mn (Note: watts at time t + DELTA_T is watts at time t minus D_WATTS * DELTA_T) Parameters: double dTot // distance to travel in km double v0 // initial speed km/h double slope // ascent in percentage (don't forget to divide by 100 when needed) Variables that can be used: t // time gamma // total acceleration with its 3 components v // speed d // distance travelled watts // biker's power ``` ### Task: Write function `temps(v0, slope, dTot)` which returns as a *rounded* integer the time `t` in minutes needed to travel `dTot`. If John gives up return `-1`. As a reminder: 1) speed at (t + DELTA_T) = (speed at t) + gamma * DELTA_T 2) distance at (t + DELTA_T) can be taken as (distance at t) + speed * DELTA_T / 60.0 where speed is calculated with 1). ``` Examples: temps(30, 5, 30) -> 114 temps(30, 20, 30) -> -1 temps(30, 8, 20) -> 110 ``` Reference: <https://en.wikipedia.org/wiki/Bicycle_performance>
reference
from math import sin, atan def temps(v0, slope, d_tot): GRAVITY_ACC = 9.81 * 3.6 * 60.0 # gravity acceleration DRAG = 60.0 * 0.3 / 3.6 # force applied by air on the cyclist DELTA_T = 1.0 / 60.0 # in minutes D_WATTS = 0.5 # power loss in Watts / minute G_THRUST = 60 * 3.6 * 3.6 # acceleration due to biker's power MASS = 80 # biker's MASS WATTS0 = 225 # initial biker's power t = 0.0 # time in minutes d = 0.0 # distance traveled in km v = v0 # initial speed km/h gamma = 0.0 # acceleration in km/h/minute # biker's power (watts at time t + DELTA_T is watts at time t - D_WATTS * DELTA_T) watts = WATTS0 slopeGravityAcc = - GRAVITY_ACC * sin(atan(slope / 100.0)) while (d <= d_tot): t += DELTA_T # new power watts -= D_WATTS * DELTA_T # tiredness # earth gravity due to slope and DRAG due to air resistance gamma = slopeGravityAcc - DRAG * abs(v) * abs(v) / MASS # acceleration due to biker's power if ((watts > 0.0) and (v > 0.0)): gamma += G_THRUST * watts / (v * MASS) # acceleration too small -> acc = 0 if (abs(gamma) <= 1e-5): gamma = 0.0 else: v += gamma * DELTA_T # new distance d += v * DELTA_T / 60.0 # v in km/h, DELTA_T in minutes # speed too slow, John stops if (v - 3.0 <= 1e-2): return - 1 return round(t)
Easy Cyclist's Training
5879f95892074d769f000272
[ "Fundamentals" ]
https://www.codewars.com/kata/5879f95892074d769f000272
5 kyu
# Task **_Given_** *a number* , **_Return_** **_The Maximum number _** *could be formed from the digits of the number given* . ___ # Notes * **_Only Natural numbers_** *passed to the function , numbers Contain digits [0:9] inclusive* * **_Digit Duplications_** *could occur* , So also **_consider it when forming the Largest_** ____ # Input >> Output Examples: ``` maxNumber (213) ==> return (321) ``` ## **_Explanation_**: As `321` is **_The Maximum number _** *could be formed from the digits of the number **_213_*** . ___ ``` maxNumber (7389) ==> return (9873) ``` ## **_Explanation_**: As `9873` is **_The Maximum number _** *could be formed from the digits of the number **_7389_*** . ___ ``` maxNumber (63729) ==> return (97632) ``` ## **_Explanation_**: As `97632` is **_The Maximum number _** *could be formed from the digits of the number **_63729_*** . ___ ``` maxNumber (566797) ==> return (977665) ``` ## **_Explanation_**: As `977665` is **_The Maximum number _** *could be formed from the digits of the number **_566797_*** . **_Note_** : **_Digit duplications are considered when forming the largest_** . ___ ``` maxNumber (17693284) ==> return (98764321) ``` ## **_Explanation_**: As `98764321` is **_The Maximum number _** *could be formed from the digits of the number **_17693284_*** . ___ ___ ___ # [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers) # [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays) # [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored) ___ ## ALL translations are welcomed ## Enjoy Learning !! # Zizou
reference
def max_number(n): return int('' . join(sorted(str(n), reverse=True)))
Form The Largest
5a4ea304b3bfa89a9900008e
[ "Fundamentals", "Numbers", "Data Types", "Mathematics", "Algorithms", "Logic", "Basic Language Features", "Loops", "Control Flow", "Conditional Statements" ]
https://www.codewars.com/kata/5a4ea304b3bfa89a9900008e
7 kyu
A **balanced number** is a number where the sum of digits to the left of the middle digit(s) and the sum of digits to the right of the middle digit(s) are equal. If the number has an odd number of digits, then there is only one middle digit. (For example, `92645` has one middle digit, `6`.) Otherwise, there are two middle digits. (For example, the middle digits of `1301` are `3` and `0`.) The middle digit(s) should **not** be considered when determining whether a number is balanced or not, e.g. `413023` is a balanced number because the left sum and right sum are both `5`. ### The task Given a number, find if it is balanced, and return the string `"Balanced"` or `"Not Balanced"` accordingly. The passed number will always be positive. ### Examples 1. ``` 7 ==> return "Balanced" ``` Explanation: * middle digit(s): 7 * sum of all digits to the left of the middle digit(s) -> 0 * sum of all digits to the right of the middle digit(s) -> 0 * 0 and 0 are equal, so it's balanced. 2. ``` 295591 ==> return "Not Balanced" ``` Explanation: * middle digit(s): 55 * sum of all digits to the left of the middle digit(s) -> 11 * sum of all digits to the right of the middle digit(s) -> 10 * 11 and 10 are not equal, so it's not balanced. 3. ``` 959 ==> return "Balanced" ``` Explanation: * middle digit(s): 5 * sum of all digits to the left of the middle digit(s) -> 9 * sum of all digits to the right of the middle digit(s) -> 9 * 9 and 9 are equal, so it's balanced. 4. ``` 27102983 ==> return "Not Balanced" ``` Explanation: * middle digit(s): 02 * sum of all digits to the left of the middle digit(s) -> 10 * sum of all digits to the right of the middle digit(s) -> 20 * 10 and 20 are not equal, so it's not balanced. ___ [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers) [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays)
reference
def balancedNum(n): s = str(n) l = (len(s) - 1) / / 2 same = len(s) < 3 or sum(map(int, s[: l])) == sum(map(int, s[- l:])) return "Balanced" if same else "Not Balanced" balanced_num = balancedNum
Balanced Number (Special Numbers Series #1 )
5a4e3782880385ba68000018
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/5a4e3782880385ba68000018
7 kyu
General primality test are often computationally expensive, so in the biggest prime number race the idea is to study special sub-families of prime number and develop more effective tests for them. [Mersenne Primes](https://en.wikipedia.org/wiki/Mersenne_prime) are prime numbers of the form: M<sub>n</sub> = 2<sup>n</sup> - 1. So far, 49 of them was found between M<sub>2</sub> (3) and M<sub>74,207,281</sub> which contains 22,338,618 digits and is (by September 2015) the biggest known prime. It has been found by GIMPS (Great Internet Mersenne Prime Search), wich use the test srudied here. (plus heuristics mentionned below) Lucas and Lehmer have developed a [simple test](https://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test) for Mersenne primes: > for `p` (an odd prime), the Mersenne number Mp is prime if and only if `S(p − 1) = 0 mod Mp`, >where `S(n + 1) = S(n) * S(n) − 2` and `S(1) = 4` The goal of this kata is to implement this test. Given an integer `>=2`, the program should calculate the sequence `S(n)` up to `p-1` and calculate the remainder modulo `Mp`, then return `True` or `False` as a result of the test. The case `n = 2` should return `True`. You should take advantage of the fact that: ```k = (k mod 2^n + floor(k/2^n)) mod Mn``` Or in other words, if we take the least significant `n` bits of `k`, and add the remaining bits of `k`, and then do this repeatedly until at most `n` bits remain, we can compute the remainder after dividing `k` by the Mersenne number `2^n−1` without using division. This test can be improved using the fact that if `n` is not prime, `2^n-1` will not be prime. So in theory you can test for the primality of `n` beforehand. But in practice the test for the primality of `n` will rapidly outgrow in difficulty the Lucas-Lehmer test. So we can only use heuristics to rule out `n` with small factors but not complete factorization algorithm. You don't need to implement such heuristics here. The rapid growth of `s^2` makes javascript reach its integer limit quickly (coherent result for `n = 13`, but not `17`). Whereas python seems to be only limited by the execution time limit and let us see that M<sub>11,213</sub> is prime (contains 3376 digits).
algorithms
def lucas_lehmer(n): return n in [2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203, 2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503, 132049, 216091, 756839, 859433, 1257787, 1398269, 2976221, 3021377, 6972593, 13466917, 20996011, 24036583, 25964951, 30402457, 32582657, 3715666]
Lucas-Lehmer Test for Mersenne Primes
5416fac7932c1dcc4f0006b4
[ "Algorithms" ]
https://www.codewars.com/kata/5416fac7932c1dcc4f0006b4
6 kyu
## Fixed xor Write a function that takes two hex strings as input and XORs them against each other. If the strings are different lengths the output should be the length of the shortest string. Hint: The strings would first need to be converted to binary to be XOR'd. ## Note: If the two strings are of different lengths, the output string should be the same length as the smallest string. This means that the longer string will be cut down to the same size as the smaller string, then xor'd ### Further help More information on the XOR operation can be found here https://www.khanacademy.org/computing/computer-science/cryptography/ciphers/a/xor-bitwise-operation More information of the binary and hex bases can be found here https://www.khanacademy.org/math/algebra-home/alg-intro-to-algebra/algebra-alternate-number-bases/v/number-systems-introduction Examples: ```haskell fixedXor "ab3f" "ac" `shouldBe` "07" fixedXor "aadf" "bce2" `shouldBe` "163d" fixedXor "1c0111001f010100061a024b53535009181c" "686974207468652062756c6c277320657965" `shouldBe` "746865206b696420646f6e277420706c6179" ``` ```c fixedXor ("ab3f", "ac") should be "07" fixedXor ("aadf", "bce2") should be "163d" fixedXor ("1c0111001f010100061a024b53535009181c", "686974207468652062756c6c277320657965") should be "746865206b696420646f6e277420706c6179" ``` ```python fixed_xor("ab3f", "ac") == "07" fixed_xor("aadf", "bce2") == "163d" fixed_xor("1c0111001f010100061a024b53535009181c", "686974207468652062756c6c277320657965") == "746865206b696420646f6e277420706c6179" ``` ```swift fixedXor("ab3f", "ac") should be "07" fixedXor("aadf", "bce2") should be "163d" fixedXor("1c0111001f010100061a024b53535009181c", "686974207468652062756c6c277320657965") should be "746865206b696420646f6e277420706c6179" ```
algorithms
def fixed_xor(a, b): return "" . join(f" { int ( x , 16 ) ^ int ( y , 16 ): x } " for x, y in zip(a, b))
Fixed xor
580f1220df91273ee90001e7
[ "Algorithms", "Mathematics", "Logic", "Algebra", "Binary", "Cryptography" ]
https://www.codewars.com/kata/580f1220df91273ee90001e7
6 kyu
Removed due to copyright infringement. <!--- &ensp;Iahub got bored, so he invented a game to be played on paper.<br> &ensp;He writes n integers a<sub>1</sub>, a<sub>2</sub>, ..., a<sub>n</sub>. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices i and j (1 ≤ i ≤ j ≤ n) and flips all values ak for which their positions are in range [i, j] (that is i ≤ k ≤ j). Flip the value of x means to apply operation x = 1 - x.<br> &ensp;The goal of the game is that after exactly one move to obtain the maximum number of ones. Write a program to solve the little game of Iahub. ``` @param {Array} line of the input there are n integers: a1, a2, ..., an. 1 ≤ n ≤ 100. It is guaranteed that each of those n values is either 0 or 1 @return {Integer} the maximal number of 1s that can be obtained after exactly one move ``` Examples : ``` [1, 0, 0, 1, 0, 0] => 5 [1, 0, 0, 1] => 4 ``` Note:<br> &ensp;In the first case, flip the segment from 2 to 6 (i = 2, j = 6). That flip changes the sequence, it becomes: [1 1 1 0 1 1]. So, it contains four ones. There is no way to make the whole sequence equal to [1 1 1 1 1 1].<br> &ensp;In the second case, flipping only the second and the third element (i = 2, j = 3) will turn all numbers into 1. (c)ll931110 & fchirica --->
algorithms
def flipping_game(a): current = best = 0 for n in a: current = max(0, current - (n or - 1)) best = max(best, current) return sum(a) + (best or - 1)
Flipping Game
59841e5084533834d6000025
[ "Algorithms", "Games", "Puzzles", "Logic" ]
https://www.codewars.com/kata/59841e5084533834d6000025
6 kyu
## Bocce Description Bocce is a game played by two competing teams, with three types of balls. Each team has its own set of balls (in this kata `red` and `black`) and there is a neutral ball called the `jack`. The jack is thrown at the beginning of each round, followed by the players trying to throw their balls as closely to it as possible. The team with their balls closest to the jack wins the round! The number of points the winning team scores equals the number of their balls being closer to jack than any of the other team's balls: if the red team has 3 balls closer to jack than any of the black team's balls, they will win scoring 3 points. Equidistant balls on opposing teams will cancel out and neither team will score beyond that point. For more information on Bocce [see here](http://en.wikipedia.org/wiki/Bocce). ___ ## Your task Implement a function that will return a message indicating the winner of the round. If there's no winner, return the string `"No points scored"`. It takes an array of `balls` that are hash tables (depending on your language). Each ball has 2 properties: `type` and `distance`. The `type` will be `"red"`, `"black"`, or `"jack"`. For all test cases, **the jack will be the last element** on the `balls` array. The `distance` property will be an array with two integer values. The first value is the distance thrown forward, the second value is the distance thrown left or right (negative values indicate distance to the left). For the purposes of this Kata, all balls are thrown from the same initial point.
algorithms
import math def bocce_score(balls): xy = balls[- 1]['distance'] balls = balls[: - 1] for b in balls: b['distance'] = math . sqrt(((xy[0] - b['distance'][0]) * * 2) + ((xy[1] - b['distance'][1]) * * 2)) reds = [x for x in balls if x['type'] == "red"] blacks = [x for x in balls if x['type'] == "black"] red = min(reds, key=lambda x: x['distance'])['distance'] black = min(blacks, key=lambda x: x['distance'])['distance'] if black == red: return "No points scored" elif black < red: return "black scores %d" % len([x for x in blacks if x['distance'] < red]) else: return "red scores %d" % len([x for x in reds if x['distance'] < black])
Bocce
55332880e679dd9cb3000081
[ "Puzzles", "Algorithms" ]
https://www.codewars.com/kata/55332880e679dd9cb3000081
6 kyu
Cheating a bit... =============== --- ### Introduction So, there is this game where you manage several soldiers, and you're losing against the machine. What can you do? Easy: patch the savegame file to restore your soldier's health! ### Details Each soldier has the following structure: * **name_length**: 16 bit integer, little endian * **name**: string of 8 bit characters * **health**: 16 bit integer, little endian Example: "\x0C\x00Maximilianus\x04\x00" The binary string is randomly generated each time, so don't try to hard-code things in your code. ### The job Your job is to code a function that will receive a string of *consecutive* binary data (the file contents) representing a random number of soldiers (a minimum of 2 are always present), and return it patched, setting each soldier's health to 500 points. Soldiers can be arranged in the output string in any order. The tests will check if the returned string is correctly formed (not empty and such) and that each soldier has 500 health points.
games
def patch_data(s): r, p = '', 0 while p < len(s): ll = ord(s[p]) + 256 * ord(s[p + 1]) r += s[p: p + ll + 2] + chr(244) + chr(1) p += 4 + ll return r
Cheating a bit...
536cce5f49aa8b3648000b52
[ "Strings", "Arrays", "Puzzles" ]
https://www.codewars.com/kata/536cce5f49aa8b3648000b52
5 kyu
Write a `sort` function that will sort a massive list of strings in caseless, lexographic order. Example Input: `['b', 'ba', 'ab', 'bb', 'c']` Expected Output: `['ab', 'b', 'ba', 'bb', 'c']` * The argument for your function will be a generator that will return a new word for each call of next() * Your function will return its own generator of the same words, except your generator will return the words in lexographic order * All words in the list are unique * All words will be comprised of lower case letters only (a-z) * All words will be between 1 and 8 characters long * There will be hundreds of thousands of words to sort * You may not use Python's sorted built-in function * You may not use Python's list.sort method * An empty list of words should result in an empty list. * `alphabet = 'abcdefghijklmnopqrstuvwxyz'` has been pre-defined for you, in case you need it
algorithms
import heapq import itertools def sort(iterable): heap = list(iterable) heapq . heapify(heap) return (heapq . heappop(heap) for i in range(len(heap)))
Sort a massive list of strings (hard)
5820e17770ca28df760012d7
[ "Data Structures", "Algorithms", "Sorting" ]
https://www.codewars.com/kata/5820e17770ca28df760012d7
5 kyu
*** Nova polynomial from roots*** This kata is from a series on polynomial handling. ( [#1](http://www.codewars.com/kata/nova-polynomial-1-add-1) [#2](http://www.codewars.com/kata/570eb07e127ad107270005fe) [#3](http://www.codewars.com/kata/5714041e8807940ff3001140 ) [#4](http://www.codewars.com/kata/571a2e2df24bdfd4e20001f5)) Consider a polynomial in a list where each element in the list element corresponds to the factors. The factor order is the position in the list. The first element is the zero order factor (the constant). p = [a0, a1, a2, a3] signifies the polynomial a0 + a1x + a2x^2 + a3*x^3 In this kata create the polynomial from a list of roots: [r0, r1 ,r2, r3 ] p = (x-r0)(x-r1)(x-r2)(x-r3) note: no roots should return the identity polynomial. ```python poly_from_roots([4]) = [-4, 1] poly_from_roots([0, 0, 0, 0] ) = [0, 0, 0, 0, 1] poly_from_roots([]) = [1] ``` The first katas of this series is preloaded in the code and can be used: [poly_add](http://www.codewars.com/kata/570eb07e127ad107270005fe) [poly_multiply](http://www.codewars.com/kata/570eb07e127ad107270005fe)
algorithms
def poly_from_roots(rs): return reduce(poly_multiply, [[- r, 1] for r in rs]) if rs else [1]
nova polynomial 5. from roots
571df7c31f95429529000092
[ "Algorithms" ]
https://www.codewars.com/kata/571df7c31f95429529000092
6 kyu
# Task Let's define a hole of size n as a matrix which is built as follows. ``` Its elements are in range [1..n^2]. The matrix is filled by rings, from the outwards the innermost. Each ring is filled with numbers in the following way: the first number is written in the top left corner; the second number is written in the top right corner; the third number is written in the bottom right corner; the fourth number is written in the bottom left corner; each next number is written next to the number written 4 steps before it, until the ring is filled. The matrix is constructed when all numbers are written.``` Given the size of the hole, return the number written at (`a, b`). # Example For `n = 4, a = 1, b = 1`, the output should be `13`. The hole looks like this: ``` [ [1, 5, 9, 2 ] [12, 13, 14, 6 ] [8, 16, 15, 10] [4, 11, 7, 3 ] ] The element at (1, 1) is 13.``` For `n = 5, a = 3, b = 2`, the output should be `23`. The hole looks like this: ``` [ [1, 5, 9, 13, 2 ] [16, 17, 21, 18, 6 ] [12, 24, 25, 22, 10] [8, 20, 23, 19, 14] [4, 15, 11, 7, 3 ] ] The element at (3, 2) is 23. ``` # Input/Output - `[input]` integer `n` Matrix size, `1 ≤ n ≤ 100`. - `[input]` integer `a` Row number, `0 ≤ a ≤ n - 1`. - `[input]` integer `b` Column number, `0 ≤ b ≤ n - 1`. - `[output]` an integer The hole[a][b]
algorithms
def black_hole(n, a, b): cont = min(a, b, n - 1 - a, n - 1 - b) start = 4 * cont * (n - 2 * cont + 1) + 4 * cont * \ (cont - 1) if cont > 0 else 0 n, a, b = n - 2 * cont, a - cont, b - cont fin = (1 + 4 * b if a == 0 and b < n - 1 else 2 + 4 * a if b == n - 1 and a < n - 1 else 3 + 4 * (n - 1 - b) if a == n - 1 and b > 0 else 4 + 4 * (n - 1 - a)) if n > 1 else 1 return start + fin
Challenge Fun #19: Black Hole
58bd011fd0efbec33400001f
[ "Algorithms" ]
https://www.codewars.com/kata/58bd011fd0efbec33400001f
6 kyu
Imagine a funnel filled with letters. The bottom letter drops out of the funnel and onto a conveyor belt: ``` \b,c/ --> \b,c/ \a/ --> \ / a ------- ------- ``` If there are two letters above a gap, the smaller letter falls into the gap. ``` \b,c/ --> \ c/ \ / --> \b/ a a ------- ------- ``` Of course, this can create a new gap, which must also be filled in the same way: ``` \f,e,d/ --> \f, ,d/ \ c/ --> \e,c/ \b/ \b/ a a ------- ------- ``` Once all the gaps above it have been filled, the bottom letter drops out of the funnel and onto the conveyorbelt. The process continues until all letters have fallen onto the conveyor. (New letters fall onto the end of the existing string) **KATA GOAL: Return the string on the conveyorbelt after all letters have fallen**. ``` \f, ,d/ \f, ,d/ --> etc --> \ / \e,c/ \e,c/ --> etc --> \ / \b/ --> \ / --> etc --> \ / a a b abcdef ------- ------- ------- ``` All letters in the funnel will be unique i.e. in every comparison one letter will be strictly smaller than the other. The funnel will be presented as a nested list, e.g: ``` [["d","a","c"], ["b","e"], ["f"]] ``` The value of a letter is defined by its codepoint. Note: this means all capital letters are defined as smaller than all lower-case letters, but your language's comparison operator will probably treat it that way automatically. The funnels will always be "nice" -- every layer will have 1 item more than the layer below, and every layer will be full, and generally there's no funny business or surprises to consider. The only characters used are standard uppercase and lowercase letters A-Z and a-z. The tests go up to 9 layer funnel. ### Fully Worked Example ``` \d,a,c/ \d,a,c/ \d,a,c/ --> \d c/ \b,e/ \b,e/ --> \ e/ --> \a,e/ \f/ --> \ / --> \b/ \b/ --> f f f ------ ------- ------- ------- \d c/ \d c/ --> \ c/ \ c/ \a,e/ --> \ e/ --> \d,e/ \d,e/ --> \ / --> \a/ \a/ --> \ / --> f b fb fb fb a ------ ------- ------- ------- \ c/ \ c/ \ c/ --> \ / \ e/ \ e/ --> \ / --> \ c/ \d/ --> \ / --> \e/ \e/ --> fba fba d fbad fbad ------- ------- -------- ------- \ / \ / \ / \ c/ --> \ / \ / \ / \c/ --> \ / fbad e fbade fbadec ------- ------- ------- DONE. Return "fbadec". ``` **For a bigger funneling challenge, check out [this kata](https://www.codewars.com/kata/create-a-funnel) by @myjinxin2015.**
reference
def funnel_out(funnel): r = "" h = len(funnel) while funnel[h - 1][0] != "~": r += funnel[h - 1][0] funnel[h - 1][0] = "~" i = h - 1 j = 0 while i > 0: if funnel[i - 1][j] < funnel[i - 1][j + 1]: funnel[i][j] = funnel[i - 1][j] funnel[i - 1][j] = "~" else: funnel[i][j] = funnel[i - 1][j + 1] funnel[i - 1][j + 1] = "~" j += 1 i -= 1 print(funnel) return r
Funnel Out A String
5a4b612ee626c5d116000084
[ "Fundamentals" ]
https://www.codewars.com/kata/5a4b612ee626c5d116000084
5 kyu
Many primes can be decomposed as a sum of two perfect squares. For example: ```python 5 = 4 + 1 = 2² + 1² 29 = 4 + 25 = 2² + 5² ``` But we have some primes that does not have this property like 3, 7, 11. Your task is to give the i-th prime in an ordered and increasing sequence of these non partitionable primes in perfect squares.. We give the name of the function with some cases bellow: ```python ith_nondecomp_prime(3) == 11 ith_nondecomp_prime(10) == 67 ``` Your code should give fast answers for primes bellow 1000000. Happy coding!! (Memoization is advisable for being able to pass many tests (more than 500) with very high values) (Hint: Study primes of the form 4n + 3)
reference
from gmpy2 import is_prime primes = [n for n in range(3, int(1e6), 4) if is_prime(n)] def ith_nondecomp_prime(i): return primes[i - 1]
Non Decomposable Primes as Sums of Perfect Squares
561c34b31dbb1b11640000de
[ "Fundamentals", "Mathematics", "Algorithms", "Memoization" ]
https://www.codewars.com/kata/561c34b31dbb1b11640000de
6 kyu
Ronald's uncle left him 3 fertile chickens in his will. When life gives you chickens, you start a business selling chicken eggs which is exactly what Ronald decided to do. A chicken lays 300 eggs in its first year. However, each chicken's egg production decreases by 20% every following year (rounded down) until when it dies (after laying its quota of eggs). After his first successful year of business, Ronald decides to buy 3 more chickens at the start of each year. <br> <p><b>Your Task: </b></p> For a given <u><i>year</i></u>, and life span of chicken <u><i>span</i></u>, calculate how many eggs Ronald's chickens will lay him that year, whereby <i>year=1</i> is when Ronald first got his inheritance and <i>span>0</i>. If <i>year=0</i>, make sure to return "No chickens yet!". <br> <p><b>Note: </b></p> 1. All chickens have the same life span regardless of when they are bought. <p>2. Let's assume all calculations are made at the end of the year so don't bother taking eggs laid per month into consideration. <p>3. <b><u>Each</u></b> chicken's egg production goes down by 20% each year, NOT the total number of eggs produced by each 'batch' of chickens. While this might appear to be the same thing, it doesn't once non-integers come into play so take care that this is reflected in your kata!
algorithms
def egged(year, span): total = 0 eggs_per_chicken = 300 for i in range(min(span, year)): total += 3 * eggs_per_chicken eggs_per_chicken = int(eggs_per_chicken * 0.8) return total or "No chickens yet!"
How many eggs?
58c1446b61aefc34620000aa
[ "Algorithms" ]
https://www.codewars.com/kata/58c1446b61aefc34620000aa
6 kyu
Strong number is a number with the sum of the factorial of its digits is equal to the number itself. For example, 145 is strong, because `1! + 4! + 5! = 1 + 24 + 120 = 145`. ### Task Given a positive number, find if it is strong or not, and return either `"STRONG!!!!"` or `"Not Strong !!"`. ### Examples - `1` is a strong number, because `1! = 1`, so return `"STRONG!!!!"`. - `123` is not a strong number, because `1! + 2! + 3! = 9` is not equal to 123, so return `"Not Strong !!"`. - `145` is a strong number, because `1! + 4! + 5! = 1 + 24 + 120 = 145`, so return `"STRONG!!!!"`. - `150` is not a strong number, because `1! + 5! + 0! = 122` is not equal to 150, so return `"Not Strong !!"`. ___ [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers) [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays) [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored)
reference
import math def strong_num(number): return "STRONG!!!!" if sum(math . factorial(int(i)) for i in str(number)) == number else "Not Strong !!"
Strong Number (Special Numbers Series #2)
5a4d303f880385399b000001
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/5a4d303f880385399b000001
7 kyu
### Welcome to the Challenge Edition of *Upside-Down Numbers* In the [original kata by @KenKamau](https://www.codewars.com/kata/59f7597716049833200001eb) you were limited to integers below `2^17`. Here, you will be given strings of digits of up to `42` characters in length (upper bound is `10^42 - 1`). Your task is essentially the same, but an additional challenge is creating a fast, efficient solution. ### Input: Your function will receive two strings, each comprised of digits representing a positive integer. These two values will represent the upper and lower bounds of a range. ### Output: Your function must return the number of valid upside down numbers within the range of the two input arguments, including both upper and lower bounds. ### What is an Upside-Down Number? An upside down number is an integer that appears the same when rotated 180 degrees, as illustrated below. ![1961 - OK, 88 - OK, 101 - OK, 25 - No](https://i.imgur.com/Biixbsd.png) **Example:** ```javascript const x = '0', y = '25'; upsideDown(x,y); //4 //the valid numbers in the range are 0, 1, 8, and 11 ``` ```python x = '0' y = '25' upsidedown(x,y) #4 # the valid numbers in the range are 0, 1, 8, and 11 ``` ```go var x,y string = "0","25" upsideDown(x,y); //4 //the valid numbers in the range are 0, 1, 8, and 11 ``` ```csharp string x = "0", y = "25"; UpsideDownNumbers.UpsideDown(x, y); //4 //the valid numbers in the range are 0, 1, 8, and 11 ``` ### Additional Notes: - All inputs will be valid. - The first argument will always be less than the second argument (ie. the range will always be valid). If you enjoyed this kata, be sure to check out [my other katas](https://www.codewars.com/users/docgunthrop/authored).
algorithms
def upsidedown(a, b): a, b = str(a), str(int(b) + 1) ans = _solve_len_ge(len(a), a) for i in range(len(a) + 1, len(b) + 1): ans += _solve_len(i) return ans - _solve_len_ge(len(b), b) def _solve_len(n): if n == 1: return 3 if n % 2 == 0: return 4 * 5 * * (n / / 2 - 1) return 4 * 5 * * (n / / 2 - 1) * 3 def _solve_len_w0(n): if n % 2 == 0: return 5 * * (n / / 2) return 5 * * (n / / 2) * 3 def _solve_len_ge(n, v): tmp = '' ans = _solve_len_w0(n) for i in range(n / / 2): for d in '01689': if tmp + d < v[: i + 1]: ans -= _solve_len_w0(n - 2 - i * 2) elif tmp + d > v[: i + 1]: return ans else: tmp += d break else: return ans if n % 2: i = n / / 2 for d in '018': if tmp + d < v[: i + 1]: ans -= 1 elif tmp + d > v[: i + 1]: return ans else: tmp += d break else: return ans trans = str . maketrans('69', '96') tmp += (tmp[:: - 1] if n % 2 == 0 else tmp[: - 1][:: - 1]). translate(trans) return ans - (tmp < v)
Upside-Down Numbers - Challenge Edition
59f98052120be4abfa000304
[ "Performance", "Algorithms" ]
https://www.codewars.com/kata/59f98052120be4abfa000304
3 kyu
A natural number is called **k-prime** if it has exactly k prime factors, counted with multiplicity. A natural number is thus prime if and only if it is 1-prime. ``` Examples of k-primes: k = 2 -> 4, 6, 9, 10, 14, 15, 21, 22, … k = 3 -> 8, 12, 18, 20, 27, 28, 30, … k = 5 -> 32, 48, 72, 80, 108, 112, … ``` The k-prime numbers are not regularly spaced. For example: between 2 and 50 we have the following 2-primes: `[4, 6, 9, 10, 14, 15, 21, 22, 25, 26, 33, 34, 35, 38, 39, 46, 49]` The `steps` between two k-primes of this list are `2, 3, 1, 4, 1, 6, 1, 3, 1, 7, 1, 1, 3, 1, 7, 3`. #### Task We will write a function `kprimes_step(k, step, start, nd)` with parameters: - `k` (integer > 0) which indicates the type of k-primes we are looking for, - `step` (integer > 0) which indicates the `step` we want to find between two k-primes, - `start` (integer >= 0) which gives the start of the search (start inclusive), - `nd` (integer >= start) which gives the end of the search (nd inclusive) In the example above `kprimes_step(2, 2, 0, 50)` will return ` [[4, 6], [33, 35]]` which are the pairs of 2-primes between 2 and 50 with a 2 steps. So this function should return an array of all the pairs (or tuples) of k-prime numbers spaced with a step of `step` between the limits `start`, `nd`. This array can be empty. #### Note (Swift) When there is no pair instead of returning an empty array, return `nil` ``` kprimes_step(5, 20, 0, 50) => nil ``` #### Examples: ``` kprimes_step(2, 2, 0, 50) => [[4, 6], [33, 35]] kprimes_step(6, 14, 2113665, 2113889) => [[2113722, 2113736]]) kprimes_step(2, 10, 0, 50) => [[4, 14], [15, 25], [25, 35], [39, 49]] kprimes_step(5, 20, 0, 50) => [] ```
reference
def prime_factors_length(n): cnt, i = 0, 2 while (i * i <= n): while (n % i == 0): cnt += 1 n /= i i += 1 if (n > 1): cnt += 1 return cnt def kprimes_step(k, step, start, nd): res = [] for i in range(start, nd - step + 1): if (prime_factors_length(i) == k and prime_factors_length(i + step) == k): res . append([i, i + step]) return res
Steps in k-primes
5a48948e145c46820b00002f
[ "Mathematics", "Number Theory" ]
https://www.codewars.com/kata/5a48948e145c46820b00002f
6 kyu
Once you complete this kata, there is a [15x15 Version](http://www.codewars.com/kata/15x15-nonogram-solver) that you can try. And once you complete that, you can do the [Multisize Version](https://www.codewars.com/kata/5a5519858803853691000069) which goes up to 50x50. # Description For this kata, you will be making a Nonogram solver. :) If you don't know what Nonograms are, you can [look at some instructions](https://www.puzzle-nonograms.com/faq.php) and also [try out some Nonograms here.](https://www.puzzle-nonograms.com/) For this kata, you will only have to solve 5x5 Nonograms. :) # Instructions You need to complete the Nonogram class and the solve method: ```python class Nonogram: def __init__(self, clues): pass def solve(self): pass ``` ```java public class Nonogram { public static int[][] solve(int[][][] clues) { //Your code here return null; } } ``` ```rust fn solve_nonogram((top_clues, left_clues): ([&[u8]; 5], [&[u8]; 5])) -> [[u8; 5]; 5] { todo!() } ``` You will be given the clues and you should return the solved puzzle. All the puzzles will be solveable so you will not need to worry about that. There will be exactly one solution to each puzzle. ```if:python The clues will be a tuple of the column clues, then the row clues, which will contain the individual clues. For example, for the Nonogram: ``` ```if:java The clues will be a three dimensional array of the column clues, then the row clues, which will contain the individual clues. For example, for the Nonogram: ``` ```if:rust The clues will be a tuple of the column clues, then the row clues, which will contain the individual clues. For example, for the Nonogram: ``` ``` | | | 1 | | | | 1 | | 1 | | | | 1 | 4 | 1 | 3 | 1 | ------------------------- 1 | | | | | | ------------------------- 2 | | | | | | ------------------------- 3 | | | | | | ------------------------- 2 1 | | | | | | ------------------------- 4 | | | | | | ------------------------- ``` The clues are on the top and the left of the puzzle, so in this case: ```if:python The column clues are: `((1, 1), (4,), (1, 1, 1), (3,), (1,))`, and the row clues are: `((1,), (2,), (3,), (2, 1), (4,))`. The column clues are given from left to right. If there is more than one clue for the same column, the upper clue is given first. The row clues are given from top to bottom. If there is more than one clue for the same row, the leftmost clue is given first. Therefore, the clue given to the `__init__` method would be `(((1, 1), (4,), (1, 1, 1), (3,), (1,)), ((1,), (2,), (3,), (2, 1), (4,)))`. You are given the column clues first then the row clues second. ``` ```if:java The column clues are: `{{1, 1}, {4}, {1, 1, 1}, {3}, {1}}`, and the row clues are: `{{1}, {2}, {3}, {2, 1}, {4}}`. The column clues are given from left to right. If there is more than one clue for the same column, the upper clue is given first. The row clues are given from top to bottom. If there is more than one clue for the same row, the leftmost clue is given first. Therefore, the clue given to the `solve` method would be `{{{1, 1}, {4}, {1, 1, 1}, {3}, {1}}, {{1}, {2}, {3}, {2, 1}, {4}}}`. You are given the column clues first then the row clues second. ``` ```if:rust The column clues are: `[&[1, 1], &[4], &[1, 1, 1], &[3], &[1]]`, and the row clues are: `[&[1], &[2], &[3], &[2, 1], &[4]]`. The column clues are given from left to right. If there is more than one clue for the same column, the upper clue is given first. The row clues are given from top to bottom. If there is more than one clue for the same row, the leftmost clue is given first. Therefore, the clue given to the `solve_nonogram` function would be `([&[1, 1], &[4], &[1, 1, 1], &[3], &[1]], [&[1], &[2], &[3], &[2, 1], &[4]])`. You are given the column clues first then the row clues second. ``` ```if:python You should return a tuple of the rows as your answer. In this case, the solved Nonogram looks like: ``` ```if:java You should return a two-dimensional array as your answer. In this case, the solved Nonogram looks like: ``` ```if:rust You should return two-dimensional array as your answer. In this case, the solved Nonogram looks like: ``` ``` | | | 1 | | | | 1 | | 1 | | | | 1 | 4 | 1 | 3 | 1 | ------------------------- 1 | | | # | | | ------------------------- 2 | # | # | | | | ------------------------- 3 | | # | # | # | | ------------------------- 2 1 | # | # | | # | | ------------------------- 4 | | # | # | # | # | ------------------------- ``` ```if:python In the tuple, you should use 0 for a unfilled square and 1 for a filled square. Therefore, in this case, you should return: ~~~ ((0, 0, 1, 0, 0), (1, 1, 0, 0, 0), (0, 1, 1, 1, 0), (1, 1, 0, 1, 0), (0, 1, 1, 1, 1)) ~~~ ``` ```if:java In the two-dimensional array, you should use 0 for a unfilled square and 1 for a filled square. Therefore, in this case, you should return: ~~~ {{0, 0, 1, 0, 0}, {1, 1, 0, 0, 0}, {0, 1, 1, 1, 0}, {1, 1, 0, 1, 0}, {0, 1, 1, 1, 1}} ~~~ ``` ```if:rust In the tuple, you should use 0 for a unfilled square and 1 for a filled square. Therefore, in this case, you should return: ~~~ [[0, 0, 1, 0, 0], [1, 1, 0, 0, 0], [0, 1, 1, 1, 0], [1, 1, 0, 1, 0], [0, 1, 1, 1, 1]] ~~~ ``` Good Luck!! If there is anything that is unclear or confusing, just let me know :)
algorithms
import itertools class Nonogram: poss = {(1, 1, 1): set([(1, 0, 1, 0, 1)]), (1, 1): set([(0, 0, 1, 0, 1), (0, 1, 0, 1, 0), (1, 0, 1, 0, 0), (0, 1, 0, 0, 1), (1, 0, 0, 1, 0), (1, 0, 0, 0, 1)]), (1, 2): set([(1, 0, 1, 1, 0), (1, 0, 0, 1, 1), (0, 1, 0, 1, 1)]), (1, 3): set([(1, 0, 1, 1, 1)]), (2, 1): set([(1, 1, 0, 1, 0), (1, 1, 0, 0, 1), (0, 1, 1, 0, 1)]), (2, 2): set([(1, 1, 0, 1, 1)]), (3, 1): set([(1, 1, 1, 0, 1)]), (1,): set([(0, 0, 0, 0, 1), (0, 0, 0, 1, 0), (0, 0, 1, 0, 0), (0, 1, 0, 0, 0), (1, 0, 0, 0, 0)]), (2,): set([(0, 0, 0, 1, 1), (0, 0, 1, 1, 0), (0, 1, 1, 0, 0), (1, 1, 0, 0, 0)]), (3,): set([(0, 0, 1, 1, 1), (0, 1, 1, 1, 0), (1, 1, 1, 0, 0)]), (4,): set([(0, 1, 1, 1, 1), (1, 1, 1, 1, 0)]), (5,): set([(1, 1, 1, 1, 1)])} def __init__(self, clues): self . h, self . w = ( tuple(Nonogram . poss[clue] for clue in side) for side in clues) def solve(self): for r in itertools . product(* self . w): if all(c in self . h[i] for i, c in enumerate(zip(* r))): return r
5x5 Nonogram Solver
5a479247e6be385a41000064
[ "Algorithms", "Logic", "Games", "Game Solvers" ]
https://www.codewars.com/kata/5a479247e6be385a41000064
4 kyu
A famous casino is suddenly faced with a sharp decline of their revenues. They decide to offer Texas hold'em also online. Can you help them by writing an algorithm that can rank poker hands? <b style='font-size:16px'>Task:</b> <ul> <li>Create a poker hand that has a constructor that accepts a string containing 5 cards:</li> ```csharp PokerHand hand = new PokerHand("KS 2H 5C JD TD"); ``` ```fsharp let hand = PokerHand("KS 2H 5C JD TD") ``` ```java PokerHand hand = new PokerHand("KS 2H 5C JD TD"); ``` ```python hand = PokerHand("KS 2H 5C JD TD") ``` <li>The characteristics of the string of cards are: <ul> <li>A space is used as card seperator</li> <li>Each card consists of two characters</li> <li>The first character is the value of the card, valid characters are: <br>`2, 3, 4, 5, 6, 7, 8, 9, T(en), J(ack), Q(ueen), K(ing), A(ce)`</li> <li>The second character represents the suit, valid characters are: <br>`S(pades), H(earts), D(iamonds), C(lubs)`</li> </ul> </li> <br> <li>The poker hands must be sortable by rank, the highest rank first:</li> ```csharp var hands = new List<PokerHand> { new PokerHand("KS 2H 5C JD TD"), new PokerHand("2C 3C AC 4C 5C") }; hands.Sort(); ``` ```fsharp let hands = [ PokerHand("KS 2H 5C JD TD"); PokerHand("2C 3C AC 4C 5C") ] let sortedHands = Seq.sort hands ``` ```java ArrayList<PokerHand> hands = new ArrayList<PokerHand>(); hands.add(new PokerHand("KS 2H 5C JD TD")); hands.add(new PokerHand("2C 3C AC 4C 5C")); Collections.sort(hands); ``` ```python hands = [] hands.append(PokerHand("KS 2H 5C JD TD")) hands.append(PokerHand("2C 3C AC 4C 5C")) hands.sort() (or sorted(hands)) ``` <li>Apply the <a href="https://en.wikipedia.org/wiki/Texas_hold_%27em">Texas Hold'em</a> rules for ranking the cards. </li> <li>There is no ranking for the suits.</li> <li>An ace can either rank high or rank low in a straight or straight flush. Example of a straight with a low ace:<br> `"5C 4D 3C 2S AS"`</li> </ul> </li> </ul> <br> Note: there are around 25000 random tests, so keep an eye on performances.
algorithms
from functools import total_ordering @ total_ordering class PokerHand (object): CARDS = "AKQJT987654321" RANKS = {card: idx for idx, card in enumerate(CARDS)} def score(self, hand): values, suits = zip(* hand . split()) idxs, ordered = zip( * sorted((self . RANKS[card], card) for card in values)) is_straight = '' . join(ordered) in self . CARDS is_flush = len(set(suits)) == 1 return (- 2 * sum(values . count(card) for card in values) - 13 * is_straight - 15 * is_flush, idxs) def __init__(self, hand): self . hand = hand self . score = min(self . score( hand), self . score(hand . replace('A', '1'))) def __repr__(self): return self . hand def __eq__(self, other): return self . score == other . score def __lt__(self, other): return self . score < other . score
Sortable Poker Hands
586423aa39c5abfcec0001e6
[ "Games", "Fundamentals", "Sorting", "Design Patterns", "Algorithms" ]
https://www.codewars.com/kata/586423aa39c5abfcec0001e6
4 kyu
In traditional [American checkers](https://en.wikipedia.org/wiki/Draughts) (also known as *draughts* outside the U.S.), when one of your pieces becomes a king, it gains the advantage of being able to move diagonally in any direction. This adds more possibilities with regard to capturing multiple enemy pieces in a single turn. In this kata you are presented with an `n x n` board. While your opponent has several pieces on the board, you have only one remaining piece — a king. Using the same mechanics as in American checkers, your goal is to capture the maximum number of enemy pieces in the next move with your king. <h2 style='color:#f66'>Input</h2> <p>Your function will receive an array of length <code>n</code> comprised of strings of length <code>n</code>. Each string value represents each row of the board, from top to bottom.</p> Each string will consist of one or more of the following: - `" "`: an unoccupied cell denoted by a space character - `X`: a cell occupied by an enemy piece - `K`: the location of your king piece <h2 style='color:#f66'>Output</h2> Your function should return the maximum number of enemy pieces that can be captured in one turn. <h2 style='color:#f66'>Test Example</h2> ```javascript let board = [ ' X', ' ', ' X X X ', ' ', ' X X X ', ' ', ' X X ', ' K ' ]; kingMoveCombo(board); //7 ``` ```python board = [ ' X', ' ', ' X X X ', ' ', ' X X X ', ' ', ' X X ', ' K ' ] king_move_combo(board) #7 ``` <p>Below (left) is a graphic representation of the example <code>board</code> and (right) a set of moves to obtain the solution.</p> ![Checkerboard image at https://i.imgur.com/KAs4tIZ.png](https://i.imgur.com/KAs4tIZ.png) <h2 style='color:#f66'>Technical Details</h2> - Input will always be valid. - Board size range: `16 >= n >= 8` - In JavaScript, prototypes have been frozen and `require` has been disabled. If you enjoyed this kata, be sure to check out [my other katas](https://www.codewars.com/users/docgunthrop/authored).
algorithms
def king_move_combo(ar): n = len(ar) field = list(map(list, ar)) def max_move(x0, y0): mm = 0 for dx, dy in ((- 1, - 1), (- 1, 1), (1, 1), (1, - 1)): x, y = x0 + 2 * dx, y0 + 2 * dy if x >= 0 and x < n and y >= 0 and y < n: xe, ye = x0 + dx, y0 + dy if field[xe][ye] == 'X': field[xe][ye] = ' ' m = max_move(x, y) + 1 if m > mm: mm = m field[xe][ye] = 'X' return mm return max_move(* next((x, y) for x, r in enumerate(field) for y, c in enumerate(r) if c == 'K'))
Checkerboard King Combo Move
5a34c8ce55519ecb15000012
[ "Games", "Puzzles", "Algorithms" ]
https://www.codewars.com/kata/5a34c8ce55519ecb15000012
5 kyu
Let's say you have a bunch of points, and you want to round them all up and calculate the area of the smallest polygon containing all of the points (nevermind why, you just want a challenge). What you're looking for is the area of the *convex hull* of these points. Here is an example, delimited in blue : <a href='https://en.wikipedia.org/wiki/Convex_hull'><img src='https://upload.wikimedia.org/wikipedia/commons/thumb/d/de/ConvexHull.svg/220px-ConvexHull.svg.png' style="background-color:white"></a> ## Your task Implement a function that will compute the area covered by the convex hull that can be formed from an array of points, the area being rounded to two decimal places. The points are given as `(x,y)`, like in an orthonormal coordinates system. ```python points = [(0, 0), (0, 3), (4, 0)] convex_hull_area(points) == 6.00 ``` ```java double[][] points = {{0, 0}, {0, 3}, {4, 0}}; assertEquals(6, ConvexHull.getArea(points), 1e-14); ``` *Note* : In Python, the scipy module has a [ready made solution](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.ConvexHull.html) for this. Of course, if you use it here, you are lame. *P. S.* : If you enjoy this kata, you may also like <a href='https://www.codewars.com/kata/compute-a-convex-hull'>this one</a>, which asks you to compute a convex hull, without finding its area.
algorithms
import numpy as np def slope(p1, p2): dx, dy = vectorize(p1, p2) return dy / dx if dx else float("inf") def vectorize(p1, p2): return [b - a for a, b in zip(p1, p2)] def getArea(p1, p2, p3): return np . cross( vectorize(p1, p2), vectorize(p1, p3)) / 2 def isConcave(p1, pivot, p2): return getArea(pivot, p1, p2) >= 0 def convex_hull_area(points): if len(points) < 3: return 0 # Leftmost point in the graph (lowest if several ones at the same x) Z = min(points) q = sorted((pt for pt in points if pt != Z), key=lambda pt: (- slope(pt, Z), - np . linalg . norm(vectorize(Z, pt)))) # sorted points accordingly to the slope of the line formed by "pt" and "Z" (in reversed order) hull = [Z, q . pop()] # Construct the convex hull (Graham Scan) while q: pt = q . pop() while len(hull) > 1 and isConcave(hull[- 2], hull[- 1], pt): hull . pop() hull . append(pt) # Calculate area of the hull by adding the area of all the triangles formed by 2 consecutive points in the hull and having Z as summit area = sum(getArea(Z, hull[i], hull[i + 1]) for i in range(1, len(hull) - 1)) return round(area, 2)
Convex hull area
59c1d64b9f0cbcf5740001ab
[ "Geometry", "Algorithms" ]
https://www.codewars.com/kata/59c1d64b9f0cbcf5740001ab
4 kyu
### The Problem Consider a flat board with pegs sticking out of one side. If you stretched a rubber band across the outermost pegs what is the set of pegs such that all other pegs are contained within the shape formed by the rubber band? ![alt text](https://upload.wikimedia.org/wikipedia/commons/b/bc/ConvexHull.png) More specifically, for this kata you will be given a list of points represented as ```[x,y]``` co-ordinates. Your aim will be to return a sublist containing points that form the perimeter of a polygon that encloses all other points contained within the original list. ### Notes: The tests may include duplicate and/or co-linear points. Co-linear points are a set of points which fall on the same straight line. Neither should be included in your returned sublist For simplicity, there will always be at least 3 points ### Help: Check out wikipedia's page on [convex hulls](https://en.wikipedia.org/wiki/Convex_hull) ```if:python Note for python users: `scipy` module has been disabled. ```
algorithms
def hull_method(points): sorted_points = sorted(points) return half_hull(sorted_points) + half_hull(reversed(sorted_points)) def half_hull(sorted_points): hull = [] for p in sorted_points: while len(hull) > 1 and not is_ccw_turn(hull[- 2], hull[- 1], p): hull . pop() hull . append(p) hull . pop() return hull def is_ccw_turn(p0, p1, p2): return (p1[0] - p0[0]) * (p2[1] - p0[1]) - (p2[0] - p0[0]) * (p1[1] - p0[1]) > 0
Compute a convex hull
5657d8bdafec0a27c800000f
[ "Algorithms", "Geometry" ]
https://www.codewars.com/kata/5657d8bdafec0a27c800000f
4 kyu
<video controls autoplay='autoplay' loop='loop' width='426'><source src="https://i.imgur.com/XSMoEuK.mp4" type='video/mp4'/></video> <sub><b>Above:</b> <a href="https://i.imgur.com/XSMoEuK.mp4">Game footage from Bloxorz online game</a></sub> This kata is inspired by [**Bloxorz**](http://miniclip.wikia.com/wiki/Bloxorz), a flash-based 3D puzzle game where the objective is to maneuver a block to have it fall through a square hole. # Objective Your goal is to maneuver a [rectangular cuboid](https://en.wikipedia.org/wiki/Cuboid) with dimensions `1 x 1 x 2` on a 2-dimensional grid made up of `1 x 1` square tiles. While moving the cuboid around, your block must never, at any point, have any part of its bottom-facing surface exposed to open air. ## Input Your function will receive an array of strings describing the layout of the grid to be traversed. A `1` represents solid ground (tiles), a `0` represents open air, a `B` represents your starting position, and an `X` represents the square hole (destination). ## Output Your function must return a string representing the minimum sequence of moves required to get the block into the square hole. It will consist of a combination of the following characters: `U` (up), `D` (down), `L` (left), `R` (right). ## Block Movement ![](https://i.imgur.com/6k4Oufb.png) The block can cover either one or two tiles with each movement, depending on whether it is standing upright or on its long end. The image above shows an overhead view; the yellow squares represent the tiles occupied by the block and the green squares represent the tiles occupied when moved toward a given cardinal direction. In Fig. 1, the block's position is standing upright, and in Fig. 2, the block is on its long end. ## Test Example ```javascript let level1 = ['1110000000', '1B11110000', '1111111110', '0111111111', '0000011X11', '0000001110']; bloxSolver(level1); //'RRDRRRD' or 'RDDRRDR' ``` ```python level1 = [ '1110000000', '1B11110000', '1111111110', '0111111111', '0000011X11', '0000001110' ] blox_solver(level1) #'RRDRRRD' or 'RDDRRDR' ``` ```kotlin val level1 = arrayOf( "1110000000", "1B11110000", "1111111110", "0111111111", "0000011X11", "0000001110" ) bloxSolver(level1) // "RRDRRRD" or "RDDRRDR" ``` ```rust let level1: Vec<&str> = vec![ "1110000000", "1B11110000", "1111111110", "0111111111", "0000011X11", "0000001110" ]; blox_solver(level1); // "RRDRRRD" or "RDDRRDR" ``` ```haskell level1 = [ "1110000000" , "1B11110000" , "1111111110" , "0111111111" , "0000011X11" , "0000001110" ] bloxSolver level1 -- "RRDRRRD" or "RDDRRDR" ``` An overhead view of the game grid for the example `level1` is shown below, with a green square representing the starting position of the block, the red square representing the square hole, the light grey squares representing the platform tiles, and the dark grey areas representing open air: ![grid layout of level1](https://i.imgur.com/41dECqx.png) Below is the sequence of moves to solve this map, numbered and highlighted in blue. ![sequence of moves for level1](https://i.imgur.com/U48beYb.png) and another possible solution: ![alternative sequence of moves for level1](https://i.imgur.com/BBZtM4w.png) ## Technical Details - Input will always be valid and there will always be a solution. - The block always begins in an upright position. - The destination exit does **not** count as open air. - The maximum grid size will be `15 x 20` (rows x colums) If you enjoyed this kata, be sure to check out [my other katas](https://www.codewars.com/users/docgunthrop/authored).
algorithms
from collections import deque def blox_solver(arr): def isSame(A, B): return A == B # bloxorz has is pieces superposed # bloxorz is vertical (looking the board from above) def isVert(A, B): return A[0] != B[0] # bloxorz is horizontal (looking the board from above) def isHorz(A, B): return A[1] != B[1] def moveBlox(m, A, B): # Move bloxorz according to its current position and the expected direction (xA, yA), (xB, yB) = A, B dx, dy, fA, fB = DELTAS[m] nA = ((xA + dx * (1 + fA(A, B))), (yA + dy * (1 + fA(A, B)))) nB = ((xB + dx * (1 + fB(A, B))), (yB + dy * (1 + fB(A, B)))) return tuple(sorted((nA, nB))) # dx,dy conditional modifiers (fA, fB) DELTAS = {"U": (- 1, 0, isSame, isVert), "D": (1, 0, isVert, isSame), "L": (0, - 1, isSame, isHorz), "R": (0, 1, isHorz, isSame)} INF = float("inf") """ Accumulate data """ board = set() for x, line in enumerate(arr): for y, c in enumerate(line): if c == '0': continue board . add((x, y)) if c == 'B': blox = ((x, y), (x, y)) # initial position elif c == 'X': end = ((x, y), (x, y)) # finish position """ VERY crude BFS search """ q, seen, prev, round = deque([blox]), {blox: 0}, {blox: (None, None)}, 0 while q and q[- 1] != end: round += 1 A, B = blox = q . pop() for m in DELTAS: nA, nB = nblox = moveBlox(m, A, B) if nA in board and nB in board and round < seen . get(nblox, INF): q . appendleft(nblox) seen[nblox] = round prev[nblox] = (blox, m) """ rebuild the shortest path """ path, (pos, m) = [], prev[end] while m is not None: path . append(m) pos, m = prev[pos] return '' . join(path[:: - 1])
Bloxorz Solver
5a2a597a8882f392020005e5
[ "Games", "Puzzles", "Game Solvers", "Algorithms" ]
https://www.codewars.com/kata/5a2a597a8882f392020005e5
3 kyu
<h1>Task</h1> Create a top-down movement system that would feel highly responsive to the player. In your Update method you have to check for the keys that are currently being pressed, the keys correspond to the enum Direction shown below, based on which key is pressed or released your method should behave this way: 1) When a key is first pressed, the player has to change his direction to that of the current key, without moving 2) If the key is still being pressed during the next Update, the player will move towards his current direction using these vectors: (Up = { 0, +1 } , Down = { 0, -1 }, Left = { -1, 0 }, Right = { +1, 0 }) 3) If a new key is pressed, it will gain precedence over the previous key and the player will act as per 1) 4-A) If the current key (A) is released, then the precedence will go back to the previous key (B) (or the one before it, if (B) is not pressed anymore, and so on), then the player will behave as per 1). 4-B) If the current key is released, and no other keys are being pressed, the player will stand still 5) If all keys are released at once, the player will not move nor change direction 6) If multiple keys are pressed at once, the order of precedence will be the following { Up, Down, Left, Right } <h1>Examples</h1> (n = pressed key, [n] = current key, p() = press, r() = release, (8,2,4,6 = up, down, left, right)): [] , p(8) -> [8] , p(4,6) -> 86[4] , r(6) -> 8[4] , r(4) -> [8] , r(8) -> [] [] , p(2486) -> 642[8] , r(2,8) -> 6[4] , r(4,6) -> [] This is what you'll need to use in your code (NB: the tile coordinates cannot be changed, you'll need to assign a new Tile each time the player moves): ```csharp public enum Direction { Up = 8, Down = 2, Left = 4, Right = 6 } public struct Tile { public int X { get; } public int Y { get; } public Tile(int x, int y); } public static class Input { // pressed = true, released = false public static bool GetState(Direction direction); } ``` ```python from enum import IntEnum class Direction(IntEnum): Up = 8 Down = 2 Right = 6 Left = 4 class Tile: @property def x(self): return self._x @property def y(self): return self._y def __str__(self): return "({},{})".format(self._x, self._y) class Input: @staticmethod def get_state(direction): # 2, 4, 6, 8 return Input.STATES[direction] # pressed = true, released = false ``` ```java class Tile { public Tile(int x, int y) public int x() // getter public int y() // getter @Override public String toString() // formated as: "(x,y)" @Override public int hashCode() @Override public boolean equals(Object other) } class Input { public static boolean getState(int direction) // pressed = true, released = false } ```
games
class PlayerMovement: def __init__(self, x, y): self . position = Tile(x, y) self . direction = 8 self . a = [] self . q = [] def update(self): a = [Input . get_state(x) for x in (6, 4, 2, 8)] for s, d in zip(a, (6, 4, 2, 8)): if d in self . q and not s: self . q . remove(d) elif d not in self . q and s: self . q . append(d) if self . q: d = self . q[- 1] if any(self . a) and d == self . direction: self . position = Tile(self . position . x + (d == 6) - (d == 4), self . position . y + (d == 8) - (d == 2)) self . direction = d self . a = a
Top Down Movement System
59315ad28f0ebeebee000159
[ "Games", "Logic", "Puzzles" ]
https://www.codewars.com/kata/59315ad28f0ebeebee000159
4 kyu
You get some nested lists. Keeping the original structures, sort only elements (integers) inside of the lists. In other words, sorting the intergers only by swapping their positions. ``` Example Input : [[[2, 1], [4, 3]], [[6, 5], [8, 7]]] Output : [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] ``` Note: The structures of the lists are regular (symmetrical) and their depths are 3.
reference
import numpy as np def sort_nested_list(A): return np . sort(A, axis=None). reshape(np . array(A). shape). tolist()
Sort only integers in Nested List
5a4bdd73d8e145f17d000035
[ "Fundamentals", "Algorithms", "Sorting" ]
https://www.codewars.com/kata/5a4bdd73d8e145f17d000035
6 kyu
Mike and Joe are fratboys that love beer and games that involve drinking. They play the following game: Mike chugs one beer, then Joe chugs 2 beers, then Mike chugs 3 beers, then Joe chugs 4 beers, and so on. Once someone can't drink what he is supposed to drink, he loses. Mike can chug at most A beers in total (otherwise he would pass out), while Joe can chug at most B beers in total. Who will win the game? Write the function ```game(A,B)``` that returns the winner, ```"Mike"``` or ```"Joe"``` accordingly, for any given integer values of A and B. Note: If either Mike or Joe cannot drink at least 1 beer, return the string ```"Non-drinkers can't play"```.
reference
def game(maxMike, maxJoe): roundsMike = int(maxMike * * .5) roundsJoe = (- 1 + (1 + 4 * maxJoe) * * .5) / / 2 return ("Non-drinkers can't play" if not maxMike or not maxJoe else "Joe" if roundsMike <= roundsJoe else "Mike")
Drinking Game
5a491f0be6be389dbb000117
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5a491f0be6be389dbb000117
7 kyu
Similar to the [previous kata](https://www.codewars.com/kata/string-subpattern-recognition-ii/), but this time you need to operate with shuffled strings to identify if they are composed repeating a subpattern Since there is no deterministic way to tell which pattern was really the original one among all the possible permutations of a fitting subpattern, return a subpattern with sorted characters, otherwise return the base string with sorted characters (you might consider this case as an edge case, with the subpattern being repeated only once and thus equalling the original input string). For example: ```cpp hasSubpattern("a") == "a"; //no repeated pattern, just one character hasSubpattern("aaaa") == "a"; //just one character repeated hasSubpattern("abcd") == "abcd"; //base pattern equals the string itself, no repetitions hasSubpattern("babababababababa") == "ab"; //remember to return the base string sorted hasSubpattern("bbabbaaabbaaaabb") == "ab"; //same as above, just shuffled ``` ```javascript hasSubpattern("a") === "a"; //no repeated pattern, just one character hasSubpattern("aaaa") === "a"; //just one character repeated hasSubpattern("abcd") === "abcd"; //base pattern equals the string itself, no repetitions hasSubpattern("babababababababa") === "ab"; //remember to return the base string sorted hasSubpattern("bbabbaaabbaaaabb") === "ab"; //same as above, just shuffled ``` ```haskell hasSubpattern "a" == "a" -- no repeated pattern, just one character hasSubpattern "aaaa" == "a" -- just one character repeated hasSubpattern "abcd" == "abcd" -- base pattern equals the string itself, no repetitions hasSubpattern "babababababababa" == "ab" -- remember to return the base string sorted hasSubpattern "bbabbaaabbaaaabb" == "ab" -- same as above, just shuffled ``` ```python has_subpattern("a") == "a"; #no repeated pattern, just one character has_subpattern("aaaa") == "a" #just one character repeated has_subpattern("abcd") == "abcd" #base pattern equals the string itself, no repetitions has_subpattern("babababababababa") == "ab" #remember to return the base string sorted" has_subpattern("bbabbaaabbaaaabb") == "ab" #same as above, just shuffled ``` ```ruby has_subpattern("a") == "a"; #no repeated pattern, just one character has_subpattern("aaaa") == "a" #just one character repeated has_subpattern("abcd") == "abcd" #base pattern equals the string itself, no repetitions has_subpattern("babababababababa") == "ab" #remember to return the base string sorted" has_subpattern("bbabbaaabbaaaabb") == "ab" #same as above, just shuffled ``` ```crystal has_subpattern("a") == "a"; #no repeated pattern, just one character has_subpattern("aaaa") == "a" #just one character repeated has_subpattern("abcd") == "abcd" #base pattern equals the string itself, no repetitions has_subpattern("babababababababa") == "ab" #remember to return the base string sorted" has_subpattern("bbabbaaabbaaaabb") == "ab" #same as above, just shuffled ``` ```csharp HasSubpattern("a") == "a"; //no repeated pattern, just one character HasSubpattern("aaaa") == "a"; //just one character repeated HasSubpattern("abcd") == "abcd"; //base patter equals the string itself, no repetitions HasSubpattern("babababababababa") == "ab"; //remembernto return the base string sorted HasSubpattern("bbabbaaabbaaaabb") == "ab"; //same as above, just shuffled ``` If you liked it, go for either the [previous kata](https://www.codewars.com/kata/string-subpattern-recognition-ii/) or the [next kata](https://www.codewars.com/kata/string-subpattern-recognition-iv/) of the series!
reference
from collections import Counter from functools import reduce from fractions import gcd def has_subpattern(s): c = Counter(s) m = reduce(gcd, c . values()) return '' . join(sorted(k * (v / / m) for k, v in c . items()))
String subpattern recognition III
5a4a2973d8e14586c700000a
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/5a4a2973d8e14586c700000a
6 kyu
Print an ordered cross table of a round robin tournament that looks like this: ``` # Player 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Pts SB ========================================================================== 1 Nash King 1 0 = 1 0 = 1 1 0 1 1 1 0 8.0 52.25 2 Karsyn Marks 0 1 1 = 1 = = 1 0 0 1 1 0 7.5 49.75 3 Yandel Briggs 1 0 = 0 = 1 1 1 = 0 1 0 1 7.5 47.25 Luka Harrell = 0 = 1 1 1 = 0 0 1 1 0 1 7.5 47.25 Pierre Medina 0 = 1 0 = 1 = 1 1 = 0 1 = 7.5 47.25 6 Carlos Koch 1 0 = 0 = = = 1 1 = 0 = 1 7.0 43.50 7 Tristan Pitts = = 0 0 0 = 1 0 1 = 1 1 1 7.0 40.75 Luke Schaefer 0 = 0 = = = 0 1 = = 1 1 1 7.0 40.75 9 Tanner Dunn 0 0 0 1 0 0 1 0 1 1 = 1 1 6.5 37.25 10 Haylee Bryan 1 1 = 1 0 0 0 = 0 1 0 0 1 6.0 39.25 11 Dylan Turner 0 1 1 0 = = = = 0 0 1 = = 6.0 38.75 12 Adyson Griffith 0 0 0 0 1 1 0 0 = 1 0 1 1 5.5 31.75 13 Dwayne Shaw 0 0 1 1 0 = 0 0 0 1 = 0 1 5.0 30.50 14 Kadin Rice 1 1 0 0 = 0 0 0 0 0 = 0 0 3.0 22.25 ``` The `#` column contains the rank. Ranks may be tied. A colum with index numbers `i` contains the match against the player on line `i`. `1` / `=` / `0` means win / draw / loss. The `Pts` column contains the score, 1 for each win, 0.5 for each draw. The `SB` column contains the Sonneborn-Berger score (see below). The rank is determined by the score, the Sonneborn-Berger score is used to break ties. Players with the same score and the same SB score share the same rank. In the cross table those tied players are ordered by their surenames. # Sonneborn-Berger score The Sonneborn-Berger score (`SB`) (sometimes also called Neustadtl Sonneborn–Berger or Neustadtl score) is a system to break ties in tournaments. This score is based on the observation that it is usually harder to score against higher ranked than against lower ranked opponents. The score is the sum of the points of opponents this player has defeated plus the half the sum of the points of opponents this player has drawn against. For examples, see the table above. # Task Write a function `crosstable(players, results)`. Input: * `players`: a list of names (`["Forename Surename", ...]`) * `results`: a list of lists of results, where result may be `1`, `0.5`, `0` or `None`. Output: * The cross table as a string. There is no whitespace at the end of the lines. The columns are separated by two spaces. The column headers for the rank (`#`) and for the rounds are right adjusted, `Players` is left-adjusted, `Pts` and `SB` are centered. The separator line consisting of `=` is just as long as the longest line in the output. # Examples ```python d, _ = 0.5, None crosstable([ 'Emmett Frost', 'Cruz Sullivan', 'Deandre Bullock', 'George Bautista', 'Norah Underwood', 'Renee Preston'], [ [_, 1, 0, 0, d, 0], [0, _, d, 1, 0, 0], [1, d, _, d, d, d], [1, 0, d, _, d, d], [d, 1, d, d, _, d], [1, 1, d, d, d, _]]) # returns '''\ # Player 1 2 3 4 5 6 Pts SB ========================================== 1 Renee Preston = = = 1 1 3.5 7.25 2 Deandre Bullock = = = = 1 3.0 6.75 Norah Underwood = = = 1 = 3.0 6.75 4 George Bautista = = = 0 1 2.5 6.25 5 Cruz Sullivan 0 = 0 1 0 1.5 4.00 6 Emmett Frost 0 0 = 0 1 1.5 3.00''' crosstable([ 'Luke Schaefer', 'Adyson Griffith', 'Dylan Turner', 'Carlos Koch', 'Luka Harrell', 'Karsyn Marks', 'Haylee Bryan', 'Dwayne Shaw', 'Pierre Medina', 'Nash King', 'Kadin Rice', 'Tristan Pitts', 'Tanner Dunn', 'Yandel Briggs'], [ [_, 1, d, d, d, d, d, 1, d, 0, 1, 0, 1, 0], [0, _, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, d, 0], [d, 1, _, d, 0, 1, 0, d, d, 0, d, d, 0, 1], [d, 0, d, _, 0, 0, 1, d, d, 1, 1, d, 1, d], [d, 1, 1, 1, _, 0, 0, 0, 1, d, 1, 1, 0, d], [d, 1, 0, 1, 1, _, 0, 1, d, 0, 0, d, 1, 1], [d, 0, 1, 0, 1, 1, _, 0, 0, 1, 1, 0, 0, d], [0, 0, d, d, 1, 0, 1, _, 0, 0, 1, 0, 0, 1], [d, 0, d, d, 0, d, 1, 1, _, 0, d, 1, 1, 1], [1, 1, 1, 0, d, 1, 0, 1, 1, _, 0, d, 1, 0], [0, 0, d, 0, 0, 1, 0, 0, d, 1, _, 0, 0, 0], [1, 1, d, d, 0, d, 1, 1, 0, d, 1, _, 0, 0], [0, d, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, _, 0], [1, 1, 0, d, d, 0, d, 0, 0, 1, 1, 1, 1, _]]) # returns '''\ # Player 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Pts SB ========================================================================== 1 Nash King 1 0 = 1 0 = 1 1 0 1 1 1 0 8.0 52.25 2 Karsyn Marks 0 1 1 = 1 = = 1 0 0 1 1 0 7.5 49.75 3 Yandel Briggs 1 0 = 0 = 1 1 1 = 0 1 0 1 7.5 47.25 Luka Harrell = 0 = 1 1 1 = 0 0 1 1 0 1 7.5 47.25 Pierre Medina 0 = 1 0 = 1 = 1 1 = 0 1 = 7.5 47.25 6 Carlos Koch 1 0 = 0 = = = 1 1 = 0 = 1 7.0 43.50 7 Tristan Pitts = = 0 0 0 = 1 0 1 = 1 1 1 7.0 40.75 Luke Schaefer 0 = 0 = = = 0 1 = = 1 1 1 7.0 40.75 9 Tanner Dunn 0 0 0 1 0 0 1 0 1 1 = 1 1 6.5 37.25 10 Haylee Bryan 1 1 = 1 0 0 0 = 0 1 0 0 1 6.0 39.25 11 Dylan Turner 0 1 1 0 = = = = 0 0 1 = = 6.0 38.75 12 Adyson Griffith 0 0 0 0 1 1 0 0 = 1 0 1 1 5.5 31.75 13 Dwayne Shaw 0 0 1 1 0 = 0 0 0 1 = 0 1 5.0 30.50 14 Kadin Rice 1 1 0 0 = 0 0 0 0 0 = 0 0 3.0 22.25''' crosstable([ 'Mikaela Orozco', 'Mekhi Mayer', 'Marcus Galvan', 'Leroy Wilkins', 'Gregory Bates', 'Jayda Lynn', 'Makena Galloway', 'Adriel Brock', 'Morgan Gillespie', 'Darwin Mack', 'Clayton Terrell', 'Bo Schmidt', 'Xzavier Clements', 'Rex Cummings', 'Aldo Jackson', 'Justus Sloan', 'Rudy Herrera', 'Leonard Ponce', 'Kaden Harding', 'Anastasia Dodson'], [ [_, 1, 1, 0, 1, d, 1, 1, 0, 1, 0, d, 0, d, d, 0, d, 0, 0, d], [0, _, 0, d, d, 0, d, 1, d, d, 0, 1, 1, d, d, d, d, 1, d, 0], [0, 1, _, 0, 0, d, 1, d, 0, d, 0, d, 0, 1, 1, 0, 0, 0, 1, 1], [1, d, 1, _, d, 0, d, 0, d, 0, 1, d, 0, 0, 1, 0, d, 1, d, 1], [0, d, 1, d, _, 1, d, 1, 1, 1, d, 1, 1, d, 0, 1, 1, 1, d, d], [d, 1, d, 1, 0, _, 0, d, d, 1, d, 0, d, 0, 0, 0, 1, d, 1, 1], [0, d, 0, d, d, 1, _, 1, 1, 1, 1, 0, d, 0, 1, 1, d, 1, 1, 0], [0, 0, d, 1, 0, d, 0, _, 1, d, 0, d, 1, d, d, 1, d, 0, 0, 0], [1, d, 1, d, 0, d, 0, 0, _, 0, 1, 0, 0, 1, 1, d, d, 1, 0, 0], [0, d, d, 1, 0, 0, 0, d, 1, _, d, d, 1, 1, d, 0, 1, d, 1, d], [1, 1, 1, 0, d, d, 0, 1, 0, d, _, 1, d, 0, 0, d, 0, 0, d, d], [d, 0, d, d, 0, 1, 1, d, 1, d, 0, _, 1, d, d, 0, 1, 0, 0, 0], [1, 0, 1, 1, 0, d, d, 0, 1, 0, d, 0, _, 1, d, d, 0, 1, d, d], [d, d, 0, 1, d, 1, 1, d, 0, 0, 1, d, 0, _, d, 0, 0, 0, 1, 1], [d, d, 0, 0, 1, 1, 0, d, 0, d, 1, d, d, d, _, d, 1, 0, 1, 1], [1, d, 1, 1, 0, 1, 0, 0, d, 1, d, 1, d, 1, d, _, 1, 1, 0, d], [d, d, 1, d, 0, 0, d, d, d, 0, 1, 0, 1, 1, 0, 0, _, 0, 0, 1], [1, 0, 1, 0, 0, d, 0, 1, 0, d, 1, 1, 0, 1, 1, 0, 1, _, d, d], [1, d, 0, d, d, 0, 0, 1, 1, 0, d, 1, d, 0, 0, 1, 1, d, _, 0], [d, 1, 0, 0, d, 0, 1, 1, 1, d, d, 1, d, 0, 0, d, 0, d, 1, _]]) # returns '''\ # Player 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Pts SB =============================================================================================== 1 Gregory Bates 1 = 0 1 1 = 1 = 1 0 = = = 1 1 = 1 1 1 13.5 124.50 2 Justus Sloan 0 0 = 1 1 = = 1 1 1 1 = 0 = 1 = 1 1 0 12.0 109.00 3 Makena Galloway = 1 1 1 1 0 = = 1 0 0 = 1 1 0 1 0 = 1 11.5 109.75 4 Aldo Jackson 1 = 0 = 0 1 = 0 1 = = = 1 0 = 1 0 1 = 10.0 95.25 5 Darwin Mack 0 0 0 = = = 1 1 0 0 1 = 1 1 = = = 1 = 10.0 89.00 6 Leonard Ponce 0 0 0 1 = = 0 0 = 1 1 0 = 0 1 1 1 1 1 10.0 87.50 7 Anastasia Dodson = = 1 0 = = = 0 0 = 0 1 1 1 1 = 0 0 1 9.5 90.25 8 Xzavier Clements 0 = = = 0 1 = 1 = 1 1 0 = 1 0 = 1 0 0 9.5 89.00 Leroy Wilkins = 0 = 1 0 1 1 0 0 1 0 = = = = 1 1 = 0 9.5 89.00 10 Jayda Lynn 0 0 0 0 1 = 1 = 1 = 0 1 1 = 0 = = 1 = 9.5 85.50 11 Mikaela Orozco 1 0 1 = 1 0 = 0 0 = = 1 0 0 = 0 1 = 1 9.0 86.75 12 Rex Cummings = 0 1 = 0 0 1 0 1 1 = = 1 0 = 1 0 0 = 9.0 86.25 13 Mekhi Mayer = = = = = 1 0 1 = 0 0 = = = 1 0 0 = 1 9.0 86.00 14 Kaden Harding = 1 0 0 0 = 0 = = 0 1 0 = 1 1 = 0 1 1 9.0 83.50 15 Morgan Gillespie 0 = 0 1 0 1 0 0 = = 1 1 = 0 0 1 1 = 0 8.5 78.50 Bo Schmidt 0 0 1 = = 0 0 1 = 1 = = 0 0 1 0 = 1 = 8.5 78.50 Clayton Terrell = = 0 0 = 0 = = 0 = 1 0 1 = 0 1 1 0 1 8.5 78.50 18 Marcus Galvan 0 0 1 1 = 0 1 0 0 = 0 1 1 1 0 = 0 0 = 8.0 75.75 19 Rudy Herrera 0 0 = 0 0 0 1 1 = 0 = 1 = 0 = 0 1 1 = 8.0 72.00 20 Adriel Brock 0 1 0 = = 0 0 1 1 = 0 = 0 0 1 = 0 = = 7.5 71.00''' ``` ```javascript const d = 0.5, _ = null; crosstable([ 'Emmett Frost', 'Cruz Sullivan', 'Deandre Bullock', 'George Bautista', 'Norah Underwood', 'Renee Preston'], [ [_, 1, 0, 0, d, 0], [0, _, d, 1, 0, 0], [1, d, _, d, d, d], [1, 0, d, _, d, d], [d, 1, d, d, _, d], [1, 1, d, d, d, _]]) // returns '# Player 1 2 3 4 5 6 Pts SB\n' + '==========================================\n' + '1 Renee Preston = = = 1 1 3.5 7.25\n' + '2 Deandre Bullock = = = = 1 3.0 6.75\n' + ' Norah Underwood = = = 1 = 3.0 6.75\n' + '4 George Bautista = = = 0 1 2.5 6.25\n' + '5 Cruz Sullivan 0 = 0 1 0 1.5 4.00\n' + '6 Emmett Frost 0 0 = 0 1 1.5 3.00' crosstable([ 'Luke Schaefer', 'Adyson Griffith', 'Dylan Turner', 'Carlos Koch', 'Luka Harrell', 'Karsyn Marks', 'Haylee Bryan', 'Dwayne Shaw', 'Pierre Medina', 'Nash King', 'Kadin Rice', 'Tristan Pitts', 'Tanner Dunn', 'Yandel Briggs'], [ [_, 1, d, d, d, d, d, 1, d, 0, 1, 0, 1, 0], [0, _, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, d, 0], [d, 1, _, d, 0, 1, 0, d, d, 0, d, d, 0, 1], [d, 0, d, _, 0, 0, 1, d, d, 1, 1, d, 1, d], [d, 1, 1, 1, _, 0, 0, 0, 1, d, 1, 1, 0, d], [d, 1, 0, 1, 1, _, 0, 1, d, 0, 0, d, 1, 1], [d, 0, 1, 0, 1, 1, _, 0, 0, 1, 1, 0, 0, d], [0, 0, d, d, 1, 0, 1, _, 0, 0, 1, 0, 0, 1], [d, 0, d, d, 0, d, 1, 1, _, 0, d, 1, 1, 1], [1, 1, 1, 0, d, 1, 0, 1, 1, _, 0, d, 1, 0], [0, 0, d, 0, 0, 1, 0, 0, d, 1, _, 0, 0, 0], [1, 1, d, d, 0, d, 1, 1, 0, d, 1, _, 0, 0], [0, d, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, _, 0], [1, 1, 0, d, d, 0, d, 0, 0, 1, 1, 1, 1, _]]) // returns ' # Player 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Pts SB\n' + '==========================================================================\n' + ' 1 Nash King 1 0 = 1 0 = 1 1 0 1 1 1 0 8.0 52.25\n' + ' 2 Karsyn Marks 0 1 1 = 1 = = 1 0 0 1 1 0 7.5 49.75\n' + ' 3 Yandel Briggs 1 0 = 0 = 1 1 1 = 0 1 0 1 7.5 47.25\n' + ' Luka Harrell = 0 = 1 1 1 = 0 0 1 1 0 1 7.5 47.25\n' + ' Pierre Medina 0 = 1 0 = 1 = 1 1 = 0 1 = 7.5 47.25\n' + ' 6 Carlos Koch 1 0 = 0 = = = 1 1 = 0 = 1 7.0 43.50\n' + ' 7 Tristan Pitts = = 0 0 0 = 1 0 1 = 1 1 1 7.0 40.75\n' + ' Luke Schaefer 0 = 0 = = = 0 1 = = 1 1 1 7.0 40.75\n' + ' 9 Tanner Dunn 0 0 0 1 0 0 1 0 1 1 = 1 1 6.5 37.25\n' + '10 Haylee Bryan 1 1 = 1 0 0 0 = 0 1 0 0 1 6.0 39.25\n' + '11 Dylan Turner 0 1 1 0 = = = = 0 0 1 = = 6.0 38.75\n' + '12 Adyson Griffith 0 0 0 0 1 1 0 0 = 1 0 1 1 5.5 31.75\n' + '13 Dwayne Shaw 0 0 1 1 0 = 0 0 0 1 = 0 1 5.0 30.50\n' + '14 Kadin Rice 1 1 0 0 = 0 0 0 0 0 = 0 0 3.0 22.25' crosstable([ 'Mikaela Orozco', 'Mekhi Mayer', 'Marcus Galvan', 'Leroy Wilkins', 'Gregory Bates', 'Jayda Lynn', 'Makena Galloway', 'Adriel Brock', 'Morgan Gillespie', 'Darwin Mack', 'Clayton Terrell', 'Bo Schmidt', 'Xzavier Clements', 'Rex Cummings', 'Aldo Jackson', 'Justus Sloan', 'Rudy Herrera', 'Leonard Ponce', 'Kaden Harding', 'Anastasia Dodson'], [ [_, 1, 1, 0, 1, d, 1, 1, 0, 1, 0, d, 0, d, d, 0, d, 0, 0, d], [0, _, 0, d, d, 0, d, 1, d, d, 0, 1, 1, d, d, d, d, 1, d, 0], [0, 1, _, 0, 0, d, 1, d, 0, d, 0, d, 0, 1, 1, 0, 0, 0, 1, 1], [1, d, 1, _, d, 0, d, 0, d, 0, 1, d, 0, 0, 1, 0, d, 1, d, 1], [0, d, 1, d, _, 1, d, 1, 1, 1, d, 1, 1, d, 0, 1, 1, 1, d, d], [d, 1, d, 1, 0, _, 0, d, d, 1, d, 0, d, 0, 0, 0, 1, d, 1, 1], [0, d, 0, d, d, 1, _, 1, 1, 1, 1, 0, d, 0, 1, 1, d, 1, 1, 0], [0, 0, d, 1, 0, d, 0, _, 1, d, 0, d, 1, d, d, 1, d, 0, 0, 0], [1, d, 1, d, 0, d, 0, 0, _, 0, 1, 0, 0, 1, 1, d, d, 1, 0, 0], [0, d, d, 1, 0, 0, 0, d, 1, _, d, d, 1, 1, d, 0, 1, d, 1, d], [1, 1, 1, 0, d, d, 0, 1, 0, d, _, 1, d, 0, 0, d, 0, 0, d, d], [d, 0, d, d, 0, 1, 1, d, 1, d, 0, _, 1, d, d, 0, 1, 0, 0, 0], [1, 0, 1, 1, 0, d, d, 0, 1, 0, d, 0, _, 1, d, d, 0, 1, d, d], [d, d, 0, 1, d, 1, 1, d, 0, 0, 1, d, 0, _, d, 0, 0, 0, 1, 1], [d, d, 0, 0, 1, 1, 0, d, 0, d, 1, d, d, d, _, d, 1, 0, 1, 1], [1, d, 1, 1, 0, 1, 0, 0, d, 1, d, 1, d, 1, d, _, 1, 1, 0, d], [d, d, 1, d, 0, 0, d, d, d, 0, 1, 0, 1, 1, 0, 0, _, 0, 0, 1], [1, 0, 1, 0, 0, d, 0, 1, 0, d, 1, 1, 0, 1, 1, 0, 1, _, d, d], [1, d, 0, d, d, 0, 0, 1, 1, 0, d, 1, d, 0, 0, 1, 1, d, _, 0], [d, 1, 0, 0, d, 0, 1, 1, 1, d, d, 1, d, 0, 0, d, 0, d, 1, _]]) // returns ' # Player 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Pts SB\n' + '===============================================================================================\n' + ' 1 Gregory Bates 1 = 0 1 1 = 1 = 1 0 = = = 1 1 = 1 1 1 13.5 124.50\n' + ' 2 Justus Sloan 0 0 = 1 1 = = 1 1 1 1 = 0 = 1 = 1 1 0 12.0 109.00\n' + ' 3 Makena Galloway = 1 1 1 1 0 = = 1 0 0 = 1 1 0 1 0 = 1 11.5 109.75\n' + ' 4 Aldo Jackson 1 = 0 = 0 1 = 0 1 = = = 1 0 = 1 0 1 = 10.0 95.25\n' + ' 5 Darwin Mack 0 0 0 = = = 1 1 0 0 1 = 1 1 = = = 1 = 10.0 89.00\n' + ' 6 Leonard Ponce 0 0 0 1 = = 0 0 = 1 1 0 = 0 1 1 1 1 1 10.0 87.50\n' + ' 7 Anastasia Dodson = = 1 0 = = = 0 0 = 0 1 1 1 1 = 0 0 1 9.5 90.25\n' + ' 8 Xzavier Clements 0 = = = 0 1 = 1 = 1 1 0 = 1 0 = 1 0 0 9.5 89.00\n' + ' Leroy Wilkins = 0 = 1 0 1 1 0 0 1 0 = = = = 1 1 = 0 9.5 89.00\n' + '10 Jayda Lynn 0 0 0 0 1 = 1 = 1 = 0 1 1 = 0 = = 1 = 9.5 85.50\n' + '11 Mikaela Orozco 1 0 1 = 1 0 = 0 0 = = 1 0 0 = 0 1 = 1 9.0 86.75\n' + '12 Rex Cummings = 0 1 = 0 0 1 0 1 1 = = 1 0 = 1 0 0 = 9.0 86.25\n' + '13 Mekhi Mayer = = = = = 1 0 1 = 0 0 = = = 1 0 0 = 1 9.0 86.00\n' + '14 Kaden Harding = 1 0 0 0 = 0 = = 0 1 0 = 1 1 = 0 1 1 9.0 83.50\n' + '15 Morgan Gillespie 0 = 0 1 0 1 0 0 = = 1 1 = 0 0 1 1 = 0 8.5 78.50\n' + ' Bo Schmidt 0 0 1 = = 0 0 1 = 1 = = 0 0 1 0 = 1 = 8.5 78.50\n' + ' Clayton Terrell = = 0 0 = 0 = = 0 = 1 0 1 = 0 1 1 0 1 8.5 78.50\n' + '18 Marcus Galvan 0 0 1 1 = 0 1 0 0 = 0 1 1 1 0 = 0 0 = 8.0 75.75\n' + '19 Rudy Herrera 0 0 = 0 0 0 1 1 = 0 = 1 = 0 = 0 1 1 = 8.0 72.00\n' + '20 Adriel Brock 0 1 0 = = 0 0 1 1 = 0 = 0 0 1 = 0 = = 7.5 71.00' ```
reference
def crosstable(players, results): n = len(players) # calculating pts = [sum(s for s in row if s != None) for row in results] sb = [sum(s * pts for (s, pts) in zip(row, pts) if s != None) for row in results] surnames = [p . split(' ')[1] for p in players] # sorting table = zip(range(n), players, pts, sb, surnames) table = sorted(table, key=lambda l: (- l[2], - l[3], l[4])) ind, players, pts, sb, surnames = zip(* table) dict = {None: ' ', 0: '0', 0.5: '=', 1: '1'} results = [[dict[results[i][j]] for i in ind] for j in ind] # ranking rank = ['1'] for i in range(1, n): same = (pts[i] == pts[i - 1] and sb[i] == sb[i - 1]) rank += [' '] if same else [str(i + 1)] # formating header = ['#', 'Player', 'Pts', 'SB'] + [str(x + 1) for x in range(n)] pts = [f" { x : .1 f } " for x in pts] sb = [f" { x : .2 f } " for x in sb] out = list(zip(rank, players, pts, sb, * results)) w = [max(len(out[i][j]) for i in range(n)) for j in range(4)] + [len(str(n))] form = "{o[0]:>{w[0]}} {o[1]:<{w[1]}} " \ + " " . join("{o[" + str(i + 4) + "]:>{w[4]}}" for i in range(n)) \ + " {o[2]:^{w[2]}} {o[3]:^{w[3]}}" header = form . format(o=header, w=w) out = [header . rstrip()] \ + ['=' * len(header)] \ + [form . replace("^", ">"). format(o=o, w=w) for o in out] return '\n' . join(out)
Tournament Cross Table with Sonneborn-Berger Score
5a392890c5e284a7a300003f
[ "Sorting", "Algorithms" ]
https://www.codewars.com/kata/5a392890c5e284a7a300003f
4 kyu