Datasets:

inputs
stringlengths
50
14k
targets
stringlengths
4
655k
Brief ===== In this easy kata your function has to take a **string** as input and **return a string** with everything removed (*whitespaces* included) but the **digits**. As you may have guessed **empty strings** are to be returned as they are & if the input string contains no digits then the output will be an **empty string**.By the way , you have to watch out for **non-string** inputs too.Return **'Invalid input !'** for them. Hint ==== If you're writing more than 1 line of code, then think again! ;) Good luck!
import re def digit_all (x): return re.sub("\D", "", x) if type(x) is str else 'Invalid input !'
Brief ===== In this easy kata your function has to take a **string** as input and **return a string** with everything removed (*whitespaces* included) but the **digits**. As you may have guessed **empty strings** are to be returned as they are & if the input string contains no digits then the output will be an **empty string**.By the way , you have to watch out for **non-string** inputs too.Return **'Invalid input !'** for them. Hint ==== If you're writing more than 1 line of code, then think again! ;) Good luck!
def digit_all (x): if type(x).__name__ != 'str': return 'Invalid input !' return ''.join(c for c in x if c in '123456789')
Brief ===== In this easy kata your function has to take a **string** as input and **return a string** with everything removed (*whitespaces* included) but the **digits**. As you may have guessed **empty strings** are to be returned as they are & if the input string contains no digits then the output will be an **empty string**.By the way , you have to watch out for **non-string** inputs too.Return **'Invalid input !'** for them. Hint ==== If you're writing more than 1 line of code, then think again! ;) Good luck!
import re def digit_all (x): try: return re.sub(r'[^\d]*','',x) except: return 'Invalid input !'
Brief ===== In this easy kata your function has to take a **string** as input and **return a string** with everything removed (*whitespaces* included) but the **digits**. As you may have guessed **empty strings** are to be returned as they are & if the input string contains no digits then the output will be an **empty string**.By the way , you have to watch out for **non-string** inputs too.Return **'Invalid input !'** for them. Hint ==== If you're writing more than 1 line of code, then think again! ;) Good luck!
import re def digit_all (x): if not isinstance(x, str): return 'Invalid input !' regex = re.compile(r'[^0-9]') return re.sub(regex, '', x)
Brief ===== In this easy kata your function has to take a **string** as input and **return a string** with everything removed (*whitespaces* included) but the **digits**. As you may have guessed **empty strings** are to be returned as they are & if the input string contains no digits then the output will be an **empty string**.By the way , you have to watch out for **non-string** inputs too.Return **'Invalid input !'** for them. Hint ==== If you're writing more than 1 line of code, then think again! ;) Good luck!
def digit_all (x): if not isinstance(x, str): return 'Invalid input !' return ''.join(filter(str.isdigit, x))
Brief ===== In this easy kata your function has to take a **string** as input and **return a string** with everything removed (*whitespaces* included) but the **digits**. As you may have guessed **empty strings** are to be returned as they are & if the input string contains no digits then the output will be an **empty string**.By the way , you have to watch out for **non-string** inputs too.Return **'Invalid input !'** for them. Hint ==== If you're writing more than 1 line of code, then think again! ;) Good luck!
import re def digit_all (x): ## Here you go : try: return re.sub(r"[\D]",'',x) except TypeError: return "Invalid input !"
Brief ===== In this easy kata your function has to take a **string** as input and **return a string** with everything removed (*whitespaces* included) but the **digits**. As you may have guessed **empty strings** are to be returned as they are & if the input string contains no digits then the output will be an **empty string**.By the way , you have to watch out for **non-string** inputs too.Return **'Invalid input !'** for them. Hint ==== If you're writing more than 1 line of code, then think again! ;) Good luck!
def digit_all (x): if isinstance(x,str): return "".join( x for x in x if x.isnumeric()) else: return 'Invalid input !'
An architect wants to construct a vaulted building supported by a family of arches Cn. fn(x) = -nx - xlog(x) is the equation of the arch Cn where `x` is a positive real number (0 < x <= 1), `log(x)` is the natural logarithm (base e), `n` a non negative integer. Let fn(0) = 0. Be An the point of Cn where the tangent to Cn is horizontal and Bn+1 the orthogonal projection of An on the x-axis (it means that An and Bn+1 have the same x -coordinate). Kn is the intersection of Cn with the x-axis. The figure shows C0, A0, B1, K0 as C(0), A0, B1, K0. ![alternative text](https://i.imgur.com/Td9aWIJ.png) The architect wants to support each arch Cn with a wall of glass filling the **curved** surface An Bn+1 Kn under the curve Cn. On the drawing you can see the surface `A0 B1 K0` in blue. He asks if we could calculate the weight of the surface of glass he needs to support all arches C0...Cn where n is a positive integer knowing he can choose glass thickness hence glass weight per square unit of surface. He gives us the absolute value of A0 B1 K0 area (in blue); call it `i0` which is approximately `0.14849853757254047` in square units. ## Task Write the function `weight` with parameters `n` and `w` where `n` is the number of arches to consider (n >= 1) and `w` is the weight of a square unit of glass depending on the wall thickness. This function should return the weight of n glass walls as described above. ## Example ``` weight(10, 700) -> 120.21882500408238 weight(8, 1108) -> 190.28922301858418 ``` ## Hint: There is no integral to calculate. You can plot C1 and try to see the relationship between the different Cn and then use `i0`. ## Note: - don't round or truncate your result
weight=lambda n,w,e=__import__('math').exp(-2):(1-3*e)/(1-e)/4*(1-e**n)*w
An architect wants to construct a vaulted building supported by a family of arches Cn. fn(x) = -nx - xlog(x) is the equation of the arch Cn where `x` is a positive real number (0 < x <= 1), `log(x)` is the natural logarithm (base e), `n` a non negative integer. Let fn(0) = 0. Be An the point of Cn where the tangent to Cn is horizontal and Bn+1 the orthogonal projection of An on the x-axis (it means that An and Bn+1 have the same x -coordinate). Kn is the intersection of Cn with the x-axis. The figure shows C0, A0, B1, K0 as C(0), A0, B1, K0. ![alternative text](https://i.imgur.com/Td9aWIJ.png) The architect wants to support each arch Cn with a wall of glass filling the **curved** surface An Bn+1 Kn under the curve Cn. On the drawing you can see the surface `A0 B1 K0` in blue. He asks if we could calculate the weight of the surface of glass he needs to support all arches C0...Cn where n is a positive integer knowing he can choose glass thickness hence glass weight per square unit of surface. He gives us the absolute value of A0 B1 K0 area (in blue); call it `i0` which is approximately `0.14849853757254047` in square units. ## Task Write the function `weight` with parameters `n` and `w` where `n` is the number of arches to consider (n >= 1) and `w` is the weight of a square unit of glass depending on the wall thickness. This function should return the weight of n glass walls as described above. ## Example ``` weight(10, 700) -> 120.21882500408238 weight(8, 1108) -> 190.28922301858418 ``` ## Hint: There is no integral to calculate. You can plot C1 and try to see the relationship between the different Cn and then use `i0`. ## Note: - don't round or truncate your result
# i0 = 0.14849853757254047 from math import e def weight(n, w): total = 1 for i in range(1, n + 1): total += e ** (-2 * i) return w * 0.14849853757254047 * total
An architect wants to construct a vaulted building supported by a family of arches Cn. fn(x) = -nx - xlog(x) is the equation of the arch Cn where `x` is a positive real number (0 < x <= 1), `log(x)` is the natural logarithm (base e), `n` a non negative integer. Let fn(0) = 0. Be An the point of Cn where the tangent to Cn is horizontal and Bn+1 the orthogonal projection of An on the x-axis (it means that An and Bn+1 have the same x -coordinate). Kn is the intersection of Cn with the x-axis. The figure shows C0, A0, B1, K0 as C(0), A0, B1, K0. ![alternative text](https://i.imgur.com/Td9aWIJ.png) The architect wants to support each arch Cn with a wall of glass filling the **curved** surface An Bn+1 Kn under the curve Cn. On the drawing you can see the surface `A0 B1 K0` in blue. He asks if we could calculate the weight of the surface of glass he needs to support all arches C0...Cn where n is a positive integer knowing he can choose glass thickness hence glass weight per square unit of surface. He gives us the absolute value of A0 B1 K0 area (in blue); call it `i0` which is approximately `0.14849853757254047` in square units. ## Task Write the function `weight` with parameters `n` and `w` where `n` is the number of arches to consider (n >= 1) and `w` is the weight of a square unit of glass depending on the wall thickness. This function should return the weight of n glass walls as described above. ## Example ``` weight(10, 700) -> 120.21882500408238 weight(8, 1108) -> 190.28922301858418 ``` ## Hint: There is no integral to calculate. You can plot C1 and try to see the relationship between the different Cn and then use `i0`. ## Note: - don't round or truncate your result
def weight(n, w): from math import e i0 = 0.14849853757254047 an = (1 - e ** -(2 * n + 2)) / (1 - e ** -2) return i0 * an * w
An architect wants to construct a vaulted building supported by a family of arches Cn. fn(x) = -nx - xlog(x) is the equation of the arch Cn where `x` is a positive real number (0 < x <= 1), `log(x)` is the natural logarithm (base e), `n` a non negative integer. Let fn(0) = 0. Be An the point of Cn where the tangent to Cn is horizontal and Bn+1 the orthogonal projection of An on the x-axis (it means that An and Bn+1 have the same x -coordinate). Kn is the intersection of Cn with the x-axis. The figure shows C0, A0, B1, K0 as C(0), A0, B1, K0. ![alternative text](https://i.imgur.com/Td9aWIJ.png) The architect wants to support each arch Cn with a wall of glass filling the **curved** surface An Bn+1 Kn under the curve Cn. On the drawing you can see the surface `A0 B1 K0` in blue. He asks if we could calculate the weight of the surface of glass he needs to support all arches C0...Cn where n is a positive integer knowing he can choose glass thickness hence glass weight per square unit of surface. He gives us the absolute value of A0 B1 K0 area (in blue); call it `i0` which is approximately `0.14849853757254047` in square units. ## Task Write the function `weight` with parameters `n` and `w` where `n` is the number of arches to consider (n >= 1) and `w` is the weight of a square unit of glass depending on the wall thickness. This function should return the weight of n glass walls as described above. ## Example ``` weight(10, 700) -> 120.21882500408238 weight(8, 1108) -> 190.28922301858418 ``` ## Hint: There is no integral to calculate. You can plot C1 and try to see the relationship between the different Cn and then use `i0`. ## Note: - don't round or truncate your result
def weight(n, w): return 0.171741178625167*w
An architect wants to construct a vaulted building supported by a family of arches Cn. fn(x) = -nx - xlog(x) is the equation of the arch Cn where `x` is a positive real number (0 < x <= 1), `log(x)` is the natural logarithm (base e), `n` a non negative integer. Let fn(0) = 0. Be An the point of Cn where the tangent to Cn is horizontal and Bn+1 the orthogonal projection of An on the x-axis (it means that An and Bn+1 have the same x -coordinate). Kn is the intersection of Cn with the x-axis. The figure shows C0, A0, B1, K0 as C(0), A0, B1, K0. ![alternative text](https://i.imgur.com/Td9aWIJ.png) The architect wants to support each arch Cn with a wall of glass filling the **curved** surface An Bn+1 Kn under the curve Cn. On the drawing you can see the surface `A0 B1 K0` in blue. He asks if we could calculate the weight of the surface of glass he needs to support all arches C0...Cn where n is a positive integer knowing he can choose glass thickness hence glass weight per square unit of surface. He gives us the absolute value of A0 B1 K0 area (in blue); call it `i0` which is approximately `0.14849853757254047` in square units. ## Task Write the function `weight` with parameters `n` and `w` where `n` is the number of arches to consider (n >= 1) and `w` is the weight of a square unit of glass depending on the wall thickness. This function should return the weight of n glass walls as described above. ## Example ``` weight(10, 700) -> 120.21882500408238 weight(8, 1108) -> 190.28922301858418 ``` ## Hint: There is no integral to calculate. You can plot C1 and try to see the relationship between the different Cn and then use `i0`. ## Note: - don't round or truncate your result
weight=lambda *_:_[-1]/5.8227
An architect wants to construct a vaulted building supported by a family of arches Cn. fn(x) = -nx - xlog(x) is the equation of the arch Cn where `x` is a positive real number (0 < x <= 1), `log(x)` is the natural logarithm (base e), `n` a non negative integer. Let fn(0) = 0. Be An the point of Cn where the tangent to Cn is horizontal and Bn+1 the orthogonal projection of An on the x-axis (it means that An and Bn+1 have the same x -coordinate). Kn is the intersection of Cn with the x-axis. The figure shows C0, A0, B1, K0 as C(0), A0, B1, K0. ![alternative text](https://i.imgur.com/Td9aWIJ.png) The architect wants to support each arch Cn with a wall of glass filling the **curved** surface An Bn+1 Kn under the curve Cn. On the drawing you can see the surface `A0 B1 K0` in blue. He asks if we could calculate the weight of the surface of glass he needs to support all arches C0...Cn where n is a positive integer knowing he can choose glass thickness hence glass weight per square unit of surface. He gives us the absolute value of A0 B1 K0 area (in blue); call it `i0` which is approximately `0.14849853757254047` in square units. ## Task Write the function `weight` with parameters `n` and `w` where `n` is the number of arches to consider (n >= 1) and `w` is the weight of a square unit of glass depending on the wall thickness. This function should return the weight of n glass walls as described above. ## Example ``` weight(10, 700) -> 120.21882500408238 weight(8, 1108) -> 190.28922301858418 ``` ## Hint: There is no integral to calculate. You can plot C1 and try to see the relationship between the different Cn and then use `i0`. ## Note: - don't round or truncate your result
import decimal def weight(n, w): I0 = decimal.Decimal(0.14849853757254047) OFFSET = decimal.Decimal(7.389056098930639) return float((OFFSET - (1 / OFFSET ** n)) / (OFFSET - 1) * w * I0)
An architect wants to construct a vaulted building supported by a family of arches Cn. fn(x) = -nx - xlog(x) is the equation of the arch Cn where `x` is a positive real number (0 < x <= 1), `log(x)` is the natural logarithm (base e), `n` a non negative integer. Let fn(0) = 0. Be An the point of Cn where the tangent to Cn is horizontal and Bn+1 the orthogonal projection of An on the x-axis (it means that An and Bn+1 have the same x -coordinate). Kn is the intersection of Cn with the x-axis. The figure shows C0, A0, B1, K0 as C(0), A0, B1, K0. ![alternative text](https://i.imgur.com/Td9aWIJ.png) The architect wants to support each arch Cn with a wall of glass filling the **curved** surface An Bn+1 Kn under the curve Cn. On the drawing you can see the surface `A0 B1 K0` in blue. He asks if we could calculate the weight of the surface of glass he needs to support all arches C0...Cn where n is a positive integer knowing he can choose glass thickness hence glass weight per square unit of surface. He gives us the absolute value of A0 B1 K0 area (in blue); call it `i0` which is approximately `0.14849853757254047` in square units. ## Task Write the function `weight` with parameters `n` and `w` where `n` is the number of arches to consider (n >= 1) and `w` is the weight of a square unit of glass depending on the wall thickness. This function should return the weight of n glass walls as described above. ## Example ``` weight(10, 700) -> 120.21882500408238 weight(8, 1108) -> 190.28922301858418 ``` ## Hint: There is no integral to calculate. You can plot C1 and try to see the relationship between the different Cn and then use `i0`. ## Note: - don't round or truncate your result
i0 = 0.14849853757254047 from math import exp def weight(n, w): area = i0 * sum([exp(-2*m) for m in range(n)]) return w*area
An architect wants to construct a vaulted building supported by a family of arches Cn. fn(x) = -nx - xlog(x) is the equation of the arch Cn where `x` is a positive real number (0 < x <= 1), `log(x)` is the natural logarithm (base e), `n` a non negative integer. Let fn(0) = 0. Be An the point of Cn where the tangent to Cn is horizontal and Bn+1 the orthogonal projection of An on the x-axis (it means that An and Bn+1 have the same x -coordinate). Kn is the intersection of Cn with the x-axis. The figure shows C0, A0, B1, K0 as C(0), A0, B1, K0. ![alternative text](https://i.imgur.com/Td9aWIJ.png) The architect wants to support each arch Cn with a wall of glass filling the **curved** surface An Bn+1 Kn under the curve Cn. On the drawing you can see the surface `A0 B1 K0` in blue. He asks if we could calculate the weight of the surface of glass he needs to support all arches C0...Cn where n is a positive integer knowing he can choose glass thickness hence glass weight per square unit of surface. He gives us the absolute value of A0 B1 K0 area (in blue); call it `i0` which is approximately `0.14849853757254047` in square units. ## Task Write the function `weight` with parameters `n` and `w` where `n` is the number of arches to consider (n >= 1) and `w` is the weight of a square unit of glass depending on the wall thickness. This function should return the weight of n glass walls as described above. ## Example ``` weight(10, 700) -> 120.21882500408238 weight(8, 1108) -> 190.28922301858418 ``` ## Hint: There is no integral to calculate. You can plot C1 and try to see the relationship between the different Cn and then use `i0`. ## Note: - don't round or truncate your result
# i0 = 0.14849853757254047 import math def weight(n, w): area=0 for n in range(0,n): Bn=math.exp(-1-n) Kn=math.exp(-n) if(Kn<1e-300)or(Bn<1e-300): n+=1 else: aire=0.5*(n*Bn**2-n*Kn**2+(Kn**2-Bn**2)/2+Bn**2*math.log(Bn)-Kn**2*math.log(Kn)) area+=aire return area*w
An architect wants to construct a vaulted building supported by a family of arches Cn. fn(x) = -nx - xlog(x) is the equation of the arch Cn where `x` is a positive real number (0 < x <= 1), `log(x)` is the natural logarithm (base e), `n` a non negative integer. Let fn(0) = 0. Be An the point of Cn where the tangent to Cn is horizontal and Bn+1 the orthogonal projection of An on the x-axis (it means that An and Bn+1 have the same x -coordinate). Kn is the intersection of Cn with the x-axis. The figure shows C0, A0, B1, K0 as C(0), A0, B1, K0. ![alternative text](https://i.imgur.com/Td9aWIJ.png) The architect wants to support each arch Cn with a wall of glass filling the **curved** surface An Bn+1 Kn under the curve Cn. On the drawing you can see the surface `A0 B1 K0` in blue. He asks if we could calculate the weight of the surface of glass he needs to support all arches C0...Cn where n is a positive integer knowing he can choose glass thickness hence glass weight per square unit of surface. He gives us the absolute value of A0 B1 K0 area (in blue); call it `i0` which is approximately `0.14849853757254047` in square units. ## Task Write the function `weight` with parameters `n` and `w` where `n` is the number of arches to consider (n >= 1) and `w` is the weight of a square unit of glass depending on the wall thickness. This function should return the weight of n glass walls as described above. ## Example ``` weight(10, 700) -> 120.21882500408238 weight(8, 1108) -> 190.28922301858418 ``` ## Hint: There is no integral to calculate. You can plot C1 and try to see the relationship between the different Cn and then use `i0`. ## Note: - don't round or truncate your result
from math import exp def weight(n, w): return w/4*(1-3*exp(-2))*(1-exp(-2*n-4))/(1-exp(-2))
An architect wants to construct a vaulted building supported by a family of arches Cn. fn(x) = -nx - xlog(x) is the equation of the arch Cn where `x` is a positive real number (0 < x <= 1), `log(x)` is the natural logarithm (base e), `n` a non negative integer. Let fn(0) = 0. Be An the point of Cn where the tangent to Cn is horizontal and Bn+1 the orthogonal projection of An on the x-axis (it means that An and Bn+1 have the same x -coordinate). Kn is the intersection of Cn with the x-axis. The figure shows C0, A0, B1, K0 as C(0), A0, B1, K0. ![alternative text](https://i.imgur.com/Td9aWIJ.png) The architect wants to support each arch Cn with a wall of glass filling the **curved** surface An Bn+1 Kn under the curve Cn. On the drawing you can see the surface `A0 B1 K0` in blue. He asks if we could calculate the weight of the surface of glass he needs to support all arches C0...Cn where n is a positive integer knowing he can choose glass thickness hence glass weight per square unit of surface. He gives us the absolute value of A0 B1 K0 area (in blue); call it `i0` which is approximately `0.14849853757254047` in square units. ## Task Write the function `weight` with parameters `n` and `w` where `n` is the number of arches to consider (n >= 1) and `w` is the weight of a square unit of glass depending on the wall thickness. This function should return the weight of n glass walls as described above. ## Example ``` weight(10, 700) -> 120.21882500408238 weight(8, 1108) -> 190.28922301858418 ``` ## Hint: There is no integral to calculate. You can plot C1 and try to see the relationship between the different Cn and then use `i0`. ## Note: - don't round or truncate your result
# i0 = 0.14849853757254047 def weight(n, w): i0 = 0.14849853757254 eConst = 2.71828182845904 eInvConstSq = 1 / (eConst ** 2) nPartialWeight = 0 nPartialSurface = i0 for iArch in range(1, n+1): nPartialWeight = nPartialWeight + ( iArch * nPartialSurface * w * (1 - eInvConstSq)) nPartialSurface = nPartialSurface / (eConst ** 2) return nPartialWeight
An architect wants to construct a vaulted building supported by a family of arches Cn. fn(x) = -nx - xlog(x) is the equation of the arch Cn where `x` is a positive real number (0 < x <= 1), `log(x)` is the natural logarithm (base e), `n` a non negative integer. Let fn(0) = 0. Be An the point of Cn where the tangent to Cn is horizontal and Bn+1 the orthogonal projection of An on the x-axis (it means that An and Bn+1 have the same x -coordinate). Kn is the intersection of Cn with the x-axis. The figure shows C0, A0, B1, K0 as C(0), A0, B1, K0. ![alternative text](https://i.imgur.com/Td9aWIJ.png) The architect wants to support each arch Cn with a wall of glass filling the **curved** surface An Bn+1 Kn under the curve Cn. On the drawing you can see the surface `A0 B1 K0` in blue. He asks if we could calculate the weight of the surface of glass he needs to support all arches C0...Cn where n is a positive integer knowing he can choose glass thickness hence glass weight per square unit of surface. He gives us the absolute value of A0 B1 K0 area (in blue); call it `i0` which is approximately `0.14849853757254047` in square units. ## Task Write the function `weight` with parameters `n` and `w` where `n` is the number of arches to consider (n >= 1) and `w` is the weight of a square unit of glass depending on the wall thickness. This function should return the weight of n glass walls as described above. ## Example ``` weight(10, 700) -> 120.21882500408238 weight(8, 1108) -> 190.28922301858418 ``` ## Hint: There is no integral to calculate. You can plot C1 and try to see the relationship between the different Cn and then use `i0`. ## Note: - don't round or truncate your result
import math def weight(n, w): x0 = math.exp(-1) i0 = 0.14849853757254047 p = i0 for i in range(1, n+1): x = math.exp(-i-1) k = x/x0 p += i0*k*k return p*w
An architect wants to construct a vaulted building supported by a family of arches Cn. fn(x) = -nx - xlog(x) is the equation of the arch Cn where `x` is a positive real number (0 < x <= 1), `log(x)` is the natural logarithm (base e), `n` a non negative integer. Let fn(0) = 0. Be An the point of Cn where the tangent to Cn is horizontal and Bn+1 the orthogonal projection of An on the x-axis (it means that An and Bn+1 have the same x -coordinate). Kn is the intersection of Cn with the x-axis. The figure shows C0, A0, B1, K0 as C(0), A0, B1, K0. ![alternative text](https://i.imgur.com/Td9aWIJ.png) The architect wants to support each arch Cn with a wall of glass filling the **curved** surface An Bn+1 Kn under the curve Cn. On the drawing you can see the surface `A0 B1 K0` in blue. He asks if we could calculate the weight of the surface of glass he needs to support all arches C0...Cn where n is a positive integer knowing he can choose glass thickness hence glass weight per square unit of surface. He gives us the absolute value of A0 B1 K0 area (in blue); call it `i0` which is approximately `0.14849853757254047` in square units. ## Task Write the function `weight` with parameters `n` and `w` where `n` is the number of arches to consider (n >= 1) and `w` is the weight of a square unit of glass depending on the wall thickness. This function should return the weight of n glass walls as described above. ## Example ``` weight(10, 700) -> 120.21882500408238 weight(8, 1108) -> 190.28922301858418 ``` ## Hint: There is no integral to calculate. You can plot C1 and try to see the relationship between the different Cn and then use `i0`. ## Note: - don't round or truncate your result
i0 = 0.14849853757254047 r = 0.1353352832366127 #r is calculated from observation of different values of Cn, Geometric series is formed def weight(n, w): return w*i0*(1-pow(r,n))/(1-r)
An architect wants to construct a vaulted building supported by a family of arches Cn. fn(x) = -nx - xlog(x) is the equation of the arch Cn where `x` is a positive real number (0 < x <= 1), `log(x)` is the natural logarithm (base e), `n` a non negative integer. Let fn(0) = 0. Be An the point of Cn where the tangent to Cn is horizontal and Bn+1 the orthogonal projection of An on the x-axis (it means that An and Bn+1 have the same x -coordinate). Kn is the intersection of Cn with the x-axis. The figure shows C0, A0, B1, K0 as C(0), A0, B1, K0. ![alternative text](https://i.imgur.com/Td9aWIJ.png) The architect wants to support each arch Cn with a wall of glass filling the **curved** surface An Bn+1 Kn under the curve Cn. On the drawing you can see the surface `A0 B1 K0` in blue. He asks if we could calculate the weight of the surface of glass he needs to support all arches C0...Cn where n is a positive integer knowing he can choose glass thickness hence glass weight per square unit of surface. He gives us the absolute value of A0 B1 K0 area (in blue); call it `i0` which is approximately `0.14849853757254047` in square units. ## Task Write the function `weight` with parameters `n` and `w` where `n` is the number of arches to consider (n >= 1) and `w` is the weight of a square unit of glass depending on the wall thickness. This function should return the weight of n glass walls as described above. ## Example ``` weight(10, 700) -> 120.21882500408238 weight(8, 1108) -> 190.28922301858418 ``` ## Hint: There is no integral to calculate. You can plot C1 and try to see the relationship between the different Cn and then use `i0`. ## Note: - don't round or truncate your result
import math def weight(n, w): i0 = 0.14849853757254047 return i0 * w * (1- math.exp(-2*n))/(1-math.exp(-2))
An architect wants to construct a vaulted building supported by a family of arches Cn. fn(x) = -nx - xlog(x) is the equation of the arch Cn where `x` is a positive real number (0 < x <= 1), `log(x)` is the natural logarithm (base e), `n` a non negative integer. Let fn(0) = 0. Be An the point of Cn where the tangent to Cn is horizontal and Bn+1 the orthogonal projection of An on the x-axis (it means that An and Bn+1 have the same x -coordinate). Kn is the intersection of Cn with the x-axis. The figure shows C0, A0, B1, K0 as C(0), A0, B1, K0. ![alternative text](https://i.imgur.com/Td9aWIJ.png) The architect wants to support each arch Cn with a wall of glass filling the **curved** surface An Bn+1 Kn under the curve Cn. On the drawing you can see the surface `A0 B1 K0` in blue. He asks if we could calculate the weight of the surface of glass he needs to support all arches C0...Cn where n is a positive integer knowing he can choose glass thickness hence glass weight per square unit of surface. He gives us the absolute value of A0 B1 K0 area (in blue); call it `i0` which is approximately `0.14849853757254047` in square units. ## Task Write the function `weight` with parameters `n` and `w` where `n` is the number of arches to consider (n >= 1) and `w` is the weight of a square unit of glass depending on the wall thickness. This function should return the weight of n glass walls as described above. ## Example ``` weight(10, 700) -> 120.21882500408238 weight(8, 1108) -> 190.28922301858418 ``` ## Hint: There is no integral to calculate. You can plot C1 and try to see the relationship between the different Cn and then use `i0`. ## Note: - don't round or truncate your result
from math import e def weight(n, w): return -0.17174117862516716*(e**(-2*n) - 1)*w
An architect wants to construct a vaulted building supported by a family of arches Cn. fn(x) = -nx - xlog(x) is the equation of the arch Cn where `x` is a positive real number (0 < x <= 1), `log(x)` is the natural logarithm (base e), `n` a non negative integer. Let fn(0) = 0. Be An the point of Cn where the tangent to Cn is horizontal and Bn+1 the orthogonal projection of An on the x-axis (it means that An and Bn+1 have the same x -coordinate). Kn is the intersection of Cn with the x-axis. The figure shows C0, A0, B1, K0 as C(0), A0, B1, K0. ![alternative text](https://i.imgur.com/Td9aWIJ.png) The architect wants to support each arch Cn with a wall of glass filling the **curved** surface An Bn+1 Kn under the curve Cn. On the drawing you can see the surface `A0 B1 K0` in blue. He asks if we could calculate the weight of the surface of glass he needs to support all arches C0...Cn where n is a positive integer knowing he can choose glass thickness hence glass weight per square unit of surface. He gives us the absolute value of A0 B1 K0 area (in blue); call it `i0` which is approximately `0.14849853757254047` in square units. ## Task Write the function `weight` with parameters `n` and `w` where `n` is the number of arches to consider (n >= 1) and `w` is the weight of a square unit of glass depending on the wall thickness. This function should return the weight of n glass walls as described above. ## Example ``` weight(10, 700) -> 120.21882500408238 weight(8, 1108) -> 190.28922301858418 ``` ## Hint: There is no integral to calculate. You can plot C1 and try to see the relationship between the different Cn and then use `i0`. ## Note: - don't round or truncate your result
from math import exp def weight(N, w): return sum(.25*exp(-2*(n+1))*(exp(2)-3) for n in range(N))*w
An architect wants to construct a vaulted building supported by a family of arches Cn. fn(x) = -nx - xlog(x) is the equation of the arch Cn where `x` is a positive real number (0 < x <= 1), `log(x)` is the natural logarithm (base e), `n` a non negative integer. Let fn(0) = 0. Be An the point of Cn where the tangent to Cn is horizontal and Bn+1 the orthogonal projection of An on the x-axis (it means that An and Bn+1 have the same x -coordinate). Kn is the intersection of Cn with the x-axis. The figure shows C0, A0, B1, K0 as C(0), A0, B1, K0. ![alternative text](https://i.imgur.com/Td9aWIJ.png) The architect wants to support each arch Cn with a wall of glass filling the **curved** surface An Bn+1 Kn under the curve Cn. On the drawing you can see the surface `A0 B1 K0` in blue. He asks if we could calculate the weight of the surface of glass he needs to support all arches C0...Cn where n is a positive integer knowing he can choose glass thickness hence glass weight per square unit of surface. He gives us the absolute value of A0 B1 K0 area (in blue); call it `i0` which is approximately `0.14849853757254047` in square units. ## Task Write the function `weight` with parameters `n` and `w` where `n` is the number of arches to consider (n >= 1) and `w` is the weight of a square unit of glass depending on the wall thickness. This function should return the weight of n glass walls as described above. ## Example ``` weight(10, 700) -> 120.21882500408238 weight(8, 1108) -> 190.28922301858418 ``` ## Hint: There is no integral to calculate. You can plot C1 and try to see the relationship between the different Cn and then use `i0`. ## Note: - don't round or truncate your result
import math import decimal def weight(n, w): weight = 0 i0 = 0.14849853757254047 ##constant estimated by dividing two integrals fundamental_constant_of_glass_windows = 0.135335283237 while n >= 0: weight += ((i0)*(fundamental_constant_of_glass_windows**n)) * w n -= 1 return weight # if something is extremly dumb but it works, it isn't dumb
An architect wants to construct a vaulted building supported by a family of arches Cn. fn(x) = -nx - xlog(x) is the equation of the arch Cn where `x` is a positive real number (0 < x <= 1), `log(x)` is the natural logarithm (base e), `n` a non negative integer. Let fn(0) = 0. Be An the point of Cn where the tangent to Cn is horizontal and Bn+1 the orthogonal projection of An on the x-axis (it means that An and Bn+1 have the same x -coordinate). Kn is the intersection of Cn with the x-axis. The figure shows C0, A0, B1, K0 as C(0), A0, B1, K0. ![alternative text](https://i.imgur.com/Td9aWIJ.png) The architect wants to support each arch Cn with a wall of glass filling the **curved** surface An Bn+1 Kn under the curve Cn. On the drawing you can see the surface `A0 B1 K0` in blue. He asks if we could calculate the weight of the surface of glass he needs to support all arches C0...Cn where n is a positive integer knowing he can choose glass thickness hence glass weight per square unit of surface. He gives us the absolute value of A0 B1 K0 area (in blue); call it `i0` which is approximately `0.14849853757254047` in square units. ## Task Write the function `weight` with parameters `n` and `w` where `n` is the number of arches to consider (n >= 1) and `w` is the weight of a square unit of glass depending on the wall thickness. This function should return the weight of n glass walls as described above. ## Example ``` weight(10, 700) -> 120.21882500408238 weight(8, 1108) -> 190.28922301858418 ``` ## Hint: There is no integral to calculate. You can plot C1 and try to see the relationship between the different Cn and then use `i0`. ## Note: - don't round or truncate your result
# i0 = 0.14849853757254047 import math def weight(n, w): i0 = (1-3*math.exp(-2))/4 iScale = [math.exp(-2*k) for k in range(n+1)] return w*i0*sum(iScale)
An architect wants to construct a vaulted building supported by a family of arches Cn. fn(x) = -nx - xlog(x) is the equation of the arch Cn where `x` is a positive real number (0 < x <= 1), `log(x)` is the natural logarithm (base e), `n` a non negative integer. Let fn(0) = 0. Be An the point of Cn where the tangent to Cn is horizontal and Bn+1 the orthogonal projection of An on the x-axis (it means that An and Bn+1 have the same x -coordinate). Kn is the intersection of Cn with the x-axis. The figure shows C0, A0, B1, K0 as C(0), A0, B1, K0. ![alternative text](https://i.imgur.com/Td9aWIJ.png) The architect wants to support each arch Cn with a wall of glass filling the **curved** surface An Bn+1 Kn under the curve Cn. On the drawing you can see the surface `A0 B1 K0` in blue. He asks if we could calculate the weight of the surface of glass he needs to support all arches C0...Cn where n is a positive integer knowing he can choose glass thickness hence glass weight per square unit of surface. He gives us the absolute value of A0 B1 K0 area (in blue); call it `i0` which is approximately `0.14849853757254047` in square units. ## Task Write the function `weight` with parameters `n` and `w` where `n` is the number of arches to consider (n >= 1) and `w` is the weight of a square unit of glass depending on the wall thickness. This function should return the weight of n glass walls as described above. ## Example ``` weight(10, 700) -> 120.21882500408238 weight(8, 1108) -> 190.28922301858418 ``` ## Hint: There is no integral to calculate. You can plot C1 and try to see the relationship between the different Cn and then use `i0`. ## Note: - don't round or truncate your result
from math import exp weight = lambda n, w: w * (1 - exp(-2 * n)) * 0.171741178625167174090959688267288041771996514689886836114
An architect wants to construct a vaulted building supported by a family of arches Cn. fn(x) = -nx - xlog(x) is the equation of the arch Cn where `x` is a positive real number (0 < x <= 1), `log(x)` is the natural logarithm (base e), `n` a non negative integer. Let fn(0) = 0. Be An the point of Cn where the tangent to Cn is horizontal and Bn+1 the orthogonal projection of An on the x-axis (it means that An and Bn+1 have the same x -coordinate). Kn is the intersection of Cn with the x-axis. The figure shows C0, A0, B1, K0 as C(0), A0, B1, K0. ![alternative text](https://i.imgur.com/Td9aWIJ.png) The architect wants to support each arch Cn with a wall of glass filling the **curved** surface An Bn+1 Kn under the curve Cn. On the drawing you can see the surface `A0 B1 K0` in blue. He asks if we could calculate the weight of the surface of glass he needs to support all arches C0...Cn where n is a positive integer knowing he can choose glass thickness hence glass weight per square unit of surface. He gives us the absolute value of A0 B1 K0 area (in blue); call it `i0` which is approximately `0.14849853757254047` in square units. ## Task Write the function `weight` with parameters `n` and `w` where `n` is the number of arches to consider (n >= 1) and `w` is the weight of a square unit of glass depending on the wall thickness. This function should return the weight of n glass walls as described above. ## Example ``` weight(10, 700) -> 120.21882500408238 weight(8, 1108) -> 190.28922301858418 ``` ## Hint: There is no integral to calculate. You can plot C1 and try to see the relationship between the different Cn and then use `i0`. ## Note: - don't round or truncate your result
from math import exp def weight(n, w): return w * (exp(2) - 3) * (1 - exp(-2*n)) / (4 * (exp(2) - 1))
An architect wants to construct a vaulted building supported by a family of arches Cn. fn(x) = -nx - xlog(x) is the equation of the arch Cn where `x` is a positive real number (0 < x <= 1), `log(x)` is the natural logarithm (base e), `n` a non negative integer. Let fn(0) = 0. Be An the point of Cn where the tangent to Cn is horizontal and Bn+1 the orthogonal projection of An on the x-axis (it means that An and Bn+1 have the same x -coordinate). Kn is the intersection of Cn with the x-axis. The figure shows C0, A0, B1, K0 as C(0), A0, B1, K0. ![alternative text](https://i.imgur.com/Td9aWIJ.png) The architect wants to support each arch Cn with a wall of glass filling the **curved** surface An Bn+1 Kn under the curve Cn. On the drawing you can see the surface `A0 B1 K0` in blue. He asks if we could calculate the weight of the surface of glass he needs to support all arches C0...Cn where n is a positive integer knowing he can choose glass thickness hence glass weight per square unit of surface. He gives us the absolute value of A0 B1 K0 area (in blue); call it `i0` which is approximately `0.14849853757254047` in square units. ## Task Write the function `weight` with parameters `n` and `w` where `n` is the number of arches to consider (n >= 1) and `w` is the weight of a square unit of glass depending on the wall thickness. This function should return the weight of n glass walls as described above. ## Example ``` weight(10, 700) -> 120.21882500408238 weight(8, 1108) -> 190.28922301858418 ``` ## Hint: There is no integral to calculate. You can plot C1 and try to see the relationship between the different Cn and then use `i0`. ## Note: - don't round or truncate your result
weight,H = lambda Q,S : (H - 3) * (1 - H ** -Q) / (H - 1) * S / 4,7.389
Consider the sequence `S(n, z) = (1 - z)(z + z**2 + z**3 + ... + z**n)` where `z` is a complex number and `n` a positive integer (n > 0). When `n` goes to infinity and `z` has a correct value (ie `z` is in its domain of convergence `D`), `S(n, z)` goes to a finite limit `lim` depending on `z`. Experiment with `S(n, z)` to guess the domain of convergence `D`of `S` and `lim` value when `z` is in `D`. Then determine the smallest integer `n` such that `abs(S(n, z) - lim) < eps` where `eps` is a given small real number and `abs(Z)` is the modulus or norm of the complex number Z. Call `f` the function `f(z, eps)` which returns `n`. If `z` is such that `S(n, z)` has no finite limit (when `z` is outside of `D`) `f` will return -1. # Examples: I is a complex number such as I * I = -1 (sometimes written `i` or `j`). `f(0.3 + 0.5 * I, 1e-4) returns 17` `f(30 + 5 * I, 1e-4) returns -1` # Remark: For languages that don't have complex numbers or "easy" complex numbers, a complex number `z` is represented by two real numbers `x` (real part) and `y` (imaginary part). `f(0.3, 0.5, 1e-4) returns 17` `f(30, 5, 1e-4) returns -1` # Note: You pass the tests if `abs(actual - exoected) <= 1`
import math def f(z, eps): if (abs(z) >= 1.0): return -1 return int(math.log(eps) / math.log(abs(z)))
Consider the sequence `S(n, z) = (1 - z)(z + z**2 + z**3 + ... + z**n)` where `z` is a complex number and `n` a positive integer (n > 0). When `n` goes to infinity and `z` has a correct value (ie `z` is in its domain of convergence `D`), `S(n, z)` goes to a finite limit `lim` depending on `z`. Experiment with `S(n, z)` to guess the domain of convergence `D`of `S` and `lim` value when `z` is in `D`. Then determine the smallest integer `n` such that `abs(S(n, z) - lim) < eps` where `eps` is a given small real number and `abs(Z)` is the modulus or norm of the complex number Z. Call `f` the function `f(z, eps)` which returns `n`. If `z` is such that `S(n, z)` has no finite limit (when `z` is outside of `D`) `f` will return -1. # Examples: I is a complex number such as I * I = -1 (sometimes written `i` or `j`). `f(0.3 + 0.5 * I, 1e-4) returns 17` `f(30 + 5 * I, 1e-4) returns -1` # Remark: For languages that don't have complex numbers or "easy" complex numbers, a complex number `z` is represented by two real numbers `x` (real part) and `y` (imaginary part). `f(0.3, 0.5, 1e-4) returns 17` `f(30, 5, 1e-4) returns -1` # Note: You pass the tests if `abs(actual - exoected) <= 1`
from math import log def f(z, eps): if z==0 or z==1 or (abs(z)**2<min([1,eps])): return 1 elif abs(z)>=1: return -1 else: return int(log(eps)/log(abs(z)))
Consider the sequence `S(n, z) = (1 - z)(z + z**2 + z**3 + ... + z**n)` where `z` is a complex number and `n` a positive integer (n > 0). When `n` goes to infinity and `z` has a correct value (ie `z` is in its domain of convergence `D`), `S(n, z)` goes to a finite limit `lim` depending on `z`. Experiment with `S(n, z)` to guess the domain of convergence `D`of `S` and `lim` value when `z` is in `D`. Then determine the smallest integer `n` such that `abs(S(n, z) - lim) < eps` where `eps` is a given small real number and `abs(Z)` is the modulus or norm of the complex number Z. Call `f` the function `f(z, eps)` which returns `n`. If `z` is such that `S(n, z)` has no finite limit (when `z` is outside of `D`) `f` will return -1. # Examples: I is a complex number such as I * I = -1 (sometimes written `i` or `j`). `f(0.3 + 0.5 * I, 1e-4) returns 17` `f(30 + 5 * I, 1e-4) returns -1` # Remark: For languages that don't have complex numbers or "easy" complex numbers, a complex number `z` is represented by two real numbers `x` (real part) and `y` (imaginary part). `f(0.3, 0.5, 1e-4) returns 17` `f(30, 5, 1e-4) returns -1` # Note: You pass the tests if `abs(actual - exoected) <= 1`
def f(z, eps, n=1): if abs(z) >= 1: return -1 while abs(z ** n) >= eps: n += 1 return n
Consider the sequence `S(n, z) = (1 - z)(z + z**2 + z**3 + ... + z**n)` where `z` is a complex number and `n` a positive integer (n > 0). When `n` goes to infinity and `z` has a correct value (ie `z` is in its domain of convergence `D`), `S(n, z)` goes to a finite limit `lim` depending on `z`. Experiment with `S(n, z)` to guess the domain of convergence `D`of `S` and `lim` value when `z` is in `D`. Then determine the smallest integer `n` such that `abs(S(n, z) - lim) < eps` where `eps` is a given small real number and `abs(Z)` is the modulus or norm of the complex number Z. Call `f` the function `f(z, eps)` which returns `n`. If `z` is such that `S(n, z)` has no finite limit (when `z` is outside of `D`) `f` will return -1. # Examples: I is a complex number such as I * I = -1 (sometimes written `i` or `j`). `f(0.3 + 0.5 * I, 1e-4) returns 17` `f(30 + 5 * I, 1e-4) returns -1` # Remark: For languages that don't have complex numbers or "easy" complex numbers, a complex number `z` is represented by two real numbers `x` (real part) and `y` (imaginary part). `f(0.3, 0.5, 1e-4) returns 17` `f(30, 5, 1e-4) returns -1` # Note: You pass the tests if `abs(actual - exoected) <= 1`
from math import log def f(z, eps): return int(log(eps) / log(abs(z))) if abs(z) < 1 else -1
Consider the sequence `S(n, z) = (1 - z)(z + z**2 + z**3 + ... + z**n)` where `z` is a complex number and `n` a positive integer (n > 0). When `n` goes to infinity and `z` has a correct value (ie `z` is in its domain of convergence `D`), `S(n, z)` goes to a finite limit `lim` depending on `z`. Experiment with `S(n, z)` to guess the domain of convergence `D`of `S` and `lim` value when `z` is in `D`. Then determine the smallest integer `n` such that `abs(S(n, z) - lim) < eps` where `eps` is a given small real number and `abs(Z)` is the modulus or norm of the complex number Z. Call `f` the function `f(z, eps)` which returns `n`. If `z` is such that `S(n, z)` has no finite limit (when `z` is outside of `D`) `f` will return -1. # Examples: I is a complex number such as I * I = -1 (sometimes written `i` or `j`). `f(0.3 + 0.5 * I, 1e-4) returns 17` `f(30 + 5 * I, 1e-4) returns -1` # Remark: For languages that don't have complex numbers or "easy" complex numbers, a complex number `z` is represented by two real numbers `x` (real part) and `y` (imaginary part). `f(0.3, 0.5, 1e-4) returns 17` `f(30, 5, 1e-4) returns -1` # Note: You pass the tests if `abs(actual - exoected) <= 1`
import math def f(z, eps): return max(-1, math.log(eps)/math.log(math.hypot(z.real, z.imag)))
Consider the sequence `S(n, z) = (1 - z)(z + z**2 + z**3 + ... + z**n)` where `z` is a complex number and `n` a positive integer (n > 0). When `n` goes to infinity and `z` has a correct value (ie `z` is in its domain of convergence `D`), `S(n, z)` goes to a finite limit `lim` depending on `z`. Experiment with `S(n, z)` to guess the domain of convergence `D`of `S` and `lim` value when `z` is in `D`. Then determine the smallest integer `n` such that `abs(S(n, z) - lim) < eps` where `eps` is a given small real number and `abs(Z)` is the modulus or norm of the complex number Z. Call `f` the function `f(z, eps)` which returns `n`. If `z` is such that `S(n, z)` has no finite limit (when `z` is outside of `D`) `f` will return -1. # Examples: I is a complex number such as I * I = -1 (sometimes written `i` or `j`). `f(0.3 + 0.5 * I, 1e-4) returns 17` `f(30 + 5 * I, 1e-4) returns -1` # Remark: For languages that don't have complex numbers or "easy" complex numbers, a complex number `z` is represented by two real numbers `x` (real part) and `y` (imaginary part). `f(0.3, 0.5, 1e-4) returns 17` `f(30, 5, 1e-4) returns -1` # Note: You pass the tests if `abs(actual - exoected) <= 1`
f=lambda z,e:-(abs(z)>=1)or __import__('math').log(e,abs(z))//1
Consider the sequence `S(n, z) = (1 - z)(z + z**2 + z**3 + ... + z**n)` where `z` is a complex number and `n` a positive integer (n > 0). When `n` goes to infinity and `z` has a correct value (ie `z` is in its domain of convergence `D`), `S(n, z)` goes to a finite limit `lim` depending on `z`. Experiment with `S(n, z)` to guess the domain of convergence `D`of `S` and `lim` value when `z` is in `D`. Then determine the smallest integer `n` such that `abs(S(n, z) - lim) < eps` where `eps` is a given small real number and `abs(Z)` is the modulus or norm of the complex number Z. Call `f` the function `f(z, eps)` which returns `n`. If `z` is such that `S(n, z)` has no finite limit (when `z` is outside of `D`) `f` will return -1. # Examples: I is a complex number such as I * I = -1 (sometimes written `i` or `j`). `f(0.3 + 0.5 * I, 1e-4) returns 17` `f(30 + 5 * I, 1e-4) returns -1` # Remark: For languages that don't have complex numbers or "easy" complex numbers, a complex number `z` is represented by two real numbers `x` (real part) and `y` (imaginary part). `f(0.3, 0.5, 1e-4) returns 17` `f(30, 5, 1e-4) returns -1` # Note: You pass the tests if `abs(actual - exoected) <= 1`
from math import * def f(z, eps): x,y = z.real,z.imag return max(-1,log(eps)/log(hypot(x,y)))
Consider the sequence `S(n, z) = (1 - z)(z + z**2 + z**3 + ... + z**n)` where `z` is a complex number and `n` a positive integer (n > 0). When `n` goes to infinity and `z` has a correct value (ie `z` is in its domain of convergence `D`), `S(n, z)` goes to a finite limit `lim` depending on `z`. Experiment with `S(n, z)` to guess the domain of convergence `D`of `S` and `lim` value when `z` is in `D`. Then determine the smallest integer `n` such that `abs(S(n, z) - lim) < eps` where `eps` is a given small real number and `abs(Z)` is the modulus or norm of the complex number Z. Call `f` the function `f(z, eps)` which returns `n`. If `z` is such that `S(n, z)` has no finite limit (when `z` is outside of `D`) `f` will return -1. # Examples: I is a complex number such as I * I = -1 (sometimes written `i` or `j`). `f(0.3 + 0.5 * I, 1e-4) returns 17` `f(30 + 5 * I, 1e-4) returns -1` # Remark: For languages that don't have complex numbers or "easy" complex numbers, a complex number `z` is represented by two real numbers `x` (real part) and `y` (imaginary part). `f(0.3, 0.5, 1e-4) returns 17` `f(30, 5, 1e-4) returns -1` # Note: You pass the tests if `abs(actual - exoected) <= 1`
def f(z, eps): import math if z ==1: return 1 elif abs(z)>=1: return -1 else: n=1 while abs(z)**(n) > eps: n+=1 return n
Consider the sequence `S(n, z) = (1 - z)(z + z**2 + z**3 + ... + z**n)` where `z` is a complex number and `n` a positive integer (n > 0). When `n` goes to infinity and `z` has a correct value (ie `z` is in its domain of convergence `D`), `S(n, z)` goes to a finite limit `lim` depending on `z`. Experiment with `S(n, z)` to guess the domain of convergence `D`of `S` and `lim` value when `z` is in `D`. Then determine the smallest integer `n` such that `abs(S(n, z) - lim) < eps` where `eps` is a given small real number and `abs(Z)` is the modulus or norm of the complex number Z. Call `f` the function `f(z, eps)` which returns `n`. If `z` is such that `S(n, z)` has no finite limit (when `z` is outside of `D`) `f` will return -1. # Examples: I is a complex number such as I * I = -1 (sometimes written `i` or `j`). `f(0.3 + 0.5 * I, 1e-4) returns 17` `f(30 + 5 * I, 1e-4) returns -1` # Remark: For languages that don't have complex numbers or "easy" complex numbers, a complex number `z` is represented by two real numbers `x` (real part) and `y` (imaginary part). `f(0.3, 0.5, 1e-4) returns 17` `f(30, 5, 1e-4) returns -1` # Note: You pass the tests if `abs(actual - exoected) <= 1`
import math def f(z, eps): tmp = math.log(eps, abs(z)) return math.trunc(tmp) if tmp>0 else -1
Consider the sequence `S(n, z) = (1 - z)(z + z**2 + z**3 + ... + z**n)` where `z` is a complex number and `n` a positive integer (n > 0). When `n` goes to infinity and `z` has a correct value (ie `z` is in its domain of convergence `D`), `S(n, z)` goes to a finite limit `lim` depending on `z`. Experiment with `S(n, z)` to guess the domain of convergence `D`of `S` and `lim` value when `z` is in `D`. Then determine the smallest integer `n` such that `abs(S(n, z) - lim) < eps` where `eps` is a given small real number and `abs(Z)` is the modulus or norm of the complex number Z. Call `f` the function `f(z, eps)` which returns `n`. If `z` is such that `S(n, z)` has no finite limit (when `z` is outside of `D`) `f` will return -1. # Examples: I is a complex number such as I * I = -1 (sometimes written `i` or `j`). `f(0.3 + 0.5 * I, 1e-4) returns 17` `f(30 + 5 * I, 1e-4) returns -1` # Remark: For languages that don't have complex numbers or "easy" complex numbers, a complex number `z` is represented by two real numbers `x` (real part) and `y` (imaginary part). `f(0.3, 0.5, 1e-4) returns 17` `f(30, 5, 1e-4) returns -1` # Note: You pass the tests if `abs(actual - exoected) <= 1`
def f(z, eps): if abs(z) >= 1: return -1 n = 1 while abs(z**n) > eps: n += 1 return n
We all use 16:9, 16:10, 4:3 etc. ratios every day. Main task is to determine image ratio by its width and height dimensions. Function should take width and height of an image and return a ratio string (ex."16:9"). If any of width or height entry is 0 function should throw an exception (or return `Nothing`).
from fractions import Fraction def calculate_ratio(w, h): if w * h == 0: raise ValueError f = Fraction(w, h) return f"{f.numerator}:{f.denominator}"
We all use 16:9, 16:10, 4:3 etc. ratios every day. Main task is to determine image ratio by its width and height dimensions. Function should take width and height of an image and return a ratio string (ex."16:9"). If any of width or height entry is 0 function should throw an exception (or return `Nothing`).
from fractions import gcd def lcm(a, b): return a * b / gcd(a, b) def calculate_ratio(w,h): if all(x > 0 for x in [w,h]): return "{}:{}".format(lcm(w,h)/h,lcm(w,h)/w) return 'You threw an error'
We all use 16:9, 16:10, 4:3 etc. ratios every day. Main task is to determine image ratio by its width and height dimensions. Function should take width and height of an image and return a ratio string (ex."16:9"). If any of width or height entry is 0 function should throw an exception (or return `Nothing`).
from fractions import gcd def calculate_ratio(w,h): if w == 0 or h == 0: raise ValueError factor = gcd(w, h) return '{}:{}'.format(w // factor, h // factor)
We all use 16:9, 16:10, 4:3 etc. ratios every day. Main task is to determine image ratio by its width and height dimensions. Function should take width and height of an image and return a ratio string (ex."16:9"). If any of width or height entry is 0 function should throw an exception (or return `Nothing`).
from fractions import Fraction def calculate_ratio(w, h): if w * h == 0: raise ValueError() return '{0.numerator}:{0.denominator}'.format(Fraction(w, h))
We all use 16:9, 16:10, 4:3 etc. ratios every day. Main task is to determine image ratio by its width and height dimensions. Function should take width and height of an image and return a ratio string (ex."16:9"). If any of width or height entry is 0 function should throw an exception (or return `Nothing`).
from fractions import gcd def calculate_ratio(w,h): c = gcd(w, h) return "{}:{}".format(w/c, h/c) if w > 0 and h > 0 else 'You threw an error'
We all use 16:9, 16:10, 4:3 etc. ratios every day. Main task is to determine image ratio by its width and height dimensions. Function should take width and height of an image and return a ratio string (ex."16:9"). If any of width or height entry is 0 function should throw an exception (or return `Nothing`).
def calculate_ratio(w,h): if w <= 0 or h <= 0: raise ValueError def gcd(a, b): while b: a, b = b, a % b return a denom = gcd(w, h) return "{}:{}".format(w/denom, h/denom)
We all use 16:9, 16:10, 4:3 etc. ratios every day. Main task is to determine image ratio by its width and height dimensions. Function should take width and height of an image and return a ratio string (ex."16:9"). If any of width or height entry is 0 function should throw an exception (or return `Nothing`).
from fractions import*;calculate_ratio=lambda w,h:w*h/w/h and`w/gcd(w,h)`+':'+`h/gcd(w,h)`
We all use 16:9, 16:10, 4:3 etc. ratios every day. Main task is to determine image ratio by its width and height dimensions. Function should take width and height of an image and return a ratio string (ex."16:9"). If any of width or height entry is 0 function should throw an exception (or return `Nothing`).
from math import gcd def calculate_ratio(w, h): if w <= 0 or h <= 0: raise ValueError("Width and height should be > 0") d = gcd(w, h) return f"{w//d}:{h//d}"
We all use 16:9, 16:10, 4:3 etc. ratios every day. Main task is to determine image ratio by its width and height dimensions. Function should take width and height of an image and return a ratio string (ex."16:9"). If any of width or height entry is 0 function should throw an exception (or return `Nothing`).
def calculate_ratio(w, h): if not h or not w: raise ValueError("Width and height should be > 0") for i in range(2, min(w, h) + 1): while h % i == w % i == 0: h //= i w //= i return f"{w}:{h}"
We all use 16:9, 16:10, 4:3 etc. ratios every day. Main task is to determine image ratio by its width and height dimensions. Function should take width and height of an image and return a ratio string (ex."16:9"). If any of width or height entry is 0 function should throw an exception (or return `Nothing`).
def calculate_ratio(w, h): for i in range (1,100000): if w==0: return ('You threw an error') elif ((w/h)*i)-int(((w/h)*i))==0: return(str(int((w/h)*i))+':'+str(i)) elif ((h/w)*i)-int(((h/w)*i))==0: return(str(i)+':'+str(int((h/w)*i))) return('You threw an error')
The built-in print function for Python class instances is not very entertaining. In this Kata, we will implement a function ```show_me(instname)``` that takes an instance name as parameter and returns the string "Hi, I'm one of those (classname)s! Have a look at my (attrs).", where (classname) is the class name and (attrs) are the class's attributes. If (attrs) contains only one element, just write it. For more than one element (e.g. a, b, c), it should list all elements sorted by name in ascending order (e.g. "...look at my a, b and c"). Example: For an instance ```porsche = Vehicle(2, 4, 'gas')``` of the class ``` class Vehicle: def __init__(self, seats, wheels, engine): self.seats = seats self.wheels = wheels self.engine = engine ``` the function call ```show_me(porsche)``` should return the string 'Hi, I'm one of those Vehicles! Have a look at my engine, seats and wheels.' Hints: For simplicity we assume that the parameter "instname" is always a class instance.
def show_me(instname): attrs = sorted(instname.__dict__.keys()) if len(attrs) == 1: attrs = attrs[0] else: attrs = '{} and {}'.format(', '.join(attrs[:-1]), attrs[-1]) return 'Hi, I\'m one of those {}s! Have a look at my {}.'\ .format(instname.__class__.__name__, attrs)
The built-in print function for Python class instances is not very entertaining. In this Kata, we will implement a function ```show_me(instname)``` that takes an instance name as parameter and returns the string "Hi, I'm one of those (classname)s! Have a look at my (attrs).", where (classname) is the class name and (attrs) are the class's attributes. If (attrs) contains only one element, just write it. For more than one element (e.g. a, b, c), it should list all elements sorted by name in ascending order (e.g. "...look at my a, b and c"). Example: For an instance ```porsche = Vehicle(2, 4, 'gas')``` of the class ``` class Vehicle: def __init__(self, seats, wheels, engine): self.seats = seats self.wheels = wheels self.engine = engine ``` the function call ```show_me(porsche)``` should return the string 'Hi, I'm one of those Vehicles! Have a look at my engine, seats and wheels.' Hints: For simplicity we assume that the parameter "instname" is always a class instance.
def show_me(instname): classname = instname.__class__.__name__ attrs = " and".join(", ".join(attr for attr in sorted(instname.__dict__.keys())).rsplit(",", 1)) return f"Hi, I'm one of those {classname}s! Have a look at my {attrs}."
The built-in print function for Python class instances is not very entertaining. In this Kata, we will implement a function ```show_me(instname)``` that takes an instance name as parameter and returns the string "Hi, I'm one of those (classname)s! Have a look at my (attrs).", where (classname) is the class name and (attrs) are the class's attributes. If (attrs) contains only one element, just write it. For more than one element (e.g. a, b, c), it should list all elements sorted by name in ascending order (e.g. "...look at my a, b and c"). Example: For an instance ```porsche = Vehicle(2, 4, 'gas')``` of the class ``` class Vehicle: def __init__(self, seats, wheels, engine): self.seats = seats self.wheels = wheels self.engine = engine ``` the function call ```show_me(porsche)``` should return the string 'Hi, I'm one of those Vehicles! Have a look at my engine, seats and wheels.' Hints: For simplicity we assume that the parameter "instname" is always a class instance.
def show_me(instname): attr = sorted(list(instname.__dict__.keys())) attr = ', '.join(attr[:-1]) + ' and '*(len(attr)>=2) + attr[-1] return "Hi, I'm one of those {}s! Have a look at my {}.".format(type(instname).__name__, attr )
The built-in print function for Python class instances is not very entertaining. In this Kata, we will implement a function ```show_me(instname)``` that takes an instance name as parameter and returns the string "Hi, I'm one of those (classname)s! Have a look at my (attrs).", where (classname) is the class name and (attrs) are the class's attributes. If (attrs) contains only one element, just write it. For more than one element (e.g. a, b, c), it should list all elements sorted by name in ascending order (e.g. "...look at my a, b and c"). Example: For an instance ```porsche = Vehicle(2, 4, 'gas')``` of the class ``` class Vehicle: def __init__(self, seats, wheels, engine): self.seats = seats self.wheels = wheels self.engine = engine ``` the function call ```show_me(porsche)``` should return the string 'Hi, I'm one of those Vehicles! Have a look at my engine, seats and wheels.' Hints: For simplicity we assume that the parameter "instname" is always a class instance.
def show_me(inst): name = inst.__class__.__name__ atts = ' and'.join(', '.join(sorted(k for k in inst.__dict__)).rsplit(',', 1)) return "Hi, I'm one of those {}s! Have a look at my {}.".format(name, atts)
The built-in print function for Python class instances is not very entertaining. In this Kata, we will implement a function ```show_me(instname)``` that takes an instance name as parameter and returns the string "Hi, I'm one of those (classname)s! Have a look at my (attrs).", where (classname) is the class name and (attrs) are the class's attributes. If (attrs) contains only one element, just write it. For more than one element (e.g. a, b, c), it should list all elements sorted by name in ascending order (e.g. "...look at my a, b and c"). Example: For an instance ```porsche = Vehicle(2, 4, 'gas')``` of the class ``` class Vehicle: def __init__(self, seats, wheels, engine): self.seats = seats self.wheels = wheels self.engine = engine ``` the function call ```show_me(porsche)``` should return the string 'Hi, I'm one of those Vehicles! Have a look at my engine, seats and wheels.' Hints: For simplicity we assume that the parameter "instname" is always a class instance.
def show_me(instname): name = type(instname).__name__ + 's' l = list(instname.__dict__.keys()) l.sort() if len(l) == 1: string = f'{l[0]}.' else: s = ', '.join(l[0:-1]) string = s + f' and {l[-1]}.' return f"Hi, I'm one of those {name}! Have a look at my {string}"
The built-in print function for Python class instances is not very entertaining. In this Kata, we will implement a function ```show_me(instname)``` that takes an instance name as parameter and returns the string "Hi, I'm one of those (classname)s! Have a look at my (attrs).", where (classname) is the class name and (attrs) are the class's attributes. If (attrs) contains only one element, just write it. For more than one element (e.g. a, b, c), it should list all elements sorted by name in ascending order (e.g. "...look at my a, b and c"). Example: For an instance ```porsche = Vehicle(2, 4, 'gas')``` of the class ``` class Vehicle: def __init__(self, seats, wheels, engine): self.seats = seats self.wheels = wheels self.engine = engine ``` the function call ```show_me(porsche)``` should return the string 'Hi, I'm one of those Vehicles! Have a look at my engine, seats and wheels.' Hints: For simplicity we assume that the parameter "instname" is always a class instance.
def show_me(instname): hi = f"Hi, I'm one of those {instname.__class__.__name__}s!" fields = sorted(vars(instname)) if len(fields) == 1: return f"{hi} Have a look at my {fields[0]}." else: return f"{hi} Have a look at my {', '.join(fields[:-1])} and {fields[-1]}."
The built-in print function for Python class instances is not very entertaining. In this Kata, we will implement a function ```show_me(instname)``` that takes an instance name as parameter and returns the string "Hi, I'm one of those (classname)s! Have a look at my (attrs).", where (classname) is the class name and (attrs) are the class's attributes. If (attrs) contains only one element, just write it. For more than one element (e.g. a, b, c), it should list all elements sorted by name in ascending order (e.g. "...look at my a, b and c"). Example: For an instance ```porsche = Vehicle(2, 4, 'gas')``` of the class ``` class Vehicle: def __init__(self, seats, wheels, engine): self.seats = seats self.wheels = wheels self.engine = engine ``` the function call ```show_me(porsche)``` should return the string 'Hi, I'm one of those Vehicles! Have a look at my engine, seats and wheels.' Hints: For simplicity we assume that the parameter "instname" is always a class instance.
def show_me(instname): return "Hi, I'm one of those {}s! Have a look at my {}.".format(instname.__class__.__name__, ', '.join(list(instname.__dict__.keys())) if len(list(instname.__dict__.keys())) == 1 else ', '.join(sorted(list(instname.__dict__.keys()))).rpartition(', ')[0] + ' and ' + ', '.join(sorted(list(instname.__dict__.keys()))).rpartition(', ')[2])
The built-in print function for Python class instances is not very entertaining. In this Kata, we will implement a function ```show_me(instname)``` that takes an instance name as parameter and returns the string "Hi, I'm one of those (classname)s! Have a look at my (attrs).", where (classname) is the class name and (attrs) are the class's attributes. If (attrs) contains only one element, just write it. For more than one element (e.g. a, b, c), it should list all elements sorted by name in ascending order (e.g. "...look at my a, b and c"). Example: For an instance ```porsche = Vehicle(2, 4, 'gas')``` of the class ``` class Vehicle: def __init__(self, seats, wheels, engine): self.seats = seats self.wheels = wheels self.engine = engine ``` the function call ```show_me(porsche)``` should return the string 'Hi, I'm one of those Vehicles! Have a look at my engine, seats and wheels.' Hints: For simplicity we assume that the parameter "instname" is always a class instance.
def show_me(instname): return "Hi, I'm one of those {}s! Have a look at my {}.".format(instname.__class__.__name__, ' and '.join(', '.join(sorted(instname.__dict__.keys())).rsplit(', ', 1)))
The built-in print function for Python class instances is not very entertaining. In this Kata, we will implement a function ```show_me(instname)``` that takes an instance name as parameter and returns the string "Hi, I'm one of those (classname)s! Have a look at my (attrs).", where (classname) is the class name and (attrs) are the class's attributes. If (attrs) contains only one element, just write it. For more than one element (e.g. a, b, c), it should list all elements sorted by name in ascending order (e.g. "...look at my a, b and c"). Example: For an instance ```porsche = Vehicle(2, 4, 'gas')``` of the class ``` class Vehicle: def __init__(self, seats, wheels, engine): self.seats = seats self.wheels = wheels self.engine = engine ``` the function call ```show_me(porsche)``` should return the string 'Hi, I'm one of those Vehicles! Have a look at my engine, seats and wheels.' Hints: For simplicity we assume that the parameter "instname" is always a class instance.
def show_me(instname): return "Hi, I'm one of those %ss!" % instname.__class__.__name__ + \ " Have a look at my %s." % ' and '.join(', '.join(sorted(instname.__dict__)).rsplit(', ', 1))
The built-in print function for Python class instances is not very entertaining. In this Kata, we will implement a function ```show_me(instname)``` that takes an instance name as parameter and returns the string "Hi, I'm one of those (classname)s! Have a look at my (attrs).", where (classname) is the class name and (attrs) are the class's attributes. If (attrs) contains only one element, just write it. For more than one element (e.g. a, b, c), it should list all elements sorted by name in ascending order (e.g. "...look at my a, b and c"). Example: For an instance ```porsche = Vehicle(2, 4, 'gas')``` of the class ``` class Vehicle: def __init__(self, seats, wheels, engine): self.seats = seats self.wheels = wheels self.engine = engine ``` the function call ```show_me(porsche)``` should return the string 'Hi, I'm one of those Vehicles! Have a look at my engine, seats and wheels.' Hints: For simplicity we assume that the parameter "instname" is always a class instance.
# create the function show_me def show_me(instname): name, attrs = instname.__class__.__name__, sorted(instname.__dict__) if len(attrs) == 1: return "Hi, I'm one of those {}s! Have a look at my {}.".format(name, attrs[0]) return "Hi, I'm one of those {}s! Have a look at my {} and {}.".format(name, ", ".join(attrs[:-1]), attrs[-1])
A sequence is usually a set or an array of numbers that has a strict way for moving from the nth term to the (n+1)th term. If ``f(n) = f(n-1) + c`` where ``c`` is a constant value, then ``f`` is an arithmetic sequence. An example would be (where the first term is 0 and the constant is 1) is [0, 1, 2, 3, 4, 5, ... and so on] ) Else if (pun) ``f(n) = f(n-1) * c`` where ``c`` is a constant value, then ``f`` is a geometric sequence. Example where the first term is 2 and the constant is 2 will be [2, 4, 8, 16, 32, 64, ... to infinity ... ] There are some sequences that aren't arithmetic nor are they geometric. Here is a link to feed your brain : Sequence ! You're going to write a function that's going to return the value in the nth index of an arithmetic sequence.(That is, adding a constant to move to the next element in the "set"). The function's name is `nthterm`/`Nthterm`, it takes three inputs `first`,`n`,`c` where: - ``first`` is the first value in the 0 INDEX. - ``n`` is the index of the value we want. - ``c`` is the constant added between the terms. Remember that `first` is in the index ``0`` .. just saying ...
def nthterm(first, n, c): return first + n * c
A sequence is usually a set or an array of numbers that has a strict way for moving from the nth term to the (n+1)th term. If ``f(n) = f(n-1) + c`` where ``c`` is a constant value, then ``f`` is an arithmetic sequence. An example would be (where the first term is 0 and the constant is 1) is [0, 1, 2, 3, 4, 5, ... and so on] ) Else if (pun) ``f(n) = f(n-1) * c`` where ``c`` is a constant value, then ``f`` is a geometric sequence. Example where the first term is 2 and the constant is 2 will be [2, 4, 8, 16, 32, 64, ... to infinity ... ] There are some sequences that aren't arithmetic nor are they geometric. Here is a link to feed your brain : Sequence ! You're going to write a function that's going to return the value in the nth index of an arithmetic sequence.(That is, adding a constant to move to the next element in the "set"). The function's name is `nthterm`/`Nthterm`, it takes three inputs `first`,`n`,`c` where: - ``first`` is the first value in the 0 INDEX. - ``n`` is the index of the value we want. - ``c`` is the constant added between the terms. Remember that `first` is in the index ``0`` .. just saying ...
def nthterm(first,n,d): return first+(n*d)
A sequence is usually a set or an array of numbers that has a strict way for moving from the nth term to the (n+1)th term. If ``f(n) = f(n-1) + c`` where ``c`` is a constant value, then ``f`` is an arithmetic sequence. An example would be (where the first term is 0 and the constant is 1) is [0, 1, 2, 3, 4, 5, ... and so on] ) Else if (pun) ``f(n) = f(n-1) * c`` where ``c`` is a constant value, then ``f`` is a geometric sequence. Example where the first term is 2 and the constant is 2 will be [2, 4, 8, 16, 32, 64, ... to infinity ... ] There are some sequences that aren't arithmetic nor are they geometric. Here is a link to feed your brain : Sequence ! You're going to write a function that's going to return the value in the nth index of an arithmetic sequence.(That is, adding a constant to move to the next element in the "set"). The function's name is `nthterm`/`Nthterm`, it takes three inputs `first`,`n`,`c` where: - ``first`` is the first value in the 0 INDEX. - ``n`` is the index of the value we want. - ``c`` is the constant added between the terms. Remember that `first` is in the index ``0`` .. just saying ...
def nthterm(first, n, c): if n == 0: return first else: return nthterm(first + c, n - 1, c)
A sequence is usually a set or an array of numbers that has a strict way for moving from the nth term to the (n+1)th term. If ``f(n) = f(n-1) + c`` where ``c`` is a constant value, then ``f`` is an arithmetic sequence. An example would be (where the first term is 0 and the constant is 1) is [0, 1, 2, 3, 4, 5, ... and so on] ) Else if (pun) ``f(n) = f(n-1) * c`` where ``c`` is a constant value, then ``f`` is a geometric sequence. Example where the first term is 2 and the constant is 2 will be [2, 4, 8, 16, 32, 64, ... to infinity ... ] There are some sequences that aren't arithmetic nor are they geometric. Here is a link to feed your brain : Sequence ! You're going to write a function that's going to return the value in the nth index of an arithmetic sequence.(That is, adding a constant to move to the next element in the "set"). The function's name is `nthterm`/`Nthterm`, it takes three inputs `first`,`n`,`c` where: - ``first`` is the first value in the 0 INDEX. - ``n`` is the index of the value we want. - ``c`` is the constant added between the terms. Remember that `first` is in the index ``0`` .. just saying ...
def nthterm(a,n,d): return a+(n*d)
A sequence is usually a set or an array of numbers that has a strict way for moving from the nth term to the (n+1)th term. If ``f(n) = f(n-1) + c`` where ``c`` is a constant value, then ``f`` is an arithmetic sequence. An example would be (where the first term is 0 and the constant is 1) is [0, 1, 2, 3, 4, 5, ... and so on] ) Else if (pun) ``f(n) = f(n-1) * c`` where ``c`` is a constant value, then ``f`` is a geometric sequence. Example where the first term is 2 and the constant is 2 will be [2, 4, 8, 16, 32, 64, ... to infinity ... ] There are some sequences that aren't arithmetic nor are they geometric. Here is a link to feed your brain : Sequence ! You're going to write a function that's going to return the value in the nth index of an arithmetic sequence.(That is, adding a constant to move to the next element in the "set"). The function's name is `nthterm`/`Nthterm`, it takes three inputs `first`,`n`,`c` where: - ``first`` is the first value in the 0 INDEX. - ``n`` is the index of the value we want. - ``c`` is the constant added between the terms. Remember that `first` is in the index ``0`` .. just saying ...
nthterm = lambda first, n, c: first + n * c
A sequence is usually a set or an array of numbers that has a strict way for moving from the nth term to the (n+1)th term. If ``f(n) = f(n-1) + c`` where ``c`` is a constant value, then ``f`` is an arithmetic sequence. An example would be (where the first term is 0 and the constant is 1) is [0, 1, 2, 3, 4, 5, ... and so on] ) Else if (pun) ``f(n) = f(n-1) * c`` where ``c`` is a constant value, then ``f`` is a geometric sequence. Example where the first term is 2 and the constant is 2 will be [2, 4, 8, 16, 32, 64, ... to infinity ... ] There are some sequences that aren't arithmetic nor are they geometric. Here is a link to feed your brain : Sequence ! You're going to write a function that's going to return the value in the nth index of an arithmetic sequence.(That is, adding a constant to move to the next element in the "set"). The function's name is `nthterm`/`Nthterm`, it takes three inputs `first`,`n`,`c` where: - ``first`` is the first value in the 0 INDEX. - ``n`` is the index of the value we want. - ``c`` is the constant added between the terms. Remember that `first` is in the index ``0`` .. just saying ...
def nthterm(first, n, d): return first if n == 0 else nthterm(first + d, n - 1, d)
A sequence is usually a set or an array of numbers that has a strict way for moving from the nth term to the (n+1)th term. If ``f(n) = f(n-1) + c`` where ``c`` is a constant value, then ``f`` is an arithmetic sequence. An example would be (where the first term is 0 and the constant is 1) is [0, 1, 2, 3, 4, 5, ... and so on] ) Else if (pun) ``f(n) = f(n-1) * c`` where ``c`` is a constant value, then ``f`` is a geometric sequence. Example where the first term is 2 and the constant is 2 will be [2, 4, 8, 16, 32, 64, ... to infinity ... ] There are some sequences that aren't arithmetic nor are they geometric. Here is a link to feed your brain : Sequence ! You're going to write a function that's going to return the value in the nth index of an arithmetic sequence.(That is, adding a constant to move to the next element in the "set"). The function's name is `nthterm`/`Nthterm`, it takes three inputs `first`,`n`,`c` where: - ``first`` is the first value in the 0 INDEX. - ``n`` is the index of the value we want. - ``c`` is the constant added between the terms. Remember that `first` is in the index ``0`` .. just saying ...
def nthterm(a, n, r): return a + n * r
A sequence is usually a set or an array of numbers that has a strict way for moving from the nth term to the (n+1)th term. If ``f(n) = f(n-1) + c`` where ``c`` is a constant value, then ``f`` is an arithmetic sequence. An example would be (where the first term is 0 and the constant is 1) is [0, 1, 2, 3, 4, 5, ... and so on] ) Else if (pun) ``f(n) = f(n-1) * c`` where ``c`` is a constant value, then ``f`` is a geometric sequence. Example where the first term is 2 and the constant is 2 will be [2, 4, 8, 16, 32, 64, ... to infinity ... ] There are some sequences that aren't arithmetic nor are they geometric. Here is a link to feed your brain : Sequence ! You're going to write a function that's going to return the value in the nth index of an arithmetic sequence.(That is, adding a constant to move to the next element in the "set"). The function's name is `nthterm`/`Nthterm`, it takes three inputs `first`,`n`,`c` where: - ``first`` is the first value in the 0 INDEX. - ``n`` is the index of the value we want. - ``c`` is the constant added between the terms. Remember that `first` is in the index ``0`` .. just saying ...
nthterm = lambda a, x, b: a+b*x
A sequence is usually a set or an array of numbers that has a strict way for moving from the nth term to the (n+1)th term. If ``f(n) = f(n-1) + c`` where ``c`` is a constant value, then ``f`` is an arithmetic sequence. An example would be (where the first term is 0 and the constant is 1) is [0, 1, 2, 3, 4, 5, ... and so on] ) Else if (pun) ``f(n) = f(n-1) * c`` where ``c`` is a constant value, then ``f`` is a geometric sequence. Example where the first term is 2 and the constant is 2 will be [2, 4, 8, 16, 32, 64, ... to infinity ... ] There are some sequences that aren't arithmetic nor are they geometric. Here is a link to feed your brain : Sequence ! You're going to write a function that's going to return the value in the nth index of an arithmetic sequence.(That is, adding a constant to move to the next element in the "set"). The function's name is `nthterm`/`Nthterm`, it takes three inputs `first`,`n`,`c` where: - ``first`` is the first value in the 0 INDEX. - ``n`` is the index of the value we want. - ``c`` is the constant added between the terms. Remember that `first` is in the index ``0`` .. just saying ...
def nthterm(f, n, c): return n * c + f
A sequence is usually a set or an array of numbers that has a strict way for moving from the nth term to the (n+1)th term. If ``f(n) = f(n-1) + c`` where ``c`` is a constant value, then ``f`` is an arithmetic sequence. An example would be (where the first term is 0 and the constant is 1) is [0, 1, 2, 3, 4, 5, ... and so on] ) Else if (pun) ``f(n) = f(n-1) * c`` where ``c`` is a constant value, then ``f`` is a geometric sequence. Example where the first term is 2 and the constant is 2 will be [2, 4, 8, 16, 32, 64, ... to infinity ... ] There are some sequences that aren't arithmetic nor are they geometric. Here is a link to feed your brain : Sequence ! You're going to write a function that's going to return the value in the nth index of an arithmetic sequence.(That is, adding a constant to move to the next element in the "set"). The function's name is `nthterm`/`Nthterm`, it takes three inputs `first`,`n`,`c` where: - ``first`` is the first value in the 0 INDEX. - ``n`` is the index of the value we want. - ``c`` is the constant added between the terms. Remember that `first` is in the index ``0`` .. just saying ...
def nthterm(first, n , c): return n*c + first
Write a function ```unpack()``` that unpacks a ```list``` of elements that can contain objects(`int`, `str`, `list`, `tuple`, `dict`, `set`) within each other without any predefined depth, meaning that there can be many levels of elements contained in one another. Example: ```python unpack([None, [1, ({2, 3}, {'foo': 'bar'})]]) == [None, 1, 2, 3, 'foo', 'bar'] ``` Note: you don't have to bother about the order of the elements, especially when unpacking a `dict` or a `set`. Just unpack all the elements.
from collections import Iterable def unpack(iterable): lst = [] for x in iterable: if isinstance(x,dict): x = unpack(x.items()) elif isinstance(x,str): x = [x] elif isinstance(x,Iterable): x = unpack(x) else: x = [x] lst.extend(x) return lst
Write a function ```unpack()``` that unpacks a ```list``` of elements that can contain objects(`int`, `str`, `list`, `tuple`, `dict`, `set`) within each other without any predefined depth, meaning that there can be many levels of elements contained in one another. Example: ```python unpack([None, [1, ({2, 3}, {'foo': 'bar'})]]) == [None, 1, 2, 3, 'foo', 'bar'] ``` Note: you don't have to bother about the order of the elements, especially when unpacking a `dict` or a `set`. Just unpack all the elements.
def unpack(l): """Unpack a list of elements that contains unpackable objects. >>> unpack([None, [1, ({2, 3}, {'foo': 'bar'})]]) [None, 1, 2, 3, 'foo', 'bar'] """ res = [] for i in l: if type(i) is list: res += unpack(i) elif type(i) is tuple: res += unpack(list(i)) elif type(i) is dict: res += unpack(list(i.keys())) res += unpack(list(i.values())) elif type(i) is set: res += unpack(list(i)) else: res += [i] return res
Write a function ```unpack()``` that unpacks a ```list``` of elements that can contain objects(`int`, `str`, `list`, `tuple`, `dict`, `set`) within each other without any predefined depth, meaning that there can be many levels of elements contained in one another. Example: ```python unpack([None, [1, ({2, 3}, {'foo': 'bar'})]]) == [None, 1, 2, 3, 'foo', 'bar'] ``` Note: you don't have to bother about the order of the elements, especially when unpacking a `dict` or a `set`. Just unpack all the elements.
def unpack(l): pac = [] for e in l: if type(e) not in [tuple, list, set, dict]: pac.append(e) elif type(e) == dict: pac += unpack(list(e.items())) else: pac += unpack(e) return pac
Write a function ```unpack()``` that unpacks a ```list``` of elements that can contain objects(`int`, `str`, `list`, `tuple`, `dict`, `set`) within each other without any predefined depth, meaning that there can be many levels of elements contained in one another. Example: ```python unpack([None, [1, ({2, 3}, {'foo': 'bar'})]]) == [None, 1, 2, 3, 'foo', 'bar'] ``` Note: you don't have to bother about the order of the elements, especially when unpacking a `dict` or a `set`. Just unpack all the elements.
def iter_unpack(x): if isinstance(x, (tuple, list, set)): for item in x: yield from iter_unpack(item) elif isinstance(x, dict): for key, value in x.items(): yield from iter_unpack(key) yield from iter_unpack(value) else: yield x def unpack(x): return list(iter_unpack(x))
Write a function ```unpack()``` that unpacks a ```list``` of elements that can contain objects(`int`, `str`, `list`, `tuple`, `dict`, `set`) within each other without any predefined depth, meaning that there can be many levels of elements contained in one another. Example: ```python unpack([None, [1, ({2, 3}, {'foo': 'bar'})]]) == [None, 1, 2, 3, 'foo', 'bar'] ``` Note: you don't have to bother about the order of the elements, especially when unpacking a `dict` or a `set`. Just unpack all the elements.
def unpack(L): res = [] for el in L: if isinstance(el, (list, tuple, set)): res.extend(unpack(el)) elif isinstance(el, dict): res.extend(unpack(el.items())) else: res.append(el) return res
Write a function ```unpack()``` that unpacks a ```list``` of elements that can contain objects(`int`, `str`, `list`, `tuple`, `dict`, `set`) within each other without any predefined depth, meaning that there can be many levels of elements contained in one another. Example: ```python unpack([None, [1, ({2, 3}, {'foo': 'bar'})]]) == [None, 1, 2, 3, 'foo', 'bar'] ``` Note: you don't have to bother about the order of the elements, especially when unpacking a `dict` or a `set`. Just unpack all the elements.
def unpack(li,s=None): if s is None : s = [] for i in li: if type(i) in [list, tuple, set] : unpack(i,s) elif type(i) == dict : unpack(sum([[k, l] for k, l in i.items()], []),s) else : s.append(i) return s
Write a function ```unpack()``` that unpacks a ```list``` of elements that can contain objects(`int`, `str`, `list`, `tuple`, `dict`, `set`) within each other without any predefined depth, meaning that there can be many levels of elements contained in one another. Example: ```python unpack([None, [1, ({2, 3}, {'foo': 'bar'})]]) == [None, 1, 2, 3, 'foo', 'bar'] ``` Note: you don't have to bother about the order of the elements, especially when unpacking a `dict` or a `set`. Just unpack all the elements.
from collections import Iterable def unpack(xs): queue = xs[:] output = [] while queue: x = queue.pop(0) if type(x) is dict: queue.append(x.items()) elif type(x) != str and isinstance(x, Iterable): queue.extend(x) else: output.append(x) return output
Write a function ```unpack()``` that unpacks a ```list``` of elements that can contain objects(`int`, `str`, `list`, `tuple`, `dict`, `set`) within each other without any predefined depth, meaning that there can be many levels of elements contained in one another. Example: ```python unpack([None, [1, ({2, 3}, {'foo': 'bar'})]]) == [None, 1, 2, 3, 'foo', 'bar'] ``` Note: you don't have to bother about the order of the elements, especially when unpacking a `dict` or a `set`. Just unpack all the elements.
from collections import Iterable def unpack(l): output = [] queue = l[:] while queue: x = queue.pop(0) if type(x) is dict: queue.append(x.items()) elif isinstance(x, Iterable) and type(x) != str: for y in x: queue.append(y) else: output.append(x) return output
Write a function ```unpack()``` that unpacks a ```list``` of elements that can contain objects(`int`, `str`, `list`, `tuple`, `dict`, `set`) within each other without any predefined depth, meaning that there can be many levels of elements contained in one another. Example: ```python unpack([None, [1, ({2, 3}, {'foo': 'bar'})]]) == [None, 1, 2, 3, 'foo', 'bar'] ``` Note: you don't have to bother about the order of the elements, especially when unpacking a `dict` or a `set`. Just unpack all the elements.
def unpack(nested): if type(nested) in (tuple, list, set): return [flat for value in nested for flat in unpack(value)] if type(nested) is dict: return [flat for key, value in list(nested.items()) for flat in unpack(key) + unpack(value)] return [nested]
Write a function ```unpack()``` that unpacks a ```list``` of elements that can contain objects(`int`, `str`, `list`, `tuple`, `dict`, `set`) within each other without any predefined depth, meaning that there can be many levels of elements contained in one another. Example: ```python unpack([None, [1, ({2, 3}, {'foo': 'bar'})]]) == [None, 1, 2, 3, 'foo', 'bar'] ``` Note: you don't have to bother about the order of the elements, especially when unpacking a `dict` or a `set`. Just unpack all the elements.
from collections import Iterable def unpack(l): return [l] if not isinstance(l, Iterable) or type(l) == str else unpack(l.items()) if type(l) == dict else [e for a in [unpack(e) for e in l] for e in a]
You're given a mystery `puzzlebox` object. Examine it to make the tests pass and solve this kata.
def answer(puzzlebox): return 42
You're given a mystery `puzzlebox` object. Examine it to make the tests pass and solve this kata.
def answer(puzzlebox): #print(dir(puzzlebox)) #puzzlebox.hint #print(puzzlebox.hint_two) #print(puzzlebox.lock(puzzlebox.key)) return 42 pass
You're given a mystery `puzzlebox` object. Examine it to make the tests pass and solve this kata.
# 09/01/2019 # I did all the work in the Sample Test section, then after submitting my answer, all of my work in the Sample Test section is gone. # So I'm doing this over and will incude my test data here as so it does not vanish when submitting the work. # I think from now on I will use my local machine so I don't loose all of my testing steps and have to do it all over again. def answer(puzzlebox): # Print statements are your friend. return(42) #*** Below is the test dataand process I used to figure out that returning then number 42 is the the solution to the challenge *** #Printing attributes of puzzlebox print((dir(puzzlebox))) # Returns the puzzlebox object attributes print((list(dir(puzzlebox))[25:30])) #prints attributes with values from puzzlebox [answer, hint, hint_two, key, lock] #See values assigned to the puzzlebox object print((puzzlebox.answer)) # returns "Ha, not quite that easy." print((puzzlebox.hint)) # returns "How do you normally unlock things? print((puzzlebox.hint_two)) # returns "The lock attribute is a method. Have you called it with anything yet? " print((puzzlebox.key)) # returns "50", but running code again returns "78", then "57", so key is a random number print((puzzlebox.lock)) # returns "<bound method Puzzlebox.lock of The built-in dir() function is useful. # Continue adding print statements till you know the answer.> #Try passing stuff to the lock function as suggested by hint_two num = 2 float = 2.3 bool = False str = "hello" print((puzzlebox.lock(num))) # returns "Did you know the key changes each time you print it?" print((puzzlebox.lock(float))) # returns "This method expects an integer." print((puzzlebox.lock(bool))) # return "This method expects an integer." print((puzzlebox.lock(str))) # returns "This method expects an integer." print((puzzlebox.lock(puzzlebox.key))) # returns "You put the key in the lock! The answer is, of course, 42. # Return that number from your answer() function to pass this kata." # HOORAY! Just return the number 42!
You're given a mystery `puzzlebox` object. Examine it to make the tests pass and solve this kata.
import random class Puzzlebox(object): """Puzzlebox for codewars kata.""" def __init__(self): self.key = random.randint(1, 99) answer = "Ha, not quite that easy.\n" hint = "How do you normally unlock things?\n" hint_two = "The lock attribute is a method. Have you called it with anything yet?\n" def lock(self, *args): if len(args) != 1: return "This method expects one argument.\n" elif type(args[0]) != int: return "This method expects an integer.\n" elif args[0] != self.key: return "Did you know the key changes each time you print it?\n" else: return "You put the key in the lock! The answer is, of course, 42. Return that number from your answer() function to pass this kata.\n" def __repr__(self): return "The built-in dir() function is useful. Continue adding print statements till you know the answer.\n" def answer(puzzlebox): return 42 print((answer(puzzlebox)))
You're given a mystery `puzzlebox` object. Examine it to make the tests pass and solve this kata.
#print(dir(puzzlebox)) #print("The answer component of puzzlebox is {}.".format(puzzlebox.answer)) #print("The hint component of puzzlebox is {}.".format(puzzlebox.hint)) #print("The hint_two component of puzzlebox is {}.".format(puzzlebox.hint_two)) #print("The key component of puzzlebox is {}.".format(puzzlebox.key)) #print("The lock component of puzzlebox is {}.".format(puzzlebox.lock)) def answer(puzzlebox): return 42 #The answer component of puzzlebox is Ha, not quite that easy.
You're given a mystery `puzzlebox` object. Examine it to make the tests pass and solve this kata.
def answer(puzzlebox): return 42 print((type(dir(puzzlebox)))) for i in dir(puzzlebox): print(i) x = Puzzlebox() print(x) print((x.answer)) print((x.hint)) print((x.hint_two)) print((x.key)) print((x.lock(x.key))) # x.lock(x.key)
You're given a mystery `puzzlebox` object. Examine it to make the tests pass and solve this kata.
def answer(puzzlebox): # Print statements are your friend. print(dir(puzzlebox)) #print(puzzlebox.answer) print(puzzlebox.hint) print(puzzlebox.hint_two) print(puzzlebox.key) print(puzzlebox.lock(puzzlebox.key)) return 42
You're given a mystery `puzzlebox` object. Examine it to make the tests pass and solve this kata.
def answer(puzzlebox): #print(puzzlebox.key) k=puzzlebox.key print(puzzlebox.lock(k)) return 42
You're given a mystery `puzzlebox` object. Examine it to make the tests pass and solve this kata.
def answer(x): return 42
You're given a mystery `puzzlebox` object. Examine it to make the tests pass and solve this kata.
def answer(puzzlebox): return 42 #print(dir(puzzlebox) # Print statements are your friend. print(dir(puzzlebox)) print(puzzlebox.answer) print(puzzlebox.hint) print(puzzlebox.hint_two) print(puzzlebox.key) print(puzzlebox.lock) print( puzzlebox.lock(puzzlebox.key)) print(puzzlebox.key)
**See Also** * [Traffic Lights - one car](.) * [Traffic Lights - multiple cars](https://www.codewars.com/kata/5d230e119dd9860028167fa5) --- # Overview A character string represents a city road. Cars travel on the road obeying the traffic lights.. Legend: * `.` = Road * `C` = Car * `G` = GREEN traffic light * `O` = ORANGE traffic light * `R` = RED traffic light Something like this: C...R............G...... # Rules ## Simulation At each iteration: 1. the lights change, according to the traffic light rules... then 2. the car moves, obeying the car rules ## Traffic Light Rules Traffic lights change colour as follows: * GREEN for `5` time units... then * ORANGE for `1` time unit... then * RED for `5` time units.... * ... and repeat the cycle ## Car Rules * Cars travel left to right on the road, moving 1 character position per time unit * Cars can move freely until they come to a traffic light. Then: * if the light is GREEN they can move forward (temporarily occupying the same cell as the light) * if the light is ORANGE then they must stop (if they have already entered the intersection they can continue through) * if the light is RED the car must stop until the light turns GREEN again # Kata Task Given the initial state of the road, return the states for all iterations of the simiulation. ## Input * `road` = the road array * `n` = how many time units to simulate (n >= 0) ## Output * An array containing the road states at every iteration (including the initial state) * Note: If a car occupies the same position as a traffic light then show only the car ## Notes * There is only one car * For the initial road state * the car is always at the first character position * traffic lights are either GREEN or RED, and are at the beginning of their countdown cycles * There are no reaction delays - when the lights change the car drivers will react immediately! * If the car goes off the end of the road it just disappears from view * There will always be some road between adjacent traffic lights # Example Run simulation for 10 time units **Input** * `road = "C...R............G......"` * `n = 10` **Result** --- Good luck! DM
def traffic_lights(road, n): lightsIdx = [ (i, 6*(c!='G')) for i,c in enumerate(road) if c in 'RG' ] car, ref = road.find('C'), road.replace('C','.') mut, out = list(ref), [road] for turn in range(1,n+1): for i,delta in lightsIdx: # Update all lights state = (delta+turn) % 11 mut[i] = 'G' if state<5 else 'O' if state==5 else 'R' car += car+1>=len(road) or mut[car+1] in '.G' # Move the car if possible (even if outside of the road) if car<len(road): old, mut[car] = mut[car], 'C' # Update, archive, then restore the road state out.append(''.join(mut)) if car<len(road): mut[car] = old return out
**See Also** * [Traffic Lights - one car](.) * [Traffic Lights - multiple cars](https://www.codewars.com/kata/5d230e119dd9860028167fa5) --- # Overview A character string represents a city road. Cars travel on the road obeying the traffic lights.. Legend: * `.` = Road * `C` = Car * `G` = GREEN traffic light * `O` = ORANGE traffic light * `R` = RED traffic light Something like this: C...R............G...... # Rules ## Simulation At each iteration: 1. the lights change, according to the traffic light rules... then 2. the car moves, obeying the car rules ## Traffic Light Rules Traffic lights change colour as follows: * GREEN for `5` time units... then * ORANGE for `1` time unit... then * RED for `5` time units.... * ... and repeat the cycle ## Car Rules * Cars travel left to right on the road, moving 1 character position per time unit * Cars can move freely until they come to a traffic light. Then: * if the light is GREEN they can move forward (temporarily occupying the same cell as the light) * if the light is ORANGE then they must stop (if they have already entered the intersection they can continue through) * if the light is RED the car must stop until the light turns GREEN again # Kata Task Given the initial state of the road, return the states for all iterations of the simiulation. ## Input * `road` = the road array * `n` = how many time units to simulate (n >= 0) ## Output * An array containing the road states at every iteration (including the initial state) * Note: If a car occupies the same position as a traffic light then show only the car ## Notes * There is only one car * For the initial road state * the car is always at the first character position * traffic lights are either GREEN or RED, and are at the beginning of their countdown cycles * There are no reaction delays - when the lights change the car drivers will react immediately! * If the car goes off the end of the road it just disappears from view * There will always be some road between adjacent traffic lights # Example Run simulation for 10 time units **Input** * `road = "C...R............G......"` * `n = 10` **Result** --- Good luck! DM
from itertools import cycle def traffic_lights(road, n): light1 = iter(cycle( 'RRRRRGGGGGO' )) light2 = iter(cycle( 'GGGGGORRRRR' )) traffic , car = [], -1 for _ in range(n+1): temp, RL, GL = [], next(light1), next(light2) for i in range(len(road)): temp.append( { 'R':RL, 'G':GL }.get(road[i], '.') ) if car<len(temp)-1 and temp[car+1] in 'RO': car -=1 car +=1 if car<len(temp): temp[car] = 'C' traffic.append(''.join(temp)) return traffic
**See Also** * [Traffic Lights - one car](.) * [Traffic Lights - multiple cars](https://www.codewars.com/kata/5d230e119dd9860028167fa5) --- # Overview A character string represents a city road. Cars travel on the road obeying the traffic lights.. Legend: * `.` = Road * `C` = Car * `G` = GREEN traffic light * `O` = ORANGE traffic light * `R` = RED traffic light Something like this: C...R............G...... # Rules ## Simulation At each iteration: 1. the lights change, according to the traffic light rules... then 2. the car moves, obeying the car rules ## Traffic Light Rules Traffic lights change colour as follows: * GREEN for `5` time units... then * ORANGE for `1` time unit... then * RED for `5` time units.... * ... and repeat the cycle ## Car Rules * Cars travel left to right on the road, moving 1 character position per time unit * Cars can move freely until they come to a traffic light. Then: * if the light is GREEN they can move forward (temporarily occupying the same cell as the light) * if the light is ORANGE then they must stop (if they have already entered the intersection they can continue through) * if the light is RED the car must stop until the light turns GREEN again # Kata Task Given the initial state of the road, return the states for all iterations of the simiulation. ## Input * `road` = the road array * `n` = how many time units to simulate (n >= 0) ## Output * An array containing the road states at every iteration (including the initial state) * Note: If a car occupies the same position as a traffic light then show only the car ## Notes * There is only one car * For the initial road state * the car is always at the first character position * traffic lights are either GREEN or RED, and are at the beginning of their countdown cycles * There are no reaction delays - when the lights change the car drivers will react immediately! * If the car goes off the end of the road it just disappears from view * There will always be some road between adjacent traffic lights # Example Run simulation for 10 time units **Input** * `road = "C...R............G......"` * `n = 10` **Result** --- Good luck! DM
def traffic_lights(road, n): light_cycle = {"R": "RRRRRGGGGGO", "G": "GGGGGORRRRR"} lights = {pos: light_cycle[light] for pos, light in enumerate(road) if light in light_cycle} car, result = 0, [road] for state in range(1 , n + 1): if car+1 not in lights or lights[car+1][state%11] not in "OR": car += 1 result.append("".join("C" if pos == car else lights[pos][state%11] if pos in lights else "." for pos in range(len(road)))) return result
**See Also** * [Traffic Lights - one car](.) * [Traffic Lights - multiple cars](https://www.codewars.com/kata/5d230e119dd9860028167fa5) --- # Overview A character string represents a city road. Cars travel on the road obeying the traffic lights.. Legend: * `.` = Road * `C` = Car * `G` = GREEN traffic light * `O` = ORANGE traffic light * `R` = RED traffic light Something like this: C...R............G...... # Rules ## Simulation At each iteration: 1. the lights change, according to the traffic light rules... then 2. the car moves, obeying the car rules ## Traffic Light Rules Traffic lights change colour as follows: * GREEN for `5` time units... then * ORANGE for `1` time unit... then * RED for `5` time units.... * ... and repeat the cycle ## Car Rules * Cars travel left to right on the road, moving 1 character position per time unit * Cars can move freely until they come to a traffic light. Then: * if the light is GREEN they can move forward (temporarily occupying the same cell as the light) * if the light is ORANGE then they must stop (if they have already entered the intersection they can continue through) * if the light is RED the car must stop until the light turns GREEN again # Kata Task Given the initial state of the road, return the states for all iterations of the simiulation. ## Input * `road` = the road array * `n` = how many time units to simulate (n >= 0) ## Output * An array containing the road states at every iteration (including the initial state) * Note: If a car occupies the same position as a traffic light then show only the car ## Notes * There is only one car * For the initial road state * the car is always at the first character position * traffic lights are either GREEN or RED, and are at the beginning of their countdown cycles * There are no reaction delays - when the lights change the car drivers will react immediately! * If the car goes off the end of the road it just disappears from view * There will always be some road between adjacent traffic lights # Example Run simulation for 10 time units **Input** * `road = "C...R............G......"` * `n = 10` **Result** --- Good luck! DM
def light_changes_iter(n, *args): ''' n - no. iterations args is a pattern in a form of tuple stores the iterations where lights must be changed ''' iteration = 0 tup = () while True: for x in args: iteration += x tup += (iteration,) #append tuple if max(tup) > n: return tup[:-1] #pop out last element, it is above last iteration def shift_lights(road_state, init_state): ''' current road_state initial_state - list with the indexes of the initial light state current_pos - current position of the car to be updated pos_index - position of the car ''' temp = road_state.split(" ") #string to list #only updates the positions correspondent to the initial signal #change current_pos if the car is in the same position as a signal for index in init_state: if temp[0][index] == "O": temp[0] = temp[0][:index] + "R" + temp[0][index+1:] elif temp[0][index] == "G": temp[0] = temp[0][:index] + "O" + temp[0][index+1:] elif temp[0][index] == "R": temp[0] = temp[0][:index] + "G" + temp[0][index+1:] return "".join(temp) def traffic_lights(road_state, n): ''' road_state is a list with the initial road state ''' road = [] + [road_state] #store road progress in a list road_simulated = "." + road_state[1:] #simulates road without car #iterations where light changes if position starts with green, orange, red green = light_changes_iter(n, 5,1,5) orange = light_changes_iter(n, 1,5,5) red = light_changes_iter(n, 5,5,1) #store the indexes of initial states of the lights to keep track #how they should change across iterations init_green = [i for i,char in enumerate(road_simulated) if char == "G"] init_orange = [i for i,char in enumerate(road_simulated) if char == "O"] init_red = [i for i,char in enumerate(road_simulated) if char == "R"] #start variables pos_index = 0 #current position of the car for ite in range(1,n+1): #update lights according to iteration if ite in green: road_simulated = shift_lights(road_simulated, init_green) if ite in orange: road_simulated = shift_lights(road_simulated, init_orange) if ite in red: road_simulated = shift_lights(road_simulated, init_red) try: #check if car should stop if road_simulated[pos_index + 1] in ("O", "R"): road_state = road_simulated[:pos_index] + "C" + road_simulated[pos_index+1:] road.append(road_state) continue #move the car pos_index += 1 road_state = road_simulated[:pos_index] + "C" + road_simulated[pos_index+1:] road.append(road_state) except IndexError: #last iteration, car goes out of road road.append(road_simulated) return road
**See Also** * [Traffic Lights - one car](.) * [Traffic Lights - multiple cars](https://www.codewars.com/kata/5d230e119dd9860028167fa5) --- # Overview A character string represents a city road. Cars travel on the road obeying the traffic lights.. Legend: * `.` = Road * `C` = Car * `G` = GREEN traffic light * `O` = ORANGE traffic light * `R` = RED traffic light Something like this: C...R............G...... # Rules ## Simulation At each iteration: 1. the lights change, according to the traffic light rules... then 2. the car moves, obeying the car rules ## Traffic Light Rules Traffic lights change colour as follows: * GREEN for `5` time units... then * ORANGE for `1` time unit... then * RED for `5` time units.... * ... and repeat the cycle ## Car Rules * Cars travel left to right on the road, moving 1 character position per time unit * Cars can move freely until they come to a traffic light. Then: * if the light is GREEN they can move forward (temporarily occupying the same cell as the light) * if the light is ORANGE then they must stop (if they have already entered the intersection they can continue through) * if the light is RED the car must stop until the light turns GREEN again # Kata Task Given the initial state of the road, return the states for all iterations of the simiulation. ## Input * `road` = the road array * `n` = how many time units to simulate (n >= 0) ## Output * An array containing the road states at every iteration (including the initial state) * Note: If a car occupies the same position as a traffic light then show only the car ## Notes * There is only one car * For the initial road state * the car is always at the first character position * traffic lights are either GREEN or RED, and are at the beginning of their countdown cycles * There are no reaction delays - when the lights change the car drivers will react immediately! * If the car goes off the end of the road it just disappears from view * There will always be some road between adjacent traffic lights # Example Run simulation for 10 time units **Input** * `road = "C...R............G......"` * `n = 10` **Result** --- Good luck! DM
def traffic_lights(road, n): print(road) index_red_init = [i for i,j in enumerate(road) if j =='R'] index_green_init = [i for i,j in enumerate(road) if j =='G'] index_orange_init = [i for i,j in enumerate(road) if j =='O'] print(index_green_init) #print(type(road)) road_lst = [i for i in road] red_init = 'RRRRRGGGGGO' green_init = 'GGGGGORRRRR' orange_init = 'ORRRRRGGGGG' index_car = 0 time = 0 count = 0 car_index = -1 final = [] while time <= n and car_index <= len(road) - 1: #if car_index == len(road) - 1: if count >= len(red_init): count = count - len(red_init) for i in index_red_init: road_lst[i] = red_init[count] for i in index_green_init: road_lst[i] = green_init[count] for i in index_orange_init: road_lst[i] = orange_init[count] #print(car_index + 1) if car_index != len(road) - 1: if road_lst[car_index + 1] == 'R': car_index = car_index elif road_lst[car_index + 1] == 'O': car_index = car_index else: car_index += 1 road_lst[car_index] = 'C' elif road[-1] == 'R': road_lst[-1] = red_init[count] elif road[-1] == 'G': road_lst[-1] = green_init[count] elif road[-1] == 'O': road_lst[-1] = orange_init[count] else: road_lst[-1] = '.' if car_index - 1 in index_red_init: road_lst[car_index - 1] = red_init[count] elif car_index - 1 in index_green_init: road_lst[car_index - 1] = green_init[count] elif car_index - 1 in index_orange_init: road_lst[car_index - 1] = orange_init[count] elif car_index - 1 >= 0: road_lst[car_index - 1] = '.' result = ''.join(road_lst) final.append(result) count += 1 time += 1 return final
**See Also** * [Traffic Lights - one car](.) * [Traffic Lights - multiple cars](https://www.codewars.com/kata/5d230e119dd9860028167fa5) --- # Overview A character string represents a city road. Cars travel on the road obeying the traffic lights.. Legend: * `.` = Road * `C` = Car * `G` = GREEN traffic light * `O` = ORANGE traffic light * `R` = RED traffic light Something like this: C...R............G...... # Rules ## Simulation At each iteration: 1. the lights change, according to the traffic light rules... then 2. the car moves, obeying the car rules ## Traffic Light Rules Traffic lights change colour as follows: * GREEN for `5` time units... then * ORANGE for `1` time unit... then * RED for `5` time units.... * ... and repeat the cycle ## Car Rules * Cars travel left to right on the road, moving 1 character position per time unit * Cars can move freely until they come to a traffic light. Then: * if the light is GREEN they can move forward (temporarily occupying the same cell as the light) * if the light is ORANGE then they must stop (if they have already entered the intersection they can continue through) * if the light is RED the car must stop until the light turns GREEN again # Kata Task Given the initial state of the road, return the states for all iterations of the simiulation. ## Input * `road` = the road array * `n` = how many time units to simulate (n >= 0) ## Output * An array containing the road states at every iteration (including the initial state) * Note: If a car occupies the same position as a traffic light then show only the car ## Notes * There is only one car * For the initial road state * the car is always at the first character position * traffic lights are either GREEN or RED, and are at the beginning of their countdown cycles * There are no reaction delays - when the lights change the car drivers will react immediately! * If the car goes off the end of the road it just disappears from view * There will always be some road between adjacent traffic lights # Example Run simulation for 10 time units **Input** * `road = "C...R............G......"` * `n = 10` **Result** --- Good luck! DM
def traffic_lights(road, n): C, D, res = 0, {i:[c, 0] for i,c in enumerate(road) if c in "GOR"}, [road] def updateLights(): for i, (c, k) in D.items(): if c == 'G': if k == 4: D[i] = ('O', 0) else: D[i] = ('G', k+1) elif c == 'O': D[i] = ('R', 0) elif k == 4: D[i] = ('G', 0) else: D[i] = ('R', k+1) for _ in range(n): updateLights() if not (C+1) in D or D[C+1][0] == 'G': C += 1 res.append(''.join('C' if i == C else D[i][0] if i in D else '.' for i in range(len(road)))) return res
**See Also** * [Traffic Lights - one car](.) * [Traffic Lights - multiple cars](https://www.codewars.com/kata/5d230e119dd9860028167fa5) --- # Overview A character string represents a city road. Cars travel on the road obeying the traffic lights.. Legend: * `.` = Road * `C` = Car * `G` = GREEN traffic light * `O` = ORANGE traffic light * `R` = RED traffic light Something like this: C...R............G...... # Rules ## Simulation At each iteration: 1. the lights change, according to the traffic light rules... then 2. the car moves, obeying the car rules ## Traffic Light Rules Traffic lights change colour as follows: * GREEN for `5` time units... then * ORANGE for `1` time unit... then * RED for `5` time units.... * ... and repeat the cycle ## Car Rules * Cars travel left to right on the road, moving 1 character position per time unit * Cars can move freely until they come to a traffic light. Then: * if the light is GREEN they can move forward (temporarily occupying the same cell as the light) * if the light is ORANGE then they must stop (if they have already entered the intersection they can continue through) * if the light is RED the car must stop until the light turns GREEN again # Kata Task Given the initial state of the road, return the states for all iterations of the simiulation. ## Input * `road` = the road array * `n` = how many time units to simulate (n >= 0) ## Output * An array containing the road states at every iteration (including the initial state) * Note: If a car occupies the same position as a traffic light then show only the car ## Notes * There is only one car * For the initial road state * the car is always at the first character position * traffic lights are either GREEN or RED, and are at the beginning of their countdown cycles * There are no reaction delays - when the lights change the car drivers will react immediately! * If the car goes off the end of the road it just disappears from view * There will always be some road between adjacent traffic lights # Example Run simulation for 10 time units **Input** * `road = "C...R............G......"` * `n = 10` **Result** --- Good luck! DM
class TrafficUnit: def __init__(self, color): # '.': road # 'R'/'G'/'B': light self.color = color self.t = 0 def can_pass(self): return self.color is '.' or self.color == 'G' def step(self): self.t = (self.t + 1) % 5 if self.color == 'G': if self.t == 0: self.color = 'O' elif self.color == 'O': self.color = 'R' self.t = 0 elif self.color == 'R': if self.t == 0: self.color = 'G' return self def __str__(self): return self.color def traffic_lights(road, n): def f(): car_pos = 0 units = [TrafficUnit(c.replace('C', '.')) for c in road + '.'] for i in range(n+1): xs = list(map(str, units)) if car_pos < len(road): xs[car_pos] = 'C' yield ''.join(xs[:-1]) units = [unit.step() for unit in units] if car_pos < len(road) and units[car_pos+1].can_pass(): car_pos += 1 return list(f())
**See Also** * [Traffic Lights - one car](.) * [Traffic Lights - multiple cars](https://www.codewars.com/kata/5d230e119dd9860028167fa5) --- # Overview A character string represents a city road. Cars travel on the road obeying the traffic lights.. Legend: * `.` = Road * `C` = Car * `G` = GREEN traffic light * `O` = ORANGE traffic light * `R` = RED traffic light Something like this: C...R............G...... # Rules ## Simulation At each iteration: 1. the lights change, according to the traffic light rules... then 2. the car moves, obeying the car rules ## Traffic Light Rules Traffic lights change colour as follows: * GREEN for `5` time units... then * ORANGE for `1` time unit... then * RED for `5` time units.... * ... and repeat the cycle ## Car Rules * Cars travel left to right on the road, moving 1 character position per time unit * Cars can move freely until they come to a traffic light. Then: * if the light is GREEN they can move forward (temporarily occupying the same cell as the light) * if the light is ORANGE then they must stop (if they have already entered the intersection they can continue through) * if the light is RED the car must stop until the light turns GREEN again # Kata Task Given the initial state of the road, return the states for all iterations of the simiulation. ## Input * `road` = the road array * `n` = how many time units to simulate (n >= 0) ## Output * An array containing the road states at every iteration (including the initial state) * Note: If a car occupies the same position as a traffic light then show only the car ## Notes * There is only one car * For the initial road state * the car is always at the first character position * traffic lights are either GREEN or RED, and are at the beginning of their countdown cycles * There are no reaction delays - when the lights change the car drivers will react immediately! * If the car goes off the end of the road it just disappears from view * There will always be some road between adjacent traffic lights # Example Run simulation for 10 time units **Input** * `road = "C...R............G......"` * `n = 10` **Result** --- Good luck! DM
def traffic_lights(road, n): k, car, res = 'GGGGGORRRRR', 0, [] for i in range(n+1): lights = [k[(k.index(s) + i) % 11] if s in 'ROG' else '.' for s in road] if car < len(road) - 1: if i: car += lights[car+1] not in 'RO' lights[car] = 'C' res.append(''.join(lights)) return res
**See Also** * [Traffic Lights - one car](.) * [Traffic Lights - multiple cars](https://www.codewars.com/kata/5d230e119dd9860028167fa5) --- # Overview A character string represents a city road. Cars travel on the road obeying the traffic lights.. Legend: * `.` = Road * `C` = Car * `G` = GREEN traffic light * `O` = ORANGE traffic light * `R` = RED traffic light Something like this: C...R............G...... # Rules ## Simulation At each iteration: 1. the lights change, according to the traffic light rules... then 2. the car moves, obeying the car rules ## Traffic Light Rules Traffic lights change colour as follows: * GREEN for `5` time units... then * ORANGE for `1` time unit... then * RED for `5` time units.... * ... and repeat the cycle ## Car Rules * Cars travel left to right on the road, moving 1 character position per time unit * Cars can move freely until they come to a traffic light. Then: * if the light is GREEN they can move forward (temporarily occupying the same cell as the light) * if the light is ORANGE then they must stop (if they have already entered the intersection they can continue through) * if the light is RED the car must stop until the light turns GREEN again # Kata Task Given the initial state of the road, return the states for all iterations of the simiulation. ## Input * `road` = the road array * `n` = how many time units to simulate (n >= 0) ## Output * An array containing the road states at every iteration (including the initial state) * Note: If a car occupies the same position as a traffic light then show only the car ## Notes * There is only one car * For the initial road state * the car is always at the first character position * traffic lights are either GREEN or RED, and are at the beginning of their countdown cycles * There are no reaction delays - when the lights change the car drivers will react immediately! * If the car goes off the end of the road it just disappears from view * There will always be some road between adjacent traffic lights # Example Run simulation for 10 time units **Input** * `road = "C...R............G......"` * `n = 10` **Result** --- Good luck! DM
def traffic_lights(road, n): empty = '.'*len(road) r = [road]+[empty]*n l = 10*(5*'G'+'O'+5*'R') for i in range(len(road)): if road[i] in l: for j in range(n+1): r[j] = r[j][:i]+l[j+l.index(road[i])]+r[j][i+1:] for i in range(n): if 'C' in r[i][:-1]: c = r[i][:-1].index('C') if r[i+1][c+1] is 'R' or r[i+1][c+1] is 'O': r[i+1] = r[i+1][:c]+'C'+r[i+1][c+1:] else: r[i+1] = r[i+1][:c+1]+'C'+r[i+1][c+2:] return r
**See Also** * [Traffic Lights - one car](.) * [Traffic Lights - multiple cars](https://www.codewars.com/kata/5d230e119dd9860028167fa5) --- # Overview A character string represents a city road. Cars travel on the road obeying the traffic lights.. Legend: * `.` = Road * `C` = Car * `G` = GREEN traffic light * `O` = ORANGE traffic light * `R` = RED traffic light Something like this: C...R............G...... # Rules ## Simulation At each iteration: 1. the lights change, according to the traffic light rules... then 2. the car moves, obeying the car rules ## Traffic Light Rules Traffic lights change colour as follows: * GREEN for `5` time units... then * ORANGE for `1` time unit... then * RED for `5` time units.... * ... and repeat the cycle ## Car Rules * Cars travel left to right on the road, moving 1 character position per time unit * Cars can move freely until they come to a traffic light. Then: * if the light is GREEN they can move forward (temporarily occupying the same cell as the light) * if the light is ORANGE then they must stop (if they have already entered the intersection they can continue through) * if the light is RED the car must stop until the light turns GREEN again # Kata Task Given the initial state of the road, return the states for all iterations of the simiulation. ## Input * `road` = the road array * `n` = how many time units to simulate (n >= 0) ## Output * An array containing the road states at every iteration (including the initial state) * Note: If a car occupies the same position as a traffic light then show only the car ## Notes * There is only one car * For the initial road state * the car is always at the first character position * traffic lights are either GREEN or RED, and are at the beginning of their countdown cycles * There are no reaction delays - when the lights change the car drivers will react immediately! * If the car goes off the end of the road it just disappears from view * There will always be some road between adjacent traffic lights # Example Run simulation for 10 time units **Input** * `road = "C...R............G......"` * `n = 10` **Result** --- Good luck! DM
def traffic_lights(road,n): a,b,c = 'GGGGGORRRRR','ORRRRRGGGGG','RRRRRGGGGGO' r,p = [road],0 for i in range(1,n+1): t = [a[i%11] if x=='G' else b[i%11] if x=='O' else c[i%11] if x=='R' else x for x in road] if p<len(road)-1: if t[p+1] not in 'RO': p += 1 t[p] = 'C' elif t[p+1] in 'RO': t[p] = 'C' t[0] = 'C' if p==0 else '.' r.append(''.join(t)) return r
# Task When a candle finishes burning it leaves a leftover. makeNew leftovers can be combined to make a new candle, which, when burning down, will in turn leave another leftover. You have candlesNumber candles in your possession. What's the total number of candles you can burn, assuming that you create new candles as soon as you have enough leftovers? # Example For candlesNumber = 5 and makeNew = 2, the output should be `9`. Here is what you can do to burn 9 candles: ``` burn 5 candles, obtain 5 leftovers; create 2 more candles, using 4 leftovers (1 leftover remains); burn 2 candles, end up with 3 leftovers; create another candle using 2 leftovers (1 leftover remains); burn the created candle, which gives another leftover (2 leftovers in total); create a candle from the remaining leftovers; burn the last candle. Thus, you can burn 5 + 2 + 1 + 1 = 9 candles, which is the answer. ``` # Input/Output - `[input]` integer `candlesNumber` The number of candles you have in your possession. Constraints: 1 ≤ candlesNumber ≤ 50. - `[input]` integer `makeNew` The number of leftovers that you can use up to create a new candle. Constraints: 2 ≤ makeNew ≤ 5. - `[output]` an integer
def candles(candles, make_new): return candles + (candles - 1) // (make_new - 1)
# Task When a candle finishes burning it leaves a leftover. makeNew leftovers can be combined to make a new candle, which, when burning down, will in turn leave another leftover. You have candlesNumber candles in your possession. What's the total number of candles you can burn, assuming that you create new candles as soon as you have enough leftovers? # Example For candlesNumber = 5 and makeNew = 2, the output should be `9`. Here is what you can do to burn 9 candles: ``` burn 5 candles, obtain 5 leftovers; create 2 more candles, using 4 leftovers (1 leftover remains); burn 2 candles, end up with 3 leftovers; create another candle using 2 leftovers (1 leftover remains); burn the created candle, which gives another leftover (2 leftovers in total); create a candle from the remaining leftovers; burn the last candle. Thus, you can burn 5 + 2 + 1 + 1 = 9 candles, which is the answer. ``` # Input/Output - `[input]` integer `candlesNumber` The number of candles you have in your possession. Constraints: 1 ≤ candlesNumber ≤ 50. - `[input]` integer `makeNew` The number of leftovers that you can use up to create a new candle. Constraints: 2 ≤ makeNew ≤ 5. - `[output]` an integer
def candles(m, n): burn = leftover = 0 while m: burn += m m, leftover = divmod(leftover + m, n) return burn
# Task When a candle finishes burning it leaves a leftover. makeNew leftovers can be combined to make a new candle, which, when burning down, will in turn leave another leftover. You have candlesNumber candles in your possession. What's the total number of candles you can burn, assuming that you create new candles as soon as you have enough leftovers? # Example For candlesNumber = 5 and makeNew = 2, the output should be `9`. Here is what you can do to burn 9 candles: ``` burn 5 candles, obtain 5 leftovers; create 2 more candles, using 4 leftovers (1 leftover remains); burn 2 candles, end up with 3 leftovers; create another candle using 2 leftovers (1 leftover remains); burn the created candle, which gives another leftover (2 leftovers in total); create a candle from the remaining leftovers; burn the last candle. Thus, you can burn 5 + 2 + 1 + 1 = 9 candles, which is the answer. ``` # Input/Output - `[input]` integer `candlesNumber` The number of candles you have in your possession. Constraints: 1 ≤ candlesNumber ≤ 50. - `[input]` integer `makeNew` The number of leftovers that you can use up to create a new candle. Constraints: 2 ≤ makeNew ≤ 5. - `[output]` an integer
def candles(a, b): return a + (a - 1) // (b - 1)