inputs
stringlengths 50
14k
| targets
stringlengths 4
655k
|
|---|---|
# Task
When a candle finishes burning it leaves a leftover. makeNew leftovers can be combined to make a new candle, which, when burning down, will in turn leave another leftover.
You have candlesNumber candles in your possession. What's the total number of candles you can burn, assuming that you create new candles as soon as you have enough leftovers?
# Example
For candlesNumber = 5 and makeNew = 2, the output should be `9`.
Here is what you can do to burn 9 candles:
```
burn 5 candles, obtain 5 leftovers;
create 2 more candles, using 4 leftovers (1 leftover remains);
burn 2 candles, end up with 3 leftovers;
create another candle using 2 leftovers (1 leftover remains);
burn the created candle, which gives another leftover (2 leftovers in total);
create a candle from the remaining leftovers;
burn the last candle.
Thus, you can burn 5 + 2 + 1 + 1 = 9 candles, which is the answer.
```
# Input/Output
- `[input]` integer `candlesNumber`
The number of candles you have in your possession.
Constraints: 1 ≤ candlesNumber ≤ 50.
- `[input]` integer `makeNew`
The number of leftovers that you can use up to create a new candle.
Constraints: 2 ≤ makeNew ≤ 5.
- `[output]` an integer
|
from functools import lru_cache
@lru_cache(maxsize=None)
def candles(m, n, l=0):
if not m and l < n: return 0
m, l = m+l//n, l%n
return m + candles(0, n, l+m)
|
# Task
When a candle finishes burning it leaves a leftover. makeNew leftovers can be combined to make a new candle, which, when burning down, will in turn leave another leftover.
You have candlesNumber candles in your possession. What's the total number of candles you can burn, assuming that you create new candles as soon as you have enough leftovers?
# Example
For candlesNumber = 5 and makeNew = 2, the output should be `9`.
Here is what you can do to burn 9 candles:
```
burn 5 candles, obtain 5 leftovers;
create 2 more candles, using 4 leftovers (1 leftover remains);
burn 2 candles, end up with 3 leftovers;
create another candle using 2 leftovers (1 leftover remains);
burn the created candle, which gives another leftover (2 leftovers in total);
create a candle from the remaining leftovers;
burn the last candle.
Thus, you can burn 5 + 2 + 1 + 1 = 9 candles, which is the answer.
```
# Input/Output
- `[input]` integer `candlesNumber`
The number of candles you have in your possession.
Constraints: 1 ≤ candlesNumber ≤ 50.
- `[input]` integer `makeNew`
The number of leftovers that you can use up to create a new candle.
Constraints: 2 ≤ makeNew ≤ 5.
- `[output]` an integer
|
def candles(m, n):
c, r = m, 0
while m:
m, r = divmod(m+r, n)
c += m
return c
|
# Task
When a candle finishes burning it leaves a leftover. makeNew leftovers can be combined to make a new candle, which, when burning down, will in turn leave another leftover.
You have candlesNumber candles in your possession. What's the total number of candles you can burn, assuming that you create new candles as soon as you have enough leftovers?
# Example
For candlesNumber = 5 and makeNew = 2, the output should be `9`.
Here is what you can do to burn 9 candles:
```
burn 5 candles, obtain 5 leftovers;
create 2 more candles, using 4 leftovers (1 leftover remains);
burn 2 candles, end up with 3 leftovers;
create another candle using 2 leftovers (1 leftover remains);
burn the created candle, which gives another leftover (2 leftovers in total);
create a candle from the remaining leftovers;
burn the last candle.
Thus, you can burn 5 + 2 + 1 + 1 = 9 candles, which is the answer.
```
# Input/Output
- `[input]` integer `candlesNumber`
The number of candles you have in your possession.
Constraints: 1 ≤ candlesNumber ≤ 50.
- `[input]` integer `makeNew`
The number of leftovers that you can use up to create a new candle.
Constraints: 2 ≤ makeNew ≤ 5.
- `[output]` an integer
|
def candles(m, n):
c = m
while m >= n:
a, b = divmod(m, n)
c += a
m = a + b
return c
|
# Task
When a candle finishes burning it leaves a leftover. makeNew leftovers can be combined to make a new candle, which, when burning down, will in turn leave another leftover.
You have candlesNumber candles in your possession. What's the total number of candles you can burn, assuming that you create new candles as soon as you have enough leftovers?
# Example
For candlesNumber = 5 and makeNew = 2, the output should be `9`.
Here is what you can do to burn 9 candles:
```
burn 5 candles, obtain 5 leftovers;
create 2 more candles, using 4 leftovers (1 leftover remains);
burn 2 candles, end up with 3 leftovers;
create another candle using 2 leftovers (1 leftover remains);
burn the created candle, which gives another leftover (2 leftovers in total);
create a candle from the remaining leftovers;
burn the last candle.
Thus, you can burn 5 + 2 + 1 + 1 = 9 candles, which is the answer.
```
# Input/Output
- `[input]` integer `candlesNumber`
The number of candles you have in your possession.
Constraints: 1 ≤ candlesNumber ≤ 50.
- `[input]` integer `makeNew`
The number of leftovers that you can use up to create a new candle.
Constraints: 2 ≤ makeNew ≤ 5.
- `[output]` an integer
|
def candles(m, n):
answer = 0
candles, leftovers = m, 0
while candles >= 1 or leftovers >= n:
answer += candles
leftovers += candles
candles = leftovers//n
leftovers -= leftovers//n*n
return answer
|
# Task
When a candle finishes burning it leaves a leftover. makeNew leftovers can be combined to make a new candle, which, when burning down, will in turn leave another leftover.
You have candlesNumber candles in your possession. What's the total number of candles you can burn, assuming that you create new candles as soon as you have enough leftovers?
# Example
For candlesNumber = 5 and makeNew = 2, the output should be `9`.
Here is what you can do to burn 9 candles:
```
burn 5 candles, obtain 5 leftovers;
create 2 more candles, using 4 leftovers (1 leftover remains);
burn 2 candles, end up with 3 leftovers;
create another candle using 2 leftovers (1 leftover remains);
burn the created candle, which gives another leftover (2 leftovers in total);
create a candle from the remaining leftovers;
burn the last candle.
Thus, you can burn 5 + 2 + 1 + 1 = 9 candles, which is the answer.
```
# Input/Output
- `[input]` integer `candlesNumber`
The number of candles you have in your possession.
Constraints: 1 ≤ candlesNumber ≤ 50.
- `[input]` integer `makeNew`
The number of leftovers that you can use up to create a new candle.
Constraints: 2 ≤ makeNew ≤ 5.
- `[output]` an integer
|
def candles(candles1, leftovers):
return candlesop(candles1, leftovers)
# Candle operations.
def candlesop(candles1, leftovers):
candle1 = candles1
answer = 0
left = 0
# while loop; as long as some candles remain, the loop keeps running.
while candle1 != 0:
answer += candle1
left += candle1
candle1 = left // leftovers
left = left % leftovers
return answer
|
# Task
When a candle finishes burning it leaves a leftover. makeNew leftovers can be combined to make a new candle, which, when burning down, will in turn leave another leftover.
You have candlesNumber candles in your possession. What's the total number of candles you can burn, assuming that you create new candles as soon as you have enough leftovers?
# Example
For candlesNumber = 5 and makeNew = 2, the output should be `9`.
Here is what you can do to burn 9 candles:
```
burn 5 candles, obtain 5 leftovers;
create 2 more candles, using 4 leftovers (1 leftover remains);
burn 2 candles, end up with 3 leftovers;
create another candle using 2 leftovers (1 leftover remains);
burn the created candle, which gives another leftover (2 leftovers in total);
create a candle from the remaining leftovers;
burn the last candle.
Thus, you can burn 5 + 2 + 1 + 1 = 9 candles, which is the answer.
```
# Input/Output
- `[input]` integer `candlesNumber`
The number of candles you have in your possession.
Constraints: 1 ≤ candlesNumber ≤ 50.
- `[input]` integer `makeNew`
The number of leftovers that you can use up to create a new candle.
Constraints: 2 ≤ makeNew ≤ 5.
- `[output]` an integer
|
def candles(m,n):
total=0
l=0
while m:
total+=m
m,l=divmod(m+l,n)
return total
|
# Task
When a candle finishes burning it leaves a leftover. makeNew leftovers can be combined to make a new candle, which, when burning down, will in turn leave another leftover.
You have candlesNumber candles in your possession. What's the total number of candles you can burn, assuming that you create new candles as soon as you have enough leftovers?
# Example
For candlesNumber = 5 and makeNew = 2, the output should be `9`.
Here is what you can do to burn 9 candles:
```
burn 5 candles, obtain 5 leftovers;
create 2 more candles, using 4 leftovers (1 leftover remains);
burn 2 candles, end up with 3 leftovers;
create another candle using 2 leftovers (1 leftover remains);
burn the created candle, which gives another leftover (2 leftovers in total);
create a candle from the remaining leftovers;
burn the last candle.
Thus, you can burn 5 + 2 + 1 + 1 = 9 candles, which is the answer.
```
# Input/Output
- `[input]` integer `candlesNumber`
The number of candles you have in your possession.
Constraints: 1 ≤ candlesNumber ≤ 50.
- `[input]` integer `makeNew`
The number of leftovers that you can use up to create a new candle.
Constraints: 2 ≤ makeNew ≤ 5.
- `[output]` an integer
|
def candles(m, n):
burnt = m
leftovers = m
while leftovers//n >= 1:
burnt += leftovers//n
leftovers = leftovers%n + leftovers//n
return burnt
|
In 1978 the British Medical Journal reported on an outbreak of influenza at a British boarding school. There were `1000` students. The outbreak began with one infected student.
We want to study the spread of the disease through the population of this school. The total population may be divided into three:
the infected `(i)`, those who have recovered `(r)`, and
those who are still susceptible `(s)` to get the disease.
We will study the disease on a period of `tm` days. One model of propagation uses 3 differential equations:
```
(1) s'(t) = -b * s(t) * i(t)
(2) i'(t) = b * s(t) * i(t) - a * i(t)
(3) r'(t) = a * i(t)
```
where `s(t), i(t), r(t)` are the susceptible, infected, recovered at time `t` and
`s'(t), i'(t), r'(t)` the corresponding derivatives.
`b` and `a` are constants:
`b` is representing a number of contacts which can spread the disease and
`a` is a fraction of the infected that will recover.
We can transform equations `(1), (2), (3)` in finite differences
(https://en.wikipedia.org/wiki/Finite_difference_method#Example:_ordinary_differential_equation)
(http://www.codewars.com/kata/56347fcfd086de8f11000014)
```
(I) S[k+1] = S[k] - dt * b * S[k] * I[k]
(II) I[k+1] = I[k] + dt * (b * S[k] * I[k] - a * I[k])
(III) R[k+1] = R[k] + dt * I[k] *a
```
The interval `[0, tm]` will be divided in `n` small intervals of length
`dt = tm/n`.
Initial conditions here could be : `S0 = 999, I0 = 1, R0 = 0`
Whatever S0 and I0, R0 (number of recovered at time 0) is always 0.
The function `epidemic` will return the maximum number of infected
as an *integer* (truncate to integer the result of max(I)).
# Example:
```
tm = 14 ;n = 336 ;s0 = 996 ;i0 = 2 ;b = 0.00206 ;a = 0.41
epidemic(tm, n, s0, i0, b, a) --> 483
```
# Notes:
- You will pass the tests if
`abs(actual - expected) <= 1`
- Keeping track of the values of susceptible, infected and recovered you can plot the solutions of the 3 differential equations. See an example below on the plot.

|
def epidemic(tm, n, s, i, b, a):
def f(s, i, r):
dt = tm / n
for t in range(n):
s, i, r = s-dt*b*s*i, i+dt*(b*s*i-a*i), r+dt*i*a
yield i
return int(max(f(s, i, 0)))
|
In 1978 the British Medical Journal reported on an outbreak of influenza at a British boarding school. There were `1000` students. The outbreak began with one infected student.
We want to study the spread of the disease through the population of this school. The total population may be divided into three:
the infected `(i)`, those who have recovered `(r)`, and
those who are still susceptible `(s)` to get the disease.
We will study the disease on a period of `tm` days. One model of propagation uses 3 differential equations:
```
(1) s'(t) = -b * s(t) * i(t)
(2) i'(t) = b * s(t) * i(t) - a * i(t)
(3) r'(t) = a * i(t)
```
where `s(t), i(t), r(t)` are the susceptible, infected, recovered at time `t` and
`s'(t), i'(t), r'(t)` the corresponding derivatives.
`b` and `a` are constants:
`b` is representing a number of contacts which can spread the disease and
`a` is a fraction of the infected that will recover.
We can transform equations `(1), (2), (3)` in finite differences
(https://en.wikipedia.org/wiki/Finite_difference_method#Example:_ordinary_differential_equation)
(http://www.codewars.com/kata/56347fcfd086de8f11000014)
```
(I) S[k+1] = S[k] - dt * b * S[k] * I[k]
(II) I[k+1] = I[k] + dt * (b * S[k] * I[k] - a * I[k])
(III) R[k+1] = R[k] + dt * I[k] *a
```
The interval `[0, tm]` will be divided in `n` small intervals of length
`dt = tm/n`.
Initial conditions here could be : `S0 = 999, I0 = 1, R0 = 0`
Whatever S0 and I0, R0 (number of recovered at time 0) is always 0.
The function `epidemic` will return the maximum number of infected
as an *integer* (truncate to integer the result of max(I)).
# Example:
```
tm = 14 ;n = 336 ;s0 = 996 ;i0 = 2 ;b = 0.00206 ;a = 0.41
epidemic(tm, n, s0, i0, b, a) --> 483
```
# Notes:
- You will pass the tests if
`abs(actual - expected) <= 1`
- Keeping track of the values of susceptible, infected and recovered you can plot the solutions of the 3 differential equations. See an example below on the plot.

|
def epidemic(tm, n, s0, i0, b, a):
timing = 0
dt = tm/n
r0 = 0
i_max = i0
while timing < tm:
timing += dt
s1 = s0 - dt*b*s0*i0
i0 = i0 + dt*(b*s0*i0-a*i0)
r0 = r0 + dt*r0*a
s0=s1
i_max=i0 if i0 > i_max else i_max
return i_max
# your code
|
In 1978 the British Medical Journal reported on an outbreak of influenza at a British boarding school. There were `1000` students. The outbreak began with one infected student.
We want to study the spread of the disease through the population of this school. The total population may be divided into three:
the infected `(i)`, those who have recovered `(r)`, and
those who are still susceptible `(s)` to get the disease.
We will study the disease on a period of `tm` days. One model of propagation uses 3 differential equations:
```
(1) s'(t) = -b * s(t) * i(t)
(2) i'(t) = b * s(t) * i(t) - a * i(t)
(3) r'(t) = a * i(t)
```
where `s(t), i(t), r(t)` are the susceptible, infected, recovered at time `t` and
`s'(t), i'(t), r'(t)` the corresponding derivatives.
`b` and `a` are constants:
`b` is representing a number of contacts which can spread the disease and
`a` is a fraction of the infected that will recover.
We can transform equations `(1), (2), (3)` in finite differences
(https://en.wikipedia.org/wiki/Finite_difference_method#Example:_ordinary_differential_equation)
(http://www.codewars.com/kata/56347fcfd086de8f11000014)
```
(I) S[k+1] = S[k] - dt * b * S[k] * I[k]
(II) I[k+1] = I[k] + dt * (b * S[k] * I[k] - a * I[k])
(III) R[k+1] = R[k] + dt * I[k] *a
```
The interval `[0, tm]` will be divided in `n` small intervals of length
`dt = tm/n`.
Initial conditions here could be : `S0 = 999, I0 = 1, R0 = 0`
Whatever S0 and I0, R0 (number of recovered at time 0) is always 0.
The function `epidemic` will return the maximum number of infected
as an *integer* (truncate to integer the result of max(I)).
# Example:
```
tm = 14 ;n = 336 ;s0 = 996 ;i0 = 2 ;b = 0.00206 ;a = 0.41
epidemic(tm, n, s0, i0, b, a) --> 483
```
# Notes:
- You will pass the tests if
`abs(actual - expected) <= 1`
- Keeping track of the values of susceptible, infected and recovered you can plot the solutions of the 3 differential equations. See an example below on the plot.

|
def epidemic(tm, n, s0, i0, b, a):
def evolve():
s, i, r, dt = s0, i0, 0, tm/n
while 1:
s, i, r = s - dt*b*s*i, i + dt*(b*s*i - a*i), r + dt*i*a
yield i
for i1 in evolve():
if i1 < i0:
return i0
i0 = i1
|
In 1978 the British Medical Journal reported on an outbreak of influenza at a British boarding school. There were `1000` students. The outbreak began with one infected student.
We want to study the spread of the disease through the population of this school. The total population may be divided into three:
the infected `(i)`, those who have recovered `(r)`, and
those who are still susceptible `(s)` to get the disease.
We will study the disease on a period of `tm` days. One model of propagation uses 3 differential equations:
```
(1) s'(t) = -b * s(t) * i(t)
(2) i'(t) = b * s(t) * i(t) - a * i(t)
(3) r'(t) = a * i(t)
```
where `s(t), i(t), r(t)` are the susceptible, infected, recovered at time `t` and
`s'(t), i'(t), r'(t)` the corresponding derivatives.
`b` and `a` are constants:
`b` is representing a number of contacts which can spread the disease and
`a` is a fraction of the infected that will recover.
We can transform equations `(1), (2), (3)` in finite differences
(https://en.wikipedia.org/wiki/Finite_difference_method#Example:_ordinary_differential_equation)
(http://www.codewars.com/kata/56347fcfd086de8f11000014)
```
(I) S[k+1] = S[k] - dt * b * S[k] * I[k]
(II) I[k+1] = I[k] + dt * (b * S[k] * I[k] - a * I[k])
(III) R[k+1] = R[k] + dt * I[k] *a
```
The interval `[0, tm]` will be divided in `n` small intervals of length
`dt = tm/n`.
Initial conditions here could be : `S0 = 999, I0 = 1, R0 = 0`
Whatever S0 and I0, R0 (number of recovered at time 0) is always 0.
The function `epidemic` will return the maximum number of infected
as an *integer* (truncate to integer the result of max(I)).
# Example:
```
tm = 14 ;n = 336 ;s0 = 996 ;i0 = 2 ;b = 0.00206 ;a = 0.41
epidemic(tm, n, s0, i0, b, a) --> 483
```
# Notes:
- You will pass the tests if
`abs(actual - expected) <= 1`
- Keeping track of the values of susceptible, infected and recovered you can plot the solutions of the 3 differential equations. See an example below on the plot.

|
def epidemic(tm, n, s0, i0, b, a):
dt = tm/float(n); t = [0] * (n+1)
s = [0] * (n+1); i = [0] * (n+1); r = [0] * (n+1)
s[0] = s0; i[0] = i0; r[0] = 0; t[0] = 0
for k in range(n):
t[k+1] = (k+1)*dt
s[k+1] = s[k] - dt*b*s[k]*i[k]
i[k+1] = i[k] + dt*(b*s[k]*i[k] - a*i[k])
r[k+1] = r[k] + dt*i[k]*a
return int(max(i))
|
In 1978 the British Medical Journal reported on an outbreak of influenza at a British boarding school. There were `1000` students. The outbreak began with one infected student.
We want to study the spread of the disease through the population of this school. The total population may be divided into three:
the infected `(i)`, those who have recovered `(r)`, and
those who are still susceptible `(s)` to get the disease.
We will study the disease on a period of `tm` days. One model of propagation uses 3 differential equations:
```
(1) s'(t) = -b * s(t) * i(t)
(2) i'(t) = b * s(t) * i(t) - a * i(t)
(3) r'(t) = a * i(t)
```
where `s(t), i(t), r(t)` are the susceptible, infected, recovered at time `t` and
`s'(t), i'(t), r'(t)` the corresponding derivatives.
`b` and `a` are constants:
`b` is representing a number of contacts which can spread the disease and
`a` is a fraction of the infected that will recover.
We can transform equations `(1), (2), (3)` in finite differences
(https://en.wikipedia.org/wiki/Finite_difference_method#Example:_ordinary_differential_equation)
(http://www.codewars.com/kata/56347fcfd086de8f11000014)
```
(I) S[k+1] = S[k] - dt * b * S[k] * I[k]
(II) I[k+1] = I[k] + dt * (b * S[k] * I[k] - a * I[k])
(III) R[k+1] = R[k] + dt * I[k] *a
```
The interval `[0, tm]` will be divided in `n` small intervals of length
`dt = tm/n`.
Initial conditions here could be : `S0 = 999, I0 = 1, R0 = 0`
Whatever S0 and I0, R0 (number of recovered at time 0) is always 0.
The function `epidemic` will return the maximum number of infected
as an *integer* (truncate to integer the result of max(I)).
# Example:
```
tm = 14 ;n = 336 ;s0 = 996 ;i0 = 2 ;b = 0.00206 ;a = 0.41
epidemic(tm, n, s0, i0, b, a) --> 483
```
# Notes:
- You will pass the tests if
`abs(actual - expected) <= 1`
- Keeping track of the values of susceptible, infected and recovered you can plot the solutions of the 3 differential equations. See an example below on the plot.

|
def epidemic( tm, n, s0, i0, b, a ):
S = { 0: s0 }
I = { 0: i0 }
dt = ( tm/n )
for k in range( n ):
S[k+1] = S[k] - (tm/n) * b * S[k] * I[k]
I[k+1] = I[k] + (tm/n) * (b * S[k] * I[k] - a * I[k])
return int( I[ max( I, key= lambda key: I[key] ) ] )
|
In 1978 the British Medical Journal reported on an outbreak of influenza at a British boarding school. There were `1000` students. The outbreak began with one infected student.
We want to study the spread of the disease through the population of this school. The total population may be divided into three:
the infected `(i)`, those who have recovered `(r)`, and
those who are still susceptible `(s)` to get the disease.
We will study the disease on a period of `tm` days. One model of propagation uses 3 differential equations:
```
(1) s'(t) = -b * s(t) * i(t)
(2) i'(t) = b * s(t) * i(t) - a * i(t)
(3) r'(t) = a * i(t)
```
where `s(t), i(t), r(t)` are the susceptible, infected, recovered at time `t` and
`s'(t), i'(t), r'(t)` the corresponding derivatives.
`b` and `a` are constants:
`b` is representing a number of contacts which can spread the disease and
`a` is a fraction of the infected that will recover.
We can transform equations `(1), (2), (3)` in finite differences
(https://en.wikipedia.org/wiki/Finite_difference_method#Example:_ordinary_differential_equation)
(http://www.codewars.com/kata/56347fcfd086de8f11000014)
```
(I) S[k+1] = S[k] - dt * b * S[k] * I[k]
(II) I[k+1] = I[k] + dt * (b * S[k] * I[k] - a * I[k])
(III) R[k+1] = R[k] + dt * I[k] *a
```
The interval `[0, tm]` will be divided in `n` small intervals of length
`dt = tm/n`.
Initial conditions here could be : `S0 = 999, I0 = 1, R0 = 0`
Whatever S0 and I0, R0 (number of recovered at time 0) is always 0.
The function `epidemic` will return the maximum number of infected
as an *integer* (truncate to integer the result of max(I)).
# Example:
```
tm = 14 ;n = 336 ;s0 = 996 ;i0 = 2 ;b = 0.00206 ;a = 0.41
epidemic(tm, n, s0, i0, b, a) --> 483
```
# Notes:
- You will pass the tests if
`abs(actual - expected) <= 1`
- Keeping track of the values of susceptible, infected and recovered you can plot the solutions of the 3 differential equations. See an example below on the plot.

|
epidemic=lambda t,n,s,i,b,a:([0 for d,r,m,S,I,R,z in[(float(t)/n,0,i,-1,-1,-1,__import__('itertools'))]],[[0 for S,I,R,s,i,r,m in[(lambda t:t+(max(m, t[4]),))((s,i,r,s-d*b*s*i,i+d*(b*s-a)*i,r+d*i*a))]]for _ in z.takewhile(lambda x:I<i,z.repeat(0))],m)[-1]
|
In 1978 the British Medical Journal reported on an outbreak of influenza at a British boarding school. There were `1000` students. The outbreak began with one infected student.
We want to study the spread of the disease through the population of this school. The total population may be divided into three:
the infected `(i)`, those who have recovered `(r)`, and
those who are still susceptible `(s)` to get the disease.
We will study the disease on a period of `tm` days. One model of propagation uses 3 differential equations:
```
(1) s'(t) = -b * s(t) * i(t)
(2) i'(t) = b * s(t) * i(t) - a * i(t)
(3) r'(t) = a * i(t)
```
where `s(t), i(t), r(t)` are the susceptible, infected, recovered at time `t` and
`s'(t), i'(t), r'(t)` the corresponding derivatives.
`b` and `a` are constants:
`b` is representing a number of contacts which can spread the disease and
`a` is a fraction of the infected that will recover.
We can transform equations `(1), (2), (3)` in finite differences
(https://en.wikipedia.org/wiki/Finite_difference_method#Example:_ordinary_differential_equation)
(http://www.codewars.com/kata/56347fcfd086de8f11000014)
```
(I) S[k+1] = S[k] - dt * b * S[k] * I[k]
(II) I[k+1] = I[k] + dt * (b * S[k] * I[k] - a * I[k])
(III) R[k+1] = R[k] + dt * I[k] *a
```
The interval `[0, tm]` will be divided in `n` small intervals of length
`dt = tm/n`.
Initial conditions here could be : `S0 = 999, I0 = 1, R0 = 0`
Whatever S0 and I0, R0 (number of recovered at time 0) is always 0.
The function `epidemic` will return the maximum number of infected
as an *integer* (truncate to integer the result of max(I)).
# Example:
```
tm = 14 ;n = 336 ;s0 = 996 ;i0 = 2 ;b = 0.00206 ;a = 0.41
epidemic(tm, n, s0, i0, b, a) --> 483
```
# Notes:
- You will pass the tests if
`abs(actual - expected) <= 1`
- Keeping track of the values of susceptible, infected and recovered you can plot the solutions of the 3 differential equations. See an example below on the plot.

|
def epidemic(tm, n, s0, i0, b, a):
s = [s0]; i = [i0]; r = [0]
t=0
dt = tm/n
t += dt
for k in range(n):
s[k] = s[k-1] - dt*b*s[k-1]*i[k-1]
i[k] = i[k-1] + dt * (b * s[k-1] * i[k-1] - a * i[k-1])
r[k] = r[k-1] + dt * i[k-1] *a
s.append(s[k])
i.append(i[k])
r.append(r[k])
return int(max(i))
|
In 1978 the British Medical Journal reported on an outbreak of influenza at a British boarding school. There were `1000` students. The outbreak began with one infected student.
We want to study the spread of the disease through the population of this school. The total population may be divided into three:
the infected `(i)`, those who have recovered `(r)`, and
those who are still susceptible `(s)` to get the disease.
We will study the disease on a period of `tm` days. One model of propagation uses 3 differential equations:
```
(1) s'(t) = -b * s(t) * i(t)
(2) i'(t) = b * s(t) * i(t) - a * i(t)
(3) r'(t) = a * i(t)
```
where `s(t), i(t), r(t)` are the susceptible, infected, recovered at time `t` and
`s'(t), i'(t), r'(t)` the corresponding derivatives.
`b` and `a` are constants:
`b` is representing a number of contacts which can spread the disease and
`a` is a fraction of the infected that will recover.
We can transform equations `(1), (2), (3)` in finite differences
(https://en.wikipedia.org/wiki/Finite_difference_method#Example:_ordinary_differential_equation)
(http://www.codewars.com/kata/56347fcfd086de8f11000014)
```
(I) S[k+1] = S[k] - dt * b * S[k] * I[k]
(II) I[k+1] = I[k] + dt * (b * S[k] * I[k] - a * I[k])
(III) R[k+1] = R[k] + dt * I[k] *a
```
The interval `[0, tm]` will be divided in `n` small intervals of length
`dt = tm/n`.
Initial conditions here could be : `S0 = 999, I0 = 1, R0 = 0`
Whatever S0 and I0, R0 (number of recovered at time 0) is always 0.
The function `epidemic` will return the maximum number of infected
as an *integer* (truncate to integer the result of max(I)).
# Example:
```
tm = 14 ;n = 336 ;s0 = 996 ;i0 = 2 ;b = 0.00206 ;a = 0.41
epidemic(tm, n, s0, i0, b, a) --> 483
```
# Notes:
- You will pass the tests if
`abs(actual - expected) <= 1`
- Keeping track of the values of susceptible, infected and recovered you can plot the solutions of the 3 differential equations. See an example below on the plot.

|
def epidemic(tm, n, s0, i0, b, a):
dt, imax = tm / n, 0
s, i, r = s0, i0, 0
for _ in range(n):
s, i, r = s - dt * b * s * i, i + dt * (b * s * i - a * i), r + dt * i * a
imax = max(int(i), imax)
return imax
|
In 1978 the British Medical Journal reported on an outbreak of influenza at a British boarding school. There were `1000` students. The outbreak began with one infected student.
We want to study the spread of the disease through the population of this school. The total population may be divided into three:
the infected `(i)`, those who have recovered `(r)`, and
those who are still susceptible `(s)` to get the disease.
We will study the disease on a period of `tm` days. One model of propagation uses 3 differential equations:
```
(1) s'(t) = -b * s(t) * i(t)
(2) i'(t) = b * s(t) * i(t) - a * i(t)
(3) r'(t) = a * i(t)
```
where `s(t), i(t), r(t)` are the susceptible, infected, recovered at time `t` and
`s'(t), i'(t), r'(t)` the corresponding derivatives.
`b` and `a` are constants:
`b` is representing a number of contacts which can spread the disease and
`a` is a fraction of the infected that will recover.
We can transform equations `(1), (2), (3)` in finite differences
(https://en.wikipedia.org/wiki/Finite_difference_method#Example:_ordinary_differential_equation)
(http://www.codewars.com/kata/56347fcfd086de8f11000014)
```
(I) S[k+1] = S[k] - dt * b * S[k] * I[k]
(II) I[k+1] = I[k] + dt * (b * S[k] * I[k] - a * I[k])
(III) R[k+1] = R[k] + dt * I[k] *a
```
The interval `[0, tm]` will be divided in `n` small intervals of length
`dt = tm/n`.
Initial conditions here could be : `S0 = 999, I0 = 1, R0 = 0`
Whatever S0 and I0, R0 (number of recovered at time 0) is always 0.
The function `epidemic` will return the maximum number of infected
as an *integer* (truncate to integer the result of max(I)).
# Example:
```
tm = 14 ;n = 336 ;s0 = 996 ;i0 = 2 ;b = 0.00206 ;a = 0.41
epidemic(tm, n, s0, i0, b, a) --> 483
```
# Notes:
- You will pass the tests if
`abs(actual - expected) <= 1`
- Keeping track of the values of susceptible, infected and recovered you can plot the solutions of the 3 differential equations. See an example below on the plot.

|
def epidemic(tm, n, s0, i0, b, a):
from math import floor
S, I = [s0], [i0]
dt = tm / n
for _ in range(n):
s = S[-1] - dt * b * S[-1] * I[-1]
i = I[-1] + dt * (b * S[-1] * I[-1] - a * I[-1])
S.append(s)
I.append(i)
return int(max(I))
|
Write a class Random that does the following:
1. Accepts a seed
```python
>>> random = Random(10)
>>> random.seed
10
```
2. Gives a random number between 0 and 1
```python
>>> random.random()
0.347957
>>> random.random()
0.932959
```
3. Gives a random int from a range
```python
>>> random.randint(0, 100)
67
>>> random.randint(0, 100)
93
```
Modules `random` and `os` are forbidden.
Dont forget to give feedback and your opinion on this kata even if you didn't solve it!
|
import hashlib
class Random():
HASH_MAX = (1 << 32 * 4) - 1
def __init__(self, seed):
self.seed = seed
def random(self):
x = int(hashlib.md5(str(self.seed).encode()).hexdigest(), 16)
self.seed += 1
return x / self.HASH_MAX
def randint(self, start, end):
return start + int(self.random() * (end+1-start))
|
Write a class Random that does the following:
1. Accepts a seed
```python
>>> random = Random(10)
>>> random.seed
10
```
2. Gives a random number between 0 and 1
```python
>>> random.random()
0.347957
>>> random.random()
0.932959
```
3. Gives a random int from a range
```python
>>> random.randint(0, 100)
67
>>> random.randint(0, 100)
93
```
Modules `random` and `os` are forbidden.
Dont forget to give feedback and your opinion on this kata even if you didn't solve it!
|
del __import__("sys").modules['random']
import random as random_
# Yeah, security isn't perfect yet
class Random():
def __init__(self, seed):
self.rand = random_.Random(seed)
def __setattr__(self, name, value):
if name == "seed": self.rand.seed(value)
else: super(Random, self).__setattr__(name, value)
def random(self):
return self.rand.uniform(0, 1)
def randint(self, start, end):
return self.rand.randint(start, end)
|
Write a class Random that does the following:
1. Accepts a seed
```python
>>> random = Random(10)
>>> random.seed
10
```
2. Gives a random number between 0 and 1
```python
>>> random.random()
0.347957
>>> random.random()
0.932959
```
3. Gives a random int from a range
```python
>>> random.randint(0, 100)
67
>>> random.randint(0, 100)
93
```
Modules `random` and `os` are forbidden.
Dont forget to give feedback and your opinion on this kata even if you didn't solve it!
|
class Random:
"""A shitty pseudo random number generator."""
def __init__(self, seed):
"""Initilize with 'seed'."""
self.seed = seed
def random(self):
"""Generate a pseudo random number x (0.0 <= x < 1.0)."""
self.seed = self.seed * 1103515245 + 12345
return ((self.seed // 65536) % 32768) / 32768
def randint(self, start, end):
"""Generate a pseudo random integer x ('start' <= x <= 'end')."""
return start + int(self.random() * (end - start + 1))
|
Write a class Random that does the following:
1. Accepts a seed
```python
>>> random = Random(10)
>>> random.seed
10
```
2. Gives a random number between 0 and 1
```python
>>> random.random()
0.347957
>>> random.random()
0.932959
```
3. Gives a random int from a range
```python
>>> random.randint(0, 100)
67
>>> random.randint(0, 100)
93
```
Modules `random` and `os` are forbidden.
Dont forget to give feedback and your opinion on this kata even if you didn't solve it!
|
class Random():
def __init__(self, seed):
self.seed = (seed if seed else 0x12345678) & 0xffffffff
def randint(self, start, end):
return int(self.random()*(end - start + 1) + start)
def random(self): # xorshift
x = self.seed
x ^= (x << 13) & 0xffffffff
x ^= (x >> 17)
x ^= (x << 5) & 0xffffffff
self.seed = x
return x/(1 << 32)
|
Write a class Random that does the following:
1. Accepts a seed
```python
>>> random = Random(10)
>>> random.seed
10
```
2. Gives a random number between 0 and 1
```python
>>> random.random()
0.347957
>>> random.random()
0.932959
```
3. Gives a random int from a range
```python
>>> random.randint(0, 100)
67
>>> random.randint(0, 100)
93
```
Modules `random` and `os` are forbidden.
Dont forget to give feedback and your opinion on this kata even if you didn't solve it!
|
import math
class Random():
def __init__(self, seed):
self.seed = seed
def random(self):
x= math.sin(self.seed) * 10000;
self.seed = x
return x-math.floor(x)
def randint(self, start, end):
return math.floor(self.random()*(end-start+1)) + start
|
Write a class Random that does the following:
1. Accepts a seed
```python
>>> random = Random(10)
>>> random.seed
10
```
2. Gives a random number between 0 and 1
```python
>>> random.random()
0.347957
>>> random.random()
0.932959
```
3. Gives a random int from a range
```python
>>> random.randint(0, 100)
67
>>> random.randint(0, 100)
93
```
Modules `random` and `os` are forbidden.
Dont forget to give feedback and your opinion on this kata even if you didn't solve it!
|
class Random():
def __init__(self, seed):
self.seed = seed
def random(self):
self.seed = (432544*self.seed+1)%1000000
return self.seed/1000000
def randint(self, start, end):
self.seed = (13*self.seed + 1)%(end-start+1)
return self.seed + start
|
Write a class Random that does the following:
1. Accepts a seed
```python
>>> random = Random(10)
>>> random.seed
10
```
2. Gives a random number between 0 and 1
```python
>>> random.random()
0.347957
>>> random.random()
0.932959
```
3. Gives a random int from a range
```python
>>> random.randint(0, 100)
67
>>> random.randint(0, 100)
93
```
Modules `random` and `os` are forbidden.
Dont forget to give feedback and your opinion on this kata even if you didn't solve it!
|
class Random():
def __init__(self, seed):
self.seed = seed
self.r_it = self.r()
def random(self):
return next(self.r_it) / 2**32
def randint(self, start, end):
return int(start + (1 + end - start) * next(self.r_it) / 2**32)
def r(self, m=2**32, a=1103515245, c=12345):
while True:
self.seed = (a * self.seed + c) % m
yield self.seed
|
Write a class Random that does the following:
1. Accepts a seed
```python
>>> random = Random(10)
>>> random.seed
10
```
2. Gives a random number between 0 and 1
```python
>>> random.random()
0.347957
>>> random.random()
0.932959
```
3. Gives a random int from a range
```python
>>> random.randint(0, 100)
67
>>> random.randint(0, 100)
93
```
Modules `random` and `os` are forbidden.
Dont forget to give feedback and your opinion on this kata even if you didn't solve it!
|
from datetime import datetime
class Random():
def __init__(self, seed):
self.seed=seed
self.x=self.next_x(self.seed)
@property
def seed(self):
return self.__seed
@seed.setter
def seed(self,seed):
self.x=self.next_x(seed)
self.__seed=seed
def next_x(self,x):
x=x^(x<<13&0xFFFFFFFF)
x=x^(x>>17&0xFFFFFFFF)
x=x^(x<<15&0xFFFFFFFF)
return x&0xFFFFFFFF
def random(self):
x=self.x
self.x=self.next_x(x)
return x/(2**32)
def randint(self, start, end):
x=self.x
self.x=self.next_x(x)
return (end-start)*x//(2**32)+start
|
Write a class Random that does the following:
1. Accepts a seed
```python
>>> random = Random(10)
>>> random.seed
10
```
2. Gives a random number between 0 and 1
```python
>>> random.random()
0.347957
>>> random.random()
0.932959
```
3. Gives a random int from a range
```python
>>> random.randint(0, 100)
67
>>> random.randint(0, 100)
93
```
Modules `random` and `os` are forbidden.
Dont forget to give feedback and your opinion on this kata even if you didn't solve it!
|
class Random():
def __init__(self, seed):
self.seed = seed
def random(self):
import math
x= math.sin(self.seed) * 10000;
self.seed = x
return x-math.floor(x)
def randint(self, start, end):
import math
return math.floor(self.random()*(end-start+1)) + start
|
Write a class Random that does the following:
1. Accepts a seed
```python
>>> random = Random(10)
>>> random.seed
10
```
2. Gives a random number between 0 and 1
```python
>>> random.random()
0.347957
>>> random.random()
0.932959
```
3. Gives a random int from a range
```python
>>> random.randint(0, 100)
67
>>> random.randint(0, 100)
93
```
Modules `random` and `os` are forbidden.
Dont forget to give feedback and your opinion on this kata even if you didn't solve it!
|
class Random():
def __init__(self, seed):
self.seed = seed
def random(self):
self.seed = (4123*self.seed+4321)%4096 #whatever
return self.seed/4096
def randint(self, start, end):
return int(start + (end-start)*self.random())
|
This kata is part one of precise fractions series (see pt. 2: http://www.codewars.com/kata/precise-fractions-pt-2-conversion).
When dealing with fractional values, there's always a problem with the precision of arithmetical operations. So lets fix it!
Your task is to implement class ```Fraction``` that takes care of simple fraction arithmetics. Requirements:
* class must have two-parameter constructor `Fraction(numerator, denominator)`; passed values will be non-zero integers, and may be positive or negative.
* two conversion methods must be supported:
* `toDecimal()` returns decimal representation of fraction
* `toString()` returns string with fractional representation of stored value in format:
[ SIGN ] [ WHOLES ] [ NUMERATOR / DENOMINATOR ]
* **Note**: each part is returned only if it is available and non-zero, with the only possible space character going between WHOLES and fraction. Examples: '-1/2', '3', '-5 3/4'
* The fractional part must always be normalized (ie. the numerator and denominators must not have any common divisors).
* Four operations need to be implemented: `add`, `subtract`, `multiply` and `divide`. Each of them may take integers as well as another `Fraction` instance as an argument, and must return a new `Fraction` instance.
* Instances must be immutable, hence none of the operations may modify either of the objects it is called upon, nor the passed argument.
#### Python Notes
* If one integer is passed into the initialiser, then the fraction should be assumed to represent an integer not a fraction.
* You must implement the standard operator overrides `__add__`, `__sub__`, `__mul__`, `__div__`, in each case you should support `other` being an `int` or another instance of `Fraction`.
* Implement `__str__` and `to_decimal` in place of `toString` and `toDecimal` as described above.
|
from fractions import Fraction
def to_string(self):
n, d = self.numerator, self.denominator
s, w, n = "-" if n < 0 else "", *divmod(abs(n), d)
r = " ".join((str(w) if w else "", f"{n}/{d}" if n else "")).strip()
return f"{s}{r}"
Fraction.__str__ = to_string
Fraction.to_decimal = lambda self: self.numerator / self.denominator
|
This kata is part one of precise fractions series (see pt. 2: http://www.codewars.com/kata/precise-fractions-pt-2-conversion).
When dealing with fractional values, there's always a problem with the precision of arithmetical operations. So lets fix it!
Your task is to implement class ```Fraction``` that takes care of simple fraction arithmetics. Requirements:
* class must have two-parameter constructor `Fraction(numerator, denominator)`; passed values will be non-zero integers, and may be positive or negative.
* two conversion methods must be supported:
* `toDecimal()` returns decimal representation of fraction
* `toString()` returns string with fractional representation of stored value in format:
[ SIGN ] [ WHOLES ] [ NUMERATOR / DENOMINATOR ]
* **Note**: each part is returned only if it is available and non-zero, with the only possible space character going between WHOLES and fraction. Examples: '-1/2', '3', '-5 3/4'
* The fractional part must always be normalized (ie. the numerator and denominators must not have any common divisors).
* Four operations need to be implemented: `add`, `subtract`, `multiply` and `divide`. Each of them may take integers as well as another `Fraction` instance as an argument, and must return a new `Fraction` instance.
* Instances must be immutable, hence none of the operations may modify either of the objects it is called upon, nor the passed argument.
#### Python Notes
* If one integer is passed into the initialiser, then the fraction should be assumed to represent an integer not a fraction.
* You must implement the standard operator overrides `__add__`, `__sub__`, `__mul__`, `__div__`, in each case you should support `other` being an `int` or another instance of `Fraction`.
* Implement `__str__` and `to_decimal` in place of `toString` and `toDecimal` as described above.
|
from fractions import Fraction
def to_string(self):
n, d = self.numerator, self.denominator
s, w, n = "-" if n < 0 else "", *divmod(abs(n), d)
r = " ".join((str(w) if w else "", f"{n}/{d}" if n else "")).strip()
return f"{s}{r}"
Fraction.__str__ = to_string
Fraction.to_decimal = lambda self: float(self.numerator) / self.denominator
|
This kata is part one of precise fractions series (see pt. 2: http://www.codewars.com/kata/precise-fractions-pt-2-conversion).
When dealing with fractional values, there's always a problem with the precision of arithmetical operations. So lets fix it!
Your task is to implement class ```Fraction``` that takes care of simple fraction arithmetics. Requirements:
* class must have two-parameter constructor `Fraction(numerator, denominator)`; passed values will be non-zero integers, and may be positive or negative.
* two conversion methods must be supported:
* `toDecimal()` returns decimal representation of fraction
* `toString()` returns string with fractional representation of stored value in format:
[ SIGN ] [ WHOLES ] [ NUMERATOR / DENOMINATOR ]
* **Note**: each part is returned only if it is available and non-zero, with the only possible space character going between WHOLES and fraction. Examples: '-1/2', '3', '-5 3/4'
* The fractional part must always be normalized (ie. the numerator and denominators must not have any common divisors).
* Four operations need to be implemented: `add`, `subtract`, `multiply` and `divide`. Each of them may take integers as well as another `Fraction` instance as an argument, and must return a new `Fraction` instance.
* Instances must be immutable, hence none of the operations may modify either of the objects it is called upon, nor the passed argument.
#### Python Notes
* If one integer is passed into the initialiser, then the fraction should be assumed to represent an integer not a fraction.
* You must implement the standard operator overrides `__add__`, `__sub__`, `__mul__`, `__div__`, in each case you should support `other` being an `int` or another instance of `Fraction`.
* Implement `__str__` and `to_decimal` in place of `toString` and `toDecimal` as described above.
|
from fractions import Fraction, gcd
def to_string(self):
n, d = self.numerator, self.denominator
s, w, n = "-" if n < 0 else "", *divmod(abs(n), d)
r = " ".join((str(w) if w else "", f"{n}/{d}" if n else "")).strip()
return f"{s}{r}"
Fraction.__str__ = to_string
Fraction.to_decimal = lambda self: float(self.numerator) / self.denominator
|
#Adding values of arrays in a shifted way
You have to write a method, that gets two parameter:
```markdown
1. An array of arrays with int-numbers
2. The shifting value
```
#The method should add the values of the arrays to one new array.
The arrays in the array will all have the same size and this size will always be greater than 0.
The shifting value is always a value from 0 up to the size of the arrays.
There are always arrays in the array, so you do not need to check for null or empty.
#1. Example:
```
[[1,2,3,4,5,6], [7,7,7,7,7,-7]], 0
1,2,3,4,5,6
7,7,7,7,7,-7
--> [8,9,10,11,12,-1]
```
#2. Example
```
[[1,2,3,4,5,6], [7,7,7,7,7,7]], 3
1,2,3,4,5,6
7,7,7,7,7,7
--> [1,2,3,11,12,13,7,7,7]
```
#3. Example
```
[[1,2,3,4,5,6], [7,7,7,-7,7,7], [1,1,1,1,1,1]], 3
1,2,3,4,5,6
7,7,7,-7,7,7
1,1,1,1,1,1
--> [1,2,3,11,12,13,-6,8,8,1,1,1]
```
Have fun coding it and please don't forget to vote and rank this kata! :-)
I have created other katas. Have a look if you like coding and challenges.
|
from itertools import zip_longest as zl
def sum_arrays(arrays, shift):
shifted = [[0] * shift * i + arr for i, arr in enumerate(arrays)]
return [sum(t) for t in zl(*shifted, fillvalue=0)]
|
#Adding values of arrays in a shifted way
You have to write a method, that gets two parameter:
```markdown
1. An array of arrays with int-numbers
2. The shifting value
```
#The method should add the values of the arrays to one new array.
The arrays in the array will all have the same size and this size will always be greater than 0.
The shifting value is always a value from 0 up to the size of the arrays.
There are always arrays in the array, so you do not need to check for null or empty.
#1. Example:
```
[[1,2,3,4,5,6], [7,7,7,7,7,-7]], 0
1,2,3,4,5,6
7,7,7,7,7,-7
--> [8,9,10,11,12,-1]
```
#2. Example
```
[[1,2,3,4,5,6], [7,7,7,7,7,7]], 3
1,2,3,4,5,6
7,7,7,7,7,7
--> [1,2,3,11,12,13,7,7,7]
```
#3. Example
```
[[1,2,3,4,5,6], [7,7,7,-7,7,7], [1,1,1,1,1,1]], 3
1,2,3,4,5,6
7,7,7,-7,7,7
1,1,1,1,1,1
--> [1,2,3,11,12,13,-6,8,8,1,1,1]
```
Have fun coding it and please don't forget to vote and rank this kata! :-)
I have created other katas. Have a look if you like coding and challenges.
|
from itertools import zip_longest
def sum_arrays(arrays, shift):
shifted = [([0] * shift * i) + array for i, array in enumerate(arrays)]
return [sum(nums) for nums in zip_longest(*shifted, fillvalue=0)]
|
#Adding values of arrays in a shifted way
You have to write a method, that gets two parameter:
```markdown
1. An array of arrays with int-numbers
2. The shifting value
```
#The method should add the values of the arrays to one new array.
The arrays in the array will all have the same size and this size will always be greater than 0.
The shifting value is always a value from 0 up to the size of the arrays.
There are always arrays in the array, so you do not need to check for null or empty.
#1. Example:
```
[[1,2,3,4,5,6], [7,7,7,7,7,-7]], 0
1,2,3,4,5,6
7,7,7,7,7,-7
--> [8,9,10,11,12,-1]
```
#2. Example
```
[[1,2,3,4,5,6], [7,7,7,7,7,7]], 3
1,2,3,4,5,6
7,7,7,7,7,7
--> [1,2,3,11,12,13,7,7,7]
```
#3. Example
```
[[1,2,3,4,5,6], [7,7,7,-7,7,7], [1,1,1,1,1,1]], 3
1,2,3,4,5,6
7,7,7,-7,7,7
1,1,1,1,1,1
--> [1,2,3,11,12,13,-6,8,8,1,1,1]
```
Have fun coding it and please don't forget to vote and rank this kata! :-)
I have created other katas. Have a look if you like coding and challenges.
|
def sum_arrays(arrays, shift):
shifted = [ [0]*i*shift + a + [0]*(len(arrays)-i-1)*shift for i, a in enumerate(arrays)]
return list(map(sum, zip(*shifted)))
|
#Adding values of arrays in a shifted way
You have to write a method, that gets two parameter:
```markdown
1. An array of arrays with int-numbers
2. The shifting value
```
#The method should add the values of the arrays to one new array.
The arrays in the array will all have the same size and this size will always be greater than 0.
The shifting value is always a value from 0 up to the size of the arrays.
There are always arrays in the array, so you do not need to check for null or empty.
#1. Example:
```
[[1,2,3,4,5,6], [7,7,7,7,7,-7]], 0
1,2,3,4,5,6
7,7,7,7,7,-7
--> [8,9,10,11,12,-1]
```
#2. Example
```
[[1,2,3,4,5,6], [7,7,7,7,7,7]], 3
1,2,3,4,5,6
7,7,7,7,7,7
--> [1,2,3,11,12,13,7,7,7]
```
#3. Example
```
[[1,2,3,4,5,6], [7,7,7,-7,7,7], [1,1,1,1,1,1]], 3
1,2,3,4,5,6
7,7,7,-7,7,7
1,1,1,1,1,1
--> [1,2,3,11,12,13,-6,8,8,1,1,1]
```
Have fun coding it and please don't forget to vote and rank this kata! :-)
I have created other katas. Have a look if you like coding and challenges.
|
def sum_arrays(arr, shift):
red = [[], arr][not shift]
if shift>0:
la = len(arr)
l0 = len(arr[0])
lr = l0 + (shift * (la-(1)))
ret = [0*l0] * lr
for i , x in zip(list(range(0,lr,shift)), list(range(la))) :
temp = ret[::]
temp[i:l0+i] = arr[x]
red.append(temp)
return [ sum(a) for a in zip(*red)]
|
#Adding values of arrays in a shifted way
You have to write a method, that gets two parameter:
```markdown
1. An array of arrays with int-numbers
2. The shifting value
```
#The method should add the values of the arrays to one new array.
The arrays in the array will all have the same size and this size will always be greater than 0.
The shifting value is always a value from 0 up to the size of the arrays.
There are always arrays in the array, so you do not need to check for null or empty.
#1. Example:
```
[[1,2,3,4,5,6], [7,7,7,7,7,-7]], 0
1,2,3,4,5,6
7,7,7,7,7,-7
--> [8,9,10,11,12,-1]
```
#2. Example
```
[[1,2,3,4,5,6], [7,7,7,7,7,7]], 3
1,2,3,4,5,6
7,7,7,7,7,7
--> [1,2,3,11,12,13,7,7,7]
```
#3. Example
```
[[1,2,3,4,5,6], [7,7,7,-7,7,7], [1,1,1,1,1,1]], 3
1,2,3,4,5,6
7,7,7,-7,7,7
1,1,1,1,1,1
--> [1,2,3,11,12,13,-6,8,8,1,1,1]
```
Have fun coding it and please don't forget to vote and rank this kata! :-)
I have created other katas. Have a look if you like coding and challenges.
|
def sum_arrays(arrays, shift):
dummy_arr = [ 0 for i in range(len(arrays[0])+(len(arrays)-1)*shift)]
modified_arrays = []
for i in range(len(arrays)):
modified_arrays.append([0 for temp in range(i*shift)])
modified_arrays[i] += arrays[i]
if len(modified_arrays[i]) < len(dummy_arr):
modified_arrays[i] += [0 for temp in range(len(dummy_arr) -len(modified_arrays[i]) )]
for i in range(len(dummy_arr)):
for arr in modified_arrays:
dummy_arr[i] += arr[i]
return dummy_arr
|
#Adding values of arrays in a shifted way
You have to write a method, that gets two parameter:
```markdown
1. An array of arrays with int-numbers
2. The shifting value
```
#The method should add the values of the arrays to one new array.
The arrays in the array will all have the same size and this size will always be greater than 0.
The shifting value is always a value from 0 up to the size of the arrays.
There are always arrays in the array, so you do not need to check for null or empty.
#1. Example:
```
[[1,2,3,4,5,6], [7,7,7,7,7,-7]], 0
1,2,3,4,5,6
7,7,7,7,7,-7
--> [8,9,10,11,12,-1]
```
#2. Example
```
[[1,2,3,4,5,6], [7,7,7,7,7,7]], 3
1,2,3,4,5,6
7,7,7,7,7,7
--> [1,2,3,11,12,13,7,7,7]
```
#3. Example
```
[[1,2,3,4,5,6], [7,7,7,-7,7,7], [1,1,1,1,1,1]], 3
1,2,3,4,5,6
7,7,7,-7,7,7
1,1,1,1,1,1
--> [1,2,3,11,12,13,-6,8,8,1,1,1]
```
Have fun coding it and please don't forget to vote and rank this kata! :-)
I have created other katas. Have a look if you like coding and challenges.
|
import itertools
def sum_arrays(arrays, shift):
return [sum(xs) for xs in itertools.zip_longest(*[[0] * (shift*i) + a for i, a in enumerate(arrays)], fillvalue=0)]
|
#Adding values of arrays in a shifted way
You have to write a method, that gets two parameter:
```markdown
1. An array of arrays with int-numbers
2. The shifting value
```
#The method should add the values of the arrays to one new array.
The arrays in the array will all have the same size and this size will always be greater than 0.
The shifting value is always a value from 0 up to the size of the arrays.
There are always arrays in the array, so you do not need to check for null or empty.
#1. Example:
```
[[1,2,3,4,5,6], [7,7,7,7,7,-7]], 0
1,2,3,4,5,6
7,7,7,7,7,-7
--> [8,9,10,11,12,-1]
```
#2. Example
```
[[1,2,3,4,5,6], [7,7,7,7,7,7]], 3
1,2,3,4,5,6
7,7,7,7,7,7
--> [1,2,3,11,12,13,7,7,7]
```
#3. Example
```
[[1,2,3,4,5,6], [7,7,7,-7,7,7], [1,1,1,1,1,1]], 3
1,2,3,4,5,6
7,7,7,-7,7,7
1,1,1,1,1,1
--> [1,2,3,11,12,13,-6,8,8,1,1,1]
```
Have fun coding it and please don't forget to vote and rank this kata! :-)
I have created other katas. Have a look if you like coding and challenges.
|
from itertools import zip_longest
def sum_arrays(arrays, shift):
new_arr = []
for i, arr in enumerate(arrays):
new_arr.append([0] * shift * i + arr)
return list(map(sum, zip_longest(*new_arr, fillvalue=0)))
|
#Adding values of arrays in a shifted way
You have to write a method, that gets two parameter:
```markdown
1. An array of arrays with int-numbers
2. The shifting value
```
#The method should add the values of the arrays to one new array.
The arrays in the array will all have the same size and this size will always be greater than 0.
The shifting value is always a value from 0 up to the size of the arrays.
There are always arrays in the array, so you do not need to check for null or empty.
#1. Example:
```
[[1,2,3,4,5,6], [7,7,7,7,7,-7]], 0
1,2,3,4,5,6
7,7,7,7,7,-7
--> [8,9,10,11,12,-1]
```
#2. Example
```
[[1,2,3,4,5,6], [7,7,7,7,7,7]], 3
1,2,3,4,5,6
7,7,7,7,7,7
--> [1,2,3,11,12,13,7,7,7]
```
#3. Example
```
[[1,2,3,4,5,6], [7,7,7,-7,7,7], [1,1,1,1,1,1]], 3
1,2,3,4,5,6
7,7,7,-7,7,7
1,1,1,1,1,1
--> [1,2,3,11,12,13,-6,8,8,1,1,1]
```
Have fun coding it and please don't forget to vote and rank this kata! :-)
I have created other katas. Have a look if you like coding and challenges.
|
def sum_arrays(arrays, shift):
m = len(arrays)
n = len(arrays[0])
result = [0] * (n + shift * (m - 1))
index = 0
for a in arrays:
for element in a:
result[index] += element
index += 1
index += shift - n
return result
|
#Adding values of arrays in a shifted way
You have to write a method, that gets two parameter:
```markdown
1. An array of arrays with int-numbers
2. The shifting value
```
#The method should add the values of the arrays to one new array.
The arrays in the array will all have the same size and this size will always be greater than 0.
The shifting value is always a value from 0 up to the size of the arrays.
There are always arrays in the array, so you do not need to check for null or empty.
#1. Example:
```
[[1,2,3,4,5,6], [7,7,7,7,7,-7]], 0
1,2,3,4,5,6
7,7,7,7,7,-7
--> [8,9,10,11,12,-1]
```
#2. Example
```
[[1,2,3,4,5,6], [7,7,7,7,7,7]], 3
1,2,3,4,5,6
7,7,7,7,7,7
--> [1,2,3,11,12,13,7,7,7]
```
#3. Example
```
[[1,2,3,4,5,6], [7,7,7,-7,7,7], [1,1,1,1,1,1]], 3
1,2,3,4,5,6
7,7,7,-7,7,7
1,1,1,1,1,1
--> [1,2,3,11,12,13,-6,8,8,1,1,1]
```
Have fun coding it and please don't forget to vote and rank this kata! :-)
I have created other katas. Have a look if you like coding and challenges.
|
def sum_arrays(arrays,shift):
arrays_new=[arr[:] for arr in arrays]
if shift==0:return list(map(sum,zip(*arrays_new)))
out=[]
i,j=1,1
while any(arr for arr in arrays_new):
out.append(sum(arr.pop(0) for arr in arrays_new[:i] if arr))
if j%shift==0:i+=1
j+=1
return out
|
#Adding values of arrays in a shifted way
You have to write a method, that gets two parameter:
```markdown
1. An array of arrays with int-numbers
2. The shifting value
```
#The method should add the values of the arrays to one new array.
The arrays in the array will all have the same size and this size will always be greater than 0.
The shifting value is always a value from 0 up to the size of the arrays.
There are always arrays in the array, so you do not need to check for null or empty.
#1. Example:
```
[[1,2,3,4,5,6], [7,7,7,7,7,-7]], 0
1,2,3,4,5,6
7,7,7,7,7,-7
--> [8,9,10,11,12,-1]
```
#2. Example
```
[[1,2,3,4,5,6], [7,7,7,7,7,7]], 3
1,2,3,4,5,6
7,7,7,7,7,7
--> [1,2,3,11,12,13,7,7,7]
```
#3. Example
```
[[1,2,3,4,5,6], [7,7,7,-7,7,7], [1,1,1,1,1,1]], 3
1,2,3,4,5,6
7,7,7,-7,7,7
1,1,1,1,1,1
--> [1,2,3,11,12,13,-6,8,8,1,1,1]
```
Have fun coding it and please don't forget to vote and rank this kata! :-)
I have created other katas. Have a look if you like coding and challenges.
|
def sum_arrays(arrays, shift):
l = []
for i in range(len(arrays)):
tmp = i * shift * [0] + arrays[i] + (len(arrays) - i - 1) * shift * [0]
l.append(tmp)
res = []
for i in range(len(l[0])):
tmp = sum([ii[i] for ii in l])
res.append(tmp)
return res
|
# Task
You are implementing your own HTML editor. To make it more comfortable for developers you would like to add an auto-completion feature to it.
Given the starting HTML tag, find the appropriate end tag which your editor should propose.
# Example
For startTag = "<button type='button' disabled>", the output should be "</button>";
For startTag = "<i>", the output should be "</i>".
# Input/Output
- `[input]` string `startTag`/`start_tag`
- `[output]` a string
|
def html_end_tag_by_start_tag(start_tag):
return "</" + start_tag[1:-1].split(" ")[0] + ">"
|
# Task
You are implementing your own HTML editor. To make it more comfortable for developers you would like to add an auto-completion feature to it.
Given the starting HTML tag, find the appropriate end tag which your editor should propose.
# Example
For startTag = "<button type='button' disabled>", the output should be "</button>";
For startTag = "<i>", the output should be "</i>".
# Input/Output
- `[input]` string `startTag`/`start_tag`
- `[output]` a string
|
def html_end_tag_by_start_tag(start_tag):
return "</{}>".format(start_tag.strip("<>").split(" ")[0])
|
# Task
You are implementing your own HTML editor. To make it more comfortable for developers you would like to add an auto-completion feature to it.
Given the starting HTML tag, find the appropriate end tag which your editor should propose.
# Example
For startTag = "<button type='button' disabled>", the output should be "</button>";
For startTag = "<i>", the output should be "</i>".
# Input/Output
- `[input]` string `startTag`/`start_tag`
- `[output]` a string
|
import re
def html_end_tag_by_start_tag(start_tag):
return re.sub('<(\w+)(?:.*)>', r'</\1>', start_tag)
|
# Task
You are implementing your own HTML editor. To make it more comfortable for developers you would like to add an auto-completion feature to it.
Given the starting HTML tag, find the appropriate end tag which your editor should propose.
# Example
For startTag = "<button type='button' disabled>", the output should be "</button>";
For startTag = "<i>", the output should be "</i>".
# Input/Output
- `[input]` string `startTag`/`start_tag`
- `[output]` a string
|
def html_end_tag_by_start_tag(s):
return '</{}>'.format(s[1:s.find(' ')])
|
# Task
You are implementing your own HTML editor. To make it more comfortable for developers you would like to add an auto-completion feature to it.
Given the starting HTML tag, find the appropriate end tag which your editor should propose.
# Example
For startTag = "<button type='button' disabled>", the output should be "</button>";
For startTag = "<i>", the output should be "</i>".
# Input/Output
- `[input]` string `startTag`/`start_tag`
- `[output]` a string
|
def html_end_tag_by_start_tag(start_tag):
w = start_tag.strip('< >').split(' ')
return '</{}>'.format(w[0])
|
# Task
You are implementing your own HTML editor. To make it more comfortable for developers you would like to add an auto-completion feature to it.
Given the starting HTML tag, find the appropriate end tag which your editor should propose.
# Example
For startTag = "<button type='button' disabled>", the output should be "</button>";
For startTag = "<i>", the output should be "</i>".
# Input/Output
- `[input]` string `startTag`/`start_tag`
- `[output]` a string
|
def html_end_tag_by_start_tag(start_tag):
if " " in start_tag:
a = start_tag.split(" ")
return "</" + a[0][1:] + ">"
else:
return "</" + start_tag[1:-1] + ">"
|
# Task
You are implementing your own HTML editor. To make it more comfortable for developers you would like to add an auto-completion feature to it.
Given the starting HTML tag, find the appropriate end tag which your editor should propose.
# Example
For startTag = "<button type='button' disabled>", the output should be "</button>";
For startTag = "<i>", the output should be "</i>".
# Input/Output
- `[input]` string `startTag`/`start_tag`
- `[output]` a string
|
import re
def html_end_tag_by_start_tag(s):
r = re.match(r'<\w+',s).group()
return f'</{r[1:]}>'
|
# Task
You are implementing your own HTML editor. To make it more comfortable for developers you would like to add an auto-completion feature to it.
Given the starting HTML tag, find the appropriate end tag which your editor should propose.
# Example
For startTag = "<button type='button' disabled>", the output should be "</button>";
For startTag = "<i>", the output should be "</i>".
# Input/Output
- `[input]` string `startTag`/`start_tag`
- `[output]` a string
|
def html_end_tag_by_start_tag(s):
result = s.split()[0][0]+'/'+s.split()[0][1:]+ '>'
if result[-2:] == '>>':
result = result.replace('>>','>')
return result
|
# Task
You are implementing your own HTML editor. To make it more comfortable for developers you would like to add an auto-completion feature to it.
Given the starting HTML tag, find the appropriate end tag which your editor should propose.
# Example
For startTag = "<button type='button' disabled>", the output should be "</button>";
For startTag = "<i>", the output should be "</i>".
# Input/Output
- `[input]` string `startTag`/`start_tag`
- `[output]` a string
|
from re import search
def html_end_tag_by_start_tag(tag):
return f"</{search('<[a-z]+',tag).group()[1:]}>"
|
# Task
You are implementing your own HTML editor. To make it more comfortable for developers you would like to add an auto-completion feature to it.
Given the starting HTML tag, find the appropriate end tag which your editor should propose.
# Example
For startTag = "<button type='button' disabled>", the output should be "</button>";
For startTag = "<i>", the output should be "</i>".
# Input/Output
- `[input]` string `startTag`/`start_tag`
- `[output]` a string
|
def html_end_tag_by_start_tag(start_tag):
init = start_tag.split()[0].strip('>').strip('<')
return f"</{init}>"
|
# Our Setup
Alice and Bob work in an office. When the workload is light and the boss isn't looking, they often play simple word games for fun. This is one of those days!
# This Game
Today Alice and Bob are playing what they like to call _Mutations_, where they take turns trying to "think up" a new four-letter word identical to the prior word except for one letter. They just keep on going until their memories fail out.
# Their Words
Alice and Bob have memories of the same size, each able to recall `10` to `2000` different four-letter words. Memory words and initial game word are randomly taken from a list of `4000` (unique, four-letter, lowercased) words, any of which may appear in both memories.
The expression to "think up" a new word means that for their turn, the player must submit as their response word the first valid, unused word that appears in their memory (by lowest array index), as their memories are ordered from the most "memorable" words to the least.
# The Rules
* a valid response word must contain four different letters
* `1` letter is replaced while the other `3` stay in position
* it must be the lowest indexed valid word in their memory
* this word cannot have already been used during the game
* the final player to provide a valid word will win the game
* if 1st player fails 1st turn, 2nd can win with a valid word
* when both players fail the initial word, there is no winner
# Your Task
To determine the winner!
# Some Examples
`alice = plat,rend,bear,soar,mare,pare,flap,neat,clan,pore`
`bob = boar,clap,farm,lend,near,peat,pure,more,plan,soap`
1) In the case of `word = "send"` and `first = 0`:
* Alice responds to `send` with `rend`
* Bob responds to `rend` with `lend`
* Alice has no valid response to `lend`
* Bob wins the game.
2) In the case of `word = "flip"` and `first = 1`:
* Bob has no valid response to `flip`
* Alice responds to `flip` with `flap`
* Alice wins the game.
3) In the case of `word = "maze"` and `first = 0`:
* Alice responds to `maze` with `mare`
* Bob responds to `mare` with `more`
* Alice responds to `more` with `pore`
* Bob responds to `pore` with `pure`
* Alice responds to `pure` with `pare`
* Bob has no valid response to `pare`
* Alice wins the game.
4) In the case of `word = "calm"` and `first = 1`:
* Bob has no valid response to `calm`
* Alice has no valid response to `calm`
* Neither wins the game.
# Input
``` c
size_t n // number of words (10 <= n <= 2000)
const char *const alice[n]; // Alice's memory of four-letter words
const char *const bob[n]; // Bob's memory of four-letter words
const char* word; // initial challenge word of the game
int first; // whom begins: 0 for Alice, 1 for Bob
```
``` python
alice # list of words in Alice's memory (10 <= n <= 2000)
bob # list of words in Bob's memory (10 <= n <= 2000)
word # string of the initial challenge word
first # integer of whom begins: 0 for Alice, 1 for Bob
```
``` javascript
let alice; // array of words in Alice's memory (10 <= n <= 2000)
let bob; // array of words in Bob's memory (10 <= n <= 2000)
let word; // string of the initial challenge word
let first; // integer of whom begins: 0 for Alice, 1 for Bob
```
# Output
``` c
return 0 // if Alice wins
return 1 // if Bob wins
return -1 // if both fail
```
``` python
return 0 # if Alice wins
return 1 # if Bob wins
return -1 # if both fail
```
``` javascript
return 0 // if Alice wins
return 1 // if Bob wins
return -1 // if both fail
```
# Enjoy!
If interested, I also have [this kata](https://www.codewars.com/kata/5cb7baa989b1c50014a53333) as well as [this other kata](https://www.codewars.com/kata/5cab471da732b30018968071) to consider solving.
|
import re
def genMask(w):
x = list(w)
for i in range(len(w)):
x[i] = '.'
yield ''.join(x)
x[i] = w[i]
def mutations(alice, bob, word, first):
players, seen = [alice,bob], {word}
win, failed, i = -1, -1, first^1
while 1:
i ^= 1
lst = players[i]
reg = re.compile('|'.join(genMask(word)))
found = next((w for w in lst if reg.match(w) and w not in seen and len(set(w))==4), None)
if found is None:
if failed==i^1: break
failed = i
else:
seen.add(found)
word, win = found, i
if failed!=-1: break
return win
|
# Our Setup
Alice and Bob work in an office. When the workload is light and the boss isn't looking, they often play simple word games for fun. This is one of those days!
# This Game
Today Alice and Bob are playing what they like to call _Mutations_, where they take turns trying to "think up" a new four-letter word identical to the prior word except for one letter. They just keep on going until their memories fail out.
# Their Words
Alice and Bob have memories of the same size, each able to recall `10` to `2000` different four-letter words. Memory words and initial game word are randomly taken from a list of `4000` (unique, four-letter, lowercased) words, any of which may appear in both memories.
The expression to "think up" a new word means that for their turn, the player must submit as their response word the first valid, unused word that appears in their memory (by lowest array index), as their memories are ordered from the most "memorable" words to the least.
# The Rules
* a valid response word must contain four different letters
* `1` letter is replaced while the other `3` stay in position
* it must be the lowest indexed valid word in their memory
* this word cannot have already been used during the game
* the final player to provide a valid word will win the game
* if 1st player fails 1st turn, 2nd can win with a valid word
* when both players fail the initial word, there is no winner
# Your Task
To determine the winner!
# Some Examples
`alice = plat,rend,bear,soar,mare,pare,flap,neat,clan,pore`
`bob = boar,clap,farm,lend,near,peat,pure,more,plan,soap`
1) In the case of `word = "send"` and `first = 0`:
* Alice responds to `send` with `rend`
* Bob responds to `rend` with `lend`
* Alice has no valid response to `lend`
* Bob wins the game.
2) In the case of `word = "flip"` and `first = 1`:
* Bob has no valid response to `flip`
* Alice responds to `flip` with `flap`
* Alice wins the game.
3) In the case of `word = "maze"` and `first = 0`:
* Alice responds to `maze` with `mare`
* Bob responds to `mare` with `more`
* Alice responds to `more` with `pore`
* Bob responds to `pore` with `pure`
* Alice responds to `pure` with `pare`
* Bob has no valid response to `pare`
* Alice wins the game.
4) In the case of `word = "calm"` and `first = 1`:
* Bob has no valid response to `calm`
* Alice has no valid response to `calm`
* Neither wins the game.
# Input
``` c
size_t n // number of words (10 <= n <= 2000)
const char *const alice[n]; // Alice's memory of four-letter words
const char *const bob[n]; // Bob's memory of four-letter words
const char* word; // initial challenge word of the game
int first; // whom begins: 0 for Alice, 1 for Bob
```
``` python
alice # list of words in Alice's memory (10 <= n <= 2000)
bob # list of words in Bob's memory (10 <= n <= 2000)
word # string of the initial challenge word
first # integer of whom begins: 0 for Alice, 1 for Bob
```
``` javascript
let alice; // array of words in Alice's memory (10 <= n <= 2000)
let bob; // array of words in Bob's memory (10 <= n <= 2000)
let word; // string of the initial challenge word
let first; // integer of whom begins: 0 for Alice, 1 for Bob
```
# Output
``` c
return 0 // if Alice wins
return 1 // if Bob wins
return -1 // if both fail
```
``` python
return 0 # if Alice wins
return 1 # if Bob wins
return -1 # if both fail
```
``` javascript
return 0 // if Alice wins
return 1 // if Bob wins
return -1 // if both fail
```
# Enjoy!
If interested, I also have [this kata](https://www.codewars.com/kata/5cb7baa989b1c50014a53333) as well as [this other kata](https://www.codewars.com/kata/5cab471da732b30018968071) to consider solving.
|
def mutations(alice, bob, word, first):
seen = {word}
mapping = {0:alice, 1:bob}
prev_state,state = -1, -1
def foo(word,first):
nonlocal state, prev_state
foo.counter += 1
if foo.counter > 2 and state < 0 or foo.counter > 2 and prev_state < 0:
return
for a_word in mapping[first]:
counter = 0
for i,x in enumerate(a_word):
if a_word[i] == word[i]:
counter += 1
if counter == 3 and len(set(a_word))==4 and a_word not in seen:
seen.add(a_word)
prev_state = state
state = first
word = a_word
break
if counter==3 or state < 0:
return foo(word,first^1)
foo.counter = 0
foo(word,first)
return state
|
# Our Setup
Alice and Bob work in an office. When the workload is light and the boss isn't looking, they often play simple word games for fun. This is one of those days!
# This Game
Today Alice and Bob are playing what they like to call _Mutations_, where they take turns trying to "think up" a new four-letter word identical to the prior word except for one letter. They just keep on going until their memories fail out.
# Their Words
Alice and Bob have memories of the same size, each able to recall `10` to `2000` different four-letter words. Memory words and initial game word are randomly taken from a list of `4000` (unique, four-letter, lowercased) words, any of which may appear in both memories.
The expression to "think up" a new word means that for their turn, the player must submit as their response word the first valid, unused word that appears in their memory (by lowest array index), as their memories are ordered from the most "memorable" words to the least.
# The Rules
* a valid response word must contain four different letters
* `1` letter is replaced while the other `3` stay in position
* it must be the lowest indexed valid word in their memory
* this word cannot have already been used during the game
* the final player to provide a valid word will win the game
* if 1st player fails 1st turn, 2nd can win with a valid word
* when both players fail the initial word, there is no winner
# Your Task
To determine the winner!
# Some Examples
`alice = plat,rend,bear,soar,mare,pare,flap,neat,clan,pore`
`bob = boar,clap,farm,lend,near,peat,pure,more,plan,soap`
1) In the case of `word = "send"` and `first = 0`:
* Alice responds to `send` with `rend`
* Bob responds to `rend` with `lend`
* Alice has no valid response to `lend`
* Bob wins the game.
2) In the case of `word = "flip"` and `first = 1`:
* Bob has no valid response to `flip`
* Alice responds to `flip` with `flap`
* Alice wins the game.
3) In the case of `word = "maze"` and `first = 0`:
* Alice responds to `maze` with `mare`
* Bob responds to `mare` with `more`
* Alice responds to `more` with `pore`
* Bob responds to `pore` with `pure`
* Alice responds to `pure` with `pare`
* Bob has no valid response to `pare`
* Alice wins the game.
4) In the case of `word = "calm"` and `first = 1`:
* Bob has no valid response to `calm`
* Alice has no valid response to `calm`
* Neither wins the game.
# Input
``` c
size_t n // number of words (10 <= n <= 2000)
const char *const alice[n]; // Alice's memory of four-letter words
const char *const bob[n]; // Bob's memory of four-letter words
const char* word; // initial challenge word of the game
int first; // whom begins: 0 for Alice, 1 for Bob
```
``` python
alice # list of words in Alice's memory (10 <= n <= 2000)
bob # list of words in Bob's memory (10 <= n <= 2000)
word # string of the initial challenge word
first # integer of whom begins: 0 for Alice, 1 for Bob
```
``` javascript
let alice; // array of words in Alice's memory (10 <= n <= 2000)
let bob; // array of words in Bob's memory (10 <= n <= 2000)
let word; // string of the initial challenge word
let first; // integer of whom begins: 0 for Alice, 1 for Bob
```
# Output
``` c
return 0 // if Alice wins
return 1 // if Bob wins
return -1 // if both fail
```
``` python
return 0 # if Alice wins
return 1 # if Bob wins
return -1 # if both fail
```
``` javascript
return 0 // if Alice wins
return 1 // if Bob wins
return -1 // if both fail
```
# Enjoy!
If interested, I also have [this kata](https://www.codewars.com/kata/5cb7baa989b1c50014a53333) as well as [this other kata](https://www.codewars.com/kata/5cab471da732b30018968071) to consider solving.
|
def mutations(alice, bob, matchWord, first):
winner = -1
aliceWords = list(alice)
bobWords = list(bob)
aliceFoundAWord = bobFoundAWord = True
matchingWordFound = True
numOfIncorrectLetters = 0
firstRound = -1
i = 0
if matchWord in aliceWords: #removes the word from both Alice's and Bob's memory, as they are not allowed to be used again
del aliceWords[aliceWords.index(matchWord)]
if matchWord in bobWords:
del bobWords[bobWords.index(matchWord)]
while (aliceFoundAWord and bobFoundAWord and matchingWordFound) or (firstRound < 1):
firstRound += 1
i = 0
numOfIncorrectLetters = 0
matchingWordFound = False
if not (first):
aliceFoundAWord = False
for word in aliceWords:
for letter in word:
if word.find(letter) != word.rfind(letter):
break
if letter != matchWord[i]:
numOfIncorrectLetters += 1
i += 1
if (i == 4) and (numOfIncorrectLetters == 1):
aliceFoundAWord = True
matchingWordFound = True
del aliceWords[aliceWords.index(word)]
matchWord = word
if matchWord in bobWords:
del bobWords[bobWords.index(word)]
break
i = 0
numOfIncorrectLetters = 0
if (aliceFoundAWord):
break
else:
bobFoundAWord = False
for word in bobWords:
for letter in word:
if word.find(letter) != word.rfind(letter):
break
if letter != matchWord[i]:
numOfIncorrectLetters += 1
i += 1
if (i == 4) and (numOfIncorrectLetters == 1):
bobFoundAWord = True
matchingWordFound = True
del bobWords[bobWords.index(word)]
matchWord = word
if matchWord in aliceWords:
del aliceWords[aliceWords.index(word)]
break
i = 0
numOfIncorrectLetters = 0
if (bobFoundAWord):
break
first = not (first)
if (aliceFoundAWord):
winner = 0
elif (bobFoundAWord):
winner = 1
else:
winner = -1
return winner
|
# Our Setup
Alice and Bob work in an office. When the workload is light and the boss isn't looking, they often play simple word games for fun. This is one of those days!
# This Game
Today Alice and Bob are playing what they like to call _Mutations_, where they take turns trying to "think up" a new four-letter word identical to the prior word except for one letter. They just keep on going until their memories fail out.
# Their Words
Alice and Bob have memories of the same size, each able to recall `10` to `2000` different four-letter words. Memory words and initial game word are randomly taken from a list of `4000` (unique, four-letter, lowercased) words, any of which may appear in both memories.
The expression to "think up" a new word means that for their turn, the player must submit as their response word the first valid, unused word that appears in their memory (by lowest array index), as their memories are ordered from the most "memorable" words to the least.
# The Rules
* a valid response word must contain four different letters
* `1` letter is replaced while the other `3` stay in position
* it must be the lowest indexed valid word in their memory
* this word cannot have already been used during the game
* the final player to provide a valid word will win the game
* if 1st player fails 1st turn, 2nd can win with a valid word
* when both players fail the initial word, there is no winner
# Your Task
To determine the winner!
# Some Examples
`alice = plat,rend,bear,soar,mare,pare,flap,neat,clan,pore`
`bob = boar,clap,farm,lend,near,peat,pure,more,plan,soap`
1) In the case of `word = "send"` and `first = 0`:
* Alice responds to `send` with `rend`
* Bob responds to `rend` with `lend`
* Alice has no valid response to `lend`
* Bob wins the game.
2) In the case of `word = "flip"` and `first = 1`:
* Bob has no valid response to `flip`
* Alice responds to `flip` with `flap`
* Alice wins the game.
3) In the case of `word = "maze"` and `first = 0`:
* Alice responds to `maze` with `mare`
* Bob responds to `mare` with `more`
* Alice responds to `more` with `pore`
* Bob responds to `pore` with `pure`
* Alice responds to `pure` with `pare`
* Bob has no valid response to `pare`
* Alice wins the game.
4) In the case of `word = "calm"` and `first = 1`:
* Bob has no valid response to `calm`
* Alice has no valid response to `calm`
* Neither wins the game.
# Input
``` c
size_t n // number of words (10 <= n <= 2000)
const char *const alice[n]; // Alice's memory of four-letter words
const char *const bob[n]; // Bob's memory of four-letter words
const char* word; // initial challenge word of the game
int first; // whom begins: 0 for Alice, 1 for Bob
```
``` python
alice # list of words in Alice's memory (10 <= n <= 2000)
bob # list of words in Bob's memory (10 <= n <= 2000)
word # string of the initial challenge word
first # integer of whom begins: 0 for Alice, 1 for Bob
```
``` javascript
let alice; // array of words in Alice's memory (10 <= n <= 2000)
let bob; // array of words in Bob's memory (10 <= n <= 2000)
let word; // string of the initial challenge word
let first; // integer of whom begins: 0 for Alice, 1 for Bob
```
# Output
``` c
return 0 // if Alice wins
return 1 // if Bob wins
return -1 // if both fail
```
``` python
return 0 # if Alice wins
return 1 # if Bob wins
return -1 # if both fail
```
``` javascript
return 0 // if Alice wins
return 1 // if Bob wins
return -1 // if both fail
```
# Enjoy!
If interested, I also have [this kata](https://www.codewars.com/kata/5cb7baa989b1c50014a53333) as well as [this other kata](https://www.codewars.com/kata/5cab471da732b30018968071) to consider solving.
|
def mutations(alice1, bob1, ini, take):
alice, bob, take_up, initial = alice1.copy(), bob1.copy(), take, ini
def do(initial):
for _ in range(bob.count(initial)) : bob.remove(initial)
for _ in range(alice.count(initial)) : alice.remove(initial)
find_first=lambda word,li:next((i for i,j in enumerate(li)if sum(k!=l for k,l in zip(j, word))==1 and len(set(j))==4),-1)
alice__, bob__ = find_first(initial, alice), find_first(initial, bob)
do(initial)
if alice__ == -1 and bob__ == -1 : return -1
while True:
alice__, bob__ = find_first(initial, alice), find_first(initial, bob)
if take_up: # bob
if bob__ == -1 : return 0
initial = bob[bob__]
else: # alice
if alice__ == -1 : return 1
initial = alice[alice__]
do(initial)
take_up ^= 1
|
# Our Setup
Alice and Bob work in an office. When the workload is light and the boss isn't looking, they often play simple word games for fun. This is one of those days!
# This Game
Today Alice and Bob are playing what they like to call _Mutations_, where they take turns trying to "think up" a new four-letter word identical to the prior word except for one letter. They just keep on going until their memories fail out.
# Their Words
Alice and Bob have memories of the same size, each able to recall `10` to `2000` different four-letter words. Memory words and initial game word are randomly taken from a list of `4000` (unique, four-letter, lowercased) words, any of which may appear in both memories.
The expression to "think up" a new word means that for their turn, the player must submit as their response word the first valid, unused word that appears in their memory (by lowest array index), as their memories are ordered from the most "memorable" words to the least.
# The Rules
* a valid response word must contain four different letters
* `1` letter is replaced while the other `3` stay in position
* it must be the lowest indexed valid word in their memory
* this word cannot have already been used during the game
* the final player to provide a valid word will win the game
* if 1st player fails 1st turn, 2nd can win with a valid word
* when both players fail the initial word, there is no winner
# Your Task
To determine the winner!
# Some Examples
`alice = plat,rend,bear,soar,mare,pare,flap,neat,clan,pore`
`bob = boar,clap,farm,lend,near,peat,pure,more,plan,soap`
1) In the case of `word = "send"` and `first = 0`:
* Alice responds to `send` with `rend`
* Bob responds to `rend` with `lend`
* Alice has no valid response to `lend`
* Bob wins the game.
2) In the case of `word = "flip"` and `first = 1`:
* Bob has no valid response to `flip`
* Alice responds to `flip` with `flap`
* Alice wins the game.
3) In the case of `word = "maze"` and `first = 0`:
* Alice responds to `maze` with `mare`
* Bob responds to `mare` with `more`
* Alice responds to `more` with `pore`
* Bob responds to `pore` with `pure`
* Alice responds to `pure` with `pare`
* Bob has no valid response to `pare`
* Alice wins the game.
4) In the case of `word = "calm"` and `first = 1`:
* Bob has no valid response to `calm`
* Alice has no valid response to `calm`
* Neither wins the game.
# Input
``` c
size_t n // number of words (10 <= n <= 2000)
const char *const alice[n]; // Alice's memory of four-letter words
const char *const bob[n]; // Bob's memory of four-letter words
const char* word; // initial challenge word of the game
int first; // whom begins: 0 for Alice, 1 for Bob
```
``` python
alice # list of words in Alice's memory (10 <= n <= 2000)
bob # list of words in Bob's memory (10 <= n <= 2000)
word # string of the initial challenge word
first # integer of whom begins: 0 for Alice, 1 for Bob
```
``` javascript
let alice; // array of words in Alice's memory (10 <= n <= 2000)
let bob; // array of words in Bob's memory (10 <= n <= 2000)
let word; // string of the initial challenge word
let first; // integer of whom begins: 0 for Alice, 1 for Bob
```
# Output
``` c
return 0 // if Alice wins
return 1 // if Bob wins
return -1 // if both fail
```
``` python
return 0 # if Alice wins
return 1 # if Bob wins
return -1 # if both fail
```
``` javascript
return 0 // if Alice wins
return 1 // if Bob wins
return -1 // if both fail
```
# Enjoy!
If interested, I also have [this kata](https://www.codewars.com/kata/5cb7baa989b1c50014a53333) as well as [this other kata](https://www.codewars.com/kata/5cab471da732b30018968071) to consider solving.
|
def done(w, seen): return w in seen
def size(w): return len(w) == len(set(w))
def check(w, word):
found = False
for c1,c2 in zip(w, word):
if c1 != c2:
if found: return False
else: found = True
return True
def mutations(alice, bob, word, first):
okay = lambda w: not done(w, seen) and size(w) and check(w, word)
player = lambda: bob if first else alice
seen, state = {word}, 0
while True:
try:
word = next(filter(okay, player()))
if state == 1: return first
if state == 0: state = 2
seen.add(word)
except:
if state == 1: return -1
if state == 2: return 1 - first
if state == 0: state = 1
first = 1 - first
|
# Our Setup
Alice and Bob work in an office. When the workload is light and the boss isn't looking, they often play simple word games for fun. This is one of those days!
# This Game
Today Alice and Bob are playing what they like to call _Mutations_, where they take turns trying to "think up" a new four-letter word identical to the prior word except for one letter. They just keep on going until their memories fail out.
# Their Words
Alice and Bob have memories of the same size, each able to recall `10` to `2000` different four-letter words. Memory words and initial game word are randomly taken from a list of `4000` (unique, four-letter, lowercased) words, any of which may appear in both memories.
The expression to "think up" a new word means that for their turn, the player must submit as their response word the first valid, unused word that appears in their memory (by lowest array index), as their memories are ordered from the most "memorable" words to the least.
# The Rules
* a valid response word must contain four different letters
* `1` letter is replaced while the other `3` stay in position
* it must be the lowest indexed valid word in their memory
* this word cannot have already been used during the game
* the final player to provide a valid word will win the game
* if 1st player fails 1st turn, 2nd can win with a valid word
* when both players fail the initial word, there is no winner
# Your Task
To determine the winner!
# Some Examples
`alice = plat,rend,bear,soar,mare,pare,flap,neat,clan,pore`
`bob = boar,clap,farm,lend,near,peat,pure,more,plan,soap`
1) In the case of `word = "send"` and `first = 0`:
* Alice responds to `send` with `rend`
* Bob responds to `rend` with `lend`
* Alice has no valid response to `lend`
* Bob wins the game.
2) In the case of `word = "flip"` and `first = 1`:
* Bob has no valid response to `flip`
* Alice responds to `flip` with `flap`
* Alice wins the game.
3) In the case of `word = "maze"` and `first = 0`:
* Alice responds to `maze` with `mare`
* Bob responds to `mare` with `more`
* Alice responds to `more` with `pore`
* Bob responds to `pore` with `pure`
* Alice responds to `pure` with `pare`
* Bob has no valid response to `pare`
* Alice wins the game.
4) In the case of `word = "calm"` and `first = 1`:
* Bob has no valid response to `calm`
* Alice has no valid response to `calm`
* Neither wins the game.
# Input
``` c
size_t n // number of words (10 <= n <= 2000)
const char *const alice[n]; // Alice's memory of four-letter words
const char *const bob[n]; // Bob's memory of four-letter words
const char* word; // initial challenge word of the game
int first; // whom begins: 0 for Alice, 1 for Bob
```
``` python
alice # list of words in Alice's memory (10 <= n <= 2000)
bob # list of words in Bob's memory (10 <= n <= 2000)
word # string of the initial challenge word
first # integer of whom begins: 0 for Alice, 1 for Bob
```
``` javascript
let alice; // array of words in Alice's memory (10 <= n <= 2000)
let bob; // array of words in Bob's memory (10 <= n <= 2000)
let word; // string of the initial challenge word
let first; // integer of whom begins: 0 for Alice, 1 for Bob
```
# Output
``` c
return 0 // if Alice wins
return 1 // if Bob wins
return -1 // if both fail
```
``` python
return 0 # if Alice wins
return 1 # if Bob wins
return -1 # if both fail
```
``` javascript
return 0 // if Alice wins
return 1 // if Bob wins
return -1 // if both fail
```
# Enjoy!
If interested, I also have [this kata](https://www.codewars.com/kata/5cb7baa989b1c50014a53333) as well as [this other kata](https://www.codewars.com/kata/5cab471da732b30018968071) to consider solving.
|
def mutations(a,b,w,f):
z,t,i,P,U=-1,-1,f^1,[a,b],{w}
while 1:
i^=1
u=next((x for x in P[i]if x not in U and sum(p==q for p,q in zip(x,w))==3and len(set(x))==4),'')
if u:
w,z,U=u,i,U|{u}
if t!=-1:return z
else:
if t==i^1:return z
t=i
|
# Our Setup
Alice and Bob work in an office. When the workload is light and the boss isn't looking, they often play simple word games for fun. This is one of those days!
# This Game
Today Alice and Bob are playing what they like to call _Mutations_, where they take turns trying to "think up" a new four-letter word identical to the prior word except for one letter. They just keep on going until their memories fail out.
# Their Words
Alice and Bob have memories of the same size, each able to recall `10` to `2000` different four-letter words. Memory words and initial game word are randomly taken from a list of `4000` (unique, four-letter, lowercased) words, any of which may appear in both memories.
The expression to "think up" a new word means that for their turn, the player must submit as their response word the first valid, unused word that appears in their memory (by lowest array index), as their memories are ordered from the most "memorable" words to the least.
# The Rules
* a valid response word must contain four different letters
* `1` letter is replaced while the other `3` stay in position
* it must be the lowest indexed valid word in their memory
* this word cannot have already been used during the game
* the final player to provide a valid word will win the game
* if 1st player fails 1st turn, 2nd can win with a valid word
* when both players fail the initial word, there is no winner
# Your Task
To determine the winner!
# Some Examples
`alice = plat,rend,bear,soar,mare,pare,flap,neat,clan,pore`
`bob = boar,clap,farm,lend,near,peat,pure,more,plan,soap`
1) In the case of `word = "send"` and `first = 0`:
* Alice responds to `send` with `rend`
* Bob responds to `rend` with `lend`
* Alice has no valid response to `lend`
* Bob wins the game.
2) In the case of `word = "flip"` and `first = 1`:
* Bob has no valid response to `flip`
* Alice responds to `flip` with `flap`
* Alice wins the game.
3) In the case of `word = "maze"` and `first = 0`:
* Alice responds to `maze` with `mare`
* Bob responds to `mare` with `more`
* Alice responds to `more` with `pore`
* Bob responds to `pore` with `pure`
* Alice responds to `pure` with `pare`
* Bob has no valid response to `pare`
* Alice wins the game.
4) In the case of `word = "calm"` and `first = 1`:
* Bob has no valid response to `calm`
* Alice has no valid response to `calm`
* Neither wins the game.
# Input
``` c
size_t n // number of words (10 <= n <= 2000)
const char *const alice[n]; // Alice's memory of four-letter words
const char *const bob[n]; // Bob's memory of four-letter words
const char* word; // initial challenge word of the game
int first; // whom begins: 0 for Alice, 1 for Bob
```
``` python
alice # list of words in Alice's memory (10 <= n <= 2000)
bob # list of words in Bob's memory (10 <= n <= 2000)
word # string of the initial challenge word
first # integer of whom begins: 0 for Alice, 1 for Bob
```
``` javascript
let alice; // array of words in Alice's memory (10 <= n <= 2000)
let bob; // array of words in Bob's memory (10 <= n <= 2000)
let word; // string of the initial challenge word
let first; // integer of whom begins: 0 for Alice, 1 for Bob
```
# Output
``` c
return 0 // if Alice wins
return 1 // if Bob wins
return -1 // if both fail
```
``` python
return 0 # if Alice wins
return 1 # if Bob wins
return -1 # if both fail
```
``` javascript
return 0 // if Alice wins
return 1 // if Bob wins
return -1 // if both fail
```
# Enjoy!
If interested, I also have [this kata](https://www.codewars.com/kata/5cb7baa989b1c50014a53333) as well as [this other kata](https://www.codewars.com/kata/5cab471da732b30018968071) to consider solving.
|
def mutations(alice, bob, word, first):
def isValid(w): return w not in seen and sum(a==b for a,b in zip(w,word))==3 and len(set(w))==4
players, seen = [alice,bob], {word}
win, failed, i = -1, -1, first^1
while 1:
i ^= 1
lst = players[i]
found = next((w for w in lst if isValid(w)), None)
if found is None:
if failed==i^1: break
failed = i
else:
seen.add(found)
word, win = found, i
if failed!=-1: break
return win
|
# Our Setup
Alice and Bob work in an office. When the workload is light and the boss isn't looking, they often play simple word games for fun. This is one of those days!
# This Game
Today Alice and Bob are playing what they like to call _Mutations_, where they take turns trying to "think up" a new four-letter word identical to the prior word except for one letter. They just keep on going until their memories fail out.
# Their Words
Alice and Bob have memories of the same size, each able to recall `10` to `2000` different four-letter words. Memory words and initial game word are randomly taken from a list of `4000` (unique, four-letter, lowercased) words, any of which may appear in both memories.
The expression to "think up" a new word means that for their turn, the player must submit as their response word the first valid, unused word that appears in their memory (by lowest array index), as their memories are ordered from the most "memorable" words to the least.
# The Rules
* a valid response word must contain four different letters
* `1` letter is replaced while the other `3` stay in position
* it must be the lowest indexed valid word in their memory
* this word cannot have already been used during the game
* the final player to provide a valid word will win the game
* if 1st player fails 1st turn, 2nd can win with a valid word
* when both players fail the initial word, there is no winner
# Your Task
To determine the winner!
# Some Examples
`alice = plat,rend,bear,soar,mare,pare,flap,neat,clan,pore`
`bob = boar,clap,farm,lend,near,peat,pure,more,plan,soap`
1) In the case of `word = "send"` and `first = 0`:
* Alice responds to `send` with `rend`
* Bob responds to `rend` with `lend`
* Alice has no valid response to `lend`
* Bob wins the game.
2) In the case of `word = "flip"` and `first = 1`:
* Bob has no valid response to `flip`
* Alice responds to `flip` with `flap`
* Alice wins the game.
3) In the case of `word = "maze"` and `first = 0`:
* Alice responds to `maze` with `mare`
* Bob responds to `mare` with `more`
* Alice responds to `more` with `pore`
* Bob responds to `pore` with `pure`
* Alice responds to `pure` with `pare`
* Bob has no valid response to `pare`
* Alice wins the game.
4) In the case of `word = "calm"` and `first = 1`:
* Bob has no valid response to `calm`
* Alice has no valid response to `calm`
* Neither wins the game.
# Input
``` c
size_t n // number of words (10 <= n <= 2000)
const char *const alice[n]; // Alice's memory of four-letter words
const char *const bob[n]; // Bob's memory of four-letter words
const char* word; // initial challenge word of the game
int first; // whom begins: 0 for Alice, 1 for Bob
```
``` python
alice # list of words in Alice's memory (10 <= n <= 2000)
bob # list of words in Bob's memory (10 <= n <= 2000)
word # string of the initial challenge word
first # integer of whom begins: 0 for Alice, 1 for Bob
```
``` javascript
let alice; // array of words in Alice's memory (10 <= n <= 2000)
let bob; // array of words in Bob's memory (10 <= n <= 2000)
let word; // string of the initial challenge word
let first; // integer of whom begins: 0 for Alice, 1 for Bob
```
# Output
``` c
return 0 // if Alice wins
return 1 // if Bob wins
return -1 // if both fail
```
``` python
return 0 # if Alice wins
return 1 # if Bob wins
return -1 # if both fail
```
``` javascript
return 0 // if Alice wins
return 1 // if Bob wins
return -1 // if both fail
```
# Enjoy!
If interested, I also have [this kata](https://www.codewars.com/kata/5cb7baa989b1c50014a53333) as well as [this other kata](https://www.codewars.com/kata/5cab471da732b30018968071) to consider solving.
|
def mutations(alice, bob, word, first):
seen = {word}
mapping = {0:alice, 1:bob}
prev_state,state = -1, -1
def foo(word,first):
nonlocal state, prev_state
foo.counter += 1
if foo.counter > 2 and (state < 0 or prev_state < 0):
return
for a_word in mapping[first]:
counter = 0
for i,x in enumerate(a_word):
if a_word[i] == word[i]:
counter += 1
if counter == 3 and len(set(a_word))==4 and a_word not in seen:
seen.add(a_word)
prev_state = state
state = first
word = a_word
break
if counter==3 or state < 0:
return foo(word,first^1)
foo.counter = 0
foo(word,first)
return state
|
# Our Setup
Alice and Bob work in an office. When the workload is light and the boss isn't looking, they often play simple word games for fun. This is one of those days!
# This Game
Today Alice and Bob are playing what they like to call _Mutations_, where they take turns trying to "think up" a new four-letter word identical to the prior word except for one letter. They just keep on going until their memories fail out.
# Their Words
Alice and Bob have memories of the same size, each able to recall `10` to `2000` different four-letter words. Memory words and initial game word are randomly taken from a list of `4000` (unique, four-letter, lowercased) words, any of which may appear in both memories.
The expression to "think up" a new word means that for their turn, the player must submit as their response word the first valid, unused word that appears in their memory (by lowest array index), as their memories are ordered from the most "memorable" words to the least.
# The Rules
* a valid response word must contain four different letters
* `1` letter is replaced while the other `3` stay in position
* it must be the lowest indexed valid word in their memory
* this word cannot have already been used during the game
* the final player to provide a valid word will win the game
* if 1st player fails 1st turn, 2nd can win with a valid word
* when both players fail the initial word, there is no winner
# Your Task
To determine the winner!
# Some Examples
`alice = plat,rend,bear,soar,mare,pare,flap,neat,clan,pore`
`bob = boar,clap,farm,lend,near,peat,pure,more,plan,soap`
1) In the case of `word = "send"` and `first = 0`:
* Alice responds to `send` with `rend`
* Bob responds to `rend` with `lend`
* Alice has no valid response to `lend`
* Bob wins the game.
2) In the case of `word = "flip"` and `first = 1`:
* Bob has no valid response to `flip`
* Alice responds to `flip` with `flap`
* Alice wins the game.
3) In the case of `word = "maze"` and `first = 0`:
* Alice responds to `maze` with `mare`
* Bob responds to `mare` with `more`
* Alice responds to `more` with `pore`
* Bob responds to `pore` with `pure`
* Alice responds to `pure` with `pare`
* Bob has no valid response to `pare`
* Alice wins the game.
4) In the case of `word = "calm"` and `first = 1`:
* Bob has no valid response to `calm`
* Alice has no valid response to `calm`
* Neither wins the game.
# Input
``` c
size_t n // number of words (10 <= n <= 2000)
const char *const alice[n]; // Alice's memory of four-letter words
const char *const bob[n]; // Bob's memory of four-letter words
const char* word; // initial challenge word of the game
int first; // whom begins: 0 for Alice, 1 for Bob
```
``` python
alice # list of words in Alice's memory (10 <= n <= 2000)
bob # list of words in Bob's memory (10 <= n <= 2000)
word # string of the initial challenge word
first # integer of whom begins: 0 for Alice, 1 for Bob
```
``` javascript
let alice; // array of words in Alice's memory (10 <= n <= 2000)
let bob; // array of words in Bob's memory (10 <= n <= 2000)
let word; // string of the initial challenge word
let first; // integer of whom begins: 0 for Alice, 1 for Bob
```
# Output
``` c
return 0 // if Alice wins
return 1 // if Bob wins
return -1 // if both fail
```
``` python
return 0 # if Alice wins
return 1 # if Bob wins
return -1 # if both fail
```
``` javascript
return 0 // if Alice wins
return 1 // if Bob wins
return -1 // if both fail
```
# Enjoy!
If interested, I also have [this kata](https://www.codewars.com/kata/5cb7baa989b1c50014a53333) as well as [this other kata](https://www.codewars.com/kata/5cab471da732b30018968071) to consider solving.
|
cmp=lambda a,b,f:(a,b)==(0,0) and -1 or a>b and 0 or a<b and 1 or a==b and not f and 1 or 0
def mutations(alice, bob, word, first):
score = {0:0, 1:0}
seen = {word}
mapping = {0:alice, 1:bob}
def foo(alice,bob,word,first):
foo.counter += 1
if foo.counter > 2 and not score[0] and not score[1]:
return
for a_word in mapping[first]:
counter = 0
for i,x in enumerate(a_word):
if a_word[i] == word[i]:
counter += 1
if counter == 3 and len(set(a_word))==4 and a_word not in seen:
seen.add(a_word)
word = a_word
score[first] += 1
break
if counter==3 or not score[first]:
return foo(alice,bob,word,first^1)
foo.counter = 0
foo(alice,bob,word,first)
return cmp(score[0],score[1],first)
|
# Our Setup
Alice and Bob work in an office. When the workload is light and the boss isn't looking, they often play simple word games for fun. This is one of those days!
# This Game
Today Alice and Bob are playing what they like to call _Mutations_, where they take turns trying to "think up" a new four-letter word identical to the prior word except for one letter. They just keep on going until their memories fail out.
# Their Words
Alice and Bob have memories of the same size, each able to recall `10` to `2000` different four-letter words. Memory words and initial game word are randomly taken from a list of `4000` (unique, four-letter, lowercased) words, any of which may appear in both memories.
The expression to "think up" a new word means that for their turn, the player must submit as their response word the first valid, unused word that appears in their memory (by lowest array index), as their memories are ordered from the most "memorable" words to the least.
# The Rules
* a valid response word must contain four different letters
* `1` letter is replaced while the other `3` stay in position
* it must be the lowest indexed valid word in their memory
* this word cannot have already been used during the game
* the final player to provide a valid word will win the game
* if 1st player fails 1st turn, 2nd can win with a valid word
* when both players fail the initial word, there is no winner
# Your Task
To determine the winner!
# Some Examples
`alice = plat,rend,bear,soar,mare,pare,flap,neat,clan,pore`
`bob = boar,clap,farm,lend,near,peat,pure,more,plan,soap`
1) In the case of `word = "send"` and `first = 0`:
* Alice responds to `send` with `rend`
* Bob responds to `rend` with `lend`
* Alice has no valid response to `lend`
* Bob wins the game.
2) In the case of `word = "flip"` and `first = 1`:
* Bob has no valid response to `flip`
* Alice responds to `flip` with `flap`
* Alice wins the game.
3) In the case of `word = "maze"` and `first = 0`:
* Alice responds to `maze` with `mare`
* Bob responds to `mare` with `more`
* Alice responds to `more` with `pore`
* Bob responds to `pore` with `pure`
* Alice responds to `pure` with `pare`
* Bob has no valid response to `pare`
* Alice wins the game.
4) In the case of `word = "calm"` and `first = 1`:
* Bob has no valid response to `calm`
* Alice has no valid response to `calm`
* Neither wins the game.
# Input
``` c
size_t n // number of words (10 <= n <= 2000)
const char *const alice[n]; // Alice's memory of four-letter words
const char *const bob[n]; // Bob's memory of four-letter words
const char* word; // initial challenge word of the game
int first; // whom begins: 0 for Alice, 1 for Bob
```
``` python
alice # list of words in Alice's memory (10 <= n <= 2000)
bob # list of words in Bob's memory (10 <= n <= 2000)
word # string of the initial challenge word
first # integer of whom begins: 0 for Alice, 1 for Bob
```
``` javascript
let alice; // array of words in Alice's memory (10 <= n <= 2000)
let bob; // array of words in Bob's memory (10 <= n <= 2000)
let word; // string of the initial challenge word
let first; // integer of whom begins: 0 for Alice, 1 for Bob
```
# Output
``` c
return 0 // if Alice wins
return 1 // if Bob wins
return -1 // if both fail
```
``` python
return 0 # if Alice wins
return 1 # if Bob wins
return -1 # if both fail
```
``` javascript
return 0 // if Alice wins
return 1 // if Bob wins
return -1 // if both fail
```
# Enjoy!
If interested, I also have [this kata](https://www.codewars.com/kata/5cb7baa989b1c50014a53333) as well as [this other kata](https://www.codewars.com/kata/5cab471da732b30018968071) to consider solving.
|
cmp=lambda a,b,f:(a,b)==(0,0) and -1 or a>b and 0 or a<b and 1 or a==b and not f and 1 or 0
def mutations(alice, bob, word, first):
al,bo = 0,0
start = first
seen = {word}
def foo(alice,bob,word,first):
nonlocal al,bo,start
if first == 0:
for a_word in alice:
c1 = 0
for i,x in enumerate(a_word):
if a_word[i] == word[i]:
c1 += 1
if c1 == 3 and len(set(a_word))==4 and a_word not in seen:
seen.add(a_word)
word = a_word
al += 1
return foo(alice,bob,word,first+1)
if not al and not start:
return foo(alice,bob,word,first+1)
else:
for b_word in bob:
c2 = 0
for i,j in enumerate(b_word):
if b_word[i] == word[i]:
c2 += 1
if c2 == 3 and len(set(b_word))==4 and b_word not in seen:
seen.add(b_word)
word = b_word
bo += 1
return foo(alice,bob,word,first-1)
if not bo and start:
return foo(alice,bob,word,first-1)
foo(alice,bob,word,first)
return cmp(al,bo,first)
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
def position(alphabet):
return "Position of alphabet: {}".format(ord(alphabet) - 96)
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
def position(alphabet):
return "Position of alphabet: %s" % ("abcdefghijklmnopqrstuvwxyz".find(alphabet) + 1)
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
from string import ascii_lowercase
def position(char):
return "Position of alphabet: {0}".format(
ascii_lowercase.index(char) + 1)
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
def position(letter):
return "Position of alphabet: %d" % (ord(letter) - 96)
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
def position(alpha):
return f"Position of alphabet: {ord(alpha)-96}"
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
from string import lowercase
def position(letter):
return 'Position of alphabet: %d' % (
1 + lowercase.index(letter))
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
def position(alphabet):
return 'Position of alphabet: ' + str(ord(alphabet) - ord('a') + 1)
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
position = lambda a: 'Position of alphabet: {}'.format(ord(a) - 96)
# def position(alphabet):
# return 'Position of alphabet: {}'.format(ord(alphabet) - 96)
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
def position(a):
return f"Position of alphabet: {ord(a) - 96}"
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
position = lambda a: "Position of alphabet: {}".format(ord(a)-96)
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
def position(alphabet):
return "Position of alphabet: {}".format(ord(alphabet.lower()) - 96)
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
def position(a):
return 'Position of alphabet: {}'.format(ord(a) - 96)
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
import string
def position(alphabet):
return f'Position of alphabet: {string.ascii_letters.index(alphabet.lower()) + 1}'
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
def position(alphabet):
abc = "abcdefghijklmnopqrstuvwxyz"
pos = abc.index(alphabet) + 1
return "Position of alphabet: " + str(pos)
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
def position(alphabet):
alph_list = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
for i in range(0, 26):
if alphabet == alph_list[i]:
j = i + 1
return "Position of alphabet: " + str(j)
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
position=lambda l: "Position of alphabet: "+str("abcdefghijklmnopqrstuvwxyz".index(l)+1)
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
def position(alphabet):
return "Position of alphabet: " + str(ord(alphabet) - 96)
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
import string
position = lambda a: 'Position of alphabet: {}'.format(string.ascii_lowercase.index(a) + 1)
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
def position(alphabet):
return f"Position of alphabet: {ord(alphabet[0]) - 96}"
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
abc = {"a": "1", "b": "2", "c": "3", "d": "4", "e": "5", "f": "6", "g": "7",
"h": "8", "i": "9", "j": "10", "k": "11", "l": "12", "m": "13", "n": "14",
"o": "15", "p": "16", "q": "17", "r": "18", "s": "19", "t": "20", "u": "21",
"v": "22", "w": "23", "x": "24", "y": "25", "z": "26"}
def position(alphabet):
return f'Position of alphabet: {abc.get(alphabet)}'
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
def position(ch):
return f"Position of alphabet: {ord(ch)-ord('a')+1}"
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
def position(alphabet):
result = ord(alphabet) - 96
return f'Position of alphabet: {result}'
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
import string
def position(alphabet):
d={}
s=string.ascii_lowercase
c=1
for i in s:
d[i]=c
c+=1
return f'Position of alphabet: {d.get(alphabet)}'
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
def position(alphabet):
print(ord('a'))
return f'Position of alphabet: {ord(alphabet)-96}'
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
def position(a):
return f'Position of alphabet: {"abcdefghijklmnopqrstuvwxyz".index(a)+1}'
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
def position(letter):
import string
alpha = string.ascii_lowercase
return 'Position of alphabet: {}'.format(alpha.index(letter)+1)
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
def position(alphabet):
dict = {
'a': 1,
'b': 2,
'c': 3,
'd': 4,
'e': 5,
'f': 6,
'g': 7,
'h': 8,
'i': 9,
'j': 10,
'k': 11,
'l': 12,
'm': 13,
'n': 14,
'o': 15,
'p': 16,
'q': 17,
'r': 18,
's': 19,
't': 20,
'u': 21,
'v': 22,
'w': 23,
'x': 24,
'y': 25,
'z': 26
}
return f'Position of alphabet: {dict.get(alphabet)}'
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
from string import ascii_lowercase as lc
def position(alphabet):
return f'Position of alphabet: {lc.find(alphabet.lower()) + 1}'
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
def position(alphabet):
alph = list('abcdefghijklmnopqrstuvwxyz')
return f'Position of alphabet: {alph.index(alphabet)+1}'
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
def position(alphabet):
a = 'abcdefghijklmnopqrstuvwxyz'
x = list(map(lambda x: a[x],range(len(a)))).index(alphabet)+1
return "Position of alphabet: "+str(x)
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
def position(a):
return "Position of alphabet: "+str(list("abcdefghijklmnopqrstuvwxyz").index(a)+1)
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
def position(alphabet):
ABC = {"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9,"j":10,"k":11,"l":12,"m":13,"n":14,
"o":15,"p":16,"q":17,"r":18,"s":19,"t":20,"u":21,"v":22,"w":23,"x":24,"y":25,"z":26,}
for i in ABC:
if i == alphabet:
return str("Position of alphabet: ") + str(ABC[alphabet])
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
import string
def position(alphabet):
dictionary = {'a':'Position of alphabet: 1',
'b': "Position of alphabet: 2",
'c': 'Position of alphabet: 3',
'd': 'Position of alphabet: 4',
'e': 'Position of alphabet: 5',
'f': "Position of alphabet: 6",
'g': "Position of alphabet: 7",
'h': 'Position of alphabet: 8',
'i': 'Position of alphabet: 9',
'j': 'Position of alphabet: 10',
'k': "Position of alphabet: 11",
'l': 'Position of alphabet: 12',
'm': "Position of alphabet: 13",
'n': 'Position of alphabet: 14',
'o': 'Position of alphabet: 15',
'p': 'Position of alphabet: 16',
'q': "Position of alphabet: 17",
'r': "Position of alphabet: 18",
's': 'Position of alphabet: 19',
't': 'Position of alphabet: 20',
'u': 'Position of alphabet: 21',
'v': "Position of alphabet: 22",
'w': 'Position of alphabet: 23',
'x': 'Position of alphabet: 24',
'y': 'Position of alphabet: 25',
'z': "Position of alphabet: 26"}
return dictionary[alphabet]
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
def position(letter):
alpahabet=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
for i in range(0,len(alpahabet)):
if alpahabet[i] ==letter:
return "Position of alphabet: "+str(i+1)
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
position = lambda letter: f"Position of alphabet: {'abcdefghijklmnopqrstuvwxyz'.index(letter) + 1}"
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
def position(alphabet):
char = ['a','b','c','d','e','f','g','h','i','j','k','l',
'm','n','o','p','q','r','s','t','u','v','w','x','y','z']
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
char_num = list(zip(char,nums))
for i,j in char_num:
if i == alphabet:
return "Position of alphabet: "+ str(j)
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
def position(alphabet):
a_l='abcdefghijklmnopqrstuvwxyz'
return f'Position of alphabet: {a_l.index(alphabet)+1}'
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
def position(alphabet):
alpha = ['', 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
if alphabet in alpha:
return f"Position of alphabet: {alpha.index(alphabet)}"
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
import string
def position(alpha):
alphabet = string.ascii_lowercase
return f"Position of alphabet: {alphabet.find(alpha) + 1}"
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
import string
def position(pos):
alphabet = string.ascii_lowercase
return f"Position of alphabet: {alphabet.index(pos) + 1}"
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
|
alp = 'abcdefghijklmnopqrstuvwxyz'
def position(alphabet):
return f"Position of alphabet: {alp.index(alphabet)+1}"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.