inputs
stringlengths 50
14k
| targets
stringlengths 4
655k
|
|---|---|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(laLiga=0, copaDelRey=0, championsLeague=0):
total_goals = laLiga +copaDelRey +championsLeague
return total_goals
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(laLiga, copaDelRey, championsLeague):
goals = 0
goals += laLiga
goals += copaDelRey
goals += championsLeague
return goals
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(laLiga, copaDelRey, championsLeague):
return sum(locals().values())
# return laLiga + copaDelRey + championsLeague
# return sum([laLiga, copaDelRey, championsLeague])
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(la, c, ch):
return sum([la,c,ch])
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
goals = lambda laLiga, copaDelRey, championsLeague: sum([laLiga, copaDelRey, championsLeague])
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
from functools import reduce
def goals(laLiga, copaDelRey, championsLeague):
return reduce(lambda x,y: x+y, [laLiga, copaDelRey, championsLeague])
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(l, c, ca):
return l+c+ca
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(laLiga, copaDelRey, championsLeague):
x = copaDelRey + championsLeague + laLiga
return x
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(laLiga, copaDelRey, championsLeague):
if(laLiga>=0 and copaDelRey >=0 and championsLeague>=0):
return laLiga+copaDelRey+championsLeague
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(laLiga, copaDelRey, championsLeague):
total_goals = int(laLiga) + int(copaDelRey) + int(championsLeague)
return total_goals
pass
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(l, c, e):
return l+c+e
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(*s):
return sum(s)
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(laLiga, copaDelRey, championsLeague):
summe=laLiga+copaDelRey+championsLeague
return summe
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(laLiga, copaDelRey, championsLeague):
return (laLiga+copaDelRey+championsLeague)
x = goals(5,10,2)
print(x)
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(laLiga: int, copaDelRey: int, championsLeague: int) -> int:
return sum((laLiga, copaDelRey, championsLeague))
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(laLiga, copaDelRey, championsLeague):
goal = lambda a, b, c: a + b + c
return(goal(laLiga, copaDelRey, championsLeague))
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(laLiga, copaDelRey, championsLeague):
res = laLiga +copaDelRey + championsLeague
return res
print(goals(5, 12, 7))
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(laLiga, copaDelRey, championsLeague):
a = laLiga
b = copaDelRey
c = championsLeague
x = a + b +c
return x
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(laLiga, copaDelRey, championsLeague):
list = [laLiga,copaDelRey,championsLeague]
return sum(list)
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(*args):
leagues = [*args]
return sum(leagues)
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(laLiga, copaDelRey, championsLeague):
all = [laLiga, copaDelRey, championsLeague]
return sum(all)
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(laLiga, copaDelRey, championsLeague):
v = laLiga + copaDelRey + championsLeague
return (v)
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(*a): # create a variable that contains all numbers
return sum(a)
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(laLiga, copaDelRey, championsLeague):
somme = sum([laLiga,copaDelRey,championsLeague])
print(somme)
return somme
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(laLiga, copaDelRey, championsLeague):
r = laLiga + copaDelRey + championsLeague
return r
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
goals = lambda ll, cd, cl:ll+cd+cl
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(laLiga, copaDelRey, championsLeague):
value = laLiga + copaDelRey + championsLeague
return value
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(laLiga, copaDelRey, championsLeague):
x = sum((laLiga, copaDelRey), championsLeague)
return x
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(laLiga, copaDelRey, championsLeague):
total = [laLiga, copaDelRey, championsLeague]
return sum(total)
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(laLiga, copaDelRey, championsLeague):
a=sum((laLiga,copaDelRey,championsLeague))
return a
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(laLiga, copaDelRey, championsLeague):
messi=laLiga+copaDelRey+championsLeague
return messi
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(laLiga, copaDelRey, championsLeague):
return(laLiga+copaDelRey+championsLeague)
print(goals(5, 6, 9))
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(laLiga, copaDelRey, championsLeague):
return laLiga + copaDelRey + championsLeague
goals(4, 5, 12)
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(laLiga, copaDelRey, championsLeague):
"""Return total number of goals from 3 leagues"""
return laLiga + copaDelRey + championsLeague
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(laLiga, copaDelRey, championsLeague):
alltogetherforever = 0
for point in laLiga, copaDelRey, championsLeague:
alltogetherforever += point
return alltogetherforever
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(laLiga, copaDelRey, championsLeague):
add = laLiga + copaDelRey + championsLeague
return add
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(laLiga, copaDelRey, championsLeague):
messi = laLiga + copaDelRey + championsLeague
print(messi)
return messi
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(laLiga, copaDelRey, ChampionsLeague):
total_goals = laLiga + copaDelRey + ChampionsLeague
return total_goals
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(laLiga, copaDelRey, championsLeague):
total_goals = copaDelRey+laLiga+championsLeague
return total_goals
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(laLiga, copaDelRey, championsLeague):
#We want the sumation of all three parameters so you can just add them together
return laLiga + copaDelRey + championsLeague
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(laLiga, copaDelRey, championsLeague):
# lst = (laLiga, copaDelRey, championsLeague)
total = (laLiga + copaDelRey + championsLeague)
return(total)
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(laLiga, copaDelRey, championsLeague):
counter = 0
for n in [laLiga, copaDelRey, championsLeague]:
counter += n
return counter
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(laLiga, copaDelRey, champions):
return laLiga+copaDelRey+champions
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
|
def goals(laLiga, copaDelRey, championsLeague):
a = [laLiga, copaDelRey, championsLeague]
return sum(a)
|
In this kata, your task is to implement what I call **Iterative Rotation Cipher (IRC)**. To complete the task, you will create an object with two methods, `encode` and `decode`. (For non-JavaScript versions, you only need to write the two functions without the enclosing dict)
Input
The encode method will receive two arguments — a positive integer n and a string value.
The decode method will receive one argument — a string value.
Output
Each method will return a string value.
How It Works
Encoding and decoding are done by performing a series of character and substring rotations on a string input.
Encoding: The number of rotations is determined by the value of n. The sequence of rotations is applied in the following order:
Step 1: remove all spaces in the string (but remember their positions)
Step 2: shift the order of characters in the new string to the right by n characters
Step 3: put the spaces back in their original positions
Step 4: shift the characters of each substring (separated by one or more consecutive spaces) to the right by n
Repeat this process until it has been completed n times in total.
The value n is then prepended to the resulting string with a space.
Decoding: Decoding simply reverses the encoding process.
Test Example
```python
quote = 'If you wish to make an apple pie from scratch, you must first invent the universe.'
solution = '10 hu fmo a,ys vi utie mr snehn rni tvte .ysushou teI fwea pmapi apfrok rei tnocsclet'
IterativeRotationCipher['encode'](10,quote) == solution; //True
'''Step-by-step breakdown:
Step 1 — remove all spaces:
'Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventtheuniverse.'
Step 2 — shift the order of string characters to the right by 10:
'euniverse.Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventth'
Step 3 — place the spaces back in their original positions:
'eu niv erse .I fyou wi shtom ake anap plepiefr oms crat ch,yo umustf irs tinventth'
Step 4 — shift the order of characters for each space-separated substring to the right by 10:
'eu vni seer .I oufy wi shtom eak apan frplepie som atcr ch,yo ustfum sir htinventt'
Repeat the steps 9 more times before returning the string with '10 ' prepended.
'''
```
Technical Details
- Input will always be valid.
- The characters used in the strings include any combination of alphanumeric characters, the space character, the newline character, and any of the following: `_!@#$%^&()[]{}+-*/="'<>,.?:;`.
If you enjoyed this kata, be sure to check out [my other katas](https://www.codewars.com/users/docgunthrop/authored).
|
def shift(string, step):
i = (step % len(string)) if string else 0
return f"{string[-i:]}{string[:-i]}"
def encode(n, string):
for _ in range(n):
shifted = shift(string.replace(" ", ""), n)
l = [len(word) for word in string.split(" ")]
string = " ".join(shift(shifted[sum(l[:i]):sum(l[:i+1])], n) for i in range(len(l)))
return f"{n} {string}"
def decode(string):
n, string = int(string.partition(" ")[0]), string.partition(" ")[2]
for _ in range(n):
shifted = shift("".join(shift(word, -n) for word in string.split(" ")), -n)
l = [len(word) for word in string.split(" ")]
string = " ".join(shifted[sum(l[:i]):sum(l[:i+1])] for i in range(len(l)))
return string
|
In this kata, your task is to implement what I call **Iterative Rotation Cipher (IRC)**. To complete the task, you will create an object with two methods, `encode` and `decode`. (For non-JavaScript versions, you only need to write the two functions without the enclosing dict)
Input
The encode method will receive two arguments — a positive integer n and a string value.
The decode method will receive one argument — a string value.
Output
Each method will return a string value.
How It Works
Encoding and decoding are done by performing a series of character and substring rotations on a string input.
Encoding: The number of rotations is determined by the value of n. The sequence of rotations is applied in the following order:
Step 1: remove all spaces in the string (but remember their positions)
Step 2: shift the order of characters in the new string to the right by n characters
Step 3: put the spaces back in their original positions
Step 4: shift the characters of each substring (separated by one or more consecutive spaces) to the right by n
Repeat this process until it has been completed n times in total.
The value n is then prepended to the resulting string with a space.
Decoding: Decoding simply reverses the encoding process.
Test Example
```python
quote = 'If you wish to make an apple pie from scratch, you must first invent the universe.'
solution = '10 hu fmo a,ys vi utie mr snehn rni tvte .ysushou teI fwea pmapi apfrok rei tnocsclet'
IterativeRotationCipher['encode'](10,quote) == solution; //True
'''Step-by-step breakdown:
Step 1 — remove all spaces:
'Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventtheuniverse.'
Step 2 — shift the order of string characters to the right by 10:
'euniverse.Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventth'
Step 3 — place the spaces back in their original positions:
'eu niv erse .I fyou wi shtom ake anap plepiefr oms crat ch,yo umustf irs tinventth'
Step 4 — shift the order of characters for each space-separated substring to the right by 10:
'eu vni seer .I oufy wi shtom eak apan frplepie som atcr ch,yo ustfum sir htinventt'
Repeat the steps 9 more times before returning the string with '10 ' prepended.
'''
```
Technical Details
- Input will always be valid.
- The characters used in the strings include any combination of alphanumeric characters, the space character, the newline character, and any of the following: `_!@#$%^&()[]{}+-*/="'<>,.?:;`.
If you enjoyed this kata, be sure to check out [my other katas](https://www.codewars.com/users/docgunthrop/authored).
|
def rotate(n, s):
if not s: return s
n = -n % len(s)
return s[n:] + s[:n]
def cipher(n, s):
sp = [i for i, c in enumerate(s) if c == ' '] + [len(s)]
s = s.split(' ')
if n < 0: s = [rotate(n, w) for w in s]
s = rotate(n, ''.join(s))
s = [s[i+1-x: j-x] for x, (i, j) in enumerate(zip([-1] + sp, sp))]
if n > 0: s = [rotate(n, w) for w in s]
return ' '.join(s)
def encode(n, s):
for _ in range(n): s = cipher(n, s)
return f'{n} {s}'
def decode(s):
n, s = s.split(' ', 1)
n = int(n)
for _ in range(n): s = cipher(-n, s)
return s
|
In this kata, your task is to implement what I call **Iterative Rotation Cipher (IRC)**. To complete the task, you will create an object with two methods, `encode` and `decode`. (For non-JavaScript versions, you only need to write the two functions without the enclosing dict)
Input
The encode method will receive two arguments — a positive integer n and a string value.
The decode method will receive one argument — a string value.
Output
Each method will return a string value.
How It Works
Encoding and decoding are done by performing a series of character and substring rotations on a string input.
Encoding: The number of rotations is determined by the value of n. The sequence of rotations is applied in the following order:
Step 1: remove all spaces in the string (but remember their positions)
Step 2: shift the order of characters in the new string to the right by n characters
Step 3: put the spaces back in their original positions
Step 4: shift the characters of each substring (separated by one or more consecutive spaces) to the right by n
Repeat this process until it has been completed n times in total.
The value n is then prepended to the resulting string with a space.
Decoding: Decoding simply reverses the encoding process.
Test Example
```python
quote = 'If you wish to make an apple pie from scratch, you must first invent the universe.'
solution = '10 hu fmo a,ys vi utie mr snehn rni tvte .ysushou teI fwea pmapi apfrok rei tnocsclet'
IterativeRotationCipher['encode'](10,quote) == solution; //True
'''Step-by-step breakdown:
Step 1 — remove all spaces:
'Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventtheuniverse.'
Step 2 — shift the order of string characters to the right by 10:
'euniverse.Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventth'
Step 3 — place the spaces back in their original positions:
'eu niv erse .I fyou wi shtom ake anap plepiefr oms crat ch,yo umustf irs tinventth'
Step 4 — shift the order of characters for each space-separated substring to the right by 10:
'eu vni seer .I oufy wi shtom eak apan frplepie som atcr ch,yo ustfum sir htinventt'
Repeat the steps 9 more times before returning the string with '10 ' prepended.
'''
```
Technical Details
- Input will always be valid.
- The characters used in the strings include any combination of alphanumeric characters, the space character, the newline character, and any of the following: `_!@#$%^&()[]{}+-*/="'<>,.?:;`.
If you enjoyed this kata, be sure to check out [my other katas](https://www.codewars.com/users/docgunthrop/authored).
|
def encode(n,strng):
for _ in range(n):
wos, spa, new, a = '', [], '', []
for i in range(len(strng)):
if strng[i] == ' ': spa.append(i)
else: wos += strng[i]
shifted = []
for i in range(len(wos)): shifted.insert((i+n)%len(wos), wos[i])
for i in spa: shifted.insert(i, ' ')
for i in [i for i in ''.join(shifted).split(' ')]:
tem = []
for j in range(len(i)): tem.insert((j+n)%len(i), i[j])
a.append(''.join(tem))
strng = ' '.join(a)
return '{} {}'.format(n, strng)
def decode(strng):
n = int(strng.split(' ')[0])
strng = strng[len(str(n))+1:]
for _ in range(n):
a, spa = [], []
for i in range(len(strng)):
if strng[i] == ' ':spa.append(i)
for i in [i for i in strng.split(' ')]:
tem = []
for j in range(len(i)): tem.insert((j-n)%len(i), i[j])
a.append(''.join(tem))
wos, shifted = ''.join(a), []
for i in range(len(wos)): shifted.insert((i-n)%len(wos), wos[i])
for i in spa:
shifted.insert(i, ' ')
strng = ''.join(shifted)
return(strng)
|
In this kata, your task is to implement what I call **Iterative Rotation Cipher (IRC)**. To complete the task, you will create an object with two methods, `encode` and `decode`. (For non-JavaScript versions, you only need to write the two functions without the enclosing dict)
Input
The encode method will receive two arguments — a positive integer n and a string value.
The decode method will receive one argument — a string value.
Output
Each method will return a string value.
How It Works
Encoding and decoding are done by performing a series of character and substring rotations on a string input.
Encoding: The number of rotations is determined by the value of n. The sequence of rotations is applied in the following order:
Step 1: remove all spaces in the string (but remember their positions)
Step 2: shift the order of characters in the new string to the right by n characters
Step 3: put the spaces back in their original positions
Step 4: shift the characters of each substring (separated by one or more consecutive spaces) to the right by n
Repeat this process until it has been completed n times in total.
The value n is then prepended to the resulting string with a space.
Decoding: Decoding simply reverses the encoding process.
Test Example
```python
quote = 'If you wish to make an apple pie from scratch, you must first invent the universe.'
solution = '10 hu fmo a,ys vi utie mr snehn rni tvte .ysushou teI fwea pmapi apfrok rei tnocsclet'
IterativeRotationCipher['encode'](10,quote) == solution; //True
'''Step-by-step breakdown:
Step 1 — remove all spaces:
'Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventtheuniverse.'
Step 2 — shift the order of string characters to the right by 10:
'euniverse.Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventth'
Step 3 — place the spaces back in their original positions:
'eu niv erse .I fyou wi shtom ake anap plepiefr oms crat ch,yo umustf irs tinventth'
Step 4 — shift the order of characters for each space-separated substring to the right by 10:
'eu vni seer .I oufy wi shtom eak apan frplepie som atcr ch,yo ustfum sir htinventt'
Repeat the steps 9 more times before returning the string with '10 ' prepended.
'''
```
Technical Details
- Input will always be valid.
- The characters used in the strings include any combination of alphanumeric characters, the space character, the newline character, and any of the following: `_!@#$%^&()[]{}+-*/="'<>,.?:;`.
If you enjoyed this kata, be sure to check out [my other katas](https://www.codewars.com/users/docgunthrop/authored).
|
def encode(n, cleartext):
def rotate_right(sequence, n):
n %= len(sequence) or 1
return sequence[-n:] + sequence[:-n]
for _ in range(n):
letters = iter(rotate_right([c for c in cleartext if c != ' '], n))
cleartext = ''.join(c if c == ' ' else next(letters) for c in cleartext)
cleartext = ' '.join(rotate_right(word, n) for word in cleartext.split(' '))
return f'{n} {cleartext}'
def decode(ciphertext):
def rotate_left(sequence, n):
n %= len(sequence) or 1
return sequence[n:] + sequence[:n]
n, ciphertext = ciphertext.split(' ', 1)
n = int(n)
for _ in range(n):
ciphertext = ' '.join(rotate_left(word, n) for word in ciphertext.split(' '))
letters = iter(rotate_left([c for c in ciphertext if c != ' '], n))
ciphertext = ''.join(c if c == ' ' else next(letters) for c in ciphertext)
return ciphertext
|
In this kata, your task is to implement what I call **Iterative Rotation Cipher (IRC)**. To complete the task, you will create an object with two methods, `encode` and `decode`. (For non-JavaScript versions, you only need to write the two functions without the enclosing dict)
Input
The encode method will receive two arguments — a positive integer n and a string value.
The decode method will receive one argument — a string value.
Output
Each method will return a string value.
How It Works
Encoding and decoding are done by performing a series of character and substring rotations on a string input.
Encoding: The number of rotations is determined by the value of n. The sequence of rotations is applied in the following order:
Step 1: remove all spaces in the string (but remember their positions)
Step 2: shift the order of characters in the new string to the right by n characters
Step 3: put the spaces back in their original positions
Step 4: shift the characters of each substring (separated by one or more consecutive spaces) to the right by n
Repeat this process until it has been completed n times in total.
The value n is then prepended to the resulting string with a space.
Decoding: Decoding simply reverses the encoding process.
Test Example
```python
quote = 'If you wish to make an apple pie from scratch, you must first invent the universe.'
solution = '10 hu fmo a,ys vi utie mr snehn rni tvte .ysushou teI fwea pmapi apfrok rei tnocsclet'
IterativeRotationCipher['encode'](10,quote) == solution; //True
'''Step-by-step breakdown:
Step 1 — remove all spaces:
'Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventtheuniverse.'
Step 2 — shift the order of string characters to the right by 10:
'euniverse.Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventth'
Step 3 — place the spaces back in their original positions:
'eu niv erse .I fyou wi shtom ake anap plepiefr oms crat ch,yo umustf irs tinventth'
Step 4 — shift the order of characters for each space-separated substring to the right by 10:
'eu vni seer .I oufy wi shtom eak apan frplepie som atcr ch,yo ustfum sir htinventt'
Repeat the steps 9 more times before returning the string with '10 ' prepended.
'''
```
Technical Details
- Input will always be valid.
- The characters used in the strings include any combination of alphanumeric characters, the space character, the newline character, and any of the following: `_!@#$%^&()[]{}+-*/="'<>,.?:;`.
If you enjoyed this kata, be sure to check out [my other katas](https://www.codewars.com/users/docgunthrop/authored).
|
SPACE, NULL_STR = " ", ""
def rotate(n, s):
if not s: return NULL_STR
if SPACE in s:
return SPACE.join(rotate(n, word) for word in s.split(SPACE))
else:
n %= len(s)
return s[-n:] + s[:-n]
def cipher(n, s):
# extract spaces
spaces = [idx for idx, char in enumerate(s) if char == SPACE]
for _ in range(abs(n)):
# rotate words (decoding)
if n < 0: s = rotate(n, s)
# remove spaces, rotate string, put back spaces
s = s.replace(SPACE, NULL_STR)
s = rotate(n, s)
for idx in spaces: s = s[:idx] + SPACE + s[idx:]
# rotate words (encoding)
if n > 0: s = rotate(n, s)
return s
def encode(n, s):
return str(n) + SPACE + cipher(n, s)
def decode(s):
n, s = s.split(SPACE, 1)
n = int(n)
return cipher(-n, s)
|
In this kata, your task is to implement what I call **Iterative Rotation Cipher (IRC)**. To complete the task, you will create an object with two methods, `encode` and `decode`. (For non-JavaScript versions, you only need to write the two functions without the enclosing dict)
Input
The encode method will receive two arguments — a positive integer n and a string value.
The decode method will receive one argument — a string value.
Output
Each method will return a string value.
How It Works
Encoding and decoding are done by performing a series of character and substring rotations on a string input.
Encoding: The number of rotations is determined by the value of n. The sequence of rotations is applied in the following order:
Step 1: remove all spaces in the string (but remember their positions)
Step 2: shift the order of characters in the new string to the right by n characters
Step 3: put the spaces back in their original positions
Step 4: shift the characters of each substring (separated by one or more consecutive spaces) to the right by n
Repeat this process until it has been completed n times in total.
The value n is then prepended to the resulting string with a space.
Decoding: Decoding simply reverses the encoding process.
Test Example
```python
quote = 'If you wish to make an apple pie from scratch, you must first invent the universe.'
solution = '10 hu fmo a,ys vi utie mr snehn rni tvte .ysushou teI fwea pmapi apfrok rei tnocsclet'
IterativeRotationCipher['encode'](10,quote) == solution; //True
'''Step-by-step breakdown:
Step 1 — remove all spaces:
'Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventtheuniverse.'
Step 2 — shift the order of string characters to the right by 10:
'euniverse.Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventth'
Step 3 — place the spaces back in their original positions:
'eu niv erse .I fyou wi shtom ake anap plepiefr oms crat ch,yo umustf irs tinventth'
Step 4 — shift the order of characters for each space-separated substring to the right by 10:
'eu vni seer .I oufy wi shtom eak apan frplepie som atcr ch,yo ustfum sir htinventt'
Repeat the steps 9 more times before returning the string with '10 ' prepended.
'''
```
Technical Details
- Input will always be valid.
- The characters used in the strings include any combination of alphanumeric characters, the space character, the newline character, and any of the following: `_!@#$%^&()[]{}+-*/="'<>,.?:;`.
If you enjoyed this kata, be sure to check out [my other katas](https://www.codewars.com/users/docgunthrop/authored).
|
def encode(n,strng):
new_strng = strng.split(" ")
for i in range(n):
strng = "".join(strng.split(" "))
strng = strng[-n:] + strng[:-n]
index_0 = 0
for i in range(len(new_strng)):
index = len(new_strng[i]) + index_0
new_strng[i] = strng[index_0:index]
index_0 = index
strng = ""
for i in new_strng:
change = n % len(i) if len(i) != 0 else i.count(" ")
strng += i[-change:] + i[:-change] + " "
strng = strng[:-1]
return f"{n} " + strng
def decode(strng):
i = 0
num = ""
while strng[i].isdigit():
num += strng[i]
i += 1
num = int("".join(num))
strng = strng[len(str(num))+1:]
new_strng = strng.split(" ")
strng = "".join(strng.split(" "))
for i in range(num):
index_0 = 0
for i in range(len(new_strng)):
index = len(new_strng[i]) + index_0
new_strng[i] = strng[index_0:index]
index_0 = index
strng = ""
for i in new_strng:
change = num % len(i) if len(i) != 0 else i.count(" ")
strng += i[change:] + i[:change]
strng = strng[num:] + strng[:num]
index_0 = 0
for i in range(len(new_strng)):
index = len(new_strng[i]) + index_0
new_strng[i] = strng[index_0:index]
index_0 = index
return " ".join(new_strng)
|
In this kata, your task is to implement what I call **Iterative Rotation Cipher (IRC)**. To complete the task, you will create an object with two methods, `encode` and `decode`. (For non-JavaScript versions, you only need to write the two functions without the enclosing dict)
Input
The encode method will receive two arguments — a positive integer n and a string value.
The decode method will receive one argument — a string value.
Output
Each method will return a string value.
How It Works
Encoding and decoding are done by performing a series of character and substring rotations on a string input.
Encoding: The number of rotations is determined by the value of n. The sequence of rotations is applied in the following order:
Step 1: remove all spaces in the string (but remember their positions)
Step 2: shift the order of characters in the new string to the right by n characters
Step 3: put the spaces back in their original positions
Step 4: shift the characters of each substring (separated by one or more consecutive spaces) to the right by n
Repeat this process until it has been completed n times in total.
The value n is then prepended to the resulting string with a space.
Decoding: Decoding simply reverses the encoding process.
Test Example
```python
quote = 'If you wish to make an apple pie from scratch, you must first invent the universe.'
solution = '10 hu fmo a,ys vi utie mr snehn rni tvte .ysushou teI fwea pmapi apfrok rei tnocsclet'
IterativeRotationCipher['encode'](10,quote) == solution; //True
'''Step-by-step breakdown:
Step 1 — remove all spaces:
'Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventtheuniverse.'
Step 2 — shift the order of string characters to the right by 10:
'euniverse.Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventth'
Step 3 — place the spaces back in their original positions:
'eu niv erse .I fyou wi shtom ake anap plepiefr oms crat ch,yo umustf irs tinventth'
Step 4 — shift the order of characters for each space-separated substring to the right by 10:
'eu vni seer .I oufy wi shtom eak apan frplepie som atcr ch,yo ustfum sir htinventt'
Repeat the steps 9 more times before returning the string with '10 ' prepended.
'''
```
Technical Details
- Input will always be valid.
- The characters used in the strings include any combination of alphanumeric characters, the space character, the newline character, and any of the following: `_!@#$%^&()[]{}+-*/="'<>,.?:;`.
If you enjoyed this kata, be sure to check out [my other katas](https://www.codewars.com/users/docgunthrop/authored).
|
from collections import deque
from itertools import chain, count
def _code(n, s, sign):
non_space, offset = [], count()
slice_points = [0,] + [
i - (0 if c != ' ' else next(offset))
for i, c in enumerate(s)
if c == ' ' or non_space.append(c)
] + [len(s),]
slices = [slice(start, end) for start, end in zip(slice_points, slice_points[1:])]
ops = ([slice(None),] * (sign == 1) + slices + [slice(None),] * (sign == -1)) * n
for op in ops:
d = deque(non_space[op])
d.rotate(sign * n)
non_space[op] = d
return ' '.join(''.join(non_space[x]) for x in slices)
def encode(n, s):
ciphered = _code(n, s, 1)
return f'{n} {ciphered}'
def decode(s):
n, s = s.split(' ', 1)
return _code(int(n), s, -1)
|
In this kata, your task is to implement what I call **Iterative Rotation Cipher (IRC)**. To complete the task, you will create an object with two methods, `encode` and `decode`. (For non-JavaScript versions, you only need to write the two functions without the enclosing dict)
Input
The encode method will receive two arguments — a positive integer n and a string value.
The decode method will receive one argument — a string value.
Output
Each method will return a string value.
How It Works
Encoding and decoding are done by performing a series of character and substring rotations on a string input.
Encoding: The number of rotations is determined by the value of n. The sequence of rotations is applied in the following order:
Step 1: remove all spaces in the string (but remember their positions)
Step 2: shift the order of characters in the new string to the right by n characters
Step 3: put the spaces back in their original positions
Step 4: shift the characters of each substring (separated by one or more consecutive spaces) to the right by n
Repeat this process until it has been completed n times in total.
The value n is then prepended to the resulting string with a space.
Decoding: Decoding simply reverses the encoding process.
Test Example
```python
quote = 'If you wish to make an apple pie from scratch, you must first invent the universe.'
solution = '10 hu fmo a,ys vi utie mr snehn rni tvte .ysushou teI fwea pmapi apfrok rei tnocsclet'
IterativeRotationCipher['encode'](10,quote) == solution; //True
'''Step-by-step breakdown:
Step 1 — remove all spaces:
'Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventtheuniverse.'
Step 2 — shift the order of string characters to the right by 10:
'euniverse.Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventth'
Step 3 — place the spaces back in their original positions:
'eu niv erse .I fyou wi shtom ake anap plepiefr oms crat ch,yo umustf irs tinventth'
Step 4 — shift the order of characters for each space-separated substring to the right by 10:
'eu vni seer .I oufy wi shtom eak apan frplepie som atcr ch,yo ustfum sir htinventt'
Repeat the steps 9 more times before returning the string with '10 ' prepended.
'''
```
Technical Details
- Input will always be valid.
- The characters used in the strings include any combination of alphanumeric characters, the space character, the newline character, and any of the following: `_!@#$%^&()[]{}+-*/="'<>,.?:;`.
If you enjoyed this kata, be sure to check out [my other katas](https://www.codewars.com/users/docgunthrop/authored).
|
import re
from collections import deque
def encode(n,s):
s = s.replace('\n', '`')
for i in range(n):
pos, s = get_pos(s), deque(s.replace(' ', ''))
deque.rotate(s, n)
s = rotate(set_pos(s,pos),n,1)
return str(n) + ' ' + s.replace('`','\n')
def decode(s):
n, s = re.search(r'^\d+', s).group(), s.replace('\n','`')
s, n = s[len(n) + 1:], int(n)
for i in range(n):
pos, s = get_pos(s), deque(''.join(deque(rotate(s,n,-1))).replace(' ', ''))
deque.rotate(s, -n)
s = ''.join(set_pos(s,pos))
return s.replace('`','\n')
get_pos = lambda s: [l for l, j in enumerate(s) if j == ' ']
def rotate(s,n,c):
li = []
for k in re.findall(r'(.+?)(\s+)|(.+$)', ''.join(s)):
t = deque(k[0] or k[-1]) ; deque.rotate(t, n*c)
li.append(''.join(t) + k[1])
return ''.join(li)
def set_pos(s,position):
for pos in position : s.insert(pos, ' ')
return s
|
In this kata, your task is to implement what I call **Iterative Rotation Cipher (IRC)**. To complete the task, you will create an object with two methods, `encode` and `decode`. (For non-JavaScript versions, you only need to write the two functions without the enclosing dict)
Input
The encode method will receive two arguments — a positive integer n and a string value.
The decode method will receive one argument — a string value.
Output
Each method will return a string value.
How It Works
Encoding and decoding are done by performing a series of character and substring rotations on a string input.
Encoding: The number of rotations is determined by the value of n. The sequence of rotations is applied in the following order:
Step 1: remove all spaces in the string (but remember their positions)
Step 2: shift the order of characters in the new string to the right by n characters
Step 3: put the spaces back in their original positions
Step 4: shift the characters of each substring (separated by one or more consecutive spaces) to the right by n
Repeat this process until it has been completed n times in total.
The value n is then prepended to the resulting string with a space.
Decoding: Decoding simply reverses the encoding process.
Test Example
```python
quote = 'If you wish to make an apple pie from scratch, you must first invent the universe.'
solution = '10 hu fmo a,ys vi utie mr snehn rni tvte .ysushou teI fwea pmapi apfrok rei tnocsclet'
IterativeRotationCipher['encode'](10,quote) == solution; //True
'''Step-by-step breakdown:
Step 1 — remove all spaces:
'Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventtheuniverse.'
Step 2 — shift the order of string characters to the right by 10:
'euniverse.Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventth'
Step 3 — place the spaces back in their original positions:
'eu niv erse .I fyou wi shtom ake anap plepiefr oms crat ch,yo umustf irs tinventth'
Step 4 — shift the order of characters for each space-separated substring to the right by 10:
'eu vni seer .I oufy wi shtom eak apan frplepie som atcr ch,yo ustfum sir htinventt'
Repeat the steps 9 more times before returning the string with '10 ' prepended.
'''
```
Technical Details
- Input will always be valid.
- The characters used in the strings include any combination of alphanumeric characters, the space character, the newline character, and any of the following: `_!@#$%^&()[]{}+-*/="'<>,.?:;`.
If you enjoyed this kata, be sure to check out [my other katas](https://www.codewars.com/users/docgunthrop/authored).
|
def encode(n,s):
for i in range(n):
s =''.join(space(re(''.join([decore(e, n)for e in space(re(decore(s.replace(' ',''),n)),ws(s)).split(' ')])),ws(s)))
return str(n)+' '+s
def decode(s):
n, s = s.split(' ', 1)
n, sps = int(n), ws(s)
for i in range(n):
s = ''.join(space(re(decore(''.join([decore(e,-n)for e in s.split(' ')]),-n)),sps))
return s
def space(stg, arr):
for i in arr: stg.insert(i, ' ')
return ''.join(stg)
def decore(code, key):
l = (len(code) or 1)
i = key % l
return code[-i:] + code[:-i]
ws = lambda s: [ i for i,e in enumerate(s) if e ==' ']
re = lambda l: [e for e in l]
|
In this kata, your task is to implement what I call **Iterative Rotation Cipher (IRC)**. To complete the task, you will create an object with two methods, `encode` and `decode`. (For non-JavaScript versions, you only need to write the two functions without the enclosing dict)
Input
The encode method will receive two arguments — a positive integer n and a string value.
The decode method will receive one argument — a string value.
Output
Each method will return a string value.
How It Works
Encoding and decoding are done by performing a series of character and substring rotations on a string input.
Encoding: The number of rotations is determined by the value of n. The sequence of rotations is applied in the following order:
Step 1: remove all spaces in the string (but remember their positions)
Step 2: shift the order of characters in the new string to the right by n characters
Step 3: put the spaces back in their original positions
Step 4: shift the characters of each substring (separated by one or more consecutive spaces) to the right by n
Repeat this process until it has been completed n times in total.
The value n is then prepended to the resulting string with a space.
Decoding: Decoding simply reverses the encoding process.
Test Example
```python
quote = 'If you wish to make an apple pie from scratch, you must first invent the universe.'
solution = '10 hu fmo a,ys vi utie mr snehn rni tvte .ysushou teI fwea pmapi apfrok rei tnocsclet'
IterativeRotationCipher['encode'](10,quote) == solution; //True
'''Step-by-step breakdown:
Step 1 — remove all spaces:
'Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventtheuniverse.'
Step 2 — shift the order of string characters to the right by 10:
'euniverse.Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventth'
Step 3 — place the spaces back in their original positions:
'eu niv erse .I fyou wi shtom ake anap plepiefr oms crat ch,yo umustf irs tinventth'
Step 4 — shift the order of characters for each space-separated substring to the right by 10:
'eu vni seer .I oufy wi shtom eak apan frplepie som atcr ch,yo ustfum sir htinventt'
Repeat the steps 9 more times before returning the string with '10 ' prepended.
'''
```
Technical Details
- Input will always be valid.
- The characters used in the strings include any combination of alphanumeric characters, the space character, the newline character, and any of the following: `_!@#$%^&()[]{}+-*/="'<>,.?:;`.
If you enjoyed this kata, be sure to check out [my other katas](https://www.codewars.com/users/docgunthrop/authored).
|
def rotate(n, s):
i = -n % len(s) if len(s) > 0 else 1
return s[i:] + s[:i]
def cipher(n, s):
sp = [i for i, c in enumerate(s) if c == " "] + [len(s)]
s = s.split(' ')
if n < 0:
s = [rotate(n, w) for w in s]
s = rotate(n, ''.join(s))
s = [s[i+1-x:j-x] for x, (i, j) in enumerate(zip([-1] + sp, sp))]
if n > 0:
s = [rotate(n, w) for w in s]
return ' '.join(s)
def encode(n, strng):
s = strng
for _ in range(n):
s = cipher(n, s)
return "{} {}".format(n, s)
def decode(strng):
n, s = strng.split(" ", 1)
n = int(n)
for _ in range(n):
s = cipher(-n, s)
return s
|
# Story
Those pesky rats have returned and this time they have taken over the Town Square.
The Pied Piper has been enlisted again to play his magical tune and coax all the rats towards him.
But some of the rats are deaf and are going the wrong way!
# Kata Task
How many deaf rats are there?
## Input Notes
* The Town Square is a rectangle of square paving stones (the Square has 1-15 pavers per side)
* The Pied Piper is always present
## Output Notes
* Deaf rats are those that are moving to paving stone **further away** from the Piper than where they are now
* Use Euclidian distance for your calculations
## Legend
* `P` = The Pied Piper
* `←` `↑` `→` `↓` `↖` `↗` `↘` `↙` = Rats going in different directions
* space = Everything else
# Examples
ex1 - has 1 deaf rat
↗ P
↘ ↖
↑
↗
---
ex2 - has 7 deaf rats
↗
P ↓ ↖ ↑
← ↓
↖ ↙ ↙
↓ ↓ ↓
|
from math import hypot
DIRS = {'←': (0,-1), '↑': (-1,0), '→': (0,1), '↓': (1,0),
'↖': (-1,-1), '↗': (-1,1), '↘': (1,1), '↙': (1,-1)}
def count_deaf_rats(town):
pipper = next( (x,y) for x,r in enumerate(town) for y,c in enumerate(r) if c=='P')
return sum( isDeaf(pipper, x,y, *DIRS[c])
for x,r in enumerate(town) for y,c in enumerate(r)
if c in DIRS )
def isDeaf(pipper,x,y,dx,dy):
dCurrent, dNext = (hypot(*(a-b for a,b in zip(pipper,pos))) for pos in ((x,y),(x+dx,y+dy)))
return dCurrent < dNext
|
# Story
Those pesky rats have returned and this time they have taken over the Town Square.
The Pied Piper has been enlisted again to play his magical tune and coax all the rats towards him.
But some of the rats are deaf and are going the wrong way!
# Kata Task
How many deaf rats are there?
## Input Notes
* The Town Square is a rectangle of square paving stones (the Square has 1-15 pavers per side)
* The Pied Piper is always present
## Output Notes
* Deaf rats are those that are moving to paving stone **further away** from the Piper than where they are now
* Use Euclidian distance for your calculations
## Legend
* `P` = The Pied Piper
* `←` `↑` `→` `↓` `↖` `↗` `↘` `↙` = Rats going in different directions
* space = Everything else
# Examples
ex1 - has 1 deaf rat
↗ P
↘ ↖
↑
↗
---
ex2 - has 7 deaf rats
↗
P ↓ ↖ ↑
← ↓
↖ ↙ ↙
↓ ↓ ↓
|
from math import copysign
directions = {
'←': (0, -1),
'↑': (-1, 0),
'→': (0, 1),
'↓': (1, 0),
'↖': (-1, -1),
'↗': (-1, 1),
'↘': (1, 1),
'↙': (1, -1),
}
def count_deaf_rats(town_square):
pi, pj = next((i,j) for i, row in enumerate(town_square) for j, x in enumerate(row) if x == 'P')
result = 0
for i, row in enumerate(town_square):
for j, x in enumerate(row):
if x not in directions:
continue
di, dj = directions[x]
if (i+di-pi)**2 + (j+dj-pj)**2 > (i-pi)**2 + (j-pj)**2:
result += 1
return result
|
# Story
Those pesky rats have returned and this time they have taken over the Town Square.
The Pied Piper has been enlisted again to play his magical tune and coax all the rats towards him.
But some of the rats are deaf and are going the wrong way!
# Kata Task
How many deaf rats are there?
## Input Notes
* The Town Square is a rectangle of square paving stones (the Square has 1-15 pavers per side)
* The Pied Piper is always present
## Output Notes
* Deaf rats are those that are moving to paving stone **further away** from the Piper than where they are now
* Use Euclidian distance for your calculations
## Legend
* `P` = The Pied Piper
* `←` `↑` `→` `↓` `↖` `↗` `↘` `↙` = Rats going in different directions
* space = Everything else
# Examples
ex1 - has 1 deaf rat
↗ P
↘ ↖
↑
↗
---
ex2 - has 7 deaf rats
↗
P ↓ ↖ ↑
← ↓
↖ ↙ ↙
↓ ↓ ↓
|
D = {
'↖': -1 -1j, '↑': -1, '↗': -1 +1j,
'←': -1j, '→': +1j,
'↙': +1 -1j, '↓': +1, '↘': +1 +1j,
}
def count_deaf_rats(town_square):
coords = [(i + j * 1j, x) for i, row in enumerate(town_square) for j, x in enumerate(row)]
p = next(c for c, x in coords if x == 'P')
return sum(abs(c+D.get(x, 0)-p) > abs(c-p) for c, x in coords)
|
# Story
Those pesky rats have returned and this time they have taken over the Town Square.
The Pied Piper has been enlisted again to play his magical tune and coax all the rats towards him.
But some of the rats are deaf and are going the wrong way!
# Kata Task
How many deaf rats are there?
## Input Notes
* The Town Square is a rectangle of square paving stones (the Square has 1-15 pavers per side)
* The Pied Piper is always present
## Output Notes
* Deaf rats are those that are moving to paving stone **further away** from the Piper than where they are now
* Use Euclidian distance for your calculations
## Legend
* `P` = The Pied Piper
* `←` `↑` `→` `↓` `↖` `↗` `↘` `↙` = Rats going in different directions
* space = Everything else
# Examples
ex1 - has 1 deaf rat
↗ P
↘ ↖
↑
↗
---
ex2 - has 7 deaf rats
↗
P ↓ ↖ ↑
← ↓
↖ ↙ ↙
↓ ↓ ↓
|
from math import hypot
moves = {"↖": (-1, -1), "←": (-1, 0), "↙": (-1, 1), "↑": (0, -1), "↓": (0, 1), "↗": (1, -1), "→": (1, 0), "↘": (1, 1)}
def count_deaf_rats(town_square):
deaf, (px, py) = 0, next((row.index("P"), y) for y, row in enumerate(town_square) if "P" in row)
dist = lambda x, y: hypot(px-x, py-y)
for y, row in enumerate(town_square):
for x, c in enumerate(row):
if c in moves:
mx, my = moves[c]
if dist(x, y) < dist(x+mx, y+my):
deaf += 1
return deaf
|
# Story
Those pesky rats have returned and this time they have taken over the Town Square.
The Pied Piper has been enlisted again to play his magical tune and coax all the rats towards him.
But some of the rats are deaf and are going the wrong way!
# Kata Task
How many deaf rats are there?
## Input Notes
* The Town Square is a rectangle of square paving stones (the Square has 1-15 pavers per side)
* The Pied Piper is always present
## Output Notes
* Deaf rats are those that are moving to paving stone **further away** from the Piper than where they are now
* Use Euclidian distance for your calculations
## Legend
* `P` = The Pied Piper
* `←` `↑` `→` `↓` `↖` `↗` `↘` `↙` = Rats going in different directions
* space = Everything else
# Examples
ex1 - has 1 deaf rat
↗ P
↘ ↖
↑
↗
---
ex2 - has 7 deaf rats
↗
P ↓ ↖ ↑
← ↓
↖ ↙ ↙
↓ ↓ ↓
|
import math
class Position:
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self, other):
return math.hypot(self.x - other.x, self.y - other.y)
Direction = {
'←': lambda position: Position(position.x - 1, position.y),
'↑': lambda position: Position(position.x, position.y - 1),
'→': lambda position: Position(position.x + 1, position.y),
'↓': lambda position: Position(position.x, position.y + 1),
'↖': lambda position: Position(position.x - 1, position.y - 1),
'↗': lambda position: Position(position.x + 1, position.y - 1),
'↘': lambda position: Position(position.x + 1, position.y + 1),
'↙': lambda position: Position(position.x - 1, position.y + 1)
}
PIEP_PIPER = 'P'
class Rat:
def __init__(self, position, move):
self.position = position
self.move = move
def is_deaf(self, piper):
current_distance = piper.distance(self.position)
distance_after_one_step = piper.distance(self.move(self.position))
return current_distance - distance_after_one_step < 0
def count_deaf_rats(town_square):
rats = []
piper = None
for y, line in enumerate(town_square):
for x, cell in enumerate(line):
if cell in Direction:
rats.append(Rat(Position(x, y), Direction[cell]))
elif cell == PIEP_PIPER:
piper = Position(x, y)
return len([rat for rat in rats if rat.is_deaf(piper)])
|
# Story
Those pesky rats have returned and this time they have taken over the Town Square.
The Pied Piper has been enlisted again to play his magical tune and coax all the rats towards him.
But some of the rats are deaf and are going the wrong way!
# Kata Task
How many deaf rats are there?
## Input Notes
* The Town Square is a rectangle of square paving stones (the Square has 1-15 pavers per side)
* The Pied Piper is always present
## Output Notes
* Deaf rats are those that are moving to paving stone **further away** from the Piper than where they are now
* Use Euclidian distance for your calculations
## Legend
* `P` = The Pied Piper
* `←` `↑` `→` `↓` `↖` `↗` `↘` `↙` = Rats going in different directions
* space = Everything else
# Examples
ex1 - has 1 deaf rat
↗ P
↘ ↖
↑
↗
---
ex2 - has 7 deaf rats
↗
P ↓ ↖ ↑
← ↓
↖ ↙ ↙
↓ ↓ ↓
|
def count_deaf_rats(board):
o, p = next([i, j] for i, l in enumerate(board) for j, k in enumerate(l) if board[i][j] == 'P')
distance = lambda x,y:((o - x) ** 2 + (p - y) ** 2) ** 0.5
d = {'←':(0, -1), '↑':(-1, 0), '→':(0, 1), '↓':(1, 0), '↖':(-1, -1), '↗':(-1, 1), '↘':(1, 1), '↙':(1, -1)}
return sum(distance(i + d[l][0], k + d[l][1]) > distance(i,k) for i,j in enumerate(board) for k,l in enumerate(j) if l in "←↑→↓↖↗↘↙")
|
# Story
Those pesky rats have returned and this time they have taken over the Town Square.
The Pied Piper has been enlisted again to play his magical tune and coax all the rats towards him.
But some of the rats are deaf and are going the wrong way!
# Kata Task
How many deaf rats are there?
## Input Notes
* The Town Square is a rectangle of square paving stones (the Square has 1-15 pavers per side)
* The Pied Piper is always present
## Output Notes
* Deaf rats are those that are moving to paving stone **further away** from the Piper than where they are now
* Use Euclidian distance for your calculations
## Legend
* `P` = The Pied Piper
* `←` `↑` `→` `↓` `↖` `↗` `↘` `↙` = Rats going in different directions
* space = Everything else
# Examples
ex1 - has 1 deaf rat
↗ P
↘ ↖
↑
↗
---
ex2 - has 7 deaf rats
↗
P ↓ ↖ ↑
← ↓
↖ ↙ ↙
↓ ↓ ↓
|
from math import hypot
DIRS = {'←': (0,-1), '↑': (-1,0), '→': (0,1), '↓': (1,0),
'↖': (-1,-1), '↗': (-1,1), '↘': (1,1), '↙': (1,-1)}
def count_deaf_rats(town):
pipper = next( (x,y) for x,r in enumerate(town) for y,c in enumerate(r) if c=='P')
return sum( isDeaf(pipper, x,y, *DIRS[c])
for x,r in enumerate(town) for y,c in enumerate(r)
if c in DIRS )
def isDeaf(pipper,x,y,dx,dy):
dPipper, dNext = (hypot(*(a-b for a,b in zip(pipper,pos))) for pos in ((x,y),(x+dx,y+dy)))
return dPipper < dNext
|
# Story
Those pesky rats have returned and this time they have taken over the Town Square.
The Pied Piper has been enlisted again to play his magical tune and coax all the rats towards him.
But some of the rats are deaf and are going the wrong way!
# Kata Task
How many deaf rats are there?
## Input Notes
* The Town Square is a rectangle of square paving stones (the Square has 1-15 pavers per side)
* The Pied Piper is always present
## Output Notes
* Deaf rats are those that are moving to paving stone **further away** from the Piper than where they are now
* Use Euclidian distance for your calculations
## Legend
* `P` = The Pied Piper
* `←` `↑` `→` `↓` `↖` `↗` `↘` `↙` = Rats going in different directions
* space = Everything else
# Examples
ex1 - has 1 deaf rat
↗ P
↘ ↖
↑
↗
---
ex2 - has 7 deaf rats
↗
P ↓ ↖ ↑
← ↓
↖ ↙ ↙
↓ ↓ ↓
|
deltas = dict(zip("←↑→↓↖↗↘↙", (-1,-1j,1,1j,-1-1j,1-1j,1+1j,-1+1j)))
def count_deaf_rats(town_square):
ii,jj = list(range(len(town_square[0]))),list(range(len(town_square)))
p = next(complex(i,j) for i in ii for j in jj if town_square[j][i] == "P")
return sum( abs(ij+d-p) > abs(ij-p) for ij,d in
((complex(i,j),deltas.get(town_square[j][i],0)) for j in jj for i in ii) )
|
# Story
Those pesky rats have returned and this time they have taken over the Town Square.
The Pied Piper has been enlisted again to play his magical tune and coax all the rats towards him.
But some of the rats are deaf and are going the wrong way!
# Kata Task
How many deaf rats are there?
## Input Notes
* The Town Square is a rectangle of square paving stones (the Square has 1-15 pavers per side)
* The Pied Piper is always present
## Output Notes
* Deaf rats are those that are moving to paving stone **further away** from the Piper than where they are now
* Use Euclidian distance for your calculations
## Legend
* `P` = The Pied Piper
* `←` `↑` `→` `↓` `↖` `↗` `↘` `↙` = Rats going in different directions
* space = Everything else
# Examples
ex1 - has 1 deaf rat
↗ P
↘ ↖
↑
↗
---
ex2 - has 7 deaf rats
↗
P ↓ ↖ ↑
← ↓
↖ ↙ ↙
↓ ↓ ↓
|
rat_dirs = {
'←': (-1, 0),
'↑': (0, -1),
'→': (1, 0),
'↓': (0, 1),
'↖': (-1, -1),
'↗': (1, -1),
'↘': (1, 1),
'↙': (-1, 1)
}
def find_piper(town_square, width, height):
for y in range(height):
for x in range(width):
if town_square[y][x] == 'P':
return x, y
return -1, -1
def is_rat_deaf(rx, ry, px, py, c):
dx, dy = px - rx, py - ry
cx, cy = rat_dirs[c]
return cx * dx + cy * dy <= 0
def count_deaf_rats(town_square):
width, height = len(town_square[0]), len(town_square)
px, py = find_piper(town_square, width, height)
num_deaf = 0
for y in range(height):
for x in range(width):
c = town_square[y][x]
if c in rat_dirs and is_rat_deaf(x, y, px, py, c):
num_deaf += 1
return num_deaf
|
# Story
Those pesky rats have returned and this time they have taken over the Town Square.
The Pied Piper has been enlisted again to play his magical tune and coax all the rats towards him.
But some of the rats are deaf and are going the wrong way!
# Kata Task
How many deaf rats are there?
## Input Notes
* The Town Square is a rectangle of square paving stones (the Square has 1-15 pavers per side)
* The Pied Piper is always present
## Output Notes
* Deaf rats are those that are moving to paving stone **further away** from the Piper than where they are now
* Use Euclidian distance for your calculations
## Legend
* `P` = The Pied Piper
* `←` `↑` `→` `↓` `↖` `↗` `↘` `↙` = Rats going in different directions
* space = Everything else
# Examples
ex1 - has 1 deaf rat
↗ P
↘ ↖
↑
↗
---
ex2 - has 7 deaf rats
↗
P ↓ ↖ ↑
← ↓
↖ ↙ ↙
↓ ↓ ↓
|
def count_deaf_rats(a):
d = [(i, j) for i in range(-1, 2) for j in range(-1, 2) if i or j]
d = {x:d[i] for i, x in enumerate("↖↑↗←→↙↓↘")}
p, r = divmod("".join(a).index("P"), len(a[0])), 0
for i, x in enumerate(a):
for j, y in enumerate(x):
if y not in " P":
z = d[y]
n = abs(i - p[0] + (j - p[1]) * 1j)
m = abs(i + z[0] - p[0] + (j + z[1] - p[1]) * 1j)
if n < m: r += 1
return r
|
#Sort the columns of a csv-file
You get a string with the content of a csv-file. The columns are separated by semicolons.
The first line contains the names of the columns.
Write a method that sorts the columns by the names of the columns alphabetically and incasesensitive.
An example:
```
Before sorting:
As table (only visualization):
|myjinxin2015|raulbc777|smile67|Dentzil|SteffenVogel_79|
|17945 |10091 |10088 |3907 |10132 |
|2 |12 |13 |48 |11 |
The csv-file:
myjinxin2015;raulbc777;smile67;Dentzil;SteffenVogel_79\n
17945;10091;10088;3907;10132\n
2;12;13;48;11
----------------------------------
After sorting:
As table (only visualization):
|Dentzil|myjinxin2015|raulbc777|smile67|SteffenVogel_79|
|3907 |17945 |10091 |10088 |10132 |
|48 |2 |12 |13 |11 |
The csv-file:
Dentzil;myjinxin2015;raulbc777;smile67;SteffenVogel_79\n
3907;17945;10091;10088;10132\n
48;2;12;13;11
```
There is no need for prechecks. You will always get a correct string with more than 1 line und more than 1 row. All columns will have different names.
Have fun coding it and please don't forget to vote and rank this kata! :-)
I have created other katas. Have a look if you like coding and challenges.
|
def sort_csv_columns(csv_file_content, sep=';', end='\n'):
'''Sort a CSV file by column name.'''
csv_columns = zip(*(row.split(sep) for row in csv_file_content.split(end)))
sorted_columns = sorted(csv_columns, key=lambda col: col[0].lower())
return end.join(sep.join(row) for row in zip(*sorted_columns))
|
#Sort the columns of a csv-file
You get a string with the content of a csv-file. The columns are separated by semicolons.
The first line contains the names of the columns.
Write a method that sorts the columns by the names of the columns alphabetically and incasesensitive.
An example:
```
Before sorting:
As table (only visualization):
|myjinxin2015|raulbc777|smile67|Dentzil|SteffenVogel_79|
|17945 |10091 |10088 |3907 |10132 |
|2 |12 |13 |48 |11 |
The csv-file:
myjinxin2015;raulbc777;smile67;Dentzil;SteffenVogel_79\n
17945;10091;10088;3907;10132\n
2;12;13;48;11
----------------------------------
After sorting:
As table (only visualization):
|Dentzil|myjinxin2015|raulbc777|smile67|SteffenVogel_79|
|3907 |17945 |10091 |10088 |10132 |
|48 |2 |12 |13 |11 |
The csv-file:
Dentzil;myjinxin2015;raulbc777;smile67;SteffenVogel_79\n
3907;17945;10091;10088;10132\n
48;2;12;13;11
```
There is no need for prechecks. You will always get a correct string with more than 1 line und more than 1 row. All columns will have different names.
Have fun coding it and please don't forget to vote and rank this kata! :-)
I have created other katas. Have a look if you like coding and challenges.
|
def sort_csv_columns(csv_file_content):
return '\n'.join(';'.join(sorted_row) for sorted_row in zip(*sorted(
(zip(*(row.split(';') for row in csv_file_content.split('\n')))),
key=lambda col: col[0].lower()
)))
|
#Sort the columns of a csv-file
You get a string with the content of a csv-file. The columns are separated by semicolons.
The first line contains the names of the columns.
Write a method that sorts the columns by the names of the columns alphabetically and incasesensitive.
An example:
```
Before sorting:
As table (only visualization):
|myjinxin2015|raulbc777|smile67|Dentzil|SteffenVogel_79|
|17945 |10091 |10088 |3907 |10132 |
|2 |12 |13 |48 |11 |
The csv-file:
myjinxin2015;raulbc777;smile67;Dentzil;SteffenVogel_79\n
17945;10091;10088;3907;10132\n
2;12;13;48;11
----------------------------------
After sorting:
As table (only visualization):
|Dentzil|myjinxin2015|raulbc777|smile67|SteffenVogel_79|
|3907 |17945 |10091 |10088 |10132 |
|48 |2 |12 |13 |11 |
The csv-file:
Dentzil;myjinxin2015;raulbc777;smile67;SteffenVogel_79\n
3907;17945;10091;10088;10132\n
48;2;12;13;11
```
There is no need for prechecks. You will always get a correct string with more than 1 line und more than 1 row. All columns will have different names.
Have fun coding it and please don't forget to vote and rank this kata! :-)
I have created other katas. Have a look if you like coding and challenges.
|
def sort_csv_columns(csv_file_content):
array = (line.split(";") for line in csv_file_content.split("\n"))
trans = list(zip(*array))
sortd = sorted(trans, key=lambda col: col[0].lower())
untrans = list(zip(*sortd))
return "\n".join(";".join(line) for line in untrans)
# ugly one-liner
#return "\n".join(";".join(t) for t in zip(*sorted(zip(*(line.split(";") for line in csv_file_content.split("\n"))), key=lambda t: t[0].lower())))
|
#Sort the columns of a csv-file
You get a string with the content of a csv-file. The columns are separated by semicolons.
The first line contains the names of the columns.
Write a method that sorts the columns by the names of the columns alphabetically and incasesensitive.
An example:
```
Before sorting:
As table (only visualization):
|myjinxin2015|raulbc777|smile67|Dentzil|SteffenVogel_79|
|17945 |10091 |10088 |3907 |10132 |
|2 |12 |13 |48 |11 |
The csv-file:
myjinxin2015;raulbc777;smile67;Dentzil;SteffenVogel_79\n
17945;10091;10088;3907;10132\n
2;12;13;48;11
----------------------------------
After sorting:
As table (only visualization):
|Dentzil|myjinxin2015|raulbc777|smile67|SteffenVogel_79|
|3907 |17945 |10091 |10088 |10132 |
|48 |2 |12 |13 |11 |
The csv-file:
Dentzil;myjinxin2015;raulbc777;smile67;SteffenVogel_79\n
3907;17945;10091;10088;10132\n
48;2;12;13;11
```
There is no need for prechecks. You will always get a correct string with more than 1 line und more than 1 row. All columns will have different names.
Have fun coding it and please don't forget to vote and rank this kata! :-)
I have created other katas. Have a look if you like coding and challenges.
|
SEP = ';'
def sort_csv_columns(csv):
names = csv.split('\n', 1)[0].lower().split(SEP)
d = {names.index(c):i for i,c in enumerate(sorted(names))}
return '\n'.join(SEP.join(e[1] for e in sorted([(d[i], field) for i, field in enumerate(row.split(SEP))])) for row in csv.split('\n'))
|
#Sort the columns of a csv-file
You get a string with the content of a csv-file. The columns are separated by semicolons.
The first line contains the names of the columns.
Write a method that sorts the columns by the names of the columns alphabetically and incasesensitive.
An example:
```
Before sorting:
As table (only visualization):
|myjinxin2015|raulbc777|smile67|Dentzil|SteffenVogel_79|
|17945 |10091 |10088 |3907 |10132 |
|2 |12 |13 |48 |11 |
The csv-file:
myjinxin2015;raulbc777;smile67;Dentzil;SteffenVogel_79\n
17945;10091;10088;3907;10132\n
2;12;13;48;11
----------------------------------
After sorting:
As table (only visualization):
|Dentzil|myjinxin2015|raulbc777|smile67|SteffenVogel_79|
|3907 |17945 |10091 |10088 |10132 |
|48 |2 |12 |13 |11 |
The csv-file:
Dentzil;myjinxin2015;raulbc777;smile67;SteffenVogel_79\n
3907;17945;10091;10088;10132\n
48;2;12;13;11
```
There is no need for prechecks. You will always get a correct string with more than 1 line und more than 1 row. All columns will have different names.
Have fun coding it and please don't forget to vote and rank this kata! :-)
I have created other katas. Have a look if you like coding and challenges.
|
def sort_csv_columns(csv_file_content):
rows = csv_file_content.split('\n')
titles = rows[0].split(";")
order = sorted(range(len(titles)), key=lambda k: titles[k].lower())
newpages = []
for row in rows:
newpages.append(';'.join([row.split(";")[c] for c in order]))
return '\n'.join(newpages)
|
#Sort the columns of a csv-file
You get a string with the content of a csv-file. The columns are separated by semicolons.
The first line contains the names of the columns.
Write a method that sorts the columns by the names of the columns alphabetically and incasesensitive.
An example:
```
Before sorting:
As table (only visualization):
|myjinxin2015|raulbc777|smile67|Dentzil|SteffenVogel_79|
|17945 |10091 |10088 |3907 |10132 |
|2 |12 |13 |48 |11 |
The csv-file:
myjinxin2015;raulbc777;smile67;Dentzil;SteffenVogel_79\n
17945;10091;10088;3907;10132\n
2;12;13;48;11
----------------------------------
After sorting:
As table (only visualization):
|Dentzil|myjinxin2015|raulbc777|smile67|SteffenVogel_79|
|3907 |17945 |10091 |10088 |10132 |
|48 |2 |12 |13 |11 |
The csv-file:
Dentzil;myjinxin2015;raulbc777;smile67;SteffenVogel_79\n
3907;17945;10091;10088;10132\n
48;2;12;13;11
```
There is no need for prechecks. You will always get a correct string with more than 1 line und more than 1 row. All columns will have different names.
Have fun coding it and please don't forget to vote and rank this kata! :-)
I have created other katas. Have a look if you like coding and challenges.
|
# Not really needed but why not?
from csv import reader
def sort_csv_columns(csv_file_content):
return '\n'.join(map(';'.join, zip(*sorted(zip(*reader(csv_file_content.split('\n'), delimiter=";")), key=lambda x:x[0].lower()))))
|
#Sort the columns of a csv-file
You get a string with the content of a csv-file. The columns are separated by semicolons.
The first line contains the names of the columns.
Write a method that sorts the columns by the names of the columns alphabetically and incasesensitive.
An example:
```
Before sorting:
As table (only visualization):
|myjinxin2015|raulbc777|smile67|Dentzil|SteffenVogel_79|
|17945 |10091 |10088 |3907 |10132 |
|2 |12 |13 |48 |11 |
The csv-file:
myjinxin2015;raulbc777;smile67;Dentzil;SteffenVogel_79\n
17945;10091;10088;3907;10132\n
2;12;13;48;11
----------------------------------
After sorting:
As table (only visualization):
|Dentzil|myjinxin2015|raulbc777|smile67|SteffenVogel_79|
|3907 |17945 |10091 |10088 |10132 |
|48 |2 |12 |13 |11 |
The csv-file:
Dentzil;myjinxin2015;raulbc777;smile67;SteffenVogel_79\n
3907;17945;10091;10088;10132\n
48;2;12;13;11
```
There is no need for prechecks. You will always get a correct string with more than 1 line und more than 1 row. All columns will have different names.
Have fun coding it and please don't forget to vote and rank this kata! :-)
I have created other katas. Have a look if you like coding and challenges.
|
def sort_csv_columns(csv):
s = ''
res = sorted(zip(*[x.split(';') for x in csv.split('\n')]), key=lambda x: x[0].lower())
for i in range(len(res[-1])):
s += ';'.join(x[i] for x in res) + '\n'
return s.strip('\n')
|
#Sort the columns of a csv-file
You get a string with the content of a csv-file. The columns are separated by semicolons.
The first line contains the names of the columns.
Write a method that sorts the columns by the names of the columns alphabetically and incasesensitive.
An example:
```
Before sorting:
As table (only visualization):
|myjinxin2015|raulbc777|smile67|Dentzil|SteffenVogel_79|
|17945 |10091 |10088 |3907 |10132 |
|2 |12 |13 |48 |11 |
The csv-file:
myjinxin2015;raulbc777;smile67;Dentzil;SteffenVogel_79\n
17945;10091;10088;3907;10132\n
2;12;13;48;11
----------------------------------
After sorting:
As table (only visualization):
|Dentzil|myjinxin2015|raulbc777|smile67|SteffenVogel_79|
|3907 |17945 |10091 |10088 |10132 |
|48 |2 |12 |13 |11 |
The csv-file:
Dentzil;myjinxin2015;raulbc777;smile67;SteffenVogel_79\n
3907;17945;10091;10088;10132\n
48;2;12;13;11
```
There is no need for prechecks. You will always get a correct string with more than 1 line und more than 1 row. All columns will have different names.
Have fun coding it and please don't forget to vote and rank this kata! :-)
I have created other katas. Have a look if you like coding and challenges.
|
from collections import defaultdict
def sort_csv_columns(s):
d = defaultdict(list)
for i in s.splitlines():
for j, k in enumerate(i.split(";")):
d[j].append(k)
r = zip(*[i[1] for i in sorted(d.items(), key=lambda x:(x[1][0].lower(),x[1][0]))])
return "\n".join([";".join(i) for i in r])
|
#Sort the columns of a csv-file
You get a string with the content of a csv-file. The columns are separated by semicolons.
The first line contains the names of the columns.
Write a method that sorts the columns by the names of the columns alphabetically and incasesensitive.
An example:
```
Before sorting:
As table (only visualization):
|myjinxin2015|raulbc777|smile67|Dentzil|SteffenVogel_79|
|17945 |10091 |10088 |3907 |10132 |
|2 |12 |13 |48 |11 |
The csv-file:
myjinxin2015;raulbc777;smile67;Dentzil;SteffenVogel_79\n
17945;10091;10088;3907;10132\n
2;12;13;48;11
----------------------------------
After sorting:
As table (only visualization):
|Dentzil|myjinxin2015|raulbc777|smile67|SteffenVogel_79|
|3907 |17945 |10091 |10088 |10132 |
|48 |2 |12 |13 |11 |
The csv-file:
Dentzil;myjinxin2015;raulbc777;smile67;SteffenVogel_79\n
3907;17945;10091;10088;10132\n
48;2;12;13;11
```
There is no need for prechecks. You will always get a correct string with more than 1 line und more than 1 row. All columns will have different names.
Have fun coding it and please don't forget to vote and rank this kata! :-)
I have created other katas. Have a look if you like coding and challenges.
|
def sort_csv_columns(csv_file_content):
table = sorted(zip(*(row.split(';') for row in csv_file_content.split('\n'))), key=lambda col: col[0].lower())
return '\n'.join(';'.join(row) for row in zip(*table))
|
#Sort the columns of a csv-file
You get a string with the content of a csv-file. The columns are separated by semicolons.
The first line contains the names of the columns.
Write a method that sorts the columns by the names of the columns alphabetically and incasesensitive.
An example:
```
Before sorting:
As table (only visualization):
|myjinxin2015|raulbc777|smile67|Dentzil|SteffenVogel_79|
|17945 |10091 |10088 |3907 |10132 |
|2 |12 |13 |48 |11 |
The csv-file:
myjinxin2015;raulbc777;smile67;Dentzil;SteffenVogel_79\n
17945;10091;10088;3907;10132\n
2;12;13;48;11
----------------------------------
After sorting:
As table (only visualization):
|Dentzil|myjinxin2015|raulbc777|smile67|SteffenVogel_79|
|3907 |17945 |10091 |10088 |10132 |
|48 |2 |12 |13 |11 |
The csv-file:
Dentzil;myjinxin2015;raulbc777;smile67;SteffenVogel_79\n
3907;17945;10091;10088;10132\n
48;2;12;13;11
```
There is no need for prechecks. You will always get a correct string with more than 1 line und more than 1 row. All columns will have different names.
Have fun coding it and please don't forget to vote and rank this kata! :-)
I have created other katas. Have a look if you like coding and challenges.
|
import string
def sort_csv_columns(csv_file_content):
orderby=' _0123456789'+string.ascii_lowercase
l=list(zip(*[i.split(';') for i in csv_file_content.split('\n')]))
l.sort(key=lambda a:[orderby.index(i) for i in a[0].lower()])
return '\n'.join(';'.join(i) for i in zip(*l))
|
Many websites use weighted averages of various polls to make projections for elections. They’re weighted based on a variety of factors, such as historical accuracy of the polling firm, sample size, as well as date(s). The weights, in this kata, are already calculated for you. All you need to do is convert a set of polls with weights, into a fixed projection for the result.
#### Task:
Your job is to convert an array of candidates (variable name `candidates`) and an array of polls (variable name `polls`), each poll with two parts, a result and a weight, into a guess of the result, with each value rounded to one decimal place, through use of a weighted average. Weights can be zero! Don't worry about the sum not totalling 100. The final result should be a hash in Ruby and Crystal, dictionary in Python, or object in JS in the format shown below:
```python
{
"": "",
"": "",
...
}
For your convenience, a function named round1 has been defined for you. You can
use it to round to the nearest tenth correctly (due to the inaccuracy of round
and floats in general).
```
_The input should not be modified._
#### Calculation for projections:
```
[(poll1 * weight1) + (poll2 * weight2) + ...] / (weight1 + weight2 + ...)
```
#### An example:
```python
candidates = ['A', 'B', 'C']
poll1res = [20, 30, 50]
poll1wt = 1
poll1 = [poll1res, poll1wt]
poll2res = [40, 40, 20]
poll2wt = 0.5
poll2 = [poll2res, poll2wt]
poll3res = [50, 40, 10]
poll3wt = 2
poll3 = [poll3res, poll3wt]
polls = [poll1, poll2, poll3]
predict(candidates, polls)
#=> {
'A': 40,
'B': 37.1,
'C': 22.9
}
# because...
candidate 'A' weighted average
= ((20 * 1) + (40 * 0.5) + (50 * 2)) / (1 + 0.5 + 2)
= (20 + 20 + 100) / 3.5
= 140 / 3.5
= 40
candidate 'B' weighted average
= ((30 * 1) + (40 * 0.5) + (40 * 2)) / (1 + 0.5 + 2)
= (30 + 20 + 80) / 3.5
= 130 / 3.5
= 37.142857...
≈ 37.1 (round to nearest tenth)
candidate 'C' weighted average
= ((50 * 1) + (20 * 0.5) + (10 * 2)) / (1 + 0.5 + 2)
= (50 + 10 + 20) / 3.5
= 80 / 3.5
= 22.857142...
≈ 22.9 (round to nearest tenth)
```
Also check out my other creations — [Keep the Order](https://www.codewars.com/kata/keep-the-order), [Naming Files](https://www.codewars.com/kata/naming-files), [Square and Cubic Factors](https://www.codewars.com/kata/square-and-cubic-factors), [Identify Case](https://www.codewars.com/kata/identify-case), [Split Without Loss](https://www.codewars.com/kata/split-without-loss), [Adding Fractions](https://www.codewars.com/kata/adding-fractions),
[Random Integers](https://www.codewars.com/kata/random-integers), [Implement String#transpose](https://www.codewars.com/kata/implement-string-number-transpose), [Implement Array#transpose!](https://www.codewars.com/kata/implement-array-number-transpose), [Arrays and Procs #1](https://www.codewars.com/kata/arrays-and-procs-number-1), and [Arrays and Procs #2](https://www.codewars.com/kata/arrays-and-procs-number-2).
If you notice any issues or have any suggestions/comments whatsoever, please don't hesitate to mark an issue or just comment. Thanks!
|
def predict(candidates, polls):
x = zip(*[list(map(lambda i: i * weight, poll)) for poll, weight in polls])
x = list(map(round1, (map(lambda i: sum(i) / sum([i[1] for i in polls]), x))))
return dict(zip(candidates,x))
|
Many websites use weighted averages of various polls to make projections for elections. They’re weighted based on a variety of factors, such as historical accuracy of the polling firm, sample size, as well as date(s). The weights, in this kata, are already calculated for you. All you need to do is convert a set of polls with weights, into a fixed projection for the result.
#### Task:
Your job is to convert an array of candidates (variable name `candidates`) and an array of polls (variable name `polls`), each poll with two parts, a result and a weight, into a guess of the result, with each value rounded to one decimal place, through use of a weighted average. Weights can be zero! Don't worry about the sum not totalling 100. The final result should be a hash in Ruby and Crystal, dictionary in Python, or object in JS in the format shown below:
```python
{
"": "",
"": "",
...
}
For your convenience, a function named round1 has been defined for you. You can
use it to round to the nearest tenth correctly (due to the inaccuracy of round
and floats in general).
```
_The input should not be modified._
#### Calculation for projections:
```
[(poll1 * weight1) + (poll2 * weight2) + ...] / (weight1 + weight2 + ...)
```
#### An example:
```python
candidates = ['A', 'B', 'C']
poll1res = [20, 30, 50]
poll1wt = 1
poll1 = [poll1res, poll1wt]
poll2res = [40, 40, 20]
poll2wt = 0.5
poll2 = [poll2res, poll2wt]
poll3res = [50, 40, 10]
poll3wt = 2
poll3 = [poll3res, poll3wt]
polls = [poll1, poll2, poll3]
predict(candidates, polls)
#=> {
'A': 40,
'B': 37.1,
'C': 22.9
}
# because...
candidate 'A' weighted average
= ((20 * 1) + (40 * 0.5) + (50 * 2)) / (1 + 0.5 + 2)
= (20 + 20 + 100) / 3.5
= 140 / 3.5
= 40
candidate 'B' weighted average
= ((30 * 1) + (40 * 0.5) + (40 * 2)) / (1 + 0.5 + 2)
= (30 + 20 + 80) / 3.5
= 130 / 3.5
= 37.142857...
≈ 37.1 (round to nearest tenth)
candidate 'C' weighted average
= ((50 * 1) + (20 * 0.5) + (10 * 2)) / (1 + 0.5 + 2)
= (50 + 10 + 20) / 3.5
= 80 / 3.5
= 22.857142...
≈ 22.9 (round to nearest tenth)
```
Also check out my other creations — [Keep the Order](https://www.codewars.com/kata/keep-the-order), [Naming Files](https://www.codewars.com/kata/naming-files), [Square and Cubic Factors](https://www.codewars.com/kata/square-and-cubic-factors), [Identify Case](https://www.codewars.com/kata/identify-case), [Split Without Loss](https://www.codewars.com/kata/split-without-loss), [Adding Fractions](https://www.codewars.com/kata/adding-fractions),
[Random Integers](https://www.codewars.com/kata/random-integers), [Implement String#transpose](https://www.codewars.com/kata/implement-string-number-transpose), [Implement Array#transpose!](https://www.codewars.com/kata/implement-array-number-transpose), [Arrays and Procs #1](https://www.codewars.com/kata/arrays-and-procs-number-1), and [Arrays and Procs #2](https://www.codewars.com/kata/arrays-and-procs-number-2).
If you notice any issues or have any suggestions/comments whatsoever, please don't hesitate to mark an issue or just comment. Thanks!
|
def predict(candidates, polls):
weight = sum(w for _, w in polls)
scores = zip(*([s * w for s in r] for r, w in polls))
return dict(zip(candidates, (round1(sum(s)/weight) for s in scores)))
|
Many websites use weighted averages of various polls to make projections for elections. They’re weighted based on a variety of factors, such as historical accuracy of the polling firm, sample size, as well as date(s). The weights, in this kata, are already calculated for you. All you need to do is convert a set of polls with weights, into a fixed projection for the result.
#### Task:
Your job is to convert an array of candidates (variable name `candidates`) and an array of polls (variable name `polls`), each poll with two parts, a result and a weight, into a guess of the result, with each value rounded to one decimal place, through use of a weighted average. Weights can be zero! Don't worry about the sum not totalling 100. The final result should be a hash in Ruby and Crystal, dictionary in Python, or object in JS in the format shown below:
```python
{
"": "",
"": "",
...
}
For your convenience, a function named round1 has been defined for you. You can
use it to round to the nearest tenth correctly (due to the inaccuracy of round
and floats in general).
```
_The input should not be modified._
#### Calculation for projections:
```
[(poll1 * weight1) + (poll2 * weight2) + ...] / (weight1 + weight2 + ...)
```
#### An example:
```python
candidates = ['A', 'B', 'C']
poll1res = [20, 30, 50]
poll1wt = 1
poll1 = [poll1res, poll1wt]
poll2res = [40, 40, 20]
poll2wt = 0.5
poll2 = [poll2res, poll2wt]
poll3res = [50, 40, 10]
poll3wt = 2
poll3 = [poll3res, poll3wt]
polls = [poll1, poll2, poll3]
predict(candidates, polls)
#=> {
'A': 40,
'B': 37.1,
'C': 22.9
}
# because...
candidate 'A' weighted average
= ((20 * 1) + (40 * 0.5) + (50 * 2)) / (1 + 0.5 + 2)
= (20 + 20 + 100) / 3.5
= 140 / 3.5
= 40
candidate 'B' weighted average
= ((30 * 1) + (40 * 0.5) + (40 * 2)) / (1 + 0.5 + 2)
= (30 + 20 + 80) / 3.5
= 130 / 3.5
= 37.142857...
≈ 37.1 (round to nearest tenth)
candidate 'C' weighted average
= ((50 * 1) + (20 * 0.5) + (10 * 2)) / (1 + 0.5 + 2)
= (50 + 10 + 20) / 3.5
= 80 / 3.5
= 22.857142...
≈ 22.9 (round to nearest tenth)
```
Also check out my other creations — [Keep the Order](https://www.codewars.com/kata/keep-the-order), [Naming Files](https://www.codewars.com/kata/naming-files), [Square and Cubic Factors](https://www.codewars.com/kata/square-and-cubic-factors), [Identify Case](https://www.codewars.com/kata/identify-case), [Split Without Loss](https://www.codewars.com/kata/split-without-loss), [Adding Fractions](https://www.codewars.com/kata/adding-fractions),
[Random Integers](https://www.codewars.com/kata/random-integers), [Implement String#transpose](https://www.codewars.com/kata/implement-string-number-transpose), [Implement Array#transpose!](https://www.codewars.com/kata/implement-array-number-transpose), [Arrays and Procs #1](https://www.codewars.com/kata/arrays-and-procs-number-1), and [Arrays and Procs #2](https://www.codewars.com/kata/arrays-and-procs-number-2).
If you notice any issues or have any suggestions/comments whatsoever, please don't hesitate to mark an issue or just comment. Thanks!
|
from operator import itemgetter
from numpy import average
def predict(candidates, polls):
votes = zip(*map(itemgetter(0), polls))
weights = list(map(itemgetter(1), polls))
return {x:round1(average(next(votes), weights=weights)) for x in candidates}
|
Many websites use weighted averages of various polls to make projections for elections. They’re weighted based on a variety of factors, such as historical accuracy of the polling firm, sample size, as well as date(s). The weights, in this kata, are already calculated for you. All you need to do is convert a set of polls with weights, into a fixed projection for the result.
#### Task:
Your job is to convert an array of candidates (variable name `candidates`) and an array of polls (variable name `polls`), each poll with two parts, a result and a weight, into a guess of the result, with each value rounded to one decimal place, through use of a weighted average. Weights can be zero! Don't worry about the sum not totalling 100. The final result should be a hash in Ruby and Crystal, dictionary in Python, or object in JS in the format shown below:
```python
{
"": "",
"": "",
...
}
For your convenience, a function named round1 has been defined for you. You can
use it to round to the nearest tenth correctly (due to the inaccuracy of round
and floats in general).
```
_The input should not be modified._
#### Calculation for projections:
```
[(poll1 * weight1) + (poll2 * weight2) + ...] / (weight1 + weight2 + ...)
```
#### An example:
```python
candidates = ['A', 'B', 'C']
poll1res = [20, 30, 50]
poll1wt = 1
poll1 = [poll1res, poll1wt]
poll2res = [40, 40, 20]
poll2wt = 0.5
poll2 = [poll2res, poll2wt]
poll3res = [50, 40, 10]
poll3wt = 2
poll3 = [poll3res, poll3wt]
polls = [poll1, poll2, poll3]
predict(candidates, polls)
#=> {
'A': 40,
'B': 37.1,
'C': 22.9
}
# because...
candidate 'A' weighted average
= ((20 * 1) + (40 * 0.5) + (50 * 2)) / (1 + 0.5 + 2)
= (20 + 20 + 100) / 3.5
= 140 / 3.5
= 40
candidate 'B' weighted average
= ((30 * 1) + (40 * 0.5) + (40 * 2)) / (1 + 0.5 + 2)
= (30 + 20 + 80) / 3.5
= 130 / 3.5
= 37.142857...
≈ 37.1 (round to nearest tenth)
candidate 'C' weighted average
= ((50 * 1) + (20 * 0.5) + (10 * 2)) / (1 + 0.5 + 2)
= (50 + 10 + 20) / 3.5
= 80 / 3.5
= 22.857142...
≈ 22.9 (round to nearest tenth)
```
Also check out my other creations — [Keep the Order](https://www.codewars.com/kata/keep-the-order), [Naming Files](https://www.codewars.com/kata/naming-files), [Square and Cubic Factors](https://www.codewars.com/kata/square-and-cubic-factors), [Identify Case](https://www.codewars.com/kata/identify-case), [Split Without Loss](https://www.codewars.com/kata/split-without-loss), [Adding Fractions](https://www.codewars.com/kata/adding-fractions),
[Random Integers](https://www.codewars.com/kata/random-integers), [Implement String#transpose](https://www.codewars.com/kata/implement-string-number-transpose), [Implement Array#transpose!](https://www.codewars.com/kata/implement-array-number-transpose), [Arrays and Procs #1](https://www.codewars.com/kata/arrays-and-procs-number-1), and [Arrays and Procs #2](https://www.codewars.com/kata/arrays-and-procs-number-2).
If you notice any issues or have any suggestions/comments whatsoever, please don't hesitate to mark an issue or just comment. Thanks!
|
def predict(cnd, p):
res,wt = list(zip(*p))
return {j:round1(sum(k*l for k,l in zip(list(zip(*res))[i],wt)) / sum(wt)) for i,j in enumerate(cnd)}
|
Many websites use weighted averages of various polls to make projections for elections. They’re weighted based on a variety of factors, such as historical accuracy of the polling firm, sample size, as well as date(s). The weights, in this kata, are already calculated for you. All you need to do is convert a set of polls with weights, into a fixed projection for the result.
#### Task:
Your job is to convert an array of candidates (variable name `candidates`) and an array of polls (variable name `polls`), each poll with two parts, a result and a weight, into a guess of the result, with each value rounded to one decimal place, through use of a weighted average. Weights can be zero! Don't worry about the sum not totalling 100. The final result should be a hash in Ruby and Crystal, dictionary in Python, or object in JS in the format shown below:
```python
{
"": "",
"": "",
...
}
For your convenience, a function named round1 has been defined for you. You can
use it to round to the nearest tenth correctly (due to the inaccuracy of round
and floats in general).
```
_The input should not be modified._
#### Calculation for projections:
```
[(poll1 * weight1) + (poll2 * weight2) + ...] / (weight1 + weight2 + ...)
```
#### An example:
```python
candidates = ['A', 'B', 'C']
poll1res = [20, 30, 50]
poll1wt = 1
poll1 = [poll1res, poll1wt]
poll2res = [40, 40, 20]
poll2wt = 0.5
poll2 = [poll2res, poll2wt]
poll3res = [50, 40, 10]
poll3wt = 2
poll3 = [poll3res, poll3wt]
polls = [poll1, poll2, poll3]
predict(candidates, polls)
#=> {
'A': 40,
'B': 37.1,
'C': 22.9
}
# because...
candidate 'A' weighted average
= ((20 * 1) + (40 * 0.5) + (50 * 2)) / (1 + 0.5 + 2)
= (20 + 20 + 100) / 3.5
= 140 / 3.5
= 40
candidate 'B' weighted average
= ((30 * 1) + (40 * 0.5) + (40 * 2)) / (1 + 0.5 + 2)
= (30 + 20 + 80) / 3.5
= 130 / 3.5
= 37.142857...
≈ 37.1 (round to nearest tenth)
candidate 'C' weighted average
= ((50 * 1) + (20 * 0.5) + (10 * 2)) / (1 + 0.5 + 2)
= (50 + 10 + 20) / 3.5
= 80 / 3.5
= 22.857142...
≈ 22.9 (round to nearest tenth)
```
Also check out my other creations — [Keep the Order](https://www.codewars.com/kata/keep-the-order), [Naming Files](https://www.codewars.com/kata/naming-files), [Square and Cubic Factors](https://www.codewars.com/kata/square-and-cubic-factors), [Identify Case](https://www.codewars.com/kata/identify-case), [Split Without Loss](https://www.codewars.com/kata/split-without-loss), [Adding Fractions](https://www.codewars.com/kata/adding-fractions),
[Random Integers](https://www.codewars.com/kata/random-integers), [Implement String#transpose](https://www.codewars.com/kata/implement-string-number-transpose), [Implement Array#transpose!](https://www.codewars.com/kata/implement-array-number-transpose), [Arrays and Procs #1](https://www.codewars.com/kata/arrays-and-procs-number-1), and [Arrays and Procs #2](https://www.codewars.com/kata/arrays-and-procs-number-2).
If you notice any issues or have any suggestions/comments whatsoever, please don't hesitate to mark an issue or just comment. Thanks!
|
def predict(cnd, p):
wt, res, polls = [], [], {}
for i in p:
wt.append(i[1])
res.append(i[0])
wt_sum, res = sum(wt), list(zip(*res))
for i,j in enumerate(cnd):
polls[j] = round1(sum(k*l for k,l in zip(res[i],wt)) / wt_sum)
return polls
|
Many websites use weighted averages of various polls to make projections for elections. They’re weighted based on a variety of factors, such as historical accuracy of the polling firm, sample size, as well as date(s). The weights, in this kata, are already calculated for you. All you need to do is convert a set of polls with weights, into a fixed projection for the result.
#### Task:
Your job is to convert an array of candidates (variable name `candidates`) and an array of polls (variable name `polls`), each poll with two parts, a result and a weight, into a guess of the result, with each value rounded to one decimal place, through use of a weighted average. Weights can be zero! Don't worry about the sum not totalling 100. The final result should be a hash in Ruby and Crystal, dictionary in Python, or object in JS in the format shown below:
```python
{
"": "",
"": "",
...
}
For your convenience, a function named round1 has been defined for you. You can
use it to round to the nearest tenth correctly (due to the inaccuracy of round
and floats in general).
```
_The input should not be modified._
#### Calculation for projections:
```
[(poll1 * weight1) + (poll2 * weight2) + ...] / (weight1 + weight2 + ...)
```
#### An example:
```python
candidates = ['A', 'B', 'C']
poll1res = [20, 30, 50]
poll1wt = 1
poll1 = [poll1res, poll1wt]
poll2res = [40, 40, 20]
poll2wt = 0.5
poll2 = [poll2res, poll2wt]
poll3res = [50, 40, 10]
poll3wt = 2
poll3 = [poll3res, poll3wt]
polls = [poll1, poll2, poll3]
predict(candidates, polls)
#=> {
'A': 40,
'B': 37.1,
'C': 22.9
}
# because...
candidate 'A' weighted average
= ((20 * 1) + (40 * 0.5) + (50 * 2)) / (1 + 0.5 + 2)
= (20 + 20 + 100) / 3.5
= 140 / 3.5
= 40
candidate 'B' weighted average
= ((30 * 1) + (40 * 0.5) + (40 * 2)) / (1 + 0.5 + 2)
= (30 + 20 + 80) / 3.5
= 130 / 3.5
= 37.142857...
≈ 37.1 (round to nearest tenth)
candidate 'C' weighted average
= ((50 * 1) + (20 * 0.5) + (10 * 2)) / (1 + 0.5 + 2)
= (50 + 10 + 20) / 3.5
= 80 / 3.5
= 22.857142...
≈ 22.9 (round to nearest tenth)
```
Also check out my other creations — [Keep the Order](https://www.codewars.com/kata/keep-the-order), [Naming Files](https://www.codewars.com/kata/naming-files), [Square and Cubic Factors](https://www.codewars.com/kata/square-and-cubic-factors), [Identify Case](https://www.codewars.com/kata/identify-case), [Split Without Loss](https://www.codewars.com/kata/split-without-loss), [Adding Fractions](https://www.codewars.com/kata/adding-fractions),
[Random Integers](https://www.codewars.com/kata/random-integers), [Implement String#transpose](https://www.codewars.com/kata/implement-string-number-transpose), [Implement Array#transpose!](https://www.codewars.com/kata/implement-array-number-transpose), [Arrays and Procs #1](https://www.codewars.com/kata/arrays-and-procs-number-1), and [Arrays and Procs #2](https://www.codewars.com/kata/arrays-and-procs-number-2).
If you notice any issues or have any suggestions/comments whatsoever, please don't hesitate to mark an issue or just comment. Thanks!
|
def predict(candidates, polls):
total_weight = sum(w for p, w in polls)
return {
c: round1(sum(ps[i] * w for ps, w in polls) / total_weight)
for i, c in enumerate(candidates)
}
|
Many websites use weighted averages of various polls to make projections for elections. They’re weighted based on a variety of factors, such as historical accuracy of the polling firm, sample size, as well as date(s). The weights, in this kata, are already calculated for you. All you need to do is convert a set of polls with weights, into a fixed projection for the result.
#### Task:
Your job is to convert an array of candidates (variable name `candidates`) and an array of polls (variable name `polls`), each poll with two parts, a result and a weight, into a guess of the result, with each value rounded to one decimal place, through use of a weighted average. Weights can be zero! Don't worry about the sum not totalling 100. The final result should be a hash in Ruby and Crystal, dictionary in Python, or object in JS in the format shown below:
```python
{
"": "",
"": "",
...
}
For your convenience, a function named round1 has been defined for you. You can
use it to round to the nearest tenth correctly (due to the inaccuracy of round
and floats in general).
```
_The input should not be modified._
#### Calculation for projections:
```
[(poll1 * weight1) + (poll2 * weight2) + ...] / (weight1 + weight2 + ...)
```
#### An example:
```python
candidates = ['A', 'B', 'C']
poll1res = [20, 30, 50]
poll1wt = 1
poll1 = [poll1res, poll1wt]
poll2res = [40, 40, 20]
poll2wt = 0.5
poll2 = [poll2res, poll2wt]
poll3res = [50, 40, 10]
poll3wt = 2
poll3 = [poll3res, poll3wt]
polls = [poll1, poll2, poll3]
predict(candidates, polls)
#=> {
'A': 40,
'B': 37.1,
'C': 22.9
}
# because...
candidate 'A' weighted average
= ((20 * 1) + (40 * 0.5) + (50 * 2)) / (1 + 0.5 + 2)
= (20 + 20 + 100) / 3.5
= 140 / 3.5
= 40
candidate 'B' weighted average
= ((30 * 1) + (40 * 0.5) + (40 * 2)) / (1 + 0.5 + 2)
= (30 + 20 + 80) / 3.5
= 130 / 3.5
= 37.142857...
≈ 37.1 (round to nearest tenth)
candidate 'C' weighted average
= ((50 * 1) + (20 * 0.5) + (10 * 2)) / (1 + 0.5 + 2)
= (50 + 10 + 20) / 3.5
= 80 / 3.5
= 22.857142...
≈ 22.9 (round to nearest tenth)
```
Also check out my other creations — [Keep the Order](https://www.codewars.com/kata/keep-the-order), [Naming Files](https://www.codewars.com/kata/naming-files), [Square and Cubic Factors](https://www.codewars.com/kata/square-and-cubic-factors), [Identify Case](https://www.codewars.com/kata/identify-case), [Split Without Loss](https://www.codewars.com/kata/split-without-loss), [Adding Fractions](https://www.codewars.com/kata/adding-fractions),
[Random Integers](https://www.codewars.com/kata/random-integers), [Implement String#transpose](https://www.codewars.com/kata/implement-string-number-transpose), [Implement Array#transpose!](https://www.codewars.com/kata/implement-array-number-transpose), [Arrays and Procs #1](https://www.codewars.com/kata/arrays-and-procs-number-1), and [Arrays and Procs #2](https://www.codewars.com/kata/arrays-and-procs-number-2).
If you notice any issues or have any suggestions/comments whatsoever, please don't hesitate to mark an issue or just comment. Thanks!
|
import math
def predict(candidates, polls):
t ={}
for i,j in enumerate(candidates):
m = 0
n = 0
for z in polls:
n += z[1]
m += z[0][i]*z[1]
t[j]= round1(m/n)
return t
|
Many websites use weighted averages of various polls to make projections for elections. They’re weighted based on a variety of factors, such as historical accuracy of the polling firm, sample size, as well as date(s). The weights, in this kata, are already calculated for you. All you need to do is convert a set of polls with weights, into a fixed projection for the result.
#### Task:
Your job is to convert an array of candidates (variable name `candidates`) and an array of polls (variable name `polls`), each poll with two parts, a result and a weight, into a guess of the result, with each value rounded to one decimal place, through use of a weighted average. Weights can be zero! Don't worry about the sum not totalling 100. The final result should be a hash in Ruby and Crystal, dictionary in Python, or object in JS in the format shown below:
```python
{
"": "",
"": "",
...
}
For your convenience, a function named round1 has been defined for you. You can
use it to round to the nearest tenth correctly (due to the inaccuracy of round
and floats in general).
```
_The input should not be modified._
#### Calculation for projections:
```
[(poll1 * weight1) + (poll2 * weight2) + ...] / (weight1 + weight2 + ...)
```
#### An example:
```python
candidates = ['A', 'B', 'C']
poll1res = [20, 30, 50]
poll1wt = 1
poll1 = [poll1res, poll1wt]
poll2res = [40, 40, 20]
poll2wt = 0.5
poll2 = [poll2res, poll2wt]
poll3res = [50, 40, 10]
poll3wt = 2
poll3 = [poll3res, poll3wt]
polls = [poll1, poll2, poll3]
predict(candidates, polls)
#=> {
'A': 40,
'B': 37.1,
'C': 22.9
}
# because...
candidate 'A' weighted average
= ((20 * 1) + (40 * 0.5) + (50 * 2)) / (1 + 0.5 + 2)
= (20 + 20 + 100) / 3.5
= 140 / 3.5
= 40
candidate 'B' weighted average
= ((30 * 1) + (40 * 0.5) + (40 * 2)) / (1 + 0.5 + 2)
= (30 + 20 + 80) / 3.5
= 130 / 3.5
= 37.142857...
≈ 37.1 (round to nearest tenth)
candidate 'C' weighted average
= ((50 * 1) + (20 * 0.5) + (10 * 2)) / (1 + 0.5 + 2)
= (50 + 10 + 20) / 3.5
= 80 / 3.5
= 22.857142...
≈ 22.9 (round to nearest tenth)
```
Also check out my other creations — [Keep the Order](https://www.codewars.com/kata/keep-the-order), [Naming Files](https://www.codewars.com/kata/naming-files), [Square and Cubic Factors](https://www.codewars.com/kata/square-and-cubic-factors), [Identify Case](https://www.codewars.com/kata/identify-case), [Split Without Loss](https://www.codewars.com/kata/split-without-loss), [Adding Fractions](https://www.codewars.com/kata/adding-fractions),
[Random Integers](https://www.codewars.com/kata/random-integers), [Implement String#transpose](https://www.codewars.com/kata/implement-string-number-transpose), [Implement Array#transpose!](https://www.codewars.com/kata/implement-array-number-transpose), [Arrays and Procs #1](https://www.codewars.com/kata/arrays-and-procs-number-1), and [Arrays and Procs #2](https://www.codewars.com/kata/arrays-and-procs-number-2).
If you notice any issues or have any suggestions/comments whatsoever, please don't hesitate to mark an issue or just comment. Thanks!
|
def predict(candidates, polls):
res = dict()
for i in range(len(candidates)):
p = 0
s = 0
for poll in polls:
p += poll[0][i]*poll[1]
s += poll[1]
res[candidates[i]] = round1(p/s)
return res
|
Many websites use weighted averages of various polls to make projections for elections. They’re weighted based on a variety of factors, such as historical accuracy of the polling firm, sample size, as well as date(s). The weights, in this kata, are already calculated for you. All you need to do is convert a set of polls with weights, into a fixed projection for the result.
#### Task:
Your job is to convert an array of candidates (variable name `candidates`) and an array of polls (variable name `polls`), each poll with two parts, a result and a weight, into a guess of the result, with each value rounded to one decimal place, through use of a weighted average. Weights can be zero! Don't worry about the sum not totalling 100. The final result should be a hash in Ruby and Crystal, dictionary in Python, or object in JS in the format shown below:
```python
{
"": "",
"": "",
...
}
For your convenience, a function named round1 has been defined for you. You can
use it to round to the nearest tenth correctly (due to the inaccuracy of round
and floats in general).
```
_The input should not be modified._
#### Calculation for projections:
```
[(poll1 * weight1) + (poll2 * weight2) + ...] / (weight1 + weight2 + ...)
```
#### An example:
```python
candidates = ['A', 'B', 'C']
poll1res = [20, 30, 50]
poll1wt = 1
poll1 = [poll1res, poll1wt]
poll2res = [40, 40, 20]
poll2wt = 0.5
poll2 = [poll2res, poll2wt]
poll3res = [50, 40, 10]
poll3wt = 2
poll3 = [poll3res, poll3wt]
polls = [poll1, poll2, poll3]
predict(candidates, polls)
#=> {
'A': 40,
'B': 37.1,
'C': 22.9
}
# because...
candidate 'A' weighted average
= ((20 * 1) + (40 * 0.5) + (50 * 2)) / (1 + 0.5 + 2)
= (20 + 20 + 100) / 3.5
= 140 / 3.5
= 40
candidate 'B' weighted average
= ((30 * 1) + (40 * 0.5) + (40 * 2)) / (1 + 0.5 + 2)
= (30 + 20 + 80) / 3.5
= 130 / 3.5
= 37.142857...
≈ 37.1 (round to nearest tenth)
candidate 'C' weighted average
= ((50 * 1) + (20 * 0.5) + (10 * 2)) / (1 + 0.5 + 2)
= (50 + 10 + 20) / 3.5
= 80 / 3.5
= 22.857142...
≈ 22.9 (round to nearest tenth)
```
Also check out my other creations — [Keep the Order](https://www.codewars.com/kata/keep-the-order), [Naming Files](https://www.codewars.com/kata/naming-files), [Square and Cubic Factors](https://www.codewars.com/kata/square-and-cubic-factors), [Identify Case](https://www.codewars.com/kata/identify-case), [Split Without Loss](https://www.codewars.com/kata/split-without-loss), [Adding Fractions](https://www.codewars.com/kata/adding-fractions),
[Random Integers](https://www.codewars.com/kata/random-integers), [Implement String#transpose](https://www.codewars.com/kata/implement-string-number-transpose), [Implement Array#transpose!](https://www.codewars.com/kata/implement-array-number-transpose), [Arrays and Procs #1](https://www.codewars.com/kata/arrays-and-procs-number-1), and [Arrays and Procs #2](https://www.codewars.com/kata/arrays-and-procs-number-2).
If you notice any issues or have any suggestions/comments whatsoever, please don't hesitate to mark an issue or just comment. Thanks!
|
predict=lambda cs, ps: {c: round1(sum(p[0][i]*p[1] for p in ps)/sum(p[1] for p in ps)) for i,c in enumerate(cs)}
|
Many websites use weighted averages of various polls to make projections for elections. They’re weighted based on a variety of factors, such as historical accuracy of the polling firm, sample size, as well as date(s). The weights, in this kata, are already calculated for you. All you need to do is convert a set of polls with weights, into a fixed projection for the result.
#### Task:
Your job is to convert an array of candidates (variable name `candidates`) and an array of polls (variable name `polls`), each poll with two parts, a result and a weight, into a guess of the result, with each value rounded to one decimal place, through use of a weighted average. Weights can be zero! Don't worry about the sum not totalling 100. The final result should be a hash in Ruby and Crystal, dictionary in Python, or object in JS in the format shown below:
```python
{
"": "",
"": "",
...
}
For your convenience, a function named round1 has been defined for you. You can
use it to round to the nearest tenth correctly (due to the inaccuracy of round
and floats in general).
```
_The input should not be modified._
#### Calculation for projections:
```
[(poll1 * weight1) + (poll2 * weight2) + ...] / (weight1 + weight2 + ...)
```
#### An example:
```python
candidates = ['A', 'B', 'C']
poll1res = [20, 30, 50]
poll1wt = 1
poll1 = [poll1res, poll1wt]
poll2res = [40, 40, 20]
poll2wt = 0.5
poll2 = [poll2res, poll2wt]
poll3res = [50, 40, 10]
poll3wt = 2
poll3 = [poll3res, poll3wt]
polls = [poll1, poll2, poll3]
predict(candidates, polls)
#=> {
'A': 40,
'B': 37.1,
'C': 22.9
}
# because...
candidate 'A' weighted average
= ((20 * 1) + (40 * 0.5) + (50 * 2)) / (1 + 0.5 + 2)
= (20 + 20 + 100) / 3.5
= 140 / 3.5
= 40
candidate 'B' weighted average
= ((30 * 1) + (40 * 0.5) + (40 * 2)) / (1 + 0.5 + 2)
= (30 + 20 + 80) / 3.5
= 130 / 3.5
= 37.142857...
≈ 37.1 (round to nearest tenth)
candidate 'C' weighted average
= ((50 * 1) + (20 * 0.5) + (10 * 2)) / (1 + 0.5 + 2)
= (50 + 10 + 20) / 3.5
= 80 / 3.5
= 22.857142...
≈ 22.9 (round to nearest tenth)
```
Also check out my other creations — [Keep the Order](https://www.codewars.com/kata/keep-the-order), [Naming Files](https://www.codewars.com/kata/naming-files), [Square and Cubic Factors](https://www.codewars.com/kata/square-and-cubic-factors), [Identify Case](https://www.codewars.com/kata/identify-case), [Split Without Loss](https://www.codewars.com/kata/split-without-loss), [Adding Fractions](https://www.codewars.com/kata/adding-fractions),
[Random Integers](https://www.codewars.com/kata/random-integers), [Implement String#transpose](https://www.codewars.com/kata/implement-string-number-transpose), [Implement Array#transpose!](https://www.codewars.com/kata/implement-array-number-transpose), [Arrays and Procs #1](https://www.codewars.com/kata/arrays-and-procs-number-1), and [Arrays and Procs #2](https://www.codewars.com/kata/arrays-and-procs-number-2).
If you notice any issues or have any suggestions/comments whatsoever, please don't hesitate to mark an issue or just comment. Thanks!
|
def predict(candidates, polls):
wts = [i[1] for i in polls]
return dict(zip(candidates, (map(lambda z: round1(sum(a*b for (a,b) in (zip(z, wts)))/sum (wts)), zip(*(i[0] for i in polls))))))
|
# Introduction
Dots and Boxes is a pencil-and-paper game for two players (sometimes more). It was first published in the 19th century by Édouard Lucas, who called it la pipopipette. It has gone by many other names, including the game of dots, boxes, dot to dot grid, and pigs in a pen.
Starting with an empty grid of dots, two players take turns adding a single horizontal or vertical line between two unjoined adjacent dots. The player who completes the fourth side of a 1×1 box earns one point and takes another turn only if another box can be made. (A point is typically recorded by placing a mark that identifies the player in the box, such as an initial). The game ends when no more lines can be placed. The winner is the player with the most points. The board may be of any size. When short on time, a 2×2 board (a square of 9 dots) is good for beginners. A 5×5 is good for experts. (Source Wikipedia)
# Task
Your task is to complete the class called Game. You will be given the board size as an integer board that will be between 1 and 26, therefore the game size will be board x board. You will be given an array of lines that have already been taken, so you must complete all possible squares.
# Rules
1. The integer board will be passed when the class is initialised.
2. board will be between 1 and 26.
3. The lines array maybe empty or contain a list of line integers.
4. You can only complete a square if 3 out of the 4 sides are already complete.
5. The lines array that is passed into the play() function may not be sorted numerically!
# Returns
Return an array of all the lines filled in including the original lines.
Return array must be sorted numerically.
Return array must not contain duplicate integers.
# Example 1
## Initialise
Initialise a board of 2 squares by 2 squares where ```board = 2```
## Line Numbering
## Line Input
So for the line input of `[1, 3, 4]` the below lines would be complete
to complete the square line `6` is needed
## Game Play
```python
board = 2
lines = [1, 3, 4]
game = Game(board)
game.play(lines) => [1, 3, 4, 6]
```
# Example 2
## Initialise
```python
board = 2
lines = [1, 2, 3, 4, 5, 8, 10, 11, 12]
game = Game.new(board)
game.play(lines) => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
```
## Solution
Good luck and enjoy!
# Kata Series
If you enjoyed this, then please try one of my other Katas. Any feedback, translations and grading of beta Katas are greatly appreciated. Thank you.
Maze Runner
Scooby Doo Puzzle
Driving License
Connect 4
Vending Machine
Snakes and Ladders
Mastermind
Guess Who?
Am I safe to drive?
Mexican Wave
Pigs in a Pen
Hungry Hippos
Plenty of Fish in the Pond
Fruit Machine
Car Park Escape
|
class Game():
def __init__(self, n):
k = 2 * n + 1
self.board = {frozenset(k * r + 1 + c + d for d in (0, n, n + 1, k))
for r in range(n) for c in range(n)}
def play(self, lines):
lines = set(lines)
while 1:
for cell in self.board:
stick = cell - lines
if len(stick) <= 1:
lines |= stick
self.board.remove(cell)
break
else: break
return sorted(lines)
|
# Introduction
Dots and Boxes is a pencil-and-paper game for two players (sometimes more). It was first published in the 19th century by Édouard Lucas, who called it la pipopipette. It has gone by many other names, including the game of dots, boxes, dot to dot grid, and pigs in a pen.
Starting with an empty grid of dots, two players take turns adding a single horizontal or vertical line between two unjoined adjacent dots. The player who completes the fourth side of a 1×1 box earns one point and takes another turn only if another box can be made. (A point is typically recorded by placing a mark that identifies the player in the box, such as an initial). The game ends when no more lines can be placed. The winner is the player with the most points. The board may be of any size. When short on time, a 2×2 board (a square of 9 dots) is good for beginners. A 5×5 is good for experts. (Source Wikipedia)
# Task
Your task is to complete the class called Game. You will be given the board size as an integer board that will be between 1 and 26, therefore the game size will be board x board. You will be given an array of lines that have already been taken, so you must complete all possible squares.
# Rules
1. The integer board will be passed when the class is initialised.
2. board will be between 1 and 26.
3. The lines array maybe empty or contain a list of line integers.
4. You can only complete a square if 3 out of the 4 sides are already complete.
5. The lines array that is passed into the play() function may not be sorted numerically!
# Returns
Return an array of all the lines filled in including the original lines.
Return array must be sorted numerically.
Return array must not contain duplicate integers.
# Example 1
## Initialise
Initialise a board of 2 squares by 2 squares where ```board = 2```
## Line Numbering
## Line Input
So for the line input of `[1, 3, 4]` the below lines would be complete
to complete the square line `6` is needed
## Game Play
```python
board = 2
lines = [1, 3, 4]
game = Game(board)
game.play(lines) => [1, 3, 4, 6]
```
# Example 2
## Initialise
```python
board = 2
lines = [1, 2, 3, 4, 5, 8, 10, 11, 12]
game = Game.new(board)
game.play(lines) => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
```
## Solution
Good luck and enjoy!
# Kata Series
If you enjoyed this, then please try one of my other Katas. Any feedback, translations and grading of beta Katas are greatly appreciated. Thank you.
Maze Runner
Scooby Doo Puzzle
Driving License
Connect 4
Vending Machine
Snakes and Ladders
Mastermind
Guess Who?
Am I safe to drive?
Mexican Wave
Pigs in a Pen
Hungry Hippos
Plenty of Fish in the Pond
Fruit Machine
Car Park Escape
|
class Game():
def __init__(self, s):
self.s = s
self.sq = [ { d+(2*s+1)*y+x for d in [0, s, s+1, 2*s+1] } for x in range(1,s+1) for y in range(s) ]
def play(self, lines):
lines, prevlen = set(lines), 0
while len(lines) != prevlen:
keep, prevlen = [], len(lines)
for sq in self.sq:
if len(sq & lines) >= 3: lines |= sq
else: keep.append(sq)
self.sq = keep
return [n for n in range(1,(2*self.s+2)*self.s+1) if n in lines]
|
# Introduction
Dots and Boxes is a pencil-and-paper game for two players (sometimes more). It was first published in the 19th century by Édouard Lucas, who called it la pipopipette. It has gone by many other names, including the game of dots, boxes, dot to dot grid, and pigs in a pen.
Starting with an empty grid of dots, two players take turns adding a single horizontal or vertical line between two unjoined adjacent dots. The player who completes the fourth side of a 1×1 box earns one point and takes another turn only if another box can be made. (A point is typically recorded by placing a mark that identifies the player in the box, such as an initial). The game ends when no more lines can be placed. The winner is the player with the most points. The board may be of any size. When short on time, a 2×2 board (a square of 9 dots) is good for beginners. A 5×5 is good for experts. (Source Wikipedia)
# Task
Your task is to complete the class called Game. You will be given the board size as an integer board that will be between 1 and 26, therefore the game size will be board x board. You will be given an array of lines that have already been taken, so you must complete all possible squares.
# Rules
1. The integer board will be passed when the class is initialised.
2. board will be between 1 and 26.
3. The lines array maybe empty or contain a list of line integers.
4. You can only complete a square if 3 out of the 4 sides are already complete.
5. The lines array that is passed into the play() function may not be sorted numerically!
# Returns
Return an array of all the lines filled in including the original lines.
Return array must be sorted numerically.
Return array must not contain duplicate integers.
# Example 1
## Initialise
Initialise a board of 2 squares by 2 squares where ```board = 2```
## Line Numbering
## Line Input
So for the line input of `[1, 3, 4]` the below lines would be complete
to complete the square line `6` is needed
## Game Play
```python
board = 2
lines = [1, 3, 4]
game = Game(board)
game.play(lines) => [1, 3, 4, 6]
```
# Example 2
## Initialise
```python
board = 2
lines = [1, 2, 3, 4, 5, 8, 10, 11, 12]
game = Game.new(board)
game.play(lines) => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
```
## Solution
Good luck and enjoy!
# Kata Series
If you enjoyed this, then please try one of my other Katas. Any feedback, translations and grading of beta Katas are greatly appreciated. Thank you.
Maze Runner
Scooby Doo Puzzle
Driving License
Connect 4
Vending Machine
Snakes and Ladders
Mastermind
Guess Who?
Am I safe to drive?
Mexican Wave
Pigs in a Pen
Hungry Hippos
Plenty of Fish in the Pond
Fruit Machine
Car Park Escape
|
class Game():
def __init__(self, board):
self.n = board
def play(self, given):
n, make, given = self.n, [list(range(1, self.n + 1))] ,set(given)
for i in range(n - 1) : make.append([k + n + (n + 1) for k in make[-1]])
possible, i = [[i, i + n, i + n + 1, i + n + 1 + n] for i in sum(make, [])], 0
while i < len(possible):
t = [k for k in possible[i] if k not in given]
if len(t)==1 : given.add(t[0]) ; i = -1
i += 1
return sorted(given)
|
# Introduction
Dots and Boxes is a pencil-and-paper game for two players (sometimes more). It was first published in the 19th century by Édouard Lucas, who called it la pipopipette. It has gone by many other names, including the game of dots, boxes, dot to dot grid, and pigs in a pen.
Starting with an empty grid of dots, two players take turns adding a single horizontal or vertical line between two unjoined adjacent dots. The player who completes the fourth side of a 1×1 box earns one point and takes another turn only if another box can be made. (A point is typically recorded by placing a mark that identifies the player in the box, such as an initial). The game ends when no more lines can be placed. The winner is the player with the most points. The board may be of any size. When short on time, a 2×2 board (a square of 9 dots) is good for beginners. A 5×5 is good for experts. (Source Wikipedia)
# Task
Your task is to complete the class called Game. You will be given the board size as an integer board that will be between 1 and 26, therefore the game size will be board x board. You will be given an array of lines that have already been taken, so you must complete all possible squares.
# Rules
1. The integer board will be passed when the class is initialised.
2. board will be between 1 and 26.
3. The lines array maybe empty or contain a list of line integers.
4. You can only complete a square if 3 out of the 4 sides are already complete.
5. The lines array that is passed into the play() function may not be sorted numerically!
# Returns
Return an array of all the lines filled in including the original lines.
Return array must be sorted numerically.
Return array must not contain duplicate integers.
# Example 1
## Initialise
Initialise a board of 2 squares by 2 squares where ```board = 2```
## Line Numbering
## Line Input
So for the line input of `[1, 3, 4]` the below lines would be complete
to complete the square line `6` is needed
## Game Play
```python
board = 2
lines = [1, 3, 4]
game = Game(board)
game.play(lines) => [1, 3, 4, 6]
```
# Example 2
## Initialise
```python
board = 2
lines = [1, 2, 3, 4, 5, 8, 10, 11, 12]
game = Game.new(board)
game.play(lines) => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
```
## Solution
Good luck and enjoy!
# Kata Series
If you enjoyed this, then please try one of my other Katas. Any feedback, translations and grading of beta Katas are greatly appreciated. Thank you.
Maze Runner
Scooby Doo Puzzle
Driving License
Connect 4
Vending Machine
Snakes and Ladders
Mastermind
Guess Who?
Am I safe to drive?
Mexican Wave
Pigs in a Pen
Hungry Hippos
Plenty of Fish in the Pond
Fruit Machine
Car Park Escape
|
class Game():
def __init__(self, board):
self.board = board
def play(self, lines):
self.lines = set(lines)
change = True
while change:
change = False
for row in range(self.board):
for col in range(self.board):
offset = row * (2 * self.board + 1)
top = offset + col + 1
left = top + self.board
right = left + 1
bottom = right + self.board
cell = [top, left, right, bottom]
sides = 0
for side in cell:
if side in self.lines:
sides += 1
if sides == 3:
self.lines = self.lines.union(set(cell))
change = True
return sorted(list(self.lines))
|
# Introduction
Dots and Boxes is a pencil-and-paper game for two players (sometimes more). It was first published in the 19th century by Édouard Lucas, who called it la pipopipette. It has gone by many other names, including the game of dots, boxes, dot to dot grid, and pigs in a pen.
Starting with an empty grid of dots, two players take turns adding a single horizontal or vertical line between two unjoined adjacent dots. The player who completes the fourth side of a 1×1 box earns one point and takes another turn only if another box can be made. (A point is typically recorded by placing a mark that identifies the player in the box, such as an initial). The game ends when no more lines can be placed. The winner is the player with the most points. The board may be of any size. When short on time, a 2×2 board (a square of 9 dots) is good for beginners. A 5×5 is good for experts. (Source Wikipedia)
# Task
Your task is to complete the class called Game. You will be given the board size as an integer board that will be between 1 and 26, therefore the game size will be board x board. You will be given an array of lines that have already been taken, so you must complete all possible squares.
# Rules
1. The integer board will be passed when the class is initialised.
2. board will be between 1 and 26.
3. The lines array maybe empty or contain a list of line integers.
4. You can only complete a square if 3 out of the 4 sides are already complete.
5. The lines array that is passed into the play() function may not be sorted numerically!
# Returns
Return an array of all the lines filled in including the original lines.
Return array must be sorted numerically.
Return array must not contain duplicate integers.
# Example 1
## Initialise
Initialise a board of 2 squares by 2 squares where ```board = 2```
## Line Numbering
## Line Input
So for the line input of `[1, 3, 4]` the below lines would be complete
to complete the square line `6` is needed
## Game Play
```python
board = 2
lines = [1, 3, 4]
game = Game(board)
game.play(lines) => [1, 3, 4, 6]
```
# Example 2
## Initialise
```python
board = 2
lines = [1, 2, 3, 4, 5, 8, 10, 11, 12]
game = Game.new(board)
game.play(lines) => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
```
## Solution
Good luck and enjoy!
# Kata Series
If you enjoyed this, then please try one of my other Katas. Any feedback, translations and grading of beta Katas are greatly appreciated. Thank you.
Maze Runner
Scooby Doo Puzzle
Driving License
Connect 4
Vending Machine
Snakes and Ladders
Mastermind
Guess Who?
Am I safe to drive?
Mexican Wave
Pigs in a Pen
Hungry Hippos
Plenty of Fish in the Pond
Fruit Machine
Car Park Escape
|
class Game():
def __init__(self, n):
k = 2 * n + 1
self.board = [{k*r + 1 + c, k*(r+1) + 1 + c, k*r + n + 1 + c, k*r + n + 2 + c} for r in range(n) for c in range(n)]
def play(self, lines):
L, last = set(lines), None
while self.board != last:
last = self.board[:]
for k in [s for s in self.board if len(L & s) == 3]:
L |= k
self.board.remove(k)
return sorted(list(L))
|
# Introduction
Dots and Boxes is a pencil-and-paper game for two players (sometimes more). It was first published in the 19th century by Édouard Lucas, who called it la pipopipette. It has gone by many other names, including the game of dots, boxes, dot to dot grid, and pigs in a pen.
Starting with an empty grid of dots, two players take turns adding a single horizontal or vertical line between two unjoined adjacent dots. The player who completes the fourth side of a 1×1 box earns one point and takes another turn only if another box can be made. (A point is typically recorded by placing a mark that identifies the player in the box, such as an initial). The game ends when no more lines can be placed. The winner is the player with the most points. The board may be of any size. When short on time, a 2×2 board (a square of 9 dots) is good for beginners. A 5×5 is good for experts. (Source Wikipedia)
# Task
Your task is to complete the class called Game. You will be given the board size as an integer board that will be between 1 and 26, therefore the game size will be board x board. You will be given an array of lines that have already been taken, so you must complete all possible squares.
# Rules
1. The integer board will be passed when the class is initialised.
2. board will be between 1 and 26.
3. The lines array maybe empty or contain a list of line integers.
4. You can only complete a square if 3 out of the 4 sides are already complete.
5. The lines array that is passed into the play() function may not be sorted numerically!
# Returns
Return an array of all the lines filled in including the original lines.
Return array must be sorted numerically.
Return array must not contain duplicate integers.
# Example 1
## Initialise
Initialise a board of 2 squares by 2 squares where ```board = 2```
## Line Numbering
## Line Input
So for the line input of `[1, 3, 4]` the below lines would be complete
to complete the square line `6` is needed
## Game Play
```python
board = 2
lines = [1, 3, 4]
game = Game(board)
game.play(lines) => [1, 3, 4, 6]
```
# Example 2
## Initialise
```python
board = 2
lines = [1, 2, 3, 4, 5, 8, 10, 11, 12]
game = Game.new(board)
game.play(lines) => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
```
## Solution
Good luck and enjoy!
# Kata Series
If you enjoyed this, then please try one of my other Katas. Any feedback, translations and grading of beta Katas are greatly appreciated. Thank you.
Maze Runner
Scooby Doo Puzzle
Driving License
Connect 4
Vending Machine
Snakes and Ladders
Mastermind
Guess Who?
Am I safe to drive?
Mexican Wave
Pigs in a Pen
Hungry Hippos
Plenty of Fish in the Pond
Fruit Machine
Car Park Escape
|
class Game():
def ad_line(self,board):
work=[[] for _ in range(board**2+1)]
line_list=[[] for _ in range(2*board*(board+1)+1)]
for i in range(1,board**2+1):
numwork=((i-1)//board)*(2*board+1)
numwork+=(i-1)%board+1
work[i].append(numwork) #top edge
line_list[numwork].append(i)
numwork+=board
work[i].append(numwork) #left edge
work[i].append(numwork+1) #right edge
line_list[numwork].append(i)
line_list[numwork+1].append(i)
numwork+=board+1
work[i].append(numwork) #bottom edge
line_list[numwork].append(i)
return work,line_list
def __init__(self, board):
self.box=[0]*(board**2+1)
work=self.ad_line(board)
self.box_line=work[0]
self.line_list=work[1]
def play(self, lines):
out=lines[:]
work_next=[]
for line in lines:
for box in self.line_list[line]:
self.box[box]+=1
if self.box[box]==3 : work_next.append(box)
while work_next:
box=work_next.pop(0)
for line in self.box_line[box]:
if line in out : continue
out.append(line)
for n_box in self.line_list[line]:
self.box[n_box]+=1
if self.box[n_box]==3 : work_next.append(n_box)
return sorted(out)
|
# Introduction
Dots and Boxes is a pencil-and-paper game for two players (sometimes more). It was first published in the 19th century by Édouard Lucas, who called it la pipopipette. It has gone by many other names, including the game of dots, boxes, dot to dot grid, and pigs in a pen.
Starting with an empty grid of dots, two players take turns adding a single horizontal or vertical line between two unjoined adjacent dots. The player who completes the fourth side of a 1×1 box earns one point and takes another turn only if another box can be made. (A point is typically recorded by placing a mark that identifies the player in the box, such as an initial). The game ends when no more lines can be placed. The winner is the player with the most points. The board may be of any size. When short on time, a 2×2 board (a square of 9 dots) is good for beginners. A 5×5 is good for experts. (Source Wikipedia)
# Task
Your task is to complete the class called Game. You will be given the board size as an integer board that will be between 1 and 26, therefore the game size will be board x board. You will be given an array of lines that have already been taken, so you must complete all possible squares.
# Rules
1. The integer board will be passed when the class is initialised.
2. board will be between 1 and 26.
3. The lines array maybe empty or contain a list of line integers.
4. You can only complete a square if 3 out of the 4 sides are already complete.
5. The lines array that is passed into the play() function may not be sorted numerically!
# Returns
Return an array of all the lines filled in including the original lines.
Return array must be sorted numerically.
Return array must not contain duplicate integers.
# Example 1
## Initialise
Initialise a board of 2 squares by 2 squares where ```board = 2```
## Line Numbering
## Line Input
So for the line input of `[1, 3, 4]` the below lines would be complete
to complete the square line `6` is needed
## Game Play
```python
board = 2
lines = [1, 3, 4]
game = Game(board)
game.play(lines) => [1, 3, 4, 6]
```
# Example 2
## Initialise
```python
board = 2
lines = [1, 2, 3, 4, 5, 8, 10, 11, 12]
game = Game.new(board)
game.play(lines) => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
```
## Solution
Good luck and enjoy!
# Kata Series
If you enjoyed this, then please try one of my other Katas. Any feedback, translations and grading of beta Katas are greatly appreciated. Thank you.
Maze Runner
Scooby Doo Puzzle
Driving License
Connect 4
Vending Machine
Snakes and Ladders
Mastermind
Guess Who?
Am I safe to drive?
Mexican Wave
Pigs in a Pen
Hungry Hippos
Plenty of Fish in the Pond
Fruit Machine
Car Park Escape
|
class Game():
def __init__(self, board):
self._board = board
self._lines = []
self._flines = []
self._gboard = []
self._cboard = []
self._sqcheck = [(0,0),(1,-1),(1,1),(2,0)]
self._sqctotal = 0
self._dot = 0
self._score = 0
self._inner = "X"
self._blank = "_"
self.createcompleteb()
def play(self, lines):
if (lines == []):
return lines
self._lines = lines
creategameb(self, self._lines)
breaker = False
lskip = False
complete = False
while not complete:
breaker = False
lskip = False
for y in range(len(self._gboard)):
if (not lskip):
lskip = True
if(y != len(self._gboard) -1):
for x in range(len(self._gboard)):
if(self._gboard[y][x] != self._dot):
for sqc in self._sqcheck:
if (self._gboard[y + sqc[0]][x + sqc[1]] != self._blank):
self._sqctotal += 1
if(self._sqctotal == 3):
for sqc in self._sqcheck:
if (self._gboard[y + sqc[0]][x + sqc[1]] == self._blank):
self._gboard[y + sqc[0]][x + sqc[1]] = self._cboard[y + sqc[0]][x + sqc[1]]
self._sqctotal = 0
self._score = 1
breaker = True
break
elif(self._sqctotal == 4):
self._sqctotal = 0
self._score = 1
else:
self._sqctotal = 0
else:
pass
else:
complete = True
else:
lskip = False
if(breaker):
breaker = False
break
for y in range(len(self._gboard)):
for x in range(len(self._gboard)):
if(isinstance(self._gboard[y][x], int) ):
if(self._gboard[y][x] > 0):
self._flines.append(self._gboard[y][x])
if(self._score):
return self._flines
else:
return self._lines
def createcompleteb(self):
#create a complete board
switch = 1 # 0 = number 1 = dot/inner
doi = 0 # 0 = dot 1 = inner
count = 1
tmp = []
for y in range(self._board + 1 + self._board):
for x in range(self._board + 1 + self._board):
if (switch):
if (not doi):
tmp.append(self._dot)
switch = 0
else:
tmp.append(self._inner)
switch = 0
else:
tmp.append(count)
count += 1
switch = 1
if(doi == 1):
doi = 0
else:
doi = 1
self._cboard.append(tmp)
tmp = []
def creategameb(self, lines):
#create a game board using provided "lines"
switch = 1 # 0 = number 1 = dot/inner
doi = 0 # 0 = dot 1 = inner
count = 1
tmp = []
for y in range(self._board + 1 + self._board):
for x in range(self._board + 1 + self._board):
if (switch):
if (not doi):
tmp.append(self._dot)
switch = 0
else:
tmp.append(self._inner)
switch = 0
else:
if (count in lines):
tmp.append(count)
count += 1
switch = 1
else:
tmp.append(self._blank)
count += 1
switch = 1
if(doi == 1):
doi = 0
else:
doi = 1
self._gboard.append(tmp)
tmp = []
|
# Introduction
Dots and Boxes is a pencil-and-paper game for two players (sometimes more). It was first published in the 19th century by Édouard Lucas, who called it la pipopipette. It has gone by many other names, including the game of dots, boxes, dot to dot grid, and pigs in a pen.
Starting with an empty grid of dots, two players take turns adding a single horizontal or vertical line between two unjoined adjacent dots. The player who completes the fourth side of a 1×1 box earns one point and takes another turn only if another box can be made. (A point is typically recorded by placing a mark that identifies the player in the box, such as an initial). The game ends when no more lines can be placed. The winner is the player with the most points. The board may be of any size. When short on time, a 2×2 board (a square of 9 dots) is good for beginners. A 5×5 is good for experts. (Source Wikipedia)
# Task
Your task is to complete the class called Game. You will be given the board size as an integer board that will be between 1 and 26, therefore the game size will be board x board. You will be given an array of lines that have already been taken, so you must complete all possible squares.
# Rules
1. The integer board will be passed when the class is initialised.
2. board will be between 1 and 26.
3. The lines array maybe empty or contain a list of line integers.
4. You can only complete a square if 3 out of the 4 sides are already complete.
5. The lines array that is passed into the play() function may not be sorted numerically!
# Returns
Return an array of all the lines filled in including the original lines.
Return array must be sorted numerically.
Return array must not contain duplicate integers.
# Example 1
## Initialise
Initialise a board of 2 squares by 2 squares where ```board = 2```
## Line Numbering
## Line Input
So for the line input of `[1, 3, 4]` the below lines would be complete
to complete the square line `6` is needed
## Game Play
```python
board = 2
lines = [1, 3, 4]
game = Game(board)
game.play(lines) => [1, 3, 4, 6]
```
# Example 2
## Initialise
```python
board = 2
lines = [1, 2, 3, 4, 5, 8, 10, 11, 12]
game = Game.new(board)
game.play(lines) => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
```
## Solution
Good luck and enjoy!
# Kata Series
If you enjoyed this, then please try one of my other Katas. Any feedback, translations and grading of beta Katas are greatly appreciated. Thank you.
Maze Runner
Scooby Doo Puzzle
Driving License
Connect 4
Vending Machine
Snakes and Ladders
Mastermind
Guess Who?
Am I safe to drive?
Mexican Wave
Pigs in a Pen
Hungry Hippos
Plenty of Fish in the Pond
Fruit Machine
Car Park Escape
|
class Game():
def __init__(self, board):
self.board_list = []
for n in range(board): #5 -> 0,1,2,3,4,5
if n == 0:
for row in range(1,board+1): #row1 -> 1-5
self.board_list.append( [row, row+board, row+board+1, row+board+1+board] )
else:
for row in range( (board+(board+1))*n+1, (board+(board+1))*n+board+1):
self.board_list.append( [row, row+board, row+board+1, row+board+1+board] )
def play(self, lines):
lines = set(lines)
changes = True
while changes == True:
changes = False
for combination in self.board_list:
if len(set(combination) & lines) == 3:
changes = True
lines.add(list(set(combination) - (set(combination)&lines))[0])
return sorted(list(lines))
|
# Introduction
Dots and Boxes is a pencil-and-paper game for two players (sometimes more). It was first published in the 19th century by Édouard Lucas, who called it la pipopipette. It has gone by many other names, including the game of dots, boxes, dot to dot grid, and pigs in a pen.
Starting with an empty grid of dots, two players take turns adding a single horizontal or vertical line between two unjoined adjacent dots. The player who completes the fourth side of a 1×1 box earns one point and takes another turn only if another box can be made. (A point is typically recorded by placing a mark that identifies the player in the box, such as an initial). The game ends when no more lines can be placed. The winner is the player with the most points. The board may be of any size. When short on time, a 2×2 board (a square of 9 dots) is good for beginners. A 5×5 is good for experts. (Source Wikipedia)
# Task
Your task is to complete the class called Game. You will be given the board size as an integer board that will be between 1 and 26, therefore the game size will be board x board. You will be given an array of lines that have already been taken, so you must complete all possible squares.
# Rules
1. The integer board will be passed when the class is initialised.
2. board will be between 1 and 26.
3. The lines array maybe empty or contain a list of line integers.
4. You can only complete a square if 3 out of the 4 sides are already complete.
5. The lines array that is passed into the play() function may not be sorted numerically!
# Returns
Return an array of all the lines filled in including the original lines.
Return array must be sorted numerically.
Return array must not contain duplicate integers.
# Example 1
## Initialise
Initialise a board of 2 squares by 2 squares where ```board = 2```
## Line Numbering
## Line Input
So for the line input of `[1, 3, 4]` the below lines would be complete
to complete the square line `6` is needed
## Game Play
```python
board = 2
lines = [1, 3, 4]
game = Game(board)
game.play(lines) => [1, 3, 4, 6]
```
# Example 2
## Initialise
```python
board = 2
lines = [1, 2, 3, 4, 5, 8, 10, 11, 12]
game = Game.new(board)
game.play(lines) => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
```
## Solution
Good luck and enjoy!
# Kata Series
If you enjoyed this, then please try one of my other Katas. Any feedback, translations and grading of beta Katas are greatly appreciated. Thank you.
Maze Runner
Scooby Doo Puzzle
Driving License
Connect 4
Vending Machine
Snakes and Ladders
Mastermind
Guess Who?
Am I safe to drive?
Mexican Wave
Pigs in a Pen
Hungry Hippos
Plenty of Fish in the Pond
Fruit Machine
Car Park Escape
|
class Game():
def __init__(self, board):
self.board = board
def internal(self, lines):
result = set()
retval = False
pts_per_line = (self.board * 2) + 1
for by in range(self.board):
for bx in range(self.board):
h1 = 1 + (by * pts_per_line) + bx
h2 = (h1 + pts_per_line)
v1 = (h1 + self.board)
v2 = (v1 + 1)
count = 0
if h1 in lines:
count += 1
result.add(h1)
if h2 in lines:
count += 1
result.add(h2)
if v1 in lines:
count += 1
result.add(v1)
if v2 in lines:
count += 1
result.add(v2)
if count == 3:
retval = True
result.add(h1)
result.add(h2)
result.add(v1)
result.add(v2)
ret = list(result)
ret.sort()
return ret, retval
def play(self, lines):
cont = True
while cont:
ret, cont = self.internal(lines)
lines = ret
return lines
|
# Introduction
Dots and Boxes is a pencil-and-paper game for two players (sometimes more). It was first published in the 19th century by Édouard Lucas, who called it la pipopipette. It has gone by many other names, including the game of dots, boxes, dot to dot grid, and pigs in a pen.
Starting with an empty grid of dots, two players take turns adding a single horizontal or vertical line between two unjoined adjacent dots. The player who completes the fourth side of a 1×1 box earns one point and takes another turn only if another box can be made. (A point is typically recorded by placing a mark that identifies the player in the box, such as an initial). The game ends when no more lines can be placed. The winner is the player with the most points. The board may be of any size. When short on time, a 2×2 board (a square of 9 dots) is good for beginners. A 5×5 is good for experts. (Source Wikipedia)
# Task
Your task is to complete the class called Game. You will be given the board size as an integer board that will be between 1 and 26, therefore the game size will be board x board. You will be given an array of lines that have already been taken, so you must complete all possible squares.
# Rules
1. The integer board will be passed when the class is initialised.
2. board will be between 1 and 26.
3. The lines array maybe empty or contain a list of line integers.
4. You can only complete a square if 3 out of the 4 sides are already complete.
5. The lines array that is passed into the play() function may not be sorted numerically!
# Returns
Return an array of all the lines filled in including the original lines.
Return array must be sorted numerically.
Return array must not contain duplicate integers.
# Example 1
## Initialise
Initialise a board of 2 squares by 2 squares where ```board = 2```
## Line Numbering
## Line Input
So for the line input of `[1, 3, 4]` the below lines would be complete
to complete the square line `6` is needed
## Game Play
```python
board = 2
lines = [1, 3, 4]
game = Game(board)
game.play(lines) => [1, 3, 4, 6]
```
# Example 2
## Initialise
```python
board = 2
lines = [1, 2, 3, 4, 5, 8, 10, 11, 12]
game = Game.new(board)
game.play(lines) => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
```
## Solution
Good luck and enjoy!
# Kata Series
If you enjoyed this, then please try one of my other Katas. Any feedback, translations and grading of beta Katas are greatly appreciated. Thank you.
Maze Runner
Scooby Doo Puzzle
Driving License
Connect 4
Vending Machine
Snakes and Ladders
Mastermind
Guess Who?
Am I safe to drive?
Mexican Wave
Pigs in a Pen
Hungry Hippos
Plenty of Fish in the Pond
Fruit Machine
Car Park Escape
|
class Game():
def __init__(self, board):
self.board=board
def play(self, lines):
r=set(lines)
while(len(r)<2*self.board*(self.board+1)):
flag=False
for i in range(self.board):
for j in range(self.board):
x=(2*self.board+1)*i+j+1
s={x,x+self.board,x+self.board+1,x+2*self.board+1}
if len(r&s)==3:
r|=s
flag=True
break
if flag:
break
if not flag:
break
return sorted(r)
|
Your task is to implement a function that takes one or more dictionaries and combines them in one result dictionary.
The keys in the given dictionaries can overlap. In that case you should combine all source values in an array. Duplicate values should be preserved.
Here is an example:
```cs
var source1 = new Dictionary{{"A", 1}, {"B", 2}};
var source2 = new Dictionary{{"A", 3}};
Dictionary result = DictionaryMerger.Merge(source1, source2);
// result should have this content: {{"A", [1, 3]}, {"B", [2]}}
```
```python
source1 = {"A": 1, "B": 2}
source2 = {"A": 3}
result = merge(source1, source2);
// result should have this content: {"A": [1, 3]}, "B": [2]}
```
You can assume that only valid dictionaries are passed to your function.
The number of given dictionaries might be large. So take care about performance.
|
def merge(*dicts):
result = {}
for d in dicts:
for key, value in d.items():
result.setdefault(key, []).append(value)
return result
from itertools import groupby, chain
|
Your task is to implement a function that takes one or more dictionaries and combines them in one result dictionary.
The keys in the given dictionaries can overlap. In that case you should combine all source values in an array. Duplicate values should be preserved.
Here is an example:
```cs
var source1 = new Dictionary{{"A", 1}, {"B", 2}};
var source2 = new Dictionary{{"A", 3}};
Dictionary result = DictionaryMerger.Merge(source1, source2);
// result should have this content: {{"A", [1, 3]}, {"B", [2]}}
```
```python
source1 = {"A": 1, "B": 2}
source2 = {"A": 3}
result = merge(source1, source2);
// result should have this content: {"A": [1, 3]}, "B": [2]}
```
You can assume that only valid dictionaries are passed to your function.
The number of given dictionaries might be large. So take care about performance.
|
from collections import defaultdict
def merge(*dicts):
d = defaultdict(list)
for dd in dicts:
for k,v in dd.items():
d[k].append(v)
return d
|
Your task is to implement a function that takes one or more dictionaries and combines them in one result dictionary.
The keys in the given dictionaries can overlap. In that case you should combine all source values in an array. Duplicate values should be preserved.
Here is an example:
```cs
var source1 = new Dictionary{{"A", 1}, {"B", 2}};
var source2 = new Dictionary{{"A", 3}};
Dictionary result = DictionaryMerger.Merge(source1, source2);
// result should have this content: {{"A", [1, 3]}, {"B", [2]}}
```
```python
source1 = {"A": 1, "B": 2}
source2 = {"A": 3}
result = merge(source1, source2);
// result should have this content: {"A": [1, 3]}, "B": [2]}
```
You can assume that only valid dictionaries are passed to your function.
The number of given dictionaries might be large. So take care about performance.
|
def merge(*dicts):
r={}
for d in dicts:
for k in d:
r[k]=r.get(k,[])+[d[k]]
return r
|
Your task is to implement a function that takes one or more dictionaries and combines them in one result dictionary.
The keys in the given dictionaries can overlap. In that case you should combine all source values in an array. Duplicate values should be preserved.
Here is an example:
```cs
var source1 = new Dictionary{{"A", 1}, {"B", 2}};
var source2 = new Dictionary{{"A", 3}};
Dictionary result = DictionaryMerger.Merge(source1, source2);
// result should have this content: {{"A", [1, 3]}, {"B", [2]}}
```
```python
source1 = {"A": 1, "B": 2}
source2 = {"A": 3}
result = merge(source1, source2);
// result should have this content: {"A": [1, 3]}, "B": [2]}
```
You can assume that only valid dictionaries are passed to your function.
The number of given dictionaries might be large. So take care about performance.
|
def merge(*dicts):
keys = set([key for d in dicts for key in d])
return {key: [d[key] for d in dicts if key in d] for key in keys}
|
Your task is to implement a function that takes one or more dictionaries and combines them in one result dictionary.
The keys in the given dictionaries can overlap. In that case you should combine all source values in an array. Duplicate values should be preserved.
Here is an example:
```cs
var source1 = new Dictionary{{"A", 1}, {"B", 2}};
var source2 = new Dictionary{{"A", 3}};
Dictionary result = DictionaryMerger.Merge(source1, source2);
// result should have this content: {{"A", [1, 3]}, {"B", [2]}}
```
```python
source1 = {"A": 1, "B": 2}
source2 = {"A": 3}
result = merge(source1, source2);
// result should have this content: {"A": [1, 3]}, "B": [2]}
```
You can assume that only valid dictionaries are passed to your function.
The number of given dictionaries might be large. So take care about performance.
|
from collections import defaultdict
def merge(*dicts):
d = defaultdict(list)
[d[key].append(value) for dictionary in dicts for key, value in list(dictionary.items()) ]
return d
|
Your task is to implement a function that takes one or more dictionaries and combines them in one result dictionary.
The keys in the given dictionaries can overlap. In that case you should combine all source values in an array. Duplicate values should be preserved.
Here is an example:
```cs
var source1 = new Dictionary{{"A", 1}, {"B", 2}};
var source2 = new Dictionary{{"A", 3}};
Dictionary result = DictionaryMerger.Merge(source1, source2);
// result should have this content: {{"A", [1, 3]}, {"B", [2]}}
```
```python
source1 = {"A": 1, "B": 2}
source2 = {"A": 3}
result = merge(source1, source2);
// result should have this content: {"A": [1, 3]}, "B": [2]}
```
You can assume that only valid dictionaries are passed to your function.
The number of given dictionaries might be large. So take care about performance.
|
def merge(*dicts):
merged = {}
for dict in dicts:
for key, value in dict.items():
if key not in merged:
merged[key] = [value]
else:
merged[key].append(value)
return merged
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.