inputs
stringlengths 50
14k
| targets
stringlengths 4
655k
|
|---|---|
Robinson Crusoe decides to explore his isle. On a sheet of paper he plans the following process.
His hut has coordinates `origin = [0, 0]`. From that origin he walks a given distance `d` on a line
that has a given angle `ang` with the x-axis. He gets to a point A.
(Angles are measured with respect to the x-axis)
From that point A he walks the distance `d` multiplied by a constant `distmult` on a line that
has the angle `ang` multiplied by a constant `angmult` and so on and on.
We have `d0 = d`, `ang0 = ang`; then `d1 = d * distmult`, `ang1 = ang * angmult` etc ...
Let us suppose he follows this process n times.
What are the coordinates `lastx, lasty` of the last point?
The function `crusoe` has parameters;
- n : numbers of steps in the process
- d : initial chosen distance
- ang : initial chosen angle in degrees
- distmult : constant multiplier of the previous distance
- angmult : constant multiplier of the previous angle
`crusoe(n, d, ang, distmult, angmult)` should return
`lastx, lasty` as an array or a tuple depending on the language.
### Example:
`crusoe(5, 0.2, 30, 1.02, 1.1)` ->
The successive `x` are : `0.0, 0.173205, 0.344294, 0.511991, 0.674744, 0.830674` (approximately)
The successive `y` are : `0.0, 0.1, 0.211106, 0.334292, 0.47052, 0.620695` (approximately)
and
```
lastx: 0.8306737544381833
lasty: 0.620694691344071
```
### A drawing:

Successive points:
- x: `0.0, 0.9659..., 1.8319..., 2.3319..., 1.8319...`
- y: `0.0, 0.2588..., 0.7588..., 1.6248..., 2.4908...`
### Note
Please could you ask before translating: some translations are already written and published when/if the kata is approved.
|
from math import sin, cos, pi
def crusoe(n, d, ang, dist_mult, ang_mult):
x = y = z = 0.0
for i in range(n):
z = ang * pi / 180
x += d * cos(z)
y += d * sin(z)
d *= dist_mult
ang *= ang_mult
return x, y
|
Robinson Crusoe decides to explore his isle. On a sheet of paper he plans the following process.
His hut has coordinates `origin = [0, 0]`. From that origin he walks a given distance `d` on a line
that has a given angle `ang` with the x-axis. He gets to a point A.
(Angles are measured with respect to the x-axis)
From that point A he walks the distance `d` multiplied by a constant `distmult` on a line that
has the angle `ang` multiplied by a constant `angmult` and so on and on.
We have `d0 = d`, `ang0 = ang`; then `d1 = d * distmult`, `ang1 = ang * angmult` etc ...
Let us suppose he follows this process n times.
What are the coordinates `lastx, lasty` of the last point?
The function `crusoe` has parameters;
- n : numbers of steps in the process
- d : initial chosen distance
- ang : initial chosen angle in degrees
- distmult : constant multiplier of the previous distance
- angmult : constant multiplier of the previous angle
`crusoe(n, d, ang, distmult, angmult)` should return
`lastx, lasty` as an array or a tuple depending on the language.
### Example:
`crusoe(5, 0.2, 30, 1.02, 1.1)` ->
The successive `x` are : `0.0, 0.173205, 0.344294, 0.511991, 0.674744, 0.830674` (approximately)
The successive `y` are : `0.0, 0.1, 0.211106, 0.334292, 0.47052, 0.620695` (approximately)
and
```
lastx: 0.8306737544381833
lasty: 0.620694691344071
```
### A drawing:

Successive points:
- x: `0.0, 0.9659..., 1.8319..., 2.3319..., 1.8319...`
- y: `0.0, 0.2588..., 0.7588..., 1.6248..., 2.4908...`
### Note
Please could you ask before translating: some translations are already written and published when/if the kata is approved.
|
from numpy import sin, cos, pi
def crusoe(n, d, ang, dist_mult, ang_mult):
return (sum(d*dist_mult**i*cos(ang*ang_mult**i/180*pi) for i in range(n)), sum(d*dist_mult**i*sin(ang*ang_mult**i/180*pi) for i in range(n)))
|
Robinson Crusoe decides to explore his isle. On a sheet of paper he plans the following process.
His hut has coordinates `origin = [0, 0]`. From that origin he walks a given distance `d` on a line
that has a given angle `ang` with the x-axis. He gets to a point A.
(Angles are measured with respect to the x-axis)
From that point A he walks the distance `d` multiplied by a constant `distmult` on a line that
has the angle `ang` multiplied by a constant `angmult` and so on and on.
We have `d0 = d`, `ang0 = ang`; then `d1 = d * distmult`, `ang1 = ang * angmult` etc ...
Let us suppose he follows this process n times.
What are the coordinates `lastx, lasty` of the last point?
The function `crusoe` has parameters;
- n : numbers of steps in the process
- d : initial chosen distance
- ang : initial chosen angle in degrees
- distmult : constant multiplier of the previous distance
- angmult : constant multiplier of the previous angle
`crusoe(n, d, ang, distmult, angmult)` should return
`lastx, lasty` as an array or a tuple depending on the language.
### Example:
`crusoe(5, 0.2, 30, 1.02, 1.1)` ->
The successive `x` are : `0.0, 0.173205, 0.344294, 0.511991, 0.674744, 0.830674` (approximately)
The successive `y` are : `0.0, 0.1, 0.211106, 0.334292, 0.47052, 0.620695` (approximately)
and
```
lastx: 0.8306737544381833
lasty: 0.620694691344071
```
### A drawing:

Successive points:
- x: `0.0, 0.9659..., 1.8319..., 2.3319..., 1.8319...`
- y: `0.0, 0.2588..., 0.7588..., 1.6248..., 2.4908...`
### Note
Please could you ask before translating: some translations are already written and published when/if the kata is approved.
|
from math import cos, sin, pi
def crusoe(n, d, ang, dis_tmult, ang_mult):
# your code
lastx=0
lasty=0
for i in range(n):
lastx += d*cos((ang*ang_mult**i)*pi/180)*dis_tmult**i
lasty += d*sin((ang*ang_mult**i)*pi/180)*dis_tmult**i
return (lastx, lasty)
|
Robinson Crusoe decides to explore his isle. On a sheet of paper he plans the following process.
His hut has coordinates `origin = [0, 0]`. From that origin he walks a given distance `d` on a line
that has a given angle `ang` with the x-axis. He gets to a point A.
(Angles are measured with respect to the x-axis)
From that point A he walks the distance `d` multiplied by a constant `distmult` on a line that
has the angle `ang` multiplied by a constant `angmult` and so on and on.
We have `d0 = d`, `ang0 = ang`; then `d1 = d * distmult`, `ang1 = ang * angmult` etc ...
Let us suppose he follows this process n times.
What are the coordinates `lastx, lasty` of the last point?
The function `crusoe` has parameters;
- n : numbers of steps in the process
- d : initial chosen distance
- ang : initial chosen angle in degrees
- distmult : constant multiplier of the previous distance
- angmult : constant multiplier of the previous angle
`crusoe(n, d, ang, distmult, angmult)` should return
`lastx, lasty` as an array or a tuple depending on the language.
### Example:
`crusoe(5, 0.2, 30, 1.02, 1.1)` ->
The successive `x` are : `0.0, 0.173205, 0.344294, 0.511991, 0.674744, 0.830674` (approximately)
The successive `y` are : `0.0, 0.1, 0.211106, 0.334292, 0.47052, 0.620695` (approximately)
and
```
lastx: 0.8306737544381833
lasty: 0.620694691344071
```
### A drawing:

Successive points:
- x: `0.0, 0.9659..., 1.8319..., 2.3319..., 1.8319...`
- y: `0.0, 0.2588..., 0.7588..., 1.6248..., 2.4908...`
### Note
Please could you ask before translating: some translations are already written and published when/if the kata is approved.
|
def crusoe(n, d, ang, dis_tmult, ang_mult):
# your code
from math import sin,cos,pi
x=0
y=0
for i in range(n):
x=x+(d*dis_tmult**i)*cos(ang*pi/180*ang_mult**i)
y=y+(d*dis_tmult**i)*sin(ang*pi/180*ang_mult**i)
return (x,y)
|
Robinson Crusoe decides to explore his isle. On a sheet of paper he plans the following process.
His hut has coordinates `origin = [0, 0]`. From that origin he walks a given distance `d` on a line
that has a given angle `ang` with the x-axis. He gets to a point A.
(Angles are measured with respect to the x-axis)
From that point A he walks the distance `d` multiplied by a constant `distmult` on a line that
has the angle `ang` multiplied by a constant `angmult` and so on and on.
We have `d0 = d`, `ang0 = ang`; then `d1 = d * distmult`, `ang1 = ang * angmult` etc ...
Let us suppose he follows this process n times.
What are the coordinates `lastx, lasty` of the last point?
The function `crusoe` has parameters;
- n : numbers of steps in the process
- d : initial chosen distance
- ang : initial chosen angle in degrees
- distmult : constant multiplier of the previous distance
- angmult : constant multiplier of the previous angle
`crusoe(n, d, ang, distmult, angmult)` should return
`lastx, lasty` as an array or a tuple depending on the language.
### Example:
`crusoe(5, 0.2, 30, 1.02, 1.1)` ->
The successive `x` are : `0.0, 0.173205, 0.344294, 0.511991, 0.674744, 0.830674` (approximately)
The successive `y` are : `0.0, 0.1, 0.211106, 0.334292, 0.47052, 0.620695` (approximately)
and
```
lastx: 0.8306737544381833
lasty: 0.620694691344071
```
### A drawing:

Successive points:
- x: `0.0, 0.9659..., 1.8319..., 2.3319..., 1.8319...`
- y: `0.0, 0.2588..., 0.7588..., 1.6248..., 2.4908...`
### Note
Please could you ask before translating: some translations are already written and published when/if the kata is approved.
|
from math import cos, sin, pi
def crusoe(n, d, ang, dist_mult, ang_mult):
def sim(center, scale, ang):
resx = center[0] + scale * cos(ang * pi / 180.0)
resy = center[1] + scale * sin(ang * pi / 180.0)
return resx, resy
center = (0.0, 0.0)
for i in range(1, n + 1):
center = sim(center, d, ang)
d *= dist_mult
ang *= ang_mult
return center
|
Robinson Crusoe decides to explore his isle. On a sheet of paper he plans the following process.
His hut has coordinates `origin = [0, 0]`. From that origin he walks a given distance `d` on a line
that has a given angle `ang` with the x-axis. He gets to a point A.
(Angles are measured with respect to the x-axis)
From that point A he walks the distance `d` multiplied by a constant `distmult` on a line that
has the angle `ang` multiplied by a constant `angmult` and so on and on.
We have `d0 = d`, `ang0 = ang`; then `d1 = d * distmult`, `ang1 = ang * angmult` etc ...
Let us suppose he follows this process n times.
What are the coordinates `lastx, lasty` of the last point?
The function `crusoe` has parameters;
- n : numbers of steps in the process
- d : initial chosen distance
- ang : initial chosen angle in degrees
- distmult : constant multiplier of the previous distance
- angmult : constant multiplier of the previous angle
`crusoe(n, d, ang, distmult, angmult)` should return
`lastx, lasty` as an array or a tuple depending on the language.
### Example:
`crusoe(5, 0.2, 30, 1.02, 1.1)` ->
The successive `x` are : `0.0, 0.173205, 0.344294, 0.511991, 0.674744, 0.830674` (approximately)
The successive `y` are : `0.0, 0.1, 0.211106, 0.334292, 0.47052, 0.620695` (approximately)
and
```
lastx: 0.8306737544381833
lasty: 0.620694691344071
```
### A drawing:

Successive points:
- x: `0.0, 0.9659..., 1.8319..., 2.3319..., 1.8319...`
- y: `0.0, 0.2588..., 0.7588..., 1.6248..., 2.4908...`
### Note
Please could you ask before translating: some translations are already written and published when/if the kata is approved.
|
from math import cos,sin,pi
def crusoe(n,d,ang,dist_mult,ang_mult):
x,y=0,0
for i in range(n):
x+=cos(ang*pi/180)*d
y+=sin(ang*pi/180)*d
ang*=ang_mult
d*=dist_mult
return [x,y]
|
Robinson Crusoe decides to explore his isle. On a sheet of paper he plans the following process.
His hut has coordinates `origin = [0, 0]`. From that origin he walks a given distance `d` on a line
that has a given angle `ang` with the x-axis. He gets to a point A.
(Angles are measured with respect to the x-axis)
From that point A he walks the distance `d` multiplied by a constant `distmult` on a line that
has the angle `ang` multiplied by a constant `angmult` and so on and on.
We have `d0 = d`, `ang0 = ang`; then `d1 = d * distmult`, `ang1 = ang * angmult` etc ...
Let us suppose he follows this process n times.
What are the coordinates `lastx, lasty` of the last point?
The function `crusoe` has parameters;
- n : numbers of steps in the process
- d : initial chosen distance
- ang : initial chosen angle in degrees
- distmult : constant multiplier of the previous distance
- angmult : constant multiplier of the previous angle
`crusoe(n, d, ang, distmult, angmult)` should return
`lastx, lasty` as an array or a tuple depending on the language.
### Example:
`crusoe(5, 0.2, 30, 1.02, 1.1)` ->
The successive `x` are : `0.0, 0.173205, 0.344294, 0.511991, 0.674744, 0.830674` (approximately)
The successive `y` are : `0.0, 0.1, 0.211106, 0.334292, 0.47052, 0.620695` (approximately)
and
```
lastx: 0.8306737544381833
lasty: 0.620694691344071
```
### A drawing:

Successive points:
- x: `0.0, 0.9659..., 1.8319..., 2.3319..., 1.8319...`
- y: `0.0, 0.2588..., 0.7588..., 1.6248..., 2.4908...`
### Note
Please could you ask before translating: some translations are already written and published when/if the kata is approved.
|
from math import cos, sin, radians as rad
def crusoe(n, d, a, dd, da):
x=y=0
for _ in range(n):
x += d * cos(rad(a))
y += d * sin(rad(a))
d, a = d*dd, a*da
return (x, y)
|
Robinson Crusoe decides to explore his isle. On a sheet of paper he plans the following process.
His hut has coordinates `origin = [0, 0]`. From that origin he walks a given distance `d` on a line
that has a given angle `ang` with the x-axis. He gets to a point A.
(Angles are measured with respect to the x-axis)
From that point A he walks the distance `d` multiplied by a constant `distmult` on a line that
has the angle `ang` multiplied by a constant `angmult` and so on and on.
We have `d0 = d`, `ang0 = ang`; then `d1 = d * distmult`, `ang1 = ang * angmult` etc ...
Let us suppose he follows this process n times.
What are the coordinates `lastx, lasty` of the last point?
The function `crusoe` has parameters;
- n : numbers of steps in the process
- d : initial chosen distance
- ang : initial chosen angle in degrees
- distmult : constant multiplier of the previous distance
- angmult : constant multiplier of the previous angle
`crusoe(n, d, ang, distmult, angmult)` should return
`lastx, lasty` as an array or a tuple depending on the language.
### Example:
`crusoe(5, 0.2, 30, 1.02, 1.1)` ->
The successive `x` are : `0.0, 0.173205, 0.344294, 0.511991, 0.674744, 0.830674` (approximately)
The successive `y` are : `0.0, 0.1, 0.211106, 0.334292, 0.47052, 0.620695` (approximately)
and
```
lastx: 0.8306737544381833
lasty: 0.620694691344071
```
### A drawing:

Successive points:
- x: `0.0, 0.9659..., 1.8319..., 2.3319..., 1.8319...`
- y: `0.0, 0.2588..., 0.7588..., 1.6248..., 2.4908...`
### Note
Please could you ask before translating: some translations are already written and published when/if the kata is approved.
|
from math import cos, sin, radians
def crusoe(n, d, ang, dist_mult, ang_mult):
x, y, theta, r = 0, 0, 1, 1
for i in range(n):
theta = ang*ang_mult**i
r = d*dist_mult**i
x += r*cos(radians(theta))
y += r*sin(radians(theta))
return (x,y)
|
### Task
Your main goal is to find two numbers(` >= 0 `), greatest common divisor of wich will be `divisor` and number of iterations, taken by Euclids algorithm will be `iterations`.
### Euclid's GCD
```CSharp
BigInteger FindGCD(BigInteger a, BigInteger b) {
// Swaping `a` and `b`
if (a < b) {
a += b;
b = a - b;
a = a - b;
}
while (b > 0) {
// Iteration of calculation
BigInteger c = a % b;
a = b;
b = c;
}
// `a` - is greates common divisor now
return a;
}
```
### Restrictions
Your program should work with numbers
`0 < divisor < 1000`
`0 <= iterations <= 50'000`
|
def find_initial_numbers (divisor, iterations):
a = divisor
b = divisor if iterations != 0 else 0
for _ in range(iterations):
c = b
b = a
a = b + c
return a, b
|
### Task
Your main goal is to find two numbers(` >= 0 `), greatest common divisor of wich will be `divisor` and number of iterations, taken by Euclids algorithm will be `iterations`.
### Euclid's GCD
```CSharp
BigInteger FindGCD(BigInteger a, BigInteger b) {
// Swaping `a` and `b`
if (a < b) {
a += b;
b = a - b;
a = a - b;
}
while (b > 0) {
// Iteration of calculation
BigInteger c = a % b;
a = b;
b = c;
}
// `a` - is greates common divisor now
return a;
}
```
### Restrictions
Your program should work with numbers
`0 < divisor < 1000`
`0 <= iterations <= 50'000`
|
def find_initial_numbers (divisor, iterations):
a, b = divisor, 0
for _ in range(iterations + (1 if iterations else 0)):
a, b = a + b, a
return a, b
|
### Task
Your main goal is to find two numbers(` >= 0 `), greatest common divisor of wich will be `divisor` and number of iterations, taken by Euclids algorithm will be `iterations`.
### Euclid's GCD
```CSharp
BigInteger FindGCD(BigInteger a, BigInteger b) {
// Swaping `a` and `b`
if (a < b) {
a += b;
b = a - b;
a = a - b;
}
while (b > 0) {
// Iteration of calculation
BigInteger c = a % b;
a = b;
b = c;
}
// `a` - is greates common divisor now
return a;
}
```
### Restrictions
Your program should work with numbers
`0 < divisor < 1000`
`0 <= iterations <= 50'000`
|
def find_initial_numbers (divisor, iterations):
a, b = divisor, 0
for i_iter in range(iterations):
a, b = a * (divisor + 1) + b, a
return [a, b]
|
### Task
Your main goal is to find two numbers(` >= 0 `), greatest common divisor of wich will be `divisor` and number of iterations, taken by Euclids algorithm will be `iterations`.
### Euclid's GCD
```CSharp
BigInteger FindGCD(BigInteger a, BigInteger b) {
// Swaping `a` and `b`
if (a < b) {
a += b;
b = a - b;
a = a - b;
}
while (b > 0) {
// Iteration of calculation
BigInteger c = a % b;
a = b;
b = c;
}
// `a` - is greates common divisor now
return a;
}
```
### Restrictions
Your program should work with numbers
`0 < divisor < 1000`
`0 <= iterations <= 50'000`
|
def find_initial_numbers (divisor, iterations):
if iterations == 0:
return (divisor,0)
a = divisor
b = 0
for _ in range(iterations+1):
a, b = a+b, a
return (a,b)
|
### Task
Your main goal is to find two numbers(` >= 0 `), greatest common divisor of wich will be `divisor` and number of iterations, taken by Euclids algorithm will be `iterations`.
### Euclid's GCD
```CSharp
BigInteger FindGCD(BigInteger a, BigInteger b) {
// Swaping `a` and `b`
if (a < b) {
a += b;
b = a - b;
a = a - b;
}
while (b > 0) {
// Iteration of calculation
BigInteger c = a % b;
a = b;
b = c;
}
// `a` - is greates common divisor now
return a;
}
```
### Restrictions
Your program should work with numbers
`0 < divisor < 1000`
`0 <= iterations <= 50'000`
|
def find_initial_numbers (divisor, iterations):
# 5 is a randomly choosen num not a must
#using different num will give different result but still correct
a, b = 5*divisor, divisor
for i in range(1,iterations):
a, b = 5*a+b, a
return (a,b) if iterations else (divisor,iterations)
|
### Task
Your main goal is to find two numbers(` >= 0 `), greatest common divisor of wich will be `divisor` and number of iterations, taken by Euclids algorithm will be `iterations`.
### Euclid's GCD
```CSharp
BigInteger FindGCD(BigInteger a, BigInteger b) {
// Swaping `a` and `b`
if (a < b) {
a += b;
b = a - b;
a = a - b;
}
while (b > 0) {
// Iteration of calculation
BigInteger c = a % b;
a = b;
b = c;
}
// `a` - is greates common divisor now
return a;
}
```
### Restrictions
Your program should work with numbers
`0 < divisor < 1000`
`0 <= iterations <= 50'000`
|
def find_initial_numbers (divisor, iterations):
if iterations==0:
return divisor,0
a,b=divisor,0
for _ in range(iterations+1):
a,b=a+b,a
return a,b
|
Take the following IPv4 address: 128.32.10.1
This address has 4 octets where each octet is a single byte (or 8 bits).
* 1st octet 128 has the binary representation: 10000000
* 2nd octet 32 has the binary representation: 00100000
* 3rd octet 10 has the binary representation: 00001010
* 4th octet 1 has the binary representation: 00000001
So 128.32.10.1 == 10000000.00100000.00001010.00000001
Because the above IP address has 32 bits, we can represent it as the 32
bit number: 2149583361.
Write a function ip_to_int32(ip) ( **JS**: `ipToInt32(ip)` ) that takes an IPv4 address and returns
a 32 bit number.
```python
ip_to_int32("128.32.10.1") => 2149583361
```
|
def ip_to_int32(ip):
"""
Take the following IPv4 address: 128.32.10.1 This address has 4 octets
where each octet is a single byte (or 8 bits).
1st octet 128 has the binary representation: 10000000
2nd octet 32 has the binary representation: 00100000
3rd octet 10 has the binary representation: 00001010
4th octet 1 has the binary representation: 00000001
So 128.32.10.1 == 10000000.00100000.00001010.00000001
Because the above IP address has 32 bits, we can represent it as
the 32 bit number: 2149583361.
Write a function ip_to_int32(ip) ( JS: ipToInt32(ip) ) that takes
an IPv4 address and returns a 32 bit number.
ip_to_int32("128.32.10.1") => 2149583361
"""
addr = ip.split(".")
res = int(addr[0]) << 24
res += int(addr[1]) << 16
res += int(addr[2]) << 8
res += int(addr[3])
return res
|
Take the following IPv4 address: 128.32.10.1
This address has 4 octets where each octet is a single byte (or 8 bits).
* 1st octet 128 has the binary representation: 10000000
* 2nd octet 32 has the binary representation: 00100000
* 3rd octet 10 has the binary representation: 00001010
* 4th octet 1 has the binary representation: 00000001
So 128.32.10.1 == 10000000.00100000.00001010.00000001
Because the above IP address has 32 bits, we can represent it as the 32
bit number: 2149583361.
Write a function ip_to_int32(ip) ( **JS**: `ipToInt32(ip)` ) that takes an IPv4 address and returns
a 32 bit number.
```python
ip_to_int32("128.32.10.1") => 2149583361
```
|
def ip_to_int32(ip):
return reduce(lambda acc, x: acc << 8 | x, (int(x) for x in ip.split('.')))
|
Take the following IPv4 address: 128.32.10.1
This address has 4 octets where each octet is a single byte (or 8 bits).
* 1st octet 128 has the binary representation: 10000000
* 2nd octet 32 has the binary representation: 00100000
* 3rd octet 10 has the binary representation: 00001010
* 4th octet 1 has the binary representation: 00000001
So 128.32.10.1 == 10000000.00100000.00001010.00000001
Because the above IP address has 32 bits, we can represent it as the 32
bit number: 2149583361.
Write a function ip_to_int32(ip) ( **JS**: `ipToInt32(ip)` ) that takes an IPv4 address and returns
a 32 bit number.
```python
ip_to_int32("128.32.10.1") => 2149583361
```
|
def ip_to_int32(ip):
r =""
for i in ip.split('.'):
r += "{0:08b}".format(int(i))
return int(r, 2)
|
Take the following IPv4 address: 128.32.10.1
This address has 4 octets where each octet is a single byte (or 8 bits).
* 1st octet 128 has the binary representation: 10000000
* 2nd octet 32 has the binary representation: 00100000
* 3rd octet 10 has the binary representation: 00001010
* 4th octet 1 has the binary representation: 00000001
So 128.32.10.1 == 10000000.00100000.00001010.00000001
Because the above IP address has 32 bits, we can represent it as the 32
bit number: 2149583361.
Write a function ip_to_int32(ip) ( **JS**: `ipToInt32(ip)` ) that takes an IPv4 address and returns
a 32 bit number.
```python
ip_to_int32("128.32.10.1") => 2149583361
```
|
def ip_to_int32(ip):
return int(''.join([(bin(int(x))[2:]).zfill(8) for x in ip.split('.')]),2)
|
Take the following IPv4 address: 128.32.10.1
This address has 4 octets where each octet is a single byte (or 8 bits).
* 1st octet 128 has the binary representation: 10000000
* 2nd octet 32 has the binary representation: 00100000
* 3rd octet 10 has the binary representation: 00001010
* 4th octet 1 has the binary representation: 00000001
So 128.32.10.1 == 10000000.00100000.00001010.00000001
Because the above IP address has 32 bits, we can represent it as the 32
bit number: 2149583361.
Write a function ip_to_int32(ip) ( **JS**: `ipToInt32(ip)` ) that takes an IPv4 address and returns
a 32 bit number.
```python
ip_to_int32("128.32.10.1") => 2149583361
```
|
def ip_to_int32(ip):
return reduce(lambda p, n: (p << 8) + int(n), ip.split('.'), 0)
|
Take the following IPv4 address: 128.32.10.1
This address has 4 octets where each octet is a single byte (or 8 bits).
* 1st octet 128 has the binary representation: 10000000
* 2nd octet 32 has the binary representation: 00100000
* 3rd octet 10 has the binary representation: 00001010
* 4th octet 1 has the binary representation: 00000001
So 128.32.10.1 == 10000000.00100000.00001010.00000001
Because the above IP address has 32 bits, we can represent it as the 32
bit number: 2149583361.
Write a function ip_to_int32(ip) ( **JS**: `ipToInt32(ip)` ) that takes an IPv4 address and returns
a 32 bit number.
```python
ip_to_int32("128.32.10.1") => 2149583361
```
|
def ip_to_int32(ip):
return sum(int(o) << (8*i) for i, o in enumerate(ip.split(".")[::-1]))
|
Take the following IPv4 address: 128.32.10.1
This address has 4 octets where each octet is a single byte (or 8 bits).
* 1st octet 128 has the binary representation: 10000000
* 2nd octet 32 has the binary representation: 00100000
* 3rd octet 10 has the binary representation: 00001010
* 4th octet 1 has the binary representation: 00000001
So 128.32.10.1 == 10000000.00100000.00001010.00000001
Because the above IP address has 32 bits, we can represent it as the 32
bit number: 2149583361.
Write a function ip_to_int32(ip) ( **JS**: `ipToInt32(ip)` ) that takes an IPv4 address and returns
a 32 bit number.
```python
ip_to_int32("128.32.10.1") => 2149583361
```
|
def ip_to_int32(ip):
retInt = 0
octets = ip.split('.')
for ndx, offset in enumerate((24, 16, 8, 0)):
retInt = retInt | int(octets[ndx]) << offset
return retInt
|
Take the following IPv4 address: 128.32.10.1
This address has 4 octets where each octet is a single byte (or 8 bits).
* 1st octet 128 has the binary representation: 10000000
* 2nd octet 32 has the binary representation: 00100000
* 3rd octet 10 has the binary representation: 00001010
* 4th octet 1 has the binary representation: 00000001
So 128.32.10.1 == 10000000.00100000.00001010.00000001
Because the above IP address has 32 bits, we can represent it as the 32
bit number: 2149583361.
Write a function ip_to_int32(ip) ( **JS**: `ipToInt32(ip)` ) that takes an IPv4 address and returns
a 32 bit number.
```python
ip_to_int32("128.32.10.1") => 2149583361
```
|
import struct
from socket import inet_aton
def ip_to_int32(ip):
return struct.unpack('>I', inet_aton(ip))[0]
|
Take the following IPv4 address: 128.32.10.1
This address has 4 octets where each octet is a single byte (or 8 bits).
* 1st octet 128 has the binary representation: 10000000
* 2nd octet 32 has the binary representation: 00100000
* 3rd octet 10 has the binary representation: 00001010
* 4th octet 1 has the binary representation: 00000001
So 128.32.10.1 == 10000000.00100000.00001010.00000001
Because the above IP address has 32 bits, we can represent it as the 32
bit number: 2149583361.
Write a function ip_to_int32(ip) ( **JS**: `ipToInt32(ip)` ) that takes an IPv4 address and returns
a 32 bit number.
```python
ip_to_int32("128.32.10.1") => 2149583361
```
|
def ip_to_int32(ip):
result = 0
for s in ip.split('.'):
result *= 256
result += int(s)
return result
|
Take the following IPv4 address: 128.32.10.1
This address has 4 octets where each octet is a single byte (or 8 bits).
* 1st octet 128 has the binary representation: 10000000
* 2nd octet 32 has the binary representation: 00100000
* 3rd octet 10 has the binary representation: 00001010
* 4th octet 1 has the binary representation: 00000001
So 128.32.10.1 == 10000000.00100000.00001010.00000001
Because the above IP address has 32 bits, we can represent it as the 32
bit number: 2149583361.
Write a function ip_to_int32(ip) ( **JS**: `ipToInt32(ip)` ) that takes an IPv4 address and returns
a 32 bit number.
```python
ip_to_int32("128.32.10.1") => 2149583361
```
|
def ip_to_int32(ip):
return int(''.join([(format(int(i),"08b")) for i in ip.split('.')]),2)
|
**The Rub**
You need to make a function that takes an object as an argument, and returns a very similar object but with a special property. The returned object should allow a user to access values by providing only the beginning of the key for the value they want. For example if the given object has a key `idNumber`, you should be able to access its value on the returned object by using a key `idNum` or even simply `id`. `Num` and `Number` shouldn't work because we are only looking for matches at the beginning of a key.
Be aware that you _could_ simply add all these partial keys one by one to the object. However, for the sake of avoiding clutter, we don't want to have a JSON with a bunch of nonsensical keys. Thus, in the random tests there will be a test to check that you did not add or remove any keys from the object passed in or the object returned.
Also, if a key is tested that appears as the beginning of more than one key in the original object (e.g. if the original object had a key `idNumber` and `idString` and we wanted to test the key `id`) then return the value corresponding with whichever key comes first **alphabetically**. (In this case it would be `idNumber`s value because it comes first alphabetically.)
**Example**
```python
o = partial_keys({"abcd": 1})
o['abcd'] == 1 # true
o['abc'] == 1 # true
o['ab'] == 1 # true
o['a'] == 1 # true
o['b'] == 1 # false!
o['b'] == None # true
list(o.keys()) # ['abcd']
```
|
def partial_keys(d):
class Dct(dict):
def __getitem__(self,pk):
k = min((k for k in self if k.startswith(pk)), default=None)
return k if k is None else super().__getitem__(k)
return Dct(d)
|
**The Rub**
You need to make a function that takes an object as an argument, and returns a very similar object but with a special property. The returned object should allow a user to access values by providing only the beginning of the key for the value they want. For example if the given object has a key `idNumber`, you should be able to access its value on the returned object by using a key `idNum` or even simply `id`. `Num` and `Number` shouldn't work because we are only looking for matches at the beginning of a key.
Be aware that you _could_ simply add all these partial keys one by one to the object. However, for the sake of avoiding clutter, we don't want to have a JSON with a bunch of nonsensical keys. Thus, in the random tests there will be a test to check that you did not add or remove any keys from the object passed in or the object returned.
Also, if a key is tested that appears as the beginning of more than one key in the original object (e.g. if the original object had a key `idNumber` and `idString` and we wanted to test the key `id`) then return the value corresponding with whichever key comes first **alphabetically**. (In this case it would be `idNumber`s value because it comes first alphabetically.)
**Example**
```python
o = partial_keys({"abcd": 1})
o['abcd'] == 1 # true
o['abc'] == 1 # true
o['ab'] == 1 # true
o['a'] == 1 # true
o['b'] == 1 # false!
o['b'] == None # true
list(o.keys()) # ['abcd']
```
|
class PartialKeysDict(dict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._keys_list = sorted(self.keys())
def __getitem__(self, key):
for q in self._keys_list:
if q.startswith(key):
return super().__getitem__(q)
partial_keys = PartialKeysDict
|
**The Rub**
You need to make a function that takes an object as an argument, and returns a very similar object but with a special property. The returned object should allow a user to access values by providing only the beginning of the key for the value they want. For example if the given object has a key `idNumber`, you should be able to access its value on the returned object by using a key `idNum` or even simply `id`. `Num` and `Number` shouldn't work because we are only looking for matches at the beginning of a key.
Be aware that you _could_ simply add all these partial keys one by one to the object. However, for the sake of avoiding clutter, we don't want to have a JSON with a bunch of nonsensical keys. Thus, in the random tests there will be a test to check that you did not add or remove any keys from the object passed in or the object returned.
Also, if a key is tested that appears as the beginning of more than one key in the original object (e.g. if the original object had a key `idNumber` and `idString` and we wanted to test the key `id`) then return the value corresponding with whichever key comes first **alphabetically**. (In this case it would be `idNumber`s value because it comes first alphabetically.)
**Example**
```python
o = partial_keys({"abcd": 1})
o['abcd'] == 1 # true
o['abc'] == 1 # true
o['ab'] == 1 # true
o['a'] == 1 # true
o['b'] == 1 # false!
o['b'] == None # true
list(o.keys()) # ['abcd']
```
|
class partial_keys(dict): __getitem__ = lambda self, key: self.get(next((k for k in sorted(self.keys()) if k.startswith(key)), None), None)
|
**The Rub**
You need to make a function that takes an object as an argument, and returns a very similar object but with a special property. The returned object should allow a user to access values by providing only the beginning of the key for the value they want. For example if the given object has a key `idNumber`, you should be able to access its value on the returned object by using a key `idNum` or even simply `id`. `Num` and `Number` shouldn't work because we are only looking for matches at the beginning of a key.
Be aware that you _could_ simply add all these partial keys one by one to the object. However, for the sake of avoiding clutter, we don't want to have a JSON with a bunch of nonsensical keys. Thus, in the random tests there will be a test to check that you did not add or remove any keys from the object passed in or the object returned.
Also, if a key is tested that appears as the beginning of more than one key in the original object (e.g. if the original object had a key `idNumber` and `idString` and we wanted to test the key `id`) then return the value corresponding with whichever key comes first **alphabetically**. (In this case it would be `idNumber`s value because it comes first alphabetically.)
**Example**
```python
o = partial_keys({"abcd": 1})
o['abcd'] == 1 # true
o['abc'] == 1 # true
o['ab'] == 1 # true
o['a'] == 1 # true
o['b'] == 1 # false!
o['b'] == None # true
list(o.keys()) # ['abcd']
```
|
class partial_keys(dict):
def __getitem__(self, key):
if key in self:
return super().__getitem__(key)
for k in sorted(self):
if k.startswith(key):
return super().__getitem__(k)
|
**The Rub**
You need to make a function that takes an object as an argument, and returns a very similar object but with a special property. The returned object should allow a user to access values by providing only the beginning of the key for the value they want. For example if the given object has a key `idNumber`, you should be able to access its value on the returned object by using a key `idNum` or even simply `id`. `Num` and `Number` shouldn't work because we are only looking for matches at the beginning of a key.
Be aware that you _could_ simply add all these partial keys one by one to the object. However, for the sake of avoiding clutter, we don't want to have a JSON with a bunch of nonsensical keys. Thus, in the random tests there will be a test to check that you did not add or remove any keys from the object passed in or the object returned.
Also, if a key is tested that appears as the beginning of more than one key in the original object (e.g. if the original object had a key `idNumber` and `idString` and we wanted to test the key `id`) then return the value corresponding with whichever key comes first **alphabetically**. (In this case it would be `idNumber`s value because it comes first alphabetically.)
**Example**
```python
o = partial_keys({"abcd": 1})
o['abcd'] == 1 # true
o['abc'] == 1 # true
o['ab'] == 1 # true
o['a'] == 1 # true
o['b'] == 1 # false!
o['b'] == None # true
list(o.keys()) # ['abcd']
```
|
class partial_keys(dict):
def __getitem__(self, key):
return next((v for k,v in sorted(self.items()) if k.startswith(key)), None)
|
**The Rub**
You need to make a function that takes an object as an argument, and returns a very similar object but with a special property. The returned object should allow a user to access values by providing only the beginning of the key for the value they want. For example if the given object has a key `idNumber`, you should be able to access its value on the returned object by using a key `idNum` or even simply `id`. `Num` and `Number` shouldn't work because we are only looking for matches at the beginning of a key.
Be aware that you _could_ simply add all these partial keys one by one to the object. However, for the sake of avoiding clutter, we don't want to have a JSON with a bunch of nonsensical keys. Thus, in the random tests there will be a test to check that you did not add or remove any keys from the object passed in or the object returned.
Also, if a key is tested that appears as the beginning of more than one key in the original object (e.g. if the original object had a key `idNumber` and `idString` and we wanted to test the key `id`) then return the value corresponding with whichever key comes first **alphabetically**. (In this case it would be `idNumber`s value because it comes first alphabetically.)
**Example**
```python
o = partial_keys({"abcd": 1})
o['abcd'] == 1 # true
o['abc'] == 1 # true
o['ab'] == 1 # true
o['a'] == 1 # true
o['b'] == 1 # false!
o['b'] == None # true
list(o.keys()) # ['abcd']
```
|
class partial_keys(dict):
def __getitem__(self, key):
keys = sorted(k for k in self.keys() if k.startswith(key))
if keys: return super().__getitem__(keys[0])
|
**The Rub**
You need to make a function that takes an object as an argument, and returns a very similar object but with a special property. The returned object should allow a user to access values by providing only the beginning of the key for the value they want. For example if the given object has a key `idNumber`, you should be able to access its value on the returned object by using a key `idNum` or even simply `id`. `Num` and `Number` shouldn't work because we are only looking for matches at the beginning of a key.
Be aware that you _could_ simply add all these partial keys one by one to the object. However, for the sake of avoiding clutter, we don't want to have a JSON with a bunch of nonsensical keys. Thus, in the random tests there will be a test to check that you did not add or remove any keys from the object passed in or the object returned.
Also, if a key is tested that appears as the beginning of more than one key in the original object (e.g. if the original object had a key `idNumber` and `idString` and we wanted to test the key `id`) then return the value corresponding with whichever key comes first **alphabetically**. (In this case it would be `idNumber`s value because it comes first alphabetically.)
**Example**
```python
o = partial_keys({"abcd": 1})
o['abcd'] == 1 # true
o['abc'] == 1 # true
o['ab'] == 1 # true
o['a'] == 1 # true
o['b'] == 1 # false!
o['b'] == None # true
list(o.keys()) # ['abcd']
```
|
import re
def partial_keys(d):
class MyDict(dict):
def __getitem__(self, item):
for key in sorted(d):
if re.match(item, key):
return d[key]
return MyDict(**d)
|
**The Rub**
You need to make a function that takes an object as an argument, and returns a very similar object but with a special property. The returned object should allow a user to access values by providing only the beginning of the key for the value they want. For example if the given object has a key `idNumber`, you should be able to access its value on the returned object by using a key `idNum` or even simply `id`. `Num` and `Number` shouldn't work because we are only looking for matches at the beginning of a key.
Be aware that you _could_ simply add all these partial keys one by one to the object. However, for the sake of avoiding clutter, we don't want to have a JSON with a bunch of nonsensical keys. Thus, in the random tests there will be a test to check that you did not add or remove any keys from the object passed in or the object returned.
Also, if a key is tested that appears as the beginning of more than one key in the original object (e.g. if the original object had a key `idNumber` and `idString` and we wanted to test the key `id`) then return the value corresponding with whichever key comes first **alphabetically**. (In this case it would be `idNumber`s value because it comes first alphabetically.)
**Example**
```python
o = partial_keys({"abcd": 1})
o['abcd'] == 1 # true
o['abc'] == 1 # true
o['ab'] == 1 # true
o['a'] == 1 # true
o['b'] == 1 # false!
o['b'] == None # true
list(o.keys()) # ['abcd']
```
|
class partial_keys(dict):
def __getitem__(self, key):
keys = sorted(k for k in self.keys() if k.startswith(key))
if keys: return dict.__getitem__(self, keys[0])
|
Lets play some Pong!

For those who don't know what Pong is, it is a simple arcade game where two players can move their paddles to hit a ball towards the opponent's side of the screen, gaining a point for each opponent's miss. You can read more about it [here](https://en.wikipedia.org/wiki/Pong).
___
# Task:
You must finish the `Pong` class. It has a constructor which accepts the `maximum score` a player can get throughout the game, and a method called `play`. This method determines whether the current player hit the ball or not, i.e. if the paddle is at the sufficient height to hit it back. There're 4 possible outcomes: player successfully hits the ball back, player misses the ball, player misses the ball **and his opponent reaches the maximum score winning the game**, either player tries to hit a ball despite the game being over. You can see the input and output description in detail below.
### "Play" method input:
* ball position - The Y coordinate of the ball
* player position - The Y coordinate of the centre(!) of the current player's paddle
### "Play" method output:
One of the following strings:
* `"Player X has hit the ball!"` - If the ball "hits" the paddle
* `"Player X has missed the ball!"` - If the ball is above/below the paddle
* `"Player X has won the game!"` - If one of the players has reached the maximum score
* `"Game Over!"` - If the game has ended but either player still hits the ball
### Important notes:
* Players take turns hitting the ball, always starting the game with the Player 1.
* The paddles are `7` pixels in height.
* The ball is `1` pixel in height.
___
## Example
|
from itertools import cycle
class Pong:
def __init__(self, max_score):
self.max_score = max_score;
self.scores = {1: 0, 2: 0}
self.players = cycle((1, 2))
def game_over(self):
return any(score >= self.max_score for score in list(self.scores.values()))
def play(self, ball_pos, player_pos):
if self.game_over():
return "Game Over!"
player = next(self.players)
if abs(ball_pos - player_pos) <= 3:
return "Player {} has hit the ball!".format(player)
else:
self.scores[player] += 1
if self.scores[player] == self.max_score:
return "Player {} has won the game!".format(next(self.players))
else:
return "Player {} has missed the ball!".format(player)
|
Lets play some Pong!

For those who don't know what Pong is, it is a simple arcade game where two players can move their paddles to hit a ball towards the opponent's side of the screen, gaining a point for each opponent's miss. You can read more about it [here](https://en.wikipedia.org/wiki/Pong).
___
# Task:
You must finish the `Pong` class. It has a constructor which accepts the `maximum score` a player can get throughout the game, and a method called `play`. This method determines whether the current player hit the ball or not, i.e. if the paddle is at the sufficient height to hit it back. There're 4 possible outcomes: player successfully hits the ball back, player misses the ball, player misses the ball **and his opponent reaches the maximum score winning the game**, either player tries to hit a ball despite the game being over. You can see the input and output description in detail below.
### "Play" method input:
* ball position - The Y coordinate of the ball
* player position - The Y coordinate of the centre(!) of the current player's paddle
### "Play" method output:
One of the following strings:
* `"Player X has hit the ball!"` - If the ball "hits" the paddle
* `"Player X has missed the ball!"` - If the ball is above/below the paddle
* `"Player X has won the game!"` - If one of the players has reached the maximum score
* `"Game Over!"` - If the game has ended but either player still hits the ball
### Important notes:
* Players take turns hitting the ball, always starting the game with the Player 1.
* The paddles are `7` pixels in height.
* The ball is `1` pixel in height.
___
## Example
|
class Pong:
def __init__(self, max_score):
self.max_score = max_score;
self.score = [0,0]
self.player = 0
def play(self, ball_pos, player_pos):
if self.max_score in self.score: return "Game Over!"
if player_pos-3 <= ball_pos <= player_pos+3:
self.player ^= 1
return "Player {} has hit the ball!".format((self.player^1) +1)
self.player ^= 1
self.score[self.player] += 1
if self.score[self.player] == self.max_score: return "Player {} has won the game!".format(self.player + 1)
return "Player {} has missed the ball!".format((self.player^1) +1)
|
Lets play some Pong!

For those who don't know what Pong is, it is a simple arcade game where two players can move their paddles to hit a ball towards the opponent's side of the screen, gaining a point for each opponent's miss. You can read more about it [here](https://en.wikipedia.org/wiki/Pong).
___
# Task:
You must finish the `Pong` class. It has a constructor which accepts the `maximum score` a player can get throughout the game, and a method called `play`. This method determines whether the current player hit the ball or not, i.e. if the paddle is at the sufficient height to hit it back. There're 4 possible outcomes: player successfully hits the ball back, player misses the ball, player misses the ball **and his opponent reaches the maximum score winning the game**, either player tries to hit a ball despite the game being over. You can see the input and output description in detail below.
### "Play" method input:
* ball position - The Y coordinate of the ball
* player position - The Y coordinate of the centre(!) of the current player's paddle
### "Play" method output:
One of the following strings:
* `"Player X has hit the ball!"` - If the ball "hits" the paddle
* `"Player X has missed the ball!"` - If the ball is above/below the paddle
* `"Player X has won the game!"` - If one of the players has reached the maximum score
* `"Game Over!"` - If the game has ended but either player still hits the ball
### Important notes:
* Players take turns hitting the ball, always starting the game with the Player 1.
* The paddles are `7` pixels in height.
* The ball is `1` pixel in height.
___
## Example
|
class Pong:
def __init__(self, max_score):
self.max_score = max_score
self.next = 1
self.score = {1: 0, 2: 0}
def play(self, ball, paddle):
if max(self.score.values()) >= self.max_score:
return "Game Over!"
current, self.next = self.next, 3 - self.next
if paddle - 4 < ball < paddle + 4:
return f"Player {current} has hit the ball!"
else:
self.score[current] += 1
if self.score[current] == self.max_score:
return f"Player {self.next} has won the game!"
return f"Player {current} has missed the ball!"
|
Lets play some Pong!

For those who don't know what Pong is, it is a simple arcade game where two players can move their paddles to hit a ball towards the opponent's side of the screen, gaining a point for each opponent's miss. You can read more about it [here](https://en.wikipedia.org/wiki/Pong).
___
# Task:
You must finish the `Pong` class. It has a constructor which accepts the `maximum score` a player can get throughout the game, and a method called `play`. This method determines whether the current player hit the ball or not, i.e. if the paddle is at the sufficient height to hit it back. There're 4 possible outcomes: player successfully hits the ball back, player misses the ball, player misses the ball **and his opponent reaches the maximum score winning the game**, either player tries to hit a ball despite the game being over. You can see the input and output description in detail below.
### "Play" method input:
* ball position - The Y coordinate of the ball
* player position - The Y coordinate of the centre(!) of the current player's paddle
### "Play" method output:
One of the following strings:
* `"Player X has hit the ball!"` - If the ball "hits" the paddle
* `"Player X has missed the ball!"` - If the ball is above/below the paddle
* `"Player X has won the game!"` - If one of the players has reached the maximum score
* `"Game Over!"` - If the game has ended but either player still hits the ball
### Important notes:
* Players take turns hitting the ball, always starting the game with the Player 1.
* The paddles are `7` pixels in height.
* The ball is `1` pixel in height.
___
## Example
|
class Pong:
def __init__(self, win):
self.win = win
self.turn = -1
self.scores = [0, 0]
def play(self, ball, player):
if max(self.scores) == self.win: return 'Game Over!'
self.turn = (self.turn + 1) % 2
if abs(ball - player) < 4: return 'Player ' + str(self.turn + 1) + ' has hit the ball!'
self.scores[(self.turn + 1) % 2] += 1
return 'Player ' + (str(1 if self.turn else 2) + ' has won the game!' if max(self.scores) == self.win else str(self.turn + 1) + ' has missed the ball!')
|
Lets play some Pong!

For those who don't know what Pong is, it is a simple arcade game where two players can move their paddles to hit a ball towards the opponent's side of the screen, gaining a point for each opponent's miss. You can read more about it [here](https://en.wikipedia.org/wiki/Pong).
___
# Task:
You must finish the `Pong` class. It has a constructor which accepts the `maximum score` a player can get throughout the game, and a method called `play`. This method determines whether the current player hit the ball or not, i.e. if the paddle is at the sufficient height to hit it back. There're 4 possible outcomes: player successfully hits the ball back, player misses the ball, player misses the ball **and his opponent reaches the maximum score winning the game**, either player tries to hit a ball despite the game being over. You can see the input and output description in detail below.
### "Play" method input:
* ball position - The Y coordinate of the ball
* player position - The Y coordinate of the centre(!) of the current player's paddle
### "Play" method output:
One of the following strings:
* `"Player X has hit the ball!"` - If the ball "hits" the paddle
* `"Player X has missed the ball!"` - If the ball is above/below the paddle
* `"Player X has won the game!"` - If one of the players has reached the maximum score
* `"Game Over!"` - If the game has ended but either player still hits the ball
### Important notes:
* Players take turns hitting the ball, always starting the game with the Player 1.
* The paddles are `7` pixels in height.
* The ball is `1` pixel in height.
___
## Example
|
class Pong:
def __init__(self, max_score):
self.max_score = max_score
self.scores = [0, 0]
self.turn = 0
def play(self, ball_pos, player_pos):
try:
if max(self.scores) == self.max_score:
return 'Game Over!'
if abs(ball_pos - player_pos) <= 3:
return f'Player {self.turn + 1} has hit the ball!'
self.scores[1 - self.turn] += 1
if self.scores[1 - self.turn] == self.max_score:
return f'Player {2 - self.turn} has won the game!'
else:
return f'Player {self.turn + 1} has missed the ball!'
finally:
self.turn = (self.turn + 1) % 2
|
Lets play some Pong!

For those who don't know what Pong is, it is a simple arcade game where two players can move their paddles to hit a ball towards the opponent's side of the screen, gaining a point for each opponent's miss. You can read more about it [here](https://en.wikipedia.org/wiki/Pong).
___
# Task:
You must finish the `Pong` class. It has a constructor which accepts the `maximum score` a player can get throughout the game, and a method called `play`. This method determines whether the current player hit the ball or not, i.e. if the paddle is at the sufficient height to hit it back. There're 4 possible outcomes: player successfully hits the ball back, player misses the ball, player misses the ball **and his opponent reaches the maximum score winning the game**, either player tries to hit a ball despite the game being over. You can see the input and output description in detail below.
### "Play" method input:
* ball position - The Y coordinate of the ball
* player position - The Y coordinate of the centre(!) of the current player's paddle
### "Play" method output:
One of the following strings:
* `"Player X has hit the ball!"` - If the ball "hits" the paddle
* `"Player X has missed the ball!"` - If the ball is above/below the paddle
* `"Player X has won the game!"` - If one of the players has reached the maximum score
* `"Game Over!"` - If the game has ended but either player still hits the ball
### Important notes:
* Players take turns hitting the ball, always starting the game with the Player 1.
* The paddles are `7` pixels in height.
* The ball is `1` pixel in height.
___
## Example
|
class Pong:
def __init__(self,m):
self.m,self.w=m,[0,0]
self.o=self.p=0
def play(self,b,a):
if self.o:return "Game Over!"
self.p+=1
if abs(b-a)<3.5:return "Player %d has hit the ball!"%(2-self.p%2)
self.w[self.p%2]+=1
if any(self.m<=x for x in self.w):self.o=1
return "Player %d has %s!"%(2-(self.o+self.p)%2,('missed the ball','won the game')[self.o])
|
Lets play some Pong!

For those who don't know what Pong is, it is a simple arcade game where two players can move their paddles to hit a ball towards the opponent's side of the screen, gaining a point for each opponent's miss. You can read more about it [here](https://en.wikipedia.org/wiki/Pong).
___
# Task:
You must finish the `Pong` class. It has a constructor which accepts the `maximum score` a player can get throughout the game, and a method called `play`. This method determines whether the current player hit the ball or not, i.e. if the paddle is at the sufficient height to hit it back. There're 4 possible outcomes: player successfully hits the ball back, player misses the ball, player misses the ball **and his opponent reaches the maximum score winning the game**, either player tries to hit a ball despite the game being over. You can see the input and output description in detail below.
### "Play" method input:
* ball position - The Y coordinate of the ball
* player position - The Y coordinate of the centre(!) of the current player's paddle
### "Play" method output:
One of the following strings:
* `"Player X has hit the ball!"` - If the ball "hits" the paddle
* `"Player X has missed the ball!"` - If the ball is above/below the paddle
* `"Player X has won the game!"` - If one of the players has reached the maximum score
* `"Game Over!"` - If the game has ended but either player still hits the ball
### Important notes:
* Players take turns hitting the ball, always starting the game with the Player 1.
* The paddles are `7` pixels in height.
* The ball is `1` pixel in height.
___
## Example
|
PADDLE_SIZE = 7
class Pong:
def __init__(self, max_score):
self.max_score = max_score;
self.player_scores = {0: 0, 1: 0}
self.current_player = 0
self.game_state = None
def play(self, ball_pos, player_pos):
if self.game_state is not None:
return self.game_state
paddle_range = (player_pos - (PADDLE_SIZE / 2),
player_pos + (PADDLE_SIZE / 2))
if ball_pos > max(paddle_range) or ball_pos < min(paddle_range):
self.player_scores[self.current_player ^ 1] += 1
if self.player_scores[self.current_player ^ 1] >= self.max_score:
self.game_state = "Game Over!"
string = "Player {} has won the game!".format(self.current_player ^ 1 + 1)
else:
string = "Player {} has missed the ball!".format(self.current_player + 1)
else:
string = "Player {} has hit the ball!".format(self.current_player + 1)
self.switch_player()
return string
def switch_player(self):
self.current_player ^= 1
|
Lets play some Pong!

For those who don't know what Pong is, it is a simple arcade game where two players can move their paddles to hit a ball towards the opponent's side of the screen, gaining a point for each opponent's miss. You can read more about it [here](https://en.wikipedia.org/wiki/Pong).
___
# Task:
You must finish the `Pong` class. It has a constructor which accepts the `maximum score` a player can get throughout the game, and a method called `play`. This method determines whether the current player hit the ball or not, i.e. if the paddle is at the sufficient height to hit it back. There're 4 possible outcomes: player successfully hits the ball back, player misses the ball, player misses the ball **and his opponent reaches the maximum score winning the game**, either player tries to hit a ball despite the game being over. You can see the input and output description in detail below.
### "Play" method input:
* ball position - The Y coordinate of the ball
* player position - The Y coordinate of the centre(!) of the current player's paddle
### "Play" method output:
One of the following strings:
* `"Player X has hit the ball!"` - If the ball "hits" the paddle
* `"Player X has missed the ball!"` - If the ball is above/below the paddle
* `"Player X has won the game!"` - If one of the players has reached the maximum score
* `"Game Over!"` - If the game has ended but either player still hits the ball
### Important notes:
* Players take turns hitting the ball, always starting the game with the Player 1.
* The paddles are `7` pixels in height.
* The ball is `1` pixel in height.
___
## Example
|
class Pong:
def __init__(self, max_score):
self.max_score = max_score;
self.player=[0,0]
self.index=0
self.win=False
def play(self, ball_pos, player_pos):
if self.win:
return "Game Over!"
self.index+=1
if abs(ball_pos-player_pos)>3:
self.player[self.index%2]+=1
if self.player[self.index%2]>=self.max_score:
self.win=True
return "Player 2 has won the game!" if self.index%2==1 else "Player 1 has won the game!"
return "Player 1 has missed the ball!" if (self.index-1)%2==0 else "Player 2 has missed the ball!"
return "Player 1 has hit the ball!" if (self.index-1)%2==0 else "Player 2 has hit the ball!"
|
Lets play some Pong!

For those who don't know what Pong is, it is a simple arcade game where two players can move their paddles to hit a ball towards the opponent's side of the screen, gaining a point for each opponent's miss. You can read more about it [here](https://en.wikipedia.org/wiki/Pong).
___
# Task:
You must finish the `Pong` class. It has a constructor which accepts the `maximum score` a player can get throughout the game, and a method called `play`. This method determines whether the current player hit the ball or not, i.e. if the paddle is at the sufficient height to hit it back. There're 4 possible outcomes: player successfully hits the ball back, player misses the ball, player misses the ball **and his opponent reaches the maximum score winning the game**, either player tries to hit a ball despite the game being over. You can see the input and output description in detail below.
### "Play" method input:
* ball position - The Y coordinate of the ball
* player position - The Y coordinate of the centre(!) of the current player's paddle
### "Play" method output:
One of the following strings:
* `"Player X has hit the ball!"` - If the ball "hits" the paddle
* `"Player X has missed the ball!"` - If the ball is above/below the paddle
* `"Player X has won the game!"` - If one of the players has reached the maximum score
* `"Game Over!"` - If the game has ended but either player still hits the ball
### Important notes:
* Players take turns hitting the ball, always starting the game with the Player 1.
* The paddles are `7` pixels in height.
* The ball is `1` pixel in height.
___
## Example
|
class Pong:
def __init__(self, max_score):
self.max_score = max_score
self.next = 1
self.score = {1: 0, 2: 0}
def play(self, ball, paddle):
if max(self.score.values()) >= self.max_score:
return "Game Over!"
current, self.next = self.next, 3 - self.next
if paddle - 4 < ball < paddle + 4:
msg = f"Player {current} has hit the ball!"
else:
msg = f"Player {current} has missed the ball!"
self.score[current] += 1
if self.score[current] == self.max_score:
msg = f"Player {self.next} has won the game!"
return msg
|
Lets play some Pong!

For those who don't know what Pong is, it is a simple arcade game where two players can move their paddles to hit a ball towards the opponent's side of the screen, gaining a point for each opponent's miss. You can read more about it [here](https://en.wikipedia.org/wiki/Pong).
___
# Task:
You must finish the `Pong` class. It has a constructor which accepts the `maximum score` a player can get throughout the game, and a method called `play`. This method determines whether the current player hit the ball or not, i.e. if the paddle is at the sufficient height to hit it back. There're 4 possible outcomes: player successfully hits the ball back, player misses the ball, player misses the ball **and his opponent reaches the maximum score winning the game**, either player tries to hit a ball despite the game being over. You can see the input and output description in detail below.
### "Play" method input:
* ball position - The Y coordinate of the ball
* player position - The Y coordinate of the centre(!) of the current player's paddle
### "Play" method output:
One of the following strings:
* `"Player X has hit the ball!"` - If the ball "hits" the paddle
* `"Player X has missed the ball!"` - If the ball is above/below the paddle
* `"Player X has won the game!"` - If one of the players has reached the maximum score
* `"Game Over!"` - If the game has ended but either player still hits the ball
### Important notes:
* Players take turns hitting the ball, always starting the game with the Player 1.
* The paddles are `7` pixels in height.
* The ball is `1` pixel in height.
___
## Example
|
class Pong:
def __init__(self, max_score):
self.max_score = max_score;
self.i = -1
self.event = "Player {} has {} the ball!"
self.score = {1:0, 2:0}
def play(self, ball, player):
if self.event:
self.i += 1
if not self.event: return "Game Over!"
hit = abs(player - ball)
if hit>3:
winer = (1,2)[not self.i%2]
self.score[winer] += 1
if self.score[winer] == self.max_score:
self.event = None
return f"Player {winer} has won the game!"
return self.event.format((1,2)[self.i%2], ('hit','missed')[hit>3])
|
Design a data structure that supports the following two operations:
* `addWord` (or `add_word`) which adds a word,
* `search` which searches a literal word or a regular expression string containing lowercase letters `"a-z"` or `"."` where `"."` can represent any letter
You may assume that all given words contain only lowercase letters.
## Examples
```python
add_word("bad")
add_word("dad")
add_word("mad")
search("pad") == False
search("bad") == True
search(".ad") == True
search("b..") == True
```
**Note:** the data structure will be initialized multiple times during the tests!
|
import re
class WordDictionary:
def __init__(self):
self.data=[]
def add_word(self,x):
self.data.append(x)
def search(self,x):
for word in self.data:
if re.match(x+"\Z",word): return True
return False
|
Design a data structure that supports the following two operations:
* `addWord` (or `add_word`) which adds a word,
* `search` which searches a literal word or a regular expression string containing lowercase letters `"a-z"` or `"."` where `"."` can represent any letter
You may assume that all given words contain only lowercase letters.
## Examples
```python
add_word("bad")
add_word("dad")
add_word("mad")
search("pad") == False
search("bad") == True
search(".ad") == True
search("b..") == True
```
**Note:** the data structure will be initialized multiple times during the tests!
|
class WordDictionary:
def __init__(self): self.dct = set()
def add_word(self, word): self.dct.add(word)
def word_match(self, w, s):
if len(w) != len(s): return False
try:
for i,c in enumerate(s):
if c != '.' and c != w[i]: return False
return True
except: return False
def search(self, s):
for w in self.dct:
if self.word_match(w, s): return True
return False
|
Design a data structure that supports the following two operations:
* `addWord` (or `add_word`) which adds a word,
* `search` which searches a literal word or a regular expression string containing lowercase letters `"a-z"` or `"."` where `"."` can represent any letter
You may assume that all given words contain only lowercase letters.
## Examples
```python
add_word("bad")
add_word("dad")
add_word("mad")
search("pad") == False
search("bad") == True
search(".ad") == True
search("b..") == True
```
**Note:** the data structure will be initialized multiple times during the tests!
|
import re
class WordDictionary:
def __init__(self):
self.d = {}
def add_word(self, w):
self.d[w] = True
def search(self, k):
if not '.' in k:
return self.d.get(k, False)
r = re.compile('^{}$'.format(k))
return any(r.match(x) for x in self.d.keys())
|
Design a data structure that supports the following two operations:
* `addWord` (or `add_word`) which adds a word,
* `search` which searches a literal word or a regular expression string containing lowercase letters `"a-z"` or `"."` where `"."` can represent any letter
You may assume that all given words contain only lowercase letters.
## Examples
```python
add_word("bad")
add_word("dad")
add_word("mad")
search("pad") == False
search("bad") == True
search(".ad") == True
search("b..") == True
```
**Note:** the data structure will be initialized multiple times during the tests!
|
from re import match
class WordDictionary:
def __init__(self):
self.db = []
def add_word(self, word):
self.db.append(word)
def search(self, word):
return bool([w for w in self.db if match(rf'^{word}$', w)])
|
Design a data structure that supports the following two operations:
* `addWord` (or `add_word`) which adds a word,
* `search` which searches a literal word or a regular expression string containing lowercase letters `"a-z"` or `"."` where `"."` can represent any letter
You may assume that all given words contain only lowercase letters.
## Examples
```python
add_word("bad")
add_word("dad")
add_word("mad")
search("pad") == False
search("bad") == True
search(".ad") == True
search("b..") == True
```
**Note:** the data structure will be initialized multiple times during the tests!
|
import re
class WordDictionary:
def __init__(self):
self.words = []
def add_word(self,v):
self.words.append(v)
def search(self,rg):
return any(re.match(r'^{}$'.format(rg),i) for i in self.words)
|
Design a data structure that supports the following two operations:
* `addWord` (or `add_word`) which adds a word,
* `search` which searches a literal word or a regular expression string containing lowercase letters `"a-z"` or `"."` where `"."` can represent any letter
You may assume that all given words contain only lowercase letters.
## Examples
```python
add_word("bad")
add_word("dad")
add_word("mad")
search("pad") == False
search("bad") == True
search(".ad") == True
search("b..") == True
```
**Note:** the data structure will be initialized multiple times during the tests!
|
from collections import defaultdict
from re import compile, match
class WordDictionary(defaultdict):
def __init__(self):
super(WordDictionary, self).__init__(list)
def add_word(self, s):
self[len(s)].append(s)
def search(self, s):
p = compile(f"^{s}$")
return any(match(p, w) for w in self[len(s)])
|
Design a data structure that supports the following two operations:
* `addWord` (or `add_word`) which adds a word,
* `search` which searches a literal word or a regular expression string containing lowercase letters `"a-z"` or `"."` where `"."` can represent any letter
You may assume that all given words contain only lowercase letters.
## Examples
```python
add_word("bad")
add_word("dad")
add_word("mad")
search("pad") == False
search("bad") == True
search(".ad") == True
search("b..") == True
```
**Note:** the data structure will be initialized multiple times during the tests!
|
from itertools import zip_longest
class WordDictionary:
def __init__(self):
self.d = set()
def add_word(self, s):
return self.d.add(s)
def search(self, s):
for w in self.d:
if all((a==b or b == '.') and a for a,b in zip_longest(w,s)):
return 1
return 0
|
Design a data structure that supports the following two operations:
* `addWord` (or `add_word`) which adds a word,
* `search` which searches a literal word or a regular expression string containing lowercase letters `"a-z"` or `"."` where `"."` can represent any letter
You may assume that all given words contain only lowercase letters.
## Examples
```python
add_word("bad")
add_word("dad")
add_word("mad")
search("pad") == False
search("bad") == True
search(".ad") == True
search("b..") == True
```
**Note:** the data structure will be initialized multiple times during the tests!
|
import re
class WordDictionary:
def __init__(self):
self.words = set()
def add_word(self, word):
self.words.add(word)
def search(self, pattern):
pattern += '$'
return any(re.match(pattern, word) for word in self.words)
|
Design a data structure that supports the following two operations:
* `addWord` (or `add_word`) which adds a word,
* `search` which searches a literal word or a regular expression string containing lowercase letters `"a-z"` or `"."` where `"."` can represent any letter
You may assume that all given words contain only lowercase letters.
## Examples
```python
add_word("bad")
add_word("dad")
add_word("mad")
search("pad") == False
search("bad") == True
search(".ad") == True
search("b..") == True
```
**Note:** the data structure will be initialized multiple times during the tests!
|
from itertools import zip_longest
class WordDictionary:
def __init__(self):
self.words = []
def add_word(self, word):
self.words.append(word)
def search(self, pattern):
return any(all((a and b == '.') or a == b for a, b in zip_longest(word, pattern)) for word in self.words)
|
It is a well-known fact that behind every good comet is a UFO. These UFOs often come to collect loyal supporters from here on Earth. Unfortunately, they only have room to pick up one group of followers on each trip. They do, however, let the groups know ahead of time which will be picked up for each comet by a clever scheme: they pick a name for the comet which, along with the name of the group, can be used to determine if it is a particular group's turn to go (who do you think names the comets?). The details of the matching scheme are given below; your job is to write a program which takes the names of a group and a comet and then determines whether the group should go with the UFO behind that comet.
Both the name of the group and the name of the comet are converted into a number in the following manner: the final number is just the product of all the letters in the name, where "A" is 1 and "Z" is 26. For instance, the group "USACO" would be `21 * 19 * 1 * 3 * 15` = 17955. If the group's number mod 47 is the same as the comet's number mod 47, then you need to tell the group to get ready! (Remember that "a mod b" is the remainder left over after dividing a by b; 34 mod 10 is 4.)
Write a program which reads in the name of the comet and the name of the group and figures out whether according to the above scheme the names are a match, printing "GO" if they match and "STAY" if not. The names of the groups and the comets will be a string of capital letters with no spaces or punctuation, up to 6 characters long.
Example:
Converting the letters to numbers:
```
C O M E T Q
3 15 13 5 20 17
H V N G A T
8 22 14 7 1 20
```
then calculate the product mod 47:
```
3 * 15 * 13 * 5 * 20 * 17 = 994500 mod 47 = 27
8 * 22 * 14 * 7 * 1 * 20 = 344960 mod 47 = 27
```
Because both products evaluate to 27 (when modded by 47), the mission is 'GO'.
|
from operator import mul
def ride(group, comet):
val = lambda name: reduce(mul, (ord(c)-64 for c in name))
return 'GO' if val(comet) % 47 == val(group) % 47 else 'STAY'
|
It is a well-known fact that behind every good comet is a UFO. These UFOs often come to collect loyal supporters from here on Earth. Unfortunately, they only have room to pick up one group of followers on each trip. They do, however, let the groups know ahead of time which will be picked up for each comet by a clever scheme: they pick a name for the comet which, along with the name of the group, can be used to determine if it is a particular group's turn to go (who do you think names the comets?). The details of the matching scheme are given below; your job is to write a program which takes the names of a group and a comet and then determines whether the group should go with the UFO behind that comet.
Both the name of the group and the name of the comet are converted into a number in the following manner: the final number is just the product of all the letters in the name, where "A" is 1 and "Z" is 26. For instance, the group "USACO" would be `21 * 19 * 1 * 3 * 15` = 17955. If the group's number mod 47 is the same as the comet's number mod 47, then you need to tell the group to get ready! (Remember that "a mod b" is the remainder left over after dividing a by b; 34 mod 10 is 4.)
Write a program which reads in the name of the comet and the name of the group and figures out whether according to the above scheme the names are a match, printing "GO" if they match and "STAY" if not. The names of the groups and the comets will be a string of capital letters with no spaces or punctuation, up to 6 characters long.
Example:
Converting the letters to numbers:
```
C O M E T Q
3 15 13 5 20 17
H V N G A T
8 22 14 7 1 20
```
then calculate the product mod 47:
```
3 * 15 * 13 * 5 * 20 * 17 = 994500 mod 47 = 27
8 * 22 * 14 * 7 * 1 * 20 = 344960 mod 47 = 27
```
Because both products evaluate to 27 (when modded by 47), the mission is 'GO'.
|
def ride(group,comet):
n1 = 1
n2 = 1
for x in group:
n1 *= ord(x.lower()) - 96
for x in comet:
n2 *= ord(x.lower()) - 96
if n1 % 47 == n2 % 47:
return "GO"
else:
return "STAY"
|
It is a well-known fact that behind every good comet is a UFO. These UFOs often come to collect loyal supporters from here on Earth. Unfortunately, they only have room to pick up one group of followers on each trip. They do, however, let the groups know ahead of time which will be picked up for each comet by a clever scheme: they pick a name for the comet which, along with the name of the group, can be used to determine if it is a particular group's turn to go (who do you think names the comets?). The details of the matching scheme are given below; your job is to write a program which takes the names of a group and a comet and then determines whether the group should go with the UFO behind that comet.
Both the name of the group and the name of the comet are converted into a number in the following manner: the final number is just the product of all the letters in the name, where "A" is 1 and "Z" is 26. For instance, the group "USACO" would be `21 * 19 * 1 * 3 * 15` = 17955. If the group's number mod 47 is the same as the comet's number mod 47, then you need to tell the group to get ready! (Remember that "a mod b" is the remainder left over after dividing a by b; 34 mod 10 is 4.)
Write a program which reads in the name of the comet and the name of the group and figures out whether according to the above scheme the names are a match, printing "GO" if they match and "STAY" if not. The names of the groups and the comets will be a string of capital letters with no spaces or punctuation, up to 6 characters long.
Example:
Converting the letters to numbers:
```
C O M E T Q
3 15 13 5 20 17
H V N G A T
8 22 14 7 1 20
```
then calculate the product mod 47:
```
3 * 15 * 13 * 5 * 20 * 17 = 994500 mod 47 = 27
8 * 22 * 14 * 7 * 1 * 20 = 344960 mod 47 = 27
```
Because both products evaluate to 27 (when modded by 47), the mission is 'GO'.
|
from operator import mul
def ride(group,comet):
g = reduce(mul, map(lambda x: x - 64, map(ord, group)))
c = reduce(mul, map(lambda x: x - 64, map(ord, comet)))
return ["GO", "STAY"][g % 47 != c % 47]
|
It is a well-known fact that behind every good comet is a UFO. These UFOs often come to collect loyal supporters from here on Earth. Unfortunately, they only have room to pick up one group of followers on each trip. They do, however, let the groups know ahead of time which will be picked up for each comet by a clever scheme: they pick a name for the comet which, along with the name of the group, can be used to determine if it is a particular group's turn to go (who do you think names the comets?). The details of the matching scheme are given below; your job is to write a program which takes the names of a group and a comet and then determines whether the group should go with the UFO behind that comet.
Both the name of the group and the name of the comet are converted into a number in the following manner: the final number is just the product of all the letters in the name, where "A" is 1 and "Z" is 26. For instance, the group "USACO" would be `21 * 19 * 1 * 3 * 15` = 17955. If the group's number mod 47 is the same as the comet's number mod 47, then you need to tell the group to get ready! (Remember that "a mod b" is the remainder left over after dividing a by b; 34 mod 10 is 4.)
Write a program which reads in the name of the comet and the name of the group and figures out whether according to the above scheme the names are a match, printing "GO" if they match and "STAY" if not. The names of the groups and the comets will be a string of capital letters with no spaces or punctuation, up to 6 characters long.
Example:
Converting the letters to numbers:
```
C O M E T Q
3 15 13 5 20 17
H V N G A T
8 22 14 7 1 20
```
then calculate the product mod 47:
```
3 * 15 * 13 * 5 * 20 * 17 = 994500 mod 47 = 27
8 * 22 * 14 * 7 * 1 * 20 = 344960 mod 47 = 27
```
Because both products evaluate to 27 (when modded by 47), the mission is 'GO'.
|
def ride(group,comet):
command = {True:'GO', False:'STAY'}
num = lambda st: reduce(lambda x,y: x*y, map(lambda x: ord(x)-ord('A')+1, st))%47
return command[num(group)==num(comet)]
|
It is a well-known fact that behind every good comet is a UFO. These UFOs often come to collect loyal supporters from here on Earth. Unfortunately, they only have room to pick up one group of followers on each trip. They do, however, let the groups know ahead of time which will be picked up for each comet by a clever scheme: they pick a name for the comet which, along with the name of the group, can be used to determine if it is a particular group's turn to go (who do you think names the comets?). The details of the matching scheme are given below; your job is to write a program which takes the names of a group and a comet and then determines whether the group should go with the UFO behind that comet.
Both the name of the group and the name of the comet are converted into a number in the following manner: the final number is just the product of all the letters in the name, where "A" is 1 and "Z" is 26. For instance, the group "USACO" would be `21 * 19 * 1 * 3 * 15` = 17955. If the group's number mod 47 is the same as the comet's number mod 47, then you need to tell the group to get ready! (Remember that "a mod b" is the remainder left over after dividing a by b; 34 mod 10 is 4.)
Write a program which reads in the name of the comet and the name of the group and figures out whether according to the above scheme the names are a match, printing "GO" if they match and "STAY" if not. The names of the groups and the comets will be a string of capital letters with no spaces or punctuation, up to 6 characters long.
Example:
Converting the letters to numbers:
```
C O M E T Q
3 15 13 5 20 17
H V N G A T
8 22 14 7 1 20
```
then calculate the product mod 47:
```
3 * 15 * 13 * 5 * 20 * 17 = 994500 mod 47 = 27
8 * 22 * 14 * 7 * 1 * 20 = 344960 mod 47 = 27
```
Because both products evaluate to 27 (when modded by 47), the mission is 'GO'.
|
from functools import reduce
ride = lambda g, c: "GO" if mod47(group) == mod47(comet) else "STAY"
mod47 = lambda s: reduce(lambda p, c: p * '-ABCDEFGHIJKLMNOPQRSTUVWXYZ'.index(c), s, 1) % 47
|
It is a well-known fact that behind every good comet is a UFO. These UFOs often come to collect loyal supporters from here on Earth. Unfortunately, they only have room to pick up one group of followers on each trip. They do, however, let the groups know ahead of time which will be picked up for each comet by a clever scheme: they pick a name for the comet which, along with the name of the group, can be used to determine if it is a particular group's turn to go (who do you think names the comets?). The details of the matching scheme are given below; your job is to write a program which takes the names of a group and a comet and then determines whether the group should go with the UFO behind that comet.
Both the name of the group and the name of the comet are converted into a number in the following manner: the final number is just the product of all the letters in the name, where "A" is 1 and "Z" is 26. For instance, the group "USACO" would be `21 * 19 * 1 * 3 * 15` = 17955. If the group's number mod 47 is the same as the comet's number mod 47, then you need to tell the group to get ready! (Remember that "a mod b" is the remainder left over after dividing a by b; 34 mod 10 is 4.)
Write a program which reads in the name of the comet and the name of the group and figures out whether according to the above scheme the names are a match, printing "GO" if they match and "STAY" if not. The names of the groups and the comets will be a string of capital letters with no spaces or punctuation, up to 6 characters long.
Example:
Converting the letters to numbers:
```
C O M E T Q
3 15 13 5 20 17
H V N G A T
8 22 14 7 1 20
```
then calculate the product mod 47:
```
3 * 15 * 13 * 5 * 20 * 17 = 994500 mod 47 = 27
8 * 22 * 14 * 7 * 1 * 20 = 344960 mod 47 = 27
```
Because both products evaluate to 27 (when modded by 47), the mission is 'GO'.
|
from functools import reduce
def ride(group, comet):
return "GO" if score(group) == score(comet) else "STAY"
def score(word):
return reduce(int.__mul__, (ord(c) - 64 for c in word)) % 47
|
It is a well-known fact that behind every good comet is a UFO. These UFOs often come to collect loyal supporters from here on Earth. Unfortunately, they only have room to pick up one group of followers on each trip. They do, however, let the groups know ahead of time which will be picked up for each comet by a clever scheme: they pick a name for the comet which, along with the name of the group, can be used to determine if it is a particular group's turn to go (who do you think names the comets?). The details of the matching scheme are given below; your job is to write a program which takes the names of a group and a comet and then determines whether the group should go with the UFO behind that comet.
Both the name of the group and the name of the comet are converted into a number in the following manner: the final number is just the product of all the letters in the name, where "A" is 1 and "Z" is 26. For instance, the group "USACO" would be `21 * 19 * 1 * 3 * 15` = 17955. If the group's number mod 47 is the same as the comet's number mod 47, then you need to tell the group to get ready! (Remember that "a mod b" is the remainder left over after dividing a by b; 34 mod 10 is 4.)
Write a program which reads in the name of the comet and the name of the group and figures out whether according to the above scheme the names are a match, printing "GO" if they match and "STAY" if not. The names of the groups and the comets will be a string of capital letters with no spaces or punctuation, up to 6 characters long.
Example:
Converting the letters to numbers:
```
C O M E T Q
3 15 13 5 20 17
H V N G A T
8 22 14 7 1 20
```
then calculate the product mod 47:
```
3 * 15 * 13 * 5 * 20 * 17 = 994500 mod 47 = 27
8 * 22 * 14 * 7 * 1 * 20 = 344960 mod 47 = 27
```
Because both products evaluate to 27 (when modded by 47), the mission is 'GO'.
|
from functools import reduce
from operator import mul
BASE = ord('A') - 1
def ride(group,comet):
g, c = [[ord(c) - BASE for c in xs] for xs in [group, comet]]
return 'GO' if reduce(mul, g) % 47 == reduce(mul, c) % 47 else 'STAY'
|
It is a well-known fact that behind every good comet is a UFO. These UFOs often come to collect loyal supporters from here on Earth. Unfortunately, they only have room to pick up one group of followers on each trip. They do, however, let the groups know ahead of time which will be picked up for each comet by a clever scheme: they pick a name for the comet which, along with the name of the group, can be used to determine if it is a particular group's turn to go (who do you think names the comets?). The details of the matching scheme are given below; your job is to write a program which takes the names of a group and a comet and then determines whether the group should go with the UFO behind that comet.
Both the name of the group and the name of the comet are converted into a number in the following manner: the final number is just the product of all the letters in the name, where "A" is 1 and "Z" is 26. For instance, the group "USACO" would be `21 * 19 * 1 * 3 * 15` = 17955. If the group's number mod 47 is the same as the comet's number mod 47, then you need to tell the group to get ready! (Remember that "a mod b" is the remainder left over after dividing a by b; 34 mod 10 is 4.)
Write a program which reads in the name of the comet and the name of the group and figures out whether according to the above scheme the names are a match, printing "GO" if they match and "STAY" if not. The names of the groups and the comets will be a string of capital letters with no spaces or punctuation, up to 6 characters long.
Example:
Converting the letters to numbers:
```
C O M E T Q
3 15 13 5 20 17
H V N G A T
8 22 14 7 1 20
```
then calculate the product mod 47:
```
3 * 15 * 13 * 5 * 20 * 17 = 994500 mod 47 = 27
8 * 22 * 14 * 7 * 1 * 20 = 344960 mod 47 = 27
```
Because both products evaluate to 27 (when modded by 47), the mission is 'GO'.
|
from functools import reduce
def ride(group,comet):
score = lambda name : reduce(lambda x, y: x*y, map(lambda c : ord(c) - 64, name) ) % 47
return ["STAY", "GO"][score(group) == score(comet)]
|
It is a well-known fact that behind every good comet is a UFO. These UFOs often come to collect loyal supporters from here on Earth. Unfortunately, they only have room to pick up one group of followers on each trip. They do, however, let the groups know ahead of time which will be picked up for each comet by a clever scheme: they pick a name for the comet which, along with the name of the group, can be used to determine if it is a particular group's turn to go (who do you think names the comets?). The details of the matching scheme are given below; your job is to write a program which takes the names of a group and a comet and then determines whether the group should go with the UFO behind that comet.
Both the name of the group and the name of the comet are converted into a number in the following manner: the final number is just the product of all the letters in the name, where "A" is 1 and "Z" is 26. For instance, the group "USACO" would be `21 * 19 * 1 * 3 * 15` = 17955. If the group's number mod 47 is the same as the comet's number mod 47, then you need to tell the group to get ready! (Remember that "a mod b" is the remainder left over after dividing a by b; 34 mod 10 is 4.)
Write a program which reads in the name of the comet and the name of the group and figures out whether according to the above scheme the names are a match, printing "GO" if they match and "STAY" if not. The names of the groups and the comets will be a string of capital letters with no spaces or punctuation, up to 6 characters long.
Example:
Converting the letters to numbers:
```
C O M E T Q
3 15 13 5 20 17
H V N G A T
8 22 14 7 1 20
```
then calculate the product mod 47:
```
3 * 15 * 13 * 5 * 20 * 17 = 994500 mod 47 = 27
8 * 22 * 14 * 7 * 1 * 20 = 344960 mod 47 = 27
```
Because both products evaluate to 27 (when modded by 47), the mission is 'GO'.
|
from numpy import product
def ride(group,comet):
alph_pos = lambda l: ord(l) - 64
compute_score = lambda name : product([ alph_pos(c) for c in name]) % 47
group_score = compute_score(group)
comet_score = compute_score(comet)
return "GO" if group_score == comet_score else "STAY"
|
It is a well-known fact that behind every good comet is a UFO. These UFOs often come to collect loyal supporters from here on Earth. Unfortunately, they only have room to pick up one group of followers on each trip. They do, however, let the groups know ahead of time which will be picked up for each comet by a clever scheme: they pick a name for the comet which, along with the name of the group, can be used to determine if it is a particular group's turn to go (who do you think names the comets?). The details of the matching scheme are given below; your job is to write a program which takes the names of a group and a comet and then determines whether the group should go with the UFO behind that comet.
Both the name of the group and the name of the comet are converted into a number in the following manner: the final number is just the product of all the letters in the name, where "A" is 1 and "Z" is 26. For instance, the group "USACO" would be `21 * 19 * 1 * 3 * 15` = 17955. If the group's number mod 47 is the same as the comet's number mod 47, then you need to tell the group to get ready! (Remember that "a mod b" is the remainder left over after dividing a by b; 34 mod 10 is 4.)
Write a program which reads in the name of the comet and the name of the group and figures out whether according to the above scheme the names are a match, printing "GO" if they match and "STAY" if not. The names of the groups and the comets will be a string of capital letters with no spaces or punctuation, up to 6 characters long.
Example:
Converting the letters to numbers:
```
C O M E T Q
3 15 13 5 20 17
H V N G A T
8 22 14 7 1 20
```
then calculate the product mod 47:
```
3 * 15 * 13 * 5 * 20 * 17 = 994500 mod 47 = 27
8 * 22 * 14 * 7 * 1 * 20 = 344960 mod 47 = 27
```
Because both products evaluate to 27 (when modded by 47), the mission is 'GO'.
|
def ride(group,comet):
g_c = 1
c_c = 1
for a in group:
g_c*= ord(a)-64
for a in comet:
c_c*= ord(a)-64
return "GO" if g_c%47==c_c%47 else "STAY"
|
Our cells go through a process called protein synthesis to translate the instructions in DNA into an amino acid chain, or polypeptide.
Your job is to replicate this!
---
**Step 1: Transcription**
Your input will be a string of DNA that looks like this:
`"TACAGCTCGCTATGAATC"`
You then must transcribe it to mRNA. Each letter, or base, gets transcribed.
```T -> A
A -> U
G -> C
C -> G```
Also, you will split it into groups of three, or _codons_.
The above example would become:
`"AUG UCG AGC GAU ACU UAG"`
---
**Step 2: Translation**
After you have the mRNA strand, you will turn it into an amino acid chain.
Each codon corresponds to an amino acid:
```
Ala GCU, GCC, GCA, GCG
Leu UUA, UUG, CUU, CUC, CUA, CUG
Arg CGU, CGC, CGA, CGG, AGA, AGG
Lys AAA, AAG
Asn AAU, AAC
Met AUG
Asp GAU, GAC
Phe UUU, UUC
Cys UGU, UGC
Pro CCU, CCC, CCA, CCG
Gln CAA, CAG
Ser UCU, UCC, UCA, UCG, AGU, AGC
Glu GAA, GAG
Thr ACU, ACC, ACA, ACG
Gly GGU, GGC, GGA, GGG
Trp UGG
His CAU, CAC
Tyr UAU, UAC
Ile AUU, AUC, AUA
Val GUU, GUC, GUA, GUG
Stop UAG, UGA, UAA```
Phew, that's a long list!
The above example would become:
`"Met Ser Ser Thr Asp Stop"`
Any additional sets of bases that aren't in a group of three aren't included. For example:
`"AUG C"`
would become
`"Met"`
---
Anyway, your final output will be the mRNA sequence and the polypeptide.
Here are some examples:
*In:*
`"TACAGCTCGCTATGAATC"`
*Out:*
`["AUG UCG AGC GAU ACU UAG","Met Ser Ser Asp Thr Stop"]`
---
*In:*
`"ACGTG"`
*Out:*
`["UGC AC","Cys"]`
|
import re
TABLE = str.maketrans('ACGT','UGCA')
def protein_synthesis(dna):
rna = re.findall(r'.{1,3}', dna.translate(TABLE))
return ' '.join(rna), ' '.join(x for x in map(CODON_DICT.get, rna) if x)
|
Our cells go through a process called protein synthesis to translate the instructions in DNA into an amino acid chain, or polypeptide.
Your job is to replicate this!
---
**Step 1: Transcription**
Your input will be a string of DNA that looks like this:
`"TACAGCTCGCTATGAATC"`
You then must transcribe it to mRNA. Each letter, or base, gets transcribed.
```T -> A
A -> U
G -> C
C -> G```
Also, you will split it into groups of three, or _codons_.
The above example would become:
`"AUG UCG AGC GAU ACU UAG"`
---
**Step 2: Translation**
After you have the mRNA strand, you will turn it into an amino acid chain.
Each codon corresponds to an amino acid:
```
Ala GCU, GCC, GCA, GCG
Leu UUA, UUG, CUU, CUC, CUA, CUG
Arg CGU, CGC, CGA, CGG, AGA, AGG
Lys AAA, AAG
Asn AAU, AAC
Met AUG
Asp GAU, GAC
Phe UUU, UUC
Cys UGU, UGC
Pro CCU, CCC, CCA, CCG
Gln CAA, CAG
Ser UCU, UCC, UCA, UCG, AGU, AGC
Glu GAA, GAG
Thr ACU, ACC, ACA, ACG
Gly GGU, GGC, GGA, GGG
Trp UGG
His CAU, CAC
Tyr UAU, UAC
Ile AUU, AUC, AUA
Val GUU, GUC, GUA, GUG
Stop UAG, UGA, UAA```
Phew, that's a long list!
The above example would become:
`"Met Ser Ser Thr Asp Stop"`
Any additional sets of bases that aren't in a group of three aren't included. For example:
`"AUG C"`
would become
`"Met"`
---
Anyway, your final output will be the mRNA sequence and the polypeptide.
Here are some examples:
*In:*
`"TACAGCTCGCTATGAATC"`
*Out:*
`["AUG UCG AGC GAU ACU UAG","Met Ser Ser Asp Thr Stop"]`
---
*In:*
`"ACGTG"`
*Out:*
`["UGC AC","Cys"]`
|
MRNA_TABLE = str.maketrans("ACGT", "UGCA")
def protein_synthesis(dna):
rna = dna.translate(MRNA_TABLE)
codons = [rna[i:i+3] for i in range(0, len(rna), 3)]
return " ".join(codons), " ".join(CODON_DICT[codon] for codon in codons if codon in CODON_DICT)
|
Our cells go through a process called protein synthesis to translate the instructions in DNA into an amino acid chain, or polypeptide.
Your job is to replicate this!
---
**Step 1: Transcription**
Your input will be a string of DNA that looks like this:
`"TACAGCTCGCTATGAATC"`
You then must transcribe it to mRNA. Each letter, or base, gets transcribed.
```T -> A
A -> U
G -> C
C -> G```
Also, you will split it into groups of three, or _codons_.
The above example would become:
`"AUG UCG AGC GAU ACU UAG"`
---
**Step 2: Translation**
After you have the mRNA strand, you will turn it into an amino acid chain.
Each codon corresponds to an amino acid:
```
Ala GCU, GCC, GCA, GCG
Leu UUA, UUG, CUU, CUC, CUA, CUG
Arg CGU, CGC, CGA, CGG, AGA, AGG
Lys AAA, AAG
Asn AAU, AAC
Met AUG
Asp GAU, GAC
Phe UUU, UUC
Cys UGU, UGC
Pro CCU, CCC, CCA, CCG
Gln CAA, CAG
Ser UCU, UCC, UCA, UCG, AGU, AGC
Glu GAA, GAG
Thr ACU, ACC, ACA, ACG
Gly GGU, GGC, GGA, GGG
Trp UGG
His CAU, CAC
Tyr UAU, UAC
Ile AUU, AUC, AUA
Val GUU, GUC, GUA, GUG
Stop UAG, UGA, UAA```
Phew, that's a long list!
The above example would become:
`"Met Ser Ser Thr Asp Stop"`
Any additional sets of bases that aren't in a group of three aren't included. For example:
`"AUG C"`
would become
`"Met"`
---
Anyway, your final output will be the mRNA sequence and the polypeptide.
Here are some examples:
*In:*
`"TACAGCTCGCTATGAATC"`
*Out:*
`["AUG UCG AGC GAU ACU UAG","Met Ser Ser Asp Thr Stop"]`
---
*In:*
`"ACGTG"`
*Out:*
`["UGC AC","Cys"]`
|
from itertools import zip_longest
tbl = str.maketrans("TAGC", "AUCG")
def protein_synthesis(dna: str):
codons = [
"".join(xs) for xs in zip_longest(*[iter(dna.translate(tbl))] * 3, fillvalue="")
]
rna = " ".join(codons)
protein = " ".join(CODON_DICT[codon] for codon in codons if codon in CODON_DICT)
return rna, protein
|
Our cells go through a process called protein synthesis to translate the instructions in DNA into an amino acid chain, or polypeptide.
Your job is to replicate this!
---
**Step 1: Transcription**
Your input will be a string of DNA that looks like this:
`"TACAGCTCGCTATGAATC"`
You then must transcribe it to mRNA. Each letter, or base, gets transcribed.
```T -> A
A -> U
G -> C
C -> G```
Also, you will split it into groups of three, or _codons_.
The above example would become:
`"AUG UCG AGC GAU ACU UAG"`
---
**Step 2: Translation**
After you have the mRNA strand, you will turn it into an amino acid chain.
Each codon corresponds to an amino acid:
```
Ala GCU, GCC, GCA, GCG
Leu UUA, UUG, CUU, CUC, CUA, CUG
Arg CGU, CGC, CGA, CGG, AGA, AGG
Lys AAA, AAG
Asn AAU, AAC
Met AUG
Asp GAU, GAC
Phe UUU, UUC
Cys UGU, UGC
Pro CCU, CCC, CCA, CCG
Gln CAA, CAG
Ser UCU, UCC, UCA, UCG, AGU, AGC
Glu GAA, GAG
Thr ACU, ACC, ACA, ACG
Gly GGU, GGC, GGA, GGG
Trp UGG
His CAU, CAC
Tyr UAU, UAC
Ile AUU, AUC, AUA
Val GUU, GUC, GUA, GUG
Stop UAG, UGA, UAA```
Phew, that's a long list!
The above example would become:
`"Met Ser Ser Thr Asp Stop"`
Any additional sets of bases that aren't in a group of three aren't included. For example:
`"AUG C"`
would become
`"Met"`
---
Anyway, your final output will be the mRNA sequence and the polypeptide.
Here are some examples:
*In:*
`"TACAGCTCGCTATGAATC"`
*Out:*
`["AUG UCG AGC GAU ACU UAG","Met Ser Ser Asp Thr Stop"]`
---
*In:*
`"ACGTG"`
*Out:*
`["UGC AC","Cys"]`
|
def protein_synthesis(dna):
r = dna.translate(str.maketrans('TACG','AUGC'))
r = list(r[i:i+3] for i in range(0,len(r),3))
return (' '.join(r), ' '.join([CODON_DICT[i] if len(i)>2 else '' for i in r]).strip())
|
Our cells go through a process called protein synthesis to translate the instructions in DNA into an amino acid chain, or polypeptide.
Your job is to replicate this!
---
**Step 1: Transcription**
Your input will be a string of DNA that looks like this:
`"TACAGCTCGCTATGAATC"`
You then must transcribe it to mRNA. Each letter, or base, gets transcribed.
```T -> A
A -> U
G -> C
C -> G```
Also, you will split it into groups of three, or _codons_.
The above example would become:
`"AUG UCG AGC GAU ACU UAG"`
---
**Step 2: Translation**
After you have the mRNA strand, you will turn it into an amino acid chain.
Each codon corresponds to an amino acid:
```
Ala GCU, GCC, GCA, GCG
Leu UUA, UUG, CUU, CUC, CUA, CUG
Arg CGU, CGC, CGA, CGG, AGA, AGG
Lys AAA, AAG
Asn AAU, AAC
Met AUG
Asp GAU, GAC
Phe UUU, UUC
Cys UGU, UGC
Pro CCU, CCC, CCA, CCG
Gln CAA, CAG
Ser UCU, UCC, UCA, UCG, AGU, AGC
Glu GAA, GAG
Thr ACU, ACC, ACA, ACG
Gly GGU, GGC, GGA, GGG
Trp UGG
His CAU, CAC
Tyr UAU, UAC
Ile AUU, AUC, AUA
Val GUU, GUC, GUA, GUG
Stop UAG, UGA, UAA```
Phew, that's a long list!
The above example would become:
`"Met Ser Ser Thr Asp Stop"`
Any additional sets of bases that aren't in a group of three aren't included. For example:
`"AUG C"`
would become
`"Met"`
---
Anyway, your final output will be the mRNA sequence and the polypeptide.
Here are some examples:
*In:*
`"TACAGCTCGCTATGAATC"`
*Out:*
`["AUG UCG AGC GAU ACU UAG","Met Ser Ser Asp Thr Stop"]`
---
*In:*
`"ACGTG"`
*Out:*
`["UGC AC","Cys"]`
|
def protein_synthesis(dna):
### Transcribe
DNA2RNA = {'A' : 'U', 'C': 'G', 'G': 'C', 'T': 'A'} # Dictionary for conversion to RNA
rnaList = [DNA2RNA[i] for i in dna] # Transcribe to RNA
# Translate
# Note: A pre-loaded CODON_DICT exists that takes 3-letter RNA keys and outputs amino acid names.
aa = [] # list to hold aa names
for i in range(0, len(rnaList)-2, 3):
aa.append(CODON_DICT[''.join(rnaList[i:i+3])])
# Convert RNA to output format
mRNA = [''.join(rnaList[i:i+3]) for i in range(0, len(rnaList), 3)]
return (" ".join(mRNA), " ".join(aa))
|
Our cells go through a process called protein synthesis to translate the instructions in DNA into an amino acid chain, or polypeptide.
Your job is to replicate this!
---
**Step 1: Transcription**
Your input will be a string of DNA that looks like this:
`"TACAGCTCGCTATGAATC"`
You then must transcribe it to mRNA. Each letter, or base, gets transcribed.
```T -> A
A -> U
G -> C
C -> G```
Also, you will split it into groups of three, or _codons_.
The above example would become:
`"AUG UCG AGC GAU ACU UAG"`
---
**Step 2: Translation**
After you have the mRNA strand, you will turn it into an amino acid chain.
Each codon corresponds to an amino acid:
```
Ala GCU, GCC, GCA, GCG
Leu UUA, UUG, CUU, CUC, CUA, CUG
Arg CGU, CGC, CGA, CGG, AGA, AGG
Lys AAA, AAG
Asn AAU, AAC
Met AUG
Asp GAU, GAC
Phe UUU, UUC
Cys UGU, UGC
Pro CCU, CCC, CCA, CCG
Gln CAA, CAG
Ser UCU, UCC, UCA, UCG, AGU, AGC
Glu GAA, GAG
Thr ACU, ACC, ACA, ACG
Gly GGU, GGC, GGA, GGG
Trp UGG
His CAU, CAC
Tyr UAU, UAC
Ile AUU, AUC, AUA
Val GUU, GUC, GUA, GUG
Stop UAG, UGA, UAA```
Phew, that's a long list!
The above example would become:
`"Met Ser Ser Thr Asp Stop"`
Any additional sets of bases that aren't in a group of three aren't included. For example:
`"AUG C"`
would become
`"Met"`
---
Anyway, your final output will be the mRNA sequence and the polypeptide.
Here are some examples:
*In:*
`"TACAGCTCGCTATGAATC"`
*Out:*
`["AUG UCG AGC GAU ACU UAG","Met Ser Ser Asp Thr Stop"]`
---
*In:*
`"ACGTG"`
*Out:*
`["UGC AC","Cys"]`
|
def protein_synthesis(dna):
# Transcribe
table = str.maketrans('GCAT', 'CGUA')
pressed_rna = dna.translate(table)
rna = []
for bit in range(0, len(pressed_rna)):
if bit % 3 == 0:
rna.append(' ')
rna.append(pressed_rna[bit])
rna = ''.join(rna).strip()
# Translate
protein = []
for rna_bit in rna.split(' '):
protein_bit = CODON_DICT.get(rna_bit, None)
if protein_bit is not None:
protein.append(protein_bit)
protein = ' '.join(protein)
return rna, protein
|
Our cells go through a process called protein synthesis to translate the instructions in DNA into an amino acid chain, or polypeptide.
Your job is to replicate this!
---
**Step 1: Transcription**
Your input will be a string of DNA that looks like this:
`"TACAGCTCGCTATGAATC"`
You then must transcribe it to mRNA. Each letter, or base, gets transcribed.
```T -> A
A -> U
G -> C
C -> G```
Also, you will split it into groups of three, or _codons_.
The above example would become:
`"AUG UCG AGC GAU ACU UAG"`
---
**Step 2: Translation**
After you have the mRNA strand, you will turn it into an amino acid chain.
Each codon corresponds to an amino acid:
```
Ala GCU, GCC, GCA, GCG
Leu UUA, UUG, CUU, CUC, CUA, CUG
Arg CGU, CGC, CGA, CGG, AGA, AGG
Lys AAA, AAG
Asn AAU, AAC
Met AUG
Asp GAU, GAC
Phe UUU, UUC
Cys UGU, UGC
Pro CCU, CCC, CCA, CCG
Gln CAA, CAG
Ser UCU, UCC, UCA, UCG, AGU, AGC
Glu GAA, GAG
Thr ACU, ACC, ACA, ACG
Gly GGU, GGC, GGA, GGG
Trp UGG
His CAU, CAC
Tyr UAU, UAC
Ile AUU, AUC, AUA
Val GUU, GUC, GUA, GUG
Stop UAG, UGA, UAA```
Phew, that's a long list!
The above example would become:
`"Met Ser Ser Thr Asp Stop"`
Any additional sets of bases that aren't in a group of three aren't included. For example:
`"AUG C"`
would become
`"Met"`
---
Anyway, your final output will be the mRNA sequence and the polypeptide.
Here are some examples:
*In:*
`"TACAGCTCGCTATGAATC"`
*Out:*
`["AUG UCG AGC GAU ACU UAG","Met Ser Ser Asp Thr Stop"]`
---
*In:*
`"ACGTG"`
*Out:*
`["UGC AC","Cys"]`
|
def protein_synthesis(dna):
# Transcribe
dna_to_rna = {'G': 'C',
'C': 'G',
'A': 'U',
'T': 'A'}
rna = ''
counter = 1
for acid in dna:
rna += dna_to_rna[acid]
if counter % 3 == 0:
rna += ' '
counter += 1
# Translate
protein = ''
for codon in rna.split(' '):
amac = CODON_DICT.get(codon, None)
if amac is not None:
protein += (amac + ' ')
return (rna.strip(), protein.strip())
|
Our cells go through a process called protein synthesis to translate the instructions in DNA into an amino acid chain, or polypeptide.
Your job is to replicate this!
---
**Step 1: Transcription**
Your input will be a string of DNA that looks like this:
`"TACAGCTCGCTATGAATC"`
You then must transcribe it to mRNA. Each letter, or base, gets transcribed.
```T -> A
A -> U
G -> C
C -> G```
Also, you will split it into groups of three, or _codons_.
The above example would become:
`"AUG UCG AGC GAU ACU UAG"`
---
**Step 2: Translation**
After you have the mRNA strand, you will turn it into an amino acid chain.
Each codon corresponds to an amino acid:
```
Ala GCU, GCC, GCA, GCG
Leu UUA, UUG, CUU, CUC, CUA, CUG
Arg CGU, CGC, CGA, CGG, AGA, AGG
Lys AAA, AAG
Asn AAU, AAC
Met AUG
Asp GAU, GAC
Phe UUU, UUC
Cys UGU, UGC
Pro CCU, CCC, CCA, CCG
Gln CAA, CAG
Ser UCU, UCC, UCA, UCG, AGU, AGC
Glu GAA, GAG
Thr ACU, ACC, ACA, ACG
Gly GGU, GGC, GGA, GGG
Trp UGG
His CAU, CAC
Tyr UAU, UAC
Ile AUU, AUC, AUA
Val GUU, GUC, GUA, GUG
Stop UAG, UGA, UAA```
Phew, that's a long list!
The above example would become:
`"Met Ser Ser Thr Asp Stop"`
Any additional sets of bases that aren't in a group of three aren't included. For example:
`"AUG C"`
would become
`"Met"`
---
Anyway, your final output will be the mRNA sequence and the polypeptide.
Here are some examples:
*In:*
`"TACAGCTCGCTATGAATC"`
*Out:*
`["AUG UCG AGC GAU ACU UAG","Met Ser Ser Asp Thr Stop"]`
---
*In:*
`"ACGTG"`
*Out:*
`["UGC AC","Cys"]`
|
def protein_synthesis(dna:str):
# Transcribe
RNA_DICT={'A': 'U', 'G':'C', 'C':'G', 'T':'A'}
rna_strand = ''.join([RNA_DICT[base] for base in dna])
rna = ' '.join([rna_strand[base:base+3] for base in range(0, len(rna_strand), 3) ])
print(rna)
# Translate
# Note: A pre-loaded CODON_DICT exists that takes 3-letter RNA keys and outputs amino acid names.
length_rna = len(rna.split(" "))
protein = [CODON_DICT.get(rna.split(" ")[codon_i],"") for codon_i in range(0,length_rna)]
print(protein)
protein =' '.join([_f for _f in protein if _f])
print(protein)
return (rna, protein)
#protein_synthesis("TACAG")
|
Our cells go through a process called protein synthesis to translate the instructions in DNA into an amino acid chain, or polypeptide.
Your job is to replicate this!
---
**Step 1: Transcription**
Your input will be a string of DNA that looks like this:
`"TACAGCTCGCTATGAATC"`
You then must transcribe it to mRNA. Each letter, or base, gets transcribed.
```T -> A
A -> U
G -> C
C -> G```
Also, you will split it into groups of three, or _codons_.
The above example would become:
`"AUG UCG AGC GAU ACU UAG"`
---
**Step 2: Translation**
After you have the mRNA strand, you will turn it into an amino acid chain.
Each codon corresponds to an amino acid:
```
Ala GCU, GCC, GCA, GCG
Leu UUA, UUG, CUU, CUC, CUA, CUG
Arg CGU, CGC, CGA, CGG, AGA, AGG
Lys AAA, AAG
Asn AAU, AAC
Met AUG
Asp GAU, GAC
Phe UUU, UUC
Cys UGU, UGC
Pro CCU, CCC, CCA, CCG
Gln CAA, CAG
Ser UCU, UCC, UCA, UCG, AGU, AGC
Glu GAA, GAG
Thr ACU, ACC, ACA, ACG
Gly GGU, GGC, GGA, GGG
Trp UGG
His CAU, CAC
Tyr UAU, UAC
Ile AUU, AUC, AUA
Val GUU, GUC, GUA, GUG
Stop UAG, UGA, UAA```
Phew, that's a long list!
The above example would become:
`"Met Ser Ser Thr Asp Stop"`
Any additional sets of bases that aren't in a group of three aren't included. For example:
`"AUG C"`
would become
`"Met"`
---
Anyway, your final output will be the mRNA sequence and the polypeptide.
Here are some examples:
*In:*
`"TACAGCTCGCTATGAATC"`
*Out:*
`["AUG UCG AGC GAU ACU UAG","Met Ser Ser Asp Thr Stop"]`
---
*In:*
`"ACGTG"`
*Out:*
`["UGC AC","Cys"]`
|
def protein_synthesis(dna):
# Transcribe
s = dna.translate(str.maketrans('TAGC', 'AUCG'))
rna = [s[i:i+3] for i in range(0, len(s), 3)]
# Translate
# Note: A pre-loaded CODON_DICT exists that takes 3-letter RNA keys and outputs amino acid names.
protein = [CODON_DICT[r] for r in rna if r in CODON_DICT]
return (' '.join(rna), ' '.join(protein))
|
Our cells go through a process called protein synthesis to translate the instructions in DNA into an amino acid chain, or polypeptide.
Your job is to replicate this!
---
**Step 1: Transcription**
Your input will be a string of DNA that looks like this:
`"TACAGCTCGCTATGAATC"`
You then must transcribe it to mRNA. Each letter, or base, gets transcribed.
```T -> A
A -> U
G -> C
C -> G```
Also, you will split it into groups of three, or _codons_.
The above example would become:
`"AUG UCG AGC GAU ACU UAG"`
---
**Step 2: Translation**
After you have the mRNA strand, you will turn it into an amino acid chain.
Each codon corresponds to an amino acid:
```
Ala GCU, GCC, GCA, GCG
Leu UUA, UUG, CUU, CUC, CUA, CUG
Arg CGU, CGC, CGA, CGG, AGA, AGG
Lys AAA, AAG
Asn AAU, AAC
Met AUG
Asp GAU, GAC
Phe UUU, UUC
Cys UGU, UGC
Pro CCU, CCC, CCA, CCG
Gln CAA, CAG
Ser UCU, UCC, UCA, UCG, AGU, AGC
Glu GAA, GAG
Thr ACU, ACC, ACA, ACG
Gly GGU, GGC, GGA, GGG
Trp UGG
His CAU, CAC
Tyr UAU, UAC
Ile AUU, AUC, AUA
Val GUU, GUC, GUA, GUG
Stop UAG, UGA, UAA```
Phew, that's a long list!
The above example would become:
`"Met Ser Ser Thr Asp Stop"`
Any additional sets of bases that aren't in a group of three aren't included. For example:
`"AUG C"`
would become
`"Met"`
---
Anyway, your final output will be the mRNA sequence and the polypeptide.
Here are some examples:
*In:*
`"TACAGCTCGCTATGAATC"`
*Out:*
`["AUG UCG AGC GAU ACU UAG","Met Ser Ser Asp Thr Stop"]`
---
*In:*
`"ACGTG"`
*Out:*
`["UGC AC","Cys"]`
|
def protein_synthesis(dna):
rna = ""
protein = ""
for i in range(len(dna)):
if i % 3 == 0 and i != 0:
rna += " "
if dna[i] == "C":
rna += "G"
elif dna[i] == "G":
rna += "C"
elif dna[i] == "T":
rna += "A"
elif dna[i] == "A":
rna += "U"
rna_list = rna.split(" ")
for element in rna_list:
if len(element) == 3:
protein += CODON_DICT[element] + " "
return (rna, protein.strip())
|
Teach snoopy and scooby doo how to bark using object methods.
Currently only snoopy can bark and not scooby doo.
```python
snoopy.bark() #return "Woof"
scoobydoo.bark() #undefined
```
Use method prototypes to enable all Dogs to bark.
|
class Dog ():
def __init__(self, breed):
self.breed = breed
def bark(self):
return "Woof"
snoopy = Dog("Beagle")
scoobydoo = Dog("Great Dane")
|
Teach snoopy and scooby doo how to bark using object methods.
Currently only snoopy can bark and not scooby doo.
```python
snoopy.bark() #return "Woof"
scoobydoo.bark() #undefined
```
Use method prototypes to enable all Dogs to bark.
|
class Dog ():
def __init__(self, breed):
self.breed = breed
self.bark = lambda: "Woof"
snoopy = Dog("Beagle")
scoobydoo = Dog("Great Dane")
|
Teach snoopy and scooby doo how to bark using object methods.
Currently only snoopy can bark and not scooby doo.
```python
snoopy.bark() #return "Woof"
scoobydoo.bark() #undefined
```
Use method prototypes to enable all Dogs to bark.
|
class Dog ():
def __init__(self, breed):
self.breed = breed
@staticmethod
def bark():
return "Woof"
snoopy = Dog("Beagle")
scoobydoo = Dog("Great Dane")
|
Teach snoopy and scooby doo how to bark using object methods.
Currently only snoopy can bark and not scooby doo.
```python
snoopy.bark() #return "Woof"
scoobydoo.bark() #undefined
```
Use method prototypes to enable all Dogs to bark.
|
class Dog ():
def __init__(self, breed):
self.breed = breed
self.bark = lambda: "Woof"
snoopy, scoobydoo = Dog("Beagle"), Dog("Great Dane")
|
Teach snoopy and scooby doo how to bark using object methods.
Currently only snoopy can bark and not scooby doo.
```python
snoopy.bark() #return "Woof"
scoobydoo.bark() #undefined
```
Use method prototypes to enable all Dogs to bark.
|
class Dog ():
def __init__(self, breed):
self.breed = breed
def bark(self):
return "Woof"
snoopy = Dog("nn")
scoobydoo = Dog("nn")
|
Teach snoopy and scooby doo how to bark using object methods.
Currently only snoopy can bark and not scooby doo.
```python
snoopy.bark() #return "Woof"
scoobydoo.bark() #undefined
```
Use method prototypes to enable all Dogs to bark.
|
class Dog ():
def __init__(self, breed):
self.breed = breed
snoopy = Dog("Beagle")
Dog.bark = lambda self: "Woof"
scoobydoo = Dog("Great Dane")
|
Teach snoopy and scooby doo how to bark using object methods.
Currently only snoopy can bark and not scooby doo.
```python
snoopy.bark() #return "Woof"
scoobydoo.bark() #undefined
```
Use method prototypes to enable all Dogs to bark.
|
class Dog ():
def __init__(self, breed):
self.breed = breed
snoopy = Dog("Beagle")
snoopy.bark = lambda: "Woof"
scoobydoo = Dog("Great Dane")
scoobydoo.bark = lambda: "Woof"
|
Teach snoopy and scooby doo how to bark using object methods.
Currently only snoopy can bark and not scooby doo.
```python
snoopy.bark() #return "Woof"
scoobydoo.bark() #undefined
```
Use method prototypes to enable all Dogs to bark.
|
class Dog():
def __init__(self, breed):
self.breed = breed
snoopy = Dog("Beagle")
Dog.bark = lambda *args: "Woof"
scoobydoo = Dog("Great Dane")
|
Teach snoopy and scooby doo how to bark using object methods.
Currently only snoopy can bark and not scooby doo.
```python
snoopy.bark() #return "Woof"
scoobydoo.bark() #undefined
```
Use method prototypes to enable all Dogs to bark.
|
class Dog ():
def __init__(self, breed):
self.breed = breed
def bark(self):
if self.breed in ["Beagle", "Great Dane"]:
return 'Woof'
snoopy = Dog("Beagle")
snoopy.bark = lambda: "Woof"
scoobydoo = Dog("Great Dane")
|
Teach snoopy and scooby doo how to bark using object methods.
Currently only snoopy can bark and not scooby doo.
```python
snoopy.bark() #return "Woof"
scoobydoo.bark() #undefined
```
Use method prototypes to enable all Dogs to bark.
|
class Dog ():
def __init__(self, breed):
self.breed = breed
snoopy = Dog("Beagle")
scoobydoo = Dog("Great Dane")
snoopy.bark = scoobydoo.bark = lambda: "Woof"
|
Teach snoopy and scooby doo how to bark using object methods.
Currently only snoopy can bark and not scooby doo.
```python
snoopy.bark() #return "Woof"
scoobydoo.bark() #undefined
```
Use method prototypes to enable all Dogs to bark.
|
class Dog:
""" Animal: Dog. """
def __init__(self, breed: str):
""" Prepare data. """
self.breed = breed
self.bark = lambda: "Woof"
snoopy = Dog("Beagle")
scoobydoo = Dog("Great Dane")
|
Teach snoopy and scooby doo how to bark using object methods.
Currently only snoopy can bark and not scooby doo.
```python
snoopy.bark() #return "Woof"
scoobydoo.bark() #undefined
```
Use method prototypes to enable all Dogs to bark.
|
class Dog ():
def __init__(self, breed):
self.breed = breed
def bark(*a):
return "Woof"
snoopy = Dog("Beagle")
scoobydoo = Dog("Great Dane")
|
Teach snoopy and scooby doo how to bark using object methods.
Currently only snoopy can bark and not scooby doo.
```python
snoopy.bark() #return "Woof"
scoobydoo.bark() #undefined
```
Use method prototypes to enable all Dogs to bark.
|
class Dog():
def __init__(self, breed):
self.breed = breed
def bark(name):
return "Woof"
snoopy = Dog("Beagle")
snoopy.bark = lambda: "Woof"
scoobydoo = Dog("Great Dane")
|
Teach snoopy and scooby doo how to bark using object methods.
Currently only snoopy can bark and not scooby doo.
```python
snoopy.bark() #return "Woof"
scoobydoo.bark() #undefined
```
Use method prototypes to enable all Dogs to bark.
|
class Dog ():
def __init__(self, breed):
self.breed = breed
def bark(self):
return "Woof"
snoopy = Dog("Beagle")
scoobydoo = Dog("Great Dane")
#snoopy.bark = lambda: "Woof" :P
|
Teach snoopy and scooby doo how to bark using object methods.
Currently only snoopy can bark and not scooby doo.
```python
snoopy.bark() #return "Woof"
scoobydoo.bark() #undefined
```
Use method prototypes to enable all Dogs to bark.
|
class Dog():
def __init__(self, breed):
self.breed = breed
def bark(self, bark="Woof"):
self.bark = bark
snoopy = Dog("Beagle")
snoopy.bark = lambda: "Woof"
scoobydoo = Dog("Great Dane")
scoobydoo.bark = lambda: "Woof"
|
Teach snoopy and scooby doo how to bark using object methods.
Currently only snoopy can bark and not scooby doo.
```python
snoopy.bark() #return "Woof"
scoobydoo.bark() #undefined
```
Use method prototypes to enable all Dogs to bark.
|
class Dog ():
def __init__(self, breed):
self.breed = breed
def bark(self):
return "Woof"
snoopy = Dog("Beagle")
scoobydoo = Dog("Great Dane")
print(Dog.bark(scoobydoo))
|
Teach snoopy and scooby doo how to bark using object methods.
Currently only snoopy can bark and not scooby doo.
```python
snoopy.bark() #return "Woof"
scoobydoo.bark() #undefined
```
Use method prototypes to enable all Dogs to bark.
|
class Dog ():
def __init__(self, breed):
self.breed = breed
def bark(self):
return "Woof"
snoopy = Dog("Beagle")
snoopy.bark = lambda: "Woof"
scoobydoo = Dog("Great Dane")
print(scoobydoo.bark())
|
Teach snoopy and scooby doo how to bark using object methods.
Currently only snoopy can bark and not scooby doo.
```python
snoopy.bark() #return "Woof"
scoobydoo.bark() #undefined
```
Use method prototypes to enable all Dogs to bark.
|
class Dog ():
def __init__(self, breed):
self.breed = breed
def bark(self):
return 'Woof'
snoopy = Dog('Test')
scoobydoo = Dog('Test')
|
Teach snoopy and scooby doo how to bark using object methods.
Currently only snoopy can bark and not scooby doo.
```python
snoopy.bark() #return "Woof"
scoobydoo.bark() #undefined
```
Use method prototypes to enable all Dogs to bark.
|
class Dog():
def __init__(self, breed):
self.breed = breed
def bark(self):
return self.breed
snoopy = Dog("Woof")
scoobydoo = Dog("Woof")
|
Teach snoopy and scooby doo how to bark using object methods.
Currently only snoopy can bark and not scooby doo.
```python
snoopy.bark() #return "Woof"
scoobydoo.bark() #undefined
```
Use method prototypes to enable all Dogs to bark.
|
class Dog:
def __init__(self, breed: str):
self.breed = breed
@staticmethod
def bark() -> str:
return "Woof"
snoopy, scoobydoo = Dog("Beagle"), Dog("Great Dane")
|
Teach snoopy and scooby doo how to bark using object methods.
Currently only snoopy can bark and not scooby doo.
```python
snoopy.bark() #return "Woof"
scoobydoo.bark() #undefined
```
Use method prototypes to enable all Dogs to bark.
|
class Dog(object):
def __init__(self, breed):
self.breed = breed
self.bark = lambda: 'Woof'
def bark(self):
return 'Woof'
snoopy = Dog("Beagle")
scoobydoo = Dog("Great Dane")
|
Teach snoopy and scooby doo how to bark using object methods.
Currently only snoopy can bark and not scooby doo.
```python
snoopy.bark() #return "Woof"
scoobydoo.bark() #undefined
```
Use method prototypes to enable all Dogs to bark.
|
class Dog ():
def __init__(self, breed):
self.breed = breed
snoopy = Dog("Beagle")
scoobydoo = Dog("rogling")
snoopy.bark = lambda: "Woof"
scoobydoo.bark = lambda: "Woof"
# Flez
|
Teach snoopy and scooby doo how to bark using object methods.
Currently only snoopy can bark and not scooby doo.
```python
snoopy.bark() #return "Woof"
scoobydoo.bark() #undefined
```
Use method prototypes to enable all Dogs to bark.
|
class Dog ():
def __init__(self, breed):
self.breed = breed
def bark(self):
return "Woof"
snoopy = Dog("Beagle")
scoobydoo = Dog("yourmom")
|
Teach snoopy and scooby doo how to bark using object methods.
Currently only snoopy can bark and not scooby doo.
```python
snoopy.bark() #return "Woof"
scoobydoo.bark() #undefined
```
Use method prototypes to enable all Dogs to bark.
|
class Dog:
def __init__(self, breed):
self.breed = breed
# Troll
def bark(self):
return 'Woof'
snoopy = Dog("Beagle")
snoopy.bark = lambda: "Woof"
scoobydoo = Dog("Great Dane")
|
Teach snoopy and scooby doo how to bark using object methods.
Currently only snoopy can bark and not scooby doo.
```python
snoopy.bark() #return "Woof"
scoobydoo.bark() #undefined
```
Use method prototypes to enable all Dogs to bark.
|
class Dog ():
def __init__(self, breed):
self.name = breed
def bark(self):
return "Woof"
snoopy = Dog("Beagle")
snoopy.bark = lambda: "Woof"
scoobydoo = Dog("Great Dane")
|
Teach snoopy and scooby doo how to bark using object methods.
Currently only snoopy can bark and not scooby doo.
```python
snoopy.bark() #return "Woof"
scoobydoo.bark() #undefined
```
Use method prototypes to enable all Dogs to bark.
|
class Dog ():
def __init__(self, breed):
self.breed = breed
def bark(self, bark='Woof'):
return bark
snoopy = Dog("Beagle")
snoopy.bark = lambda: "Woof"
scoobydoo = Dog("Great Dane")
|
Teach snoopy and scooby doo how to bark using object methods.
Currently only snoopy can bark and not scooby doo.
```python
snoopy.bark() #return "Woof"
scoobydoo.bark() #undefined
```
Use method prototypes to enable all Dogs to bark.
|
class Dog ():
def __init__(self, breed):
self.breed = breed
def bark(self):
if self.breed == 'Beagle':
return "Woof"
else:
return "Woof"
snoopy = Dog("Beagle")
snoopy.bark = lambda: "Woof"
scoobydoo = Dog("Great Dane")
|
Teach snoopy and scooby doo how to bark using object methods.
Currently only snoopy can bark and not scooby doo.
```python
snoopy.bark() #return "Woof"
scoobydoo.bark() #undefined
```
Use method prototypes to enable all Dogs to bark.
|
class Dog:
def __init__(self, breed):
self.breed = breed
def bark(self):
return "Woof"
snoopy = Dog("Code")
scoobydoo = Dog("Wars")
|
Teach snoopy and scooby doo how to bark using object methods.
Currently only snoopy can bark and not scooby doo.
```python
snoopy.bark() #return "Woof"
scoobydoo.bark() #undefined
```
Use method prototypes to enable all Dogs to bark.
|
class Dog ():
def __init__(self, breed):
self.breed = breed
snoopy = Dog("Beagle")
snoopy.bark = lambda: "Woof"
scoobydoo = Dog("Great Dane")
scoobydoo.bark= lambda: "Woof"
#I solved this Kata on 8/17/2019 12:46 AM...#Hussam'sCodingDiary
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.