Datasets:

inputs
stringlengths
50
14k
targets
stringlengths
4
655k
In this simple exercise, you will create a program that will take two lists of integers, ```a``` and ```b```. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids ```a``` and ```b```. You must find the difference of the cuboids' volumes regardless of which is bigger. For example, if the parameters passed are ```([2, 2, 3], [5, 4, 1])```, the volume of ```a``` is 12 and the volume of ```b``` is 20. Therefore, the function should return ```8```. Your function will be tested with pre-made examples as well as random ones. **If you can, try writing it in one line of code.**
def find_difference(a, b): x = 1 y = 1 for i in a: x = x * i for i in b: y = y * i return x-y if x-y>0 else y-x
In this simple exercise, you will create a program that will take two lists of integers, ```a``` and ```b```. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids ```a``` and ```b```. You must find the difference of the cuboids' volumes regardless of which is bigger. For example, if the parameters passed are ```([2, 2, 3], [5, 4, 1])```, the volume of ```a``` is 12 and the volume of ```b``` is 20. Therefore, the function should return ```8```. Your function will be tested with pre-made examples as well as random ones. **If you can, try writing it in one line of code.**
def volume(lens): return lens[0] * lens[1] * lens[2] def find_difference(a, b): return abs(volume(a) - volume(b))
In this simple exercise, you will create a program that will take two lists of integers, ```a``` and ```b```. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids ```a``` and ```b```. You must find the difference of the cuboids' volumes regardless of which is bigger. For example, if the parameters passed are ```([2, 2, 3], [5, 4, 1])```, the volume of ```a``` is 12 and the volume of ```b``` is 20. Therefore, the function should return ```8```. Your function will be tested with pre-made examples as well as random ones. **If you can, try writing it in one line of code.**
def find_difference(a, b): accumulator1 = 1 accumulator2 = 1 for eachvalue in a: accumulator1 = accumulator1 * eachvalue for eachvalue in b: accumulator2 = accumulator2 * eachvalue return abs(accumulator1 - accumulator2)
In this simple exercise, you will create a program that will take two lists of integers, ```a``` and ```b```. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids ```a``` and ```b```. You must find the difference of the cuboids' volumes regardless of which is bigger. For example, if the parameters passed are ```([2, 2, 3], [5, 4, 1])```, the volume of ```a``` is 12 and the volume of ```b``` is 20. Therefore, the function should return ```8```. Your function will be tested with pre-made examples as well as random ones. **If you can, try writing it in one line of code.**
def find_difference(a, b): x, y, z = a[0], a[1], a[2] r, s, t = b[0], b[1], b[2] volume1 = x * y * z volume2 = r * s * t difference = volume1 - volume2 if volume1 > volume2: return difference else: return -difference
In this simple exercise, you will create a program that will take two lists of integers, ```a``` and ```b```. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids ```a``` and ```b```. You must find the difference of the cuboids' volumes regardless of which is bigger. For example, if the parameters passed are ```([2, 2, 3], [5, 4, 1])```, the volume of ```a``` is 12 and the volume of ```b``` is 20. Therefore, the function should return ```8```. Your function will be tested with pre-made examples as well as random ones. **If you can, try writing it in one line of code.**
def find_difference(a, b): vol1=1 vol2=1 for i in range(len(a)): vol1=vol1*a[i] vol2=vol2*b[i] return max(vol1,vol2)-min(vol1,vol2)
In this simple exercise, you will create a program that will take two lists of integers, ```a``` and ```b```. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids ```a``` and ```b```. You must find the difference of the cuboids' volumes regardless of which is bigger. For example, if the parameters passed are ```([2, 2, 3], [5, 4, 1])```, the volume of ```a``` is 12 and the volume of ```b``` is 20. Therefore, the function should return ```8```. Your function will be tested with pre-made examples as well as random ones. **If you can, try writing it in one line of code.**
from functools import reduce def find_difference(a, b): a_vol = reduce(lambda x, y: x*y, a) b_vol = reduce(lambda x, y: x*y, b) return max(a_vol, b_vol) - min(a_vol, b_vol)
In this simple exercise, you will create a program that will take two lists of integers, ```a``` and ```b```. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids ```a``` and ```b```. You must find the difference of the cuboids' volumes regardless of which is bigger. For example, if the parameters passed are ```([2, 2, 3], [5, 4, 1])```, the volume of ```a``` is 12 and the volume of ```b``` is 20. Therefore, the function should return ```8```. Your function will be tested with pre-made examples as well as random ones. **If you can, try writing it in one line of code.**
def find_difference(a, b): print((a,b)) resulta = 1 resultb = 1 for aa in a: resulta = aa * resulta print((resulta, 'resulta')) for bb in b: resultb = bb * resultb print((resultb, 'resultb')) if resulta > resultb: return resulta - resultb else: return resultb - resulta
In this simple exercise, you will create a program that will take two lists of integers, ```a``` and ```b```. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids ```a``` and ```b```. You must find the difference of the cuboids' volumes regardless of which is bigger. For example, if the parameters passed are ```([2, 2, 3], [5, 4, 1])```, the volume of ```a``` is 12 and the volume of ```b``` is 20. Therefore, the function should return ```8```. Your function will be tested with pre-made examples as well as random ones. **If you can, try writing it in one line of code.**
def find_difference(a, b): v1 = a[0] * a[1] * a[2] v2 = b[0] * b[1] * b[2] if(v1>v2): return v1 - v2 else: return v2 - v1 # Your code here!
In this simple exercise, you will create a program that will take two lists of integers, ```a``` and ```b```. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids ```a``` and ```b```. You must find the difference of the cuboids' volumes regardless of which is bigger. For example, if the parameters passed are ```([2, 2, 3], [5, 4, 1])```, the volume of ```a``` is 12 and the volume of ```b``` is 20. Therefore, the function should return ```8```. Your function will be tested with pre-made examples as well as random ones. **If you can, try writing it in one line of code.**
def find_difference(a, b): qa = a[0] * a[1] * a[2] qb = b[0] * b[1] * b[2] return qa - qb if qa > qb else qb - qa
In this simple exercise, you will create a program that will take two lists of integers, ```a``` and ```b```. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids ```a``` and ```b```. You must find the difference of the cuboids' volumes regardless of which is bigger. For example, if the parameters passed are ```([2, 2, 3], [5, 4, 1])```, the volume of ```a``` is 12 and the volume of ```b``` is 20. Therefore, the function should return ```8```. Your function will be tested with pre-made examples as well as random ones. **If you can, try writing it in one line of code.**
def find_difference(a, b): res1 = a[0] * a[1] * a[2] res2 = b[0] * b[1] * b[2] if res2 > res1: res = res2 - res1 else: res = res1 - res2 return res
In this simple exercise, you will create a program that will take two lists of integers, ```a``` and ```b```. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids ```a``` and ```b```. You must find the difference of the cuboids' volumes regardless of which is bigger. For example, if the parameters passed are ```([2, 2, 3], [5, 4, 1])```, the volume of ```a``` is 12 and the volume of ```b``` is 20. Therefore, the function should return ```8```. Your function will be tested with pre-made examples as well as random ones. **If you can, try writing it in one line of code.**
from functools import reduce vol = lambda l: reduce(lambda x,y:x * y, l) def find_difference(a, b): return abs(vol(b)-vol(a))
In this simple exercise, you will create a program that will take two lists of integers, ```a``` and ```b```. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids ```a``` and ```b```. You must find the difference of the cuboids' volumes regardless of which is bigger. For example, if the parameters passed are ```([2, 2, 3], [5, 4, 1])```, the volume of ```a``` is 12 and the volume of ```b``` is 20. Therefore, the function should return ```8```. Your function will be tested with pre-made examples as well as random ones. **If you can, try writing it in one line of code.**
def find_difference(a, b): d1 = a[0] a = a[1:] d2 = b[0] b = b[1:] for i in b: d2*=i for i in a: d1*=i total = d1-d2 if total >= 0 : return total else: return -total
In this simple exercise, you will create a program that will take two lists of integers, ```a``` and ```b```. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids ```a``` and ```b```. You must find the difference of the cuboids' volumes regardless of which is bigger. For example, if the parameters passed are ```([2, 2, 3], [5, 4, 1])```, the volume of ```a``` is 12 and the volume of ```b``` is 20. Therefore, the function should return ```8```. Your function will be tested with pre-made examples as well as random ones. **If you can, try writing it in one line of code.**
def find_difference(a, b): cube1 = 1 cube2 = 1 for x in a: cube1 = cube1 * x for y in b: cube2 = cube2 * y if cube1 >= cube2: return cube1 - cube2 else: return cube2 - cube1
In this simple exercise, you will create a program that will take two lists of integers, ```a``` and ```b```. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids ```a``` and ```b```. You must find the difference of the cuboids' volumes regardless of which is bigger. For example, if the parameters passed are ```([2, 2, 3], [5, 4, 1])```, the volume of ```a``` is 12 and the volume of ```b``` is 20. Therefore, the function should return ```8```. Your function will be tested with pre-made examples as well as random ones. **If you can, try writing it in one line of code.**
from numpy import prod as vol def find_difference(a, b): return abs(vol(a)-vol(b))
In this simple exercise, you will create a program that will take two lists of integers, ```a``` and ```b```. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids ```a``` and ```b```. You must find the difference of the cuboids' volumes regardless of which is bigger. For example, if the parameters passed are ```([2, 2, 3], [5, 4, 1])```, the volume of ```a``` is 12 and the volume of ```b``` is 20. Therefore, the function should return ```8```. Your function will be tested with pre-made examples as well as random ones. **If you can, try writing it in one line of code.**
def find_difference(a, b): sum1 = 1 sum2 = 1 for i in a: sum1 = sum1 * i for j in b: sum2 = sum2 * j return abs(sum1 - sum2)
In this simple exercise, you will create a program that will take two lists of integers, ```a``` and ```b```. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids ```a``` and ```b```. You must find the difference of the cuboids' volumes regardless of which is bigger. For example, if the parameters passed are ```([2, 2, 3], [5, 4, 1])```, the volume of ```a``` is 12 and the volume of ```b``` is 20. Therefore, the function should return ```8```. Your function will be tested with pre-made examples as well as random ones. **If you can, try writing it in one line of code.**
import numpy def find_difference(a, b): aa = numpy.prod(a) bb = numpy.prod(b) return aa - bb if aa > bb else bb - aa
In this simple exercise, you will create a program that will take two lists of integers, ```a``` and ```b```. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids ```a``` and ```b```. You must find the difference of the cuboids' volumes regardless of which is bigger. For example, if the parameters passed are ```([2, 2, 3], [5, 4, 1])```, the volume of ```a``` is 12 and the volume of ```b``` is 20. Therefore, the function should return ```8```. Your function will be tested with pre-made examples as well as random ones. **If you can, try writing it in one line of code.**
def find_difference(a, b): a1 = a[0] * a[1] * a[2] b1 = b[0] * b[1] * b[2] m = max(a1, b1) m1 = min(a1, b1) return m - m1
In this simple exercise, you will create a program that will take two lists of integers, ```a``` and ```b```. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids ```a``` and ```b```. You must find the difference of the cuboids' volumes regardless of which is bigger. For example, if the parameters passed are ```([2, 2, 3], [5, 4, 1])```, the volume of ```a``` is 12 and the volume of ```b``` is 20. Therefore, the function should return ```8```. Your function will be tested with pre-made examples as well as random ones. **If you can, try writing it in one line of code.**
def find_difference(a, b): diff = (a[1] * a[2] * a[0]) - (b[1] * b[2] * b[0]) return abs(diff)
In this simple exercise, you will create a program that will take two lists of integers, ```a``` and ```b```. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids ```a``` and ```b```. You must find the difference of the cuboids' volumes regardless of which is bigger. For example, if the parameters passed are ```([2, 2, 3], [5, 4, 1])```, the volume of ```a``` is 12 and the volume of ```b``` is 20. Therefore, the function should return ```8```. Your function will be tested with pre-made examples as well as random ones. **If you can, try writing it in one line of code.**
def find_difference(a, b): result_a = 1 result_b = 1 for i in a: result_a = result_a*i for t in b: result_b = result_b*t return abs(result_b-result_a)
In this simple exercise, you will create a program that will take two lists of integers, ```a``` and ```b```. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids ```a``` and ```b```. You must find the difference of the cuboids' volumes regardless of which is bigger. For example, if the parameters passed are ```([2, 2, 3], [5, 4, 1])```, the volume of ```a``` is 12 and the volume of ```b``` is 20. Therefore, the function should return ```8```. Your function will be tested with pre-made examples as well as random ones. **If you can, try writing it in one line of code.**
def find_difference(a, b): # Your code here! aa = a[0] ab = a[1] ac = a[2] ba = b[0] bb = b[1] bc = b[2] return abs(aa*ab*ac - ba*bb*bc)
In this simple exercise, you will create a program that will take two lists of integers, ```a``` and ```b```. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids ```a``` and ```b```. You must find the difference of the cuboids' volumes regardless of which is bigger. For example, if the parameters passed are ```([2, 2, 3], [5, 4, 1])```, the volume of ```a``` is 12 and the volume of ```b``` is 20. Therefore, the function should return ```8```. Your function will be tested with pre-made examples as well as random ones. **If you can, try writing it in one line of code.**
def find_difference(a, b): sum = 1 sum1 = 1 for i in a: sum = sum * i for j in b: sum1 = sum1 * j if sum - sum1 > 0: return sum - sum1 else: return (sum - sum1) * -1
In this simple exercise, you will create a program that will take two lists of integers, ```a``` and ```b```. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids ```a``` and ```b```. You must find the difference of the cuboids' volumes regardless of which is bigger. For example, if the parameters passed are ```([2, 2, 3], [5, 4, 1])```, the volume of ```a``` is 12 and the volume of ```b``` is 20. Therefore, the function should return ```8```. Your function will be tested with pre-made examples as well as random ones. **If you can, try writing it in one line of code.**
def find_difference(a, b): v1=1 v2=1 for i,j in zip(a,b): v1 = v1*i v2 = v2*j return abs(v1-v2)
In this simple exercise, you will create a program that will take two lists of integers, ```a``` and ```b```. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids ```a``` and ```b```. You must find the difference of the cuboids' volumes regardless of which is bigger. For example, if the parameters passed are ```([2, 2, 3], [5, 4, 1])```, the volume of ```a``` is 12 and the volume of ```b``` is 20. Therefore, the function should return ```8```. Your function will be tested with pre-made examples as well as random ones. **If you can, try writing it in one line of code.**
def prod(arr): result = 1 for i in arr: result *= i return result def find_difference(a, b): return abs(prod(a) - prod(b))
In this simple exercise, you will create a program that will take two lists of integers, ```a``` and ```b```. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids ```a``` and ```b```. You must find the difference of the cuboids' volumes regardless of which is bigger. For example, if the parameters passed are ```([2, 2, 3], [5, 4, 1])```, the volume of ```a``` is 12 and the volume of ```b``` is 20. Therefore, the function should return ```8```. Your function will be tested with pre-made examples as well as random ones. **If you can, try writing it in one line of code.**
from functools import reduce import math def find_difference(a, b): return math.fabs(reduce(lambda x, y: x*y, a)-reduce(lambda p,q: p*q,b))
In this simple exercise, you will create a program that will take two lists of integers, ```a``` and ```b```. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids ```a``` and ```b```. You must find the difference of the cuboids' volumes regardless of which is bigger. For example, if the parameters passed are ```([2, 2, 3], [5, 4, 1])```, the volume of ```a``` is 12 and the volume of ```b``` is 20. Therefore, the function should return ```8```. Your function will be tested with pre-made examples as well as random ones. **If you can, try writing it in one line of code.**
def find_difference(a, b): total_a = 1 for i in range(0, len(a)): total_a *= a[i] total_b = 1 for j in range(0, len(b)): total_b *= b[j] return abs(total_a - total_b)
In this simple exercise, you will create a program that will take two lists of integers, ```a``` and ```b```. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids ```a``` and ```b```. You must find the difference of the cuboids' volumes regardless of which is bigger. For example, if the parameters passed are ```([2, 2, 3], [5, 4, 1])```, the volume of ```a``` is 12 and the volume of ```b``` is 20. Therefore, the function should return ```8```. Your function will be tested with pre-made examples as well as random ones. **If you can, try writing it in one line of code.**
def find_difference(a, b): la = len(a) reza = 1 rezb = 1 for i in range(la): reza *= a[i] rezb *= b[i] return abs(reza - rezb)
In this simple exercise, you will create a program that will take two lists of integers, ```a``` and ```b```. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids ```a``` and ```b```. You must find the difference of the cuboids' volumes regardless of which is bigger. For example, if the parameters passed are ```([2, 2, 3], [5, 4, 1])```, the volume of ```a``` is 12 and the volume of ```b``` is 20. Therefore, the function should return ```8```. Your function will be tested with pre-made examples as well as random ones. **If you can, try writing it in one line of code.**
def find_difference(a, b): vola=a[0]*a[1]*a[2] volb=b[0]*b[1]*b[2] if vola > volb: diff=vola-volb return diff if volb > vola: diff=volb-vola return diff if vola-volb or volb-vola == 0: return 0
In this simple exercise, you will create a program that will take two lists of integers, ```a``` and ```b```. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids ```a``` and ```b```. You must find the difference of the cuboids' volumes regardless of which is bigger. For example, if the parameters passed are ```([2, 2, 3], [5, 4, 1])```, the volume of ```a``` is 12 and the volume of ```b``` is 20. Therefore, the function should return ```8```. Your function will be tested with pre-made examples as well as random ones. **If you can, try writing it in one line of code.**
def find_difference(a, b): if ((a[0] * a[1] * a [2]) - (b[0] * b[1] * b[2])) >= 0: return ((a[0] * a[1] * a [2]) - (b[0] * b[1] * b[2])) elif ((b[0] * b[1] * b[2]) - (a[0] * a[1] * a [2])) >= 0: return (b[0] * b[1] * b[2]) - (a[0] * a[1] * a [2])
In this simple exercise, you will create a program that will take two lists of integers, ```a``` and ```b```. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids ```a``` and ```b```. You must find the difference of the cuboids' volumes regardless of which is bigger. For example, if the parameters passed are ```([2, 2, 3], [5, 4, 1])```, the volume of ```a``` is 12 and the volume of ```b``` is 20. Therefore, the function should return ```8```. Your function will be tested with pre-made examples as well as random ones. **If you can, try writing it in one line of code.**
def find_difference(a, b): prod1 = 1 prod2 = 1 for i in range(3): prod1 *= a[i] prod2 *= b[i] return abs(prod1-prod2)
In this simple exercise, you will create a program that will take two lists of integers, ```a``` and ```b```. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids ```a``` and ```b```. You must find the difference of the cuboids' volumes regardless of which is bigger. For example, if the parameters passed are ```([2, 2, 3], [5, 4, 1])```, the volume of ```a``` is 12 and the volume of ```b``` is 20. Therefore, the function should return ```8```. Your function will be tested with pre-made examples as well as random ones. **If you can, try writing it in one line of code.**
def find_difference(a, b): p=a[0]*a[1]*a[2] q=b[0]*b[1]*b[2] return abs(p-q)
Your task is to build a model^(1) which can predict y-coordinate. You can pass tests if predicted y-coordinates are inside error margin. You will receive train set which should be used to build a model. After you build a model tests will call function ```predict``` and pass x to it. Error is going to be calculated with RMSE. Blocked libraries: sklearn, pandas, tensorflow, numpy, scipy Explanation [1] A mining model is created by applying an algorithm to data, but it is more than an algorithm or a metadata container: it is a set of data, statistics, and patterns that can be applied to new data to generate predictions and make inferences about relationships.
class Datamining: a = 0 b = 0 def __init__(self, train_set): sx = sy = sxx = sxy = 0 n = len(train_set) for i in range(n): sx += train_set[i][0] sy += train_set[i][1] sxx += train_set[i][0]**2 sxy += train_set[i][0]*train_set[i][1] self.b = (n*sxy-sx*sy)/(n*sxx-sx**2) self.a = (sy-self.b*sx)/n def predict(self, x): return self.a + self.b*x
Your task is to build a model^(1) which can predict y-coordinate. You can pass tests if predicted y-coordinates are inside error margin. You will receive train set which should be used to build a model. After you build a model tests will call function ```predict``` and pass x to it. Error is going to be calculated with RMSE. Blocked libraries: sklearn, pandas, tensorflow, numpy, scipy Explanation [1] A mining model is created by applying an algorithm to data, but it is more than an algorithm or a metadata container: it is a set of data, statistics, and patterns that can be applied to new data to generate predictions and make inferences about relationships.
class Datamining: def __init__(self, train_set): n = len(train_set) X = [i[0] for i in train_set] Y = [i[1] for i in train_set] x_mean = sum(X) / n y_mean = sum(Y) / n numerator = 0 denominator = 0 for i in range(n): numerator += (X[i] - x_mean) * (Y[i] - y_mean) denominator += (X[i] - x_mean) ** 2 self.b1 = numerator / denominator self.b0 = y_mean - (self.b1 * x_mean) def predict(self, x): return x*self.b1 + self.b0
Your task is to build a model^(1) which can predict y-coordinate. You can pass tests if predicted y-coordinates are inside error margin. You will receive train set which should be used to build a model. After you build a model tests will call function ```predict``` and pass x to it. Error is going to be calculated with RMSE. Blocked libraries: sklearn, pandas, tensorflow, numpy, scipy Explanation [1] A mining model is created by applying an algorithm to data, but it is more than an algorithm or a metadata container: it is a set of data, statistics, and patterns that can be applied to new data to generate predictions and make inferences about relationships.
from operator import itemgetter class Datamining: def __init__(self, train_set): X, Y = map(lambda L: sum(L)/len(train_set), zip(*train_set)) COV = sum((x-X)*(y-Y) for x,y in train_set) VAR = sum((x-X)**2 for x in map(itemgetter(0), train_set)) self.A = COV / VAR self.B = Y - self.A * X def predict(self, x): return self.A * x + self.B
Your task is to build a model^(1) which can predict y-coordinate. You can pass tests if predicted y-coordinates are inside error margin. You will receive train set which should be used to build a model. After you build a model tests will call function ```predict``` and pass x to it. Error is going to be calculated with RMSE. Blocked libraries: sklearn, pandas, tensorflow, numpy, scipy Explanation [1] A mining model is created by applying an algorithm to data, but it is more than an algorithm or a metadata container: it is a set of data, statistics, and patterns that can be applied to new data to generate predictions and make inferences about relationships.
class Datamining: def __init__(self, train_set): n = len(train_set) M1 = [i[0] for i in train_set] M2 = [i[1] for i in train_set] x_mean = sum(M1) / n y_mean = sum(M2) / n numerator = 0 denominator = 0 for i in range(n): numerator += (M1[i] - x_mean) * (M2[i] - y_mean) denominator += (M1[i] - x_mean) ** 2 self.n = numerator / denominator self.o = y_mean - (self.n * x_mean) def predict(self, x): return x*self.n + self.o
Your task is to build a model^(1) which can predict y-coordinate. You can pass tests if predicted y-coordinates are inside error margin. You will receive train set which should be used to build a model. After you build a model tests will call function ```predict``` and pass x to it. Error is going to be calculated with RMSE. Blocked libraries: sklearn, pandas, tensorflow, numpy, scipy Explanation [1] A mining model is created by applying an algorithm to data, but it is more than an algorithm or a metadata container: it is a set of data, statistics, and patterns that can be applied to new data to generate predictions and make inferences about relationships.
class Datamining: def __init__(self, train_set): x_mean = lambda train_set: sum( [i[0] for i in train_set] ) / len( [i[0] for i in train_set] ) y_mean = lambda train_set: sum( [i[1] for i in train_set] ) / len( [i[1] for i in train_set] ) f = lambda x_mean, y_mean, train_set: sum( (x - x_mean) * (y - y_mean) for x, y in train_set ) g = lambda x_mean, train_set: sum( (x - x_mean) ** 2 for x in [i[0] for i in train_set] ) self.a = f( x_mean(train_set), y_mean (train_set), train_set ) / g ( x_mean (train_set), train_set ) self.b = y_mean(train_set) - self.a * x_mean(train_set) def predict(self, x): return x * self.a + self.b
Your task is to build a model^(1) which can predict y-coordinate. You can pass tests if predicted y-coordinates are inside error margin. You will receive train set which should be used to build a model. After you build a model tests will call function ```predict``` and pass x to it. Error is going to be calculated with RMSE. Blocked libraries: sklearn, pandas, tensorflow, numpy, scipy Explanation [1] A mining model is created by applying an algorithm to data, but it is more than an algorithm or a metadata container: it is a set of data, statistics, and patterns that can be applied to new data to generate predictions and make inferences about relationships.
class Datamining: def __init__(self, train_set): x_mean=sum([i[0] for i in train_set])/len([i[0] for i in train_set]) y_mean=sum([i[1] for i in train_set])/len([i[1] for i in train_set]) self.a = (sum((x - x_mean) * (y - y_mean) for x, y in train_set)) / \ (sum((x - x_mean) ** 2 for x in [i[0] for i in train_set])) self.b = y_mean - self.a * x_mean def predict(self, x): return x * self.a + self.b
Your task is to build a model^(1) which can predict y-coordinate. You can pass tests if predicted y-coordinates are inside error margin. You will receive train set which should be used to build a model. After you build a model tests will call function ```predict``` and pass x to it. Error is going to be calculated with RMSE. Blocked libraries: sklearn, pandas, tensorflow, numpy, scipy Explanation [1] A mining model is created by applying an algorithm to data, but it is more than an algorithm or a metadata container: it is a set of data, statistics, and patterns that can be applied to new data to generate predictions and make inferences about relationships.
class Datamining: def __init__(self, train_set): a_x,a_y=[],[] for x,y in train_set: a_x.append(x) a_y.append(y) mean_x=sum(a_x)/len(a_x) mean_y=sum(a_y)/len(a_y) cov=sum((x-mean_x)*(y-mean_y) for x,y in train_set) x_v=sum((x-mean_x)**2 for x in a_x) self.a=cov/x_v self.b=mean_y-self.a*mean_x def predict(self, x): return self.a*x+self.b
Your task is to build a model^(1) which can predict y-coordinate. You can pass tests if predicted y-coordinates are inside error margin. You will receive train set which should be used to build a model. After you build a model tests will call function ```predict``` and pass x to it. Error is going to be calculated with RMSE. Blocked libraries: sklearn, pandas, tensorflow, numpy, scipy Explanation [1] A mining model is created by applying an algorithm to data, but it is more than an algorithm or a metadata container: it is a set of data, statistics, and patterns that can be applied to new data to generate predictions and make inferences about relationships.
class Datamining: def __init__(self, ts): self.N = len(ts) self.m = (self.N * sum(x*y for x, y in ts) - sum(x for x,_ in ts)*sum(y for _, y in ts)) / (self.N * sum(x**2 for x,_ in ts) - sum(x for x,_ in ts)**2) self.b = (sum(y for _,y in ts) - self.m * sum(x for x, _ in ts)) / (self.N) def predict(self, x): return self.m*x + self.b
Your task is to build a model^(1) which can predict y-coordinate. You can pass tests if predicted y-coordinates are inside error margin. You will receive train set which should be used to build a model. After you build a model tests will call function ```predict``` and pass x to it. Error is going to be calculated with RMSE. Blocked libraries: sklearn, pandas, tensorflow, numpy, scipy Explanation [1] A mining model is created by applying an algorithm to data, but it is more than an algorithm or a metadata container: it is a set of data, statistics, and patterns that can be applied to new data to generate predictions and make inferences about relationships.
class Datamining: def __init__(self, train_set): n = len(train_set) xbar = sum([s[0] for s in train_set]) / n ybar = sum([s[1] for s in train_set]) / n print(xbar, ybar) xe = [s[0] - xbar for s in train_set] ye = [s[1] - ybar for s in train_set] self.beta = sum(xe[i] * ye[i] for i in range(n)) / sum(xe[i] ** 2 for i in range(n)) self.alpha = ybar - self.beta * xbar predict = [self.alpha + self.beta * s[0] for s in train_set] def predict(self, x): return self.alpha + self.beta * x
Your task is to build a model^(1) which can predict y-coordinate. You can pass tests if predicted y-coordinates are inside error margin. You will receive train set which should be used to build a model. After you build a model tests will call function ```predict``` and pass x to it. Error is going to be calculated with RMSE. Blocked libraries: sklearn, pandas, tensorflow, numpy, scipy Explanation [1] A mining model is created by applying an algorithm to data, but it is more than an algorithm or a metadata container: it is a set of data, statistics, and patterns that can be applied to new data to generate predictions and make inferences about relationships.
class Datamining: def __init__(self, train_set): total = len(train_set) x = [] for i in train_set: x.append(i[0]) y = [] for i in train_set: y.append(i[1]) xmean = sum(x)/total ymean = sum(y)/total a = 0 b = 0 for i in range(total): a += (x[i]-xmean) * (y[i] - ymean) b+= (x[i]-xmean)**2 self.z = a/b self.y = ymean - (self.z*xmean) def predict(self, x): return x*self.z + self.y pass
We need a function that may receive a list of an unknown amount of points in the same plane, having each of them, cartesian coordinates of the form (x, y) and may find the biggest triangle (the one with the largest area) formed by all of the possible combinations of groups of three points of that given list. Of course, we will have some combinations of three points that does not form a triangle, because the three points are aligned. The function find_biggTriang(listOfPoints), will output a list with the following data in the order presented bellow: ```python [(1), (2), (3), (4), 5] (1) - Number of points received (You may assume that you will not receive duplicates) (2) - Maximum possible amount of triangles that can be formed with the amount of received points (number in data (1) above). It should be expressed as an integer, (no L for long type variables) (3) - Real Number of triangles that can be formed with the given points. (The function should have a counter for all the cases of three points aligned). It should be expressedas as an integer. (4) - The triangles that have maximum area in a sorted list. If there are two triangles with the biggest area, the result will be presented in this way: [[[xA1, yA1], [xB1, yB1], [xC1, yC1]], [[xA2, yA2], [xB2, yB2], [xC2, yC2]]] But if we have only one triangle with max. area, there is no need of a spare level of braces, so it will be as follows: [[xA1, yA1], [xB1, yB1], [xC1, yC1]] (5) - The value of max. area (absolute value) that was found as a float. As we did not define the units of length for the coordinates, the units for the area will be ignored. ``` It would be useful to apply the expression for the area of a triangle with vertices A, B, and C, is equal to the half of the determinant of the matrix, using the respective coordinates as follows: ```python | xA yA 1| Area Triangle(A, B, C) = 1/2 . | xB yB 1| | xC yC 1| ``` The negative sign for the area should be ignored for the purpose of the exercise, and we will consider the absolute value for all cases. See how to calculate the determinant of a matrix 3 x 3, rule of Sarrus. https://en.wikipedia.org/wiki/Rule_of_Sarrus Using this expression, it would be easy to detect the cases when three points are aligned. Let's see some simple cases. ```python listOfPoints1 = [(0, 1), (7, 3), (9, 0), (7, 10), (2, 9), (10, 7), (2, 8), (9, 8), (4, 4), (2, 10), (10, 1), (0, 4), (4, 3), (10, 0), (0, 3), (3, 4), (1, 1), (7, 2), (4, 0)] (19 points received) find_biggTriang(listOfPoints1) --------> [19, 969, 953, [[0, 1], [7, 10], [10, 0]], 48.5] /// Combinations (19, 3) = 969 (We do not have repeated points) 953 real cases for triangles because the function detected 16 cases when three points are aligned. The function found one triangle [[0, 1], [7, 10], [10, 0]] with its area equals to 49.5/// listOfPoints2 = [(7, 4), (0, 0), (9, 10), (5, 0), (8, 1), (7, 6), (9, 3), (2, 4), (6, 3), (5, 6), (3, 6), (10, 0), (9, 7), (3, 10), (10, 2)] (15 points received) find_biggTriang(listOfPoints2) --------> [15, 455, 446, [[[0, 0], [9, 10], [10, 0]], [[0, 0], [10, 0], [3, 10]]], 50.0] /// Combinations(15, 3) = 455 but there were only 446 real triangles We found two triangles: [[0, 0], [9, 10], [10, 0]] and [[0, 0], [10, 0], [3, 10]] (both in a sorted list. Both triangles have an area of 50.0/// ``` Your code will be tested with lists created randomly up to 70 points. Have a nice moment and enjoy it!!
from itertools import combinations def area(t): (a,b),(c,d),(e,f) = t return abs(a*d+b*e+c*f-d*e-a*f-b*c)/2 def find_biggTriang(lst): tris = list(combinations(lst,3)) areas = list(map(area,tris)) m = max(areas) mTris = [list(map(list,t)) for t,v in zip(tris,areas) if v==m] return [ len(lst), len(tris), sum(map(bool,areas)), mTris if len(mTris)!=1 else mTris.pop(), m]
We need a function that may receive a list of an unknown amount of points in the same plane, having each of them, cartesian coordinates of the form (x, y) and may find the biggest triangle (the one with the largest area) formed by all of the possible combinations of groups of three points of that given list. Of course, we will have some combinations of three points that does not form a triangle, because the three points are aligned. The function find_biggTriang(listOfPoints), will output a list with the following data in the order presented bellow: ```python [(1), (2), (3), (4), 5] (1) - Number of points received (You may assume that you will not receive duplicates) (2) - Maximum possible amount of triangles that can be formed with the amount of received points (number in data (1) above). It should be expressed as an integer, (no L for long type variables) (3) - Real Number of triangles that can be formed with the given points. (The function should have a counter for all the cases of three points aligned). It should be expressedas as an integer. (4) - The triangles that have maximum area in a sorted list. If there are two triangles with the biggest area, the result will be presented in this way: [[[xA1, yA1], [xB1, yB1], [xC1, yC1]], [[xA2, yA2], [xB2, yB2], [xC2, yC2]]] But if we have only one triangle with max. area, there is no need of a spare level of braces, so it will be as follows: [[xA1, yA1], [xB1, yB1], [xC1, yC1]] (5) - The value of max. area (absolute value) that was found as a float. As we did not define the units of length for the coordinates, the units for the area will be ignored. ``` It would be useful to apply the expression for the area of a triangle with vertices A, B, and C, is equal to the half of the determinant of the matrix, using the respective coordinates as follows: ```python | xA yA 1| Area Triangle(A, B, C) = 1/2 . | xB yB 1| | xC yC 1| ``` The negative sign for the area should be ignored for the purpose of the exercise, and we will consider the absolute value for all cases. See how to calculate the determinant of a matrix 3 x 3, rule of Sarrus. https://en.wikipedia.org/wiki/Rule_of_Sarrus Using this expression, it would be easy to detect the cases when three points are aligned. Let's see some simple cases. ```python listOfPoints1 = [(0, 1), (7, 3), (9, 0), (7, 10), (2, 9), (10, 7), (2, 8), (9, 8), (4, 4), (2, 10), (10, 1), (0, 4), (4, 3), (10, 0), (0, 3), (3, 4), (1, 1), (7, 2), (4, 0)] (19 points received) find_biggTriang(listOfPoints1) --------> [19, 969, 953, [[0, 1], [7, 10], [10, 0]], 48.5] /// Combinations (19, 3) = 969 (We do not have repeated points) 953 real cases for triangles because the function detected 16 cases when three points are aligned. The function found one triangle [[0, 1], [7, 10], [10, 0]] with its area equals to 49.5/// listOfPoints2 = [(7, 4), (0, 0), (9, 10), (5, 0), (8, 1), (7, 6), (9, 3), (2, 4), (6, 3), (5, 6), (3, 6), (10, 0), (9, 7), (3, 10), (10, 2)] (15 points received) find_biggTriang(listOfPoints2) --------> [15, 455, 446, [[[0, 0], [9, 10], [10, 0]], [[0, 0], [10, 0], [3, 10]]], 50.0] /// Combinations(15, 3) = 455 but there were only 446 real triangles We found two triangles: [[0, 0], [9, 10], [10, 0]] and [[0, 0], [10, 0], [3, 10]] (both in a sorted list. Both triangles have an area of 50.0/// ``` Your code will be tested with lists created randomly up to 70 points. Have a nice moment and enjoy it!!
from itertools import combinations as com from collections import defaultdict def area(points): (ax, ay), (bx, by), (cx, cy) = points return abs(ax * (by - cy) + bx * (cy - ay) + cx * (ay - by)) / 2 def find_biggTriang(listPoints): allcom = [[[j[0], j[1]] for j in i] for i in set(com(listPoints, 3))] aaa = defaultdict(list) count = 0 for i in allcom: ar = area(i) if ar != 0: count += 1 aaa[ar].append(i) maxarea = max(set(aaa.keys())) po = aaa[maxarea] if len(po) == 1: po = po[0] return([len(listPoints), len(allcom), count, po, maxarea])
We need a function that may receive a list of an unknown amount of points in the same plane, having each of them, cartesian coordinates of the form (x, y) and may find the biggest triangle (the one with the largest area) formed by all of the possible combinations of groups of three points of that given list. Of course, we will have some combinations of three points that does not form a triangle, because the three points are aligned. The function find_biggTriang(listOfPoints), will output a list with the following data in the order presented bellow: ```python [(1), (2), (3), (4), 5] (1) - Number of points received (You may assume that you will not receive duplicates) (2) - Maximum possible amount of triangles that can be formed with the amount of received points (number in data (1) above). It should be expressed as an integer, (no L for long type variables) (3) - Real Number of triangles that can be formed with the given points. (The function should have a counter for all the cases of three points aligned). It should be expressedas as an integer. (4) - The triangles that have maximum area in a sorted list. If there are two triangles with the biggest area, the result will be presented in this way: [[[xA1, yA1], [xB1, yB1], [xC1, yC1]], [[xA2, yA2], [xB2, yB2], [xC2, yC2]]] But if we have only one triangle with max. area, there is no need of a spare level of braces, so it will be as follows: [[xA1, yA1], [xB1, yB1], [xC1, yC1]] (5) - The value of max. area (absolute value) that was found as a float. As we did not define the units of length for the coordinates, the units for the area will be ignored. ``` It would be useful to apply the expression for the area of a triangle with vertices A, B, and C, is equal to the half of the determinant of the matrix, using the respective coordinates as follows: ```python | xA yA 1| Area Triangle(A, B, C) = 1/2 . | xB yB 1| | xC yC 1| ``` The negative sign for the area should be ignored for the purpose of the exercise, and we will consider the absolute value for all cases. See how to calculate the determinant of a matrix 3 x 3, rule of Sarrus. https://en.wikipedia.org/wiki/Rule_of_Sarrus Using this expression, it would be easy to detect the cases when three points are aligned. Let's see some simple cases. ```python listOfPoints1 = [(0, 1), (7, 3), (9, 0), (7, 10), (2, 9), (10, 7), (2, 8), (9, 8), (4, 4), (2, 10), (10, 1), (0, 4), (4, 3), (10, 0), (0, 3), (3, 4), (1, 1), (7, 2), (4, 0)] (19 points received) find_biggTriang(listOfPoints1) --------> [19, 969, 953, [[0, 1], [7, 10], [10, 0]], 48.5] /// Combinations (19, 3) = 969 (We do not have repeated points) 953 real cases for triangles because the function detected 16 cases when three points are aligned. The function found one triangle [[0, 1], [7, 10], [10, 0]] with its area equals to 49.5/// listOfPoints2 = [(7, 4), (0, 0), (9, 10), (5, 0), (8, 1), (7, 6), (9, 3), (2, 4), (6, 3), (5, 6), (3, 6), (10, 0), (9, 7), (3, 10), (10, 2)] (15 points received) find_biggTriang(listOfPoints2) --------> [15, 455, 446, [[[0, 0], [9, 10], [10, 0]], [[0, 0], [10, 0], [3, 10]]], 50.0] /// Combinations(15, 3) = 455 but there were only 446 real triangles We found two triangles: [[0, 0], [9, 10], [10, 0]] and [[0, 0], [10, 0], [3, 10]] (both in a sorted list. Both triangles have an area of 50.0/// ``` Your code will be tested with lists created randomly up to 70 points. Have a nice moment and enjoy it!!
from itertools import combinations def find_biggTriang(points): num_triplets = num_triangles = 0 max_area, max_triangles = 0, [] for triangle in map(list, combinations(map(list, points), 3)): num_triplets += 1 (ax, ay), (bx, by), (cx, cy) = triangle area = abs(ax * (by - cy) + bx * (cy - ay) + cx * (ay - by)) / 2 if not area: continue num_triangles += 1 if area > max_area: max_area, max_triangles = area, [] if area == max_area: max_triangles.append(triangle) return [len(points), num_triplets, num_triangles, max_triangles.pop() if len(max_triangles) == 1 else max_triangles, max_area]
We need a function that may receive a list of an unknown amount of points in the same plane, having each of them, cartesian coordinates of the form (x, y) and may find the biggest triangle (the one with the largest area) formed by all of the possible combinations of groups of three points of that given list. Of course, we will have some combinations of three points that does not form a triangle, because the three points are aligned. The function find_biggTriang(listOfPoints), will output a list with the following data in the order presented bellow: ```python [(1), (2), (3), (4), 5] (1) - Number of points received (You may assume that you will not receive duplicates) (2) - Maximum possible amount of triangles that can be formed with the amount of received points (number in data (1) above). It should be expressed as an integer, (no L for long type variables) (3) - Real Number of triangles that can be formed with the given points. (The function should have a counter for all the cases of three points aligned). It should be expressedas as an integer. (4) - The triangles that have maximum area in a sorted list. If there are two triangles with the biggest area, the result will be presented in this way: [[[xA1, yA1], [xB1, yB1], [xC1, yC1]], [[xA2, yA2], [xB2, yB2], [xC2, yC2]]] But if we have only one triangle with max. area, there is no need of a spare level of braces, so it will be as follows: [[xA1, yA1], [xB1, yB1], [xC1, yC1]] (5) - The value of max. area (absolute value) that was found as a float. As we did not define the units of length for the coordinates, the units for the area will be ignored. ``` It would be useful to apply the expression for the area of a triangle with vertices A, B, and C, is equal to the half of the determinant of the matrix, using the respective coordinates as follows: ```python | xA yA 1| Area Triangle(A, B, C) = 1/2 . | xB yB 1| | xC yC 1| ``` The negative sign for the area should be ignored for the purpose of the exercise, and we will consider the absolute value for all cases. See how to calculate the determinant of a matrix 3 x 3, rule of Sarrus. https://en.wikipedia.org/wiki/Rule_of_Sarrus Using this expression, it would be easy to detect the cases when three points are aligned. Let's see some simple cases. ```python listOfPoints1 = [(0, 1), (7, 3), (9, 0), (7, 10), (2, 9), (10, 7), (2, 8), (9, 8), (4, 4), (2, 10), (10, 1), (0, 4), (4, 3), (10, 0), (0, 3), (3, 4), (1, 1), (7, 2), (4, 0)] (19 points received) find_biggTriang(listOfPoints1) --------> [19, 969, 953, [[0, 1], [7, 10], [10, 0]], 48.5] /// Combinations (19, 3) = 969 (We do not have repeated points) 953 real cases for triangles because the function detected 16 cases when three points are aligned. The function found one triangle [[0, 1], [7, 10], [10, 0]] with its area equals to 49.5/// listOfPoints2 = [(7, 4), (0, 0), (9, 10), (5, 0), (8, 1), (7, 6), (9, 3), (2, 4), (6, 3), (5, 6), (3, 6), (10, 0), (9, 7), (3, 10), (10, 2)] (15 points received) find_biggTriang(listOfPoints2) --------> [15, 455, 446, [[[0, 0], [9, 10], [10, 0]], [[0, 0], [10, 0], [3, 10]]], 50.0] /// Combinations(15, 3) = 455 but there were only 446 real triangles We found two triangles: [[0, 0], [9, 10], [10, 0]] and [[0, 0], [10, 0], [3, 10]] (both in a sorted list. Both triangles have an area of 50.0/// ``` Your code will be tested with lists created randomly up to 70 points. Have a nice moment and enjoy it!!
def find_biggTriang(ps): n = len(ps) count = 0 max_area = -1.0 max_area_triangles = [] for i in xrange(n): for j in xrange(i + 1, n): dx1, dy1 = ps[j][0] - ps[i][0], ps[j][1] - ps[i][1] for k in xrange(j + 1, n): dx2, dy2 = ps[k][0] - ps[i][0], ps[k][1] - ps[i][1] a = abs(0.5 * (dx1 * dy2 - dx2 * dy1)) count += a != 0 if a < max_area: continue triangle = [ps[i], ps[j], ps[k]] if a > max_area: max_area = a max_area_triangles = [triangle] elif a == max_area: max_area_triangles.append(triangle) max_area_triangles = [map(list, tr) for tr in max_area_triangles] if len(max_area_triangles) == 1: max_area_triangles = max_area_triangles[0] return [n, n * (n-1) * (n-2) // 6, count, max_area_triangles, max_area]
We need a function that may receive a list of an unknown amount of points in the same plane, having each of them, cartesian coordinates of the form (x, y) and may find the biggest triangle (the one with the largest area) formed by all of the possible combinations of groups of three points of that given list. Of course, we will have some combinations of three points that does not form a triangle, because the three points are aligned. The function find_biggTriang(listOfPoints), will output a list with the following data in the order presented bellow: ```python [(1), (2), (3), (4), 5] (1) - Number of points received (You may assume that you will not receive duplicates) (2) - Maximum possible amount of triangles that can be formed with the amount of received points (number in data (1) above). It should be expressed as an integer, (no L for long type variables) (3) - Real Number of triangles that can be formed with the given points. (The function should have a counter for all the cases of three points aligned). It should be expressedas as an integer. (4) - The triangles that have maximum area in a sorted list. If there are two triangles with the biggest area, the result will be presented in this way: [[[xA1, yA1], [xB1, yB1], [xC1, yC1]], [[xA2, yA2], [xB2, yB2], [xC2, yC2]]] But if we have only one triangle with max. area, there is no need of a spare level of braces, so it will be as follows: [[xA1, yA1], [xB1, yB1], [xC1, yC1]] (5) - The value of max. area (absolute value) that was found as a float. As we did not define the units of length for the coordinates, the units for the area will be ignored. ``` It would be useful to apply the expression for the area of a triangle with vertices A, B, and C, is equal to the half of the determinant of the matrix, using the respective coordinates as follows: ```python | xA yA 1| Area Triangle(A, B, C) = 1/2 . | xB yB 1| | xC yC 1| ``` The negative sign for the area should be ignored for the purpose of the exercise, and we will consider the absolute value for all cases. See how to calculate the determinant of a matrix 3 x 3, rule of Sarrus. https://en.wikipedia.org/wiki/Rule_of_Sarrus Using this expression, it would be easy to detect the cases when three points are aligned. Let's see some simple cases. ```python listOfPoints1 = [(0, 1), (7, 3), (9, 0), (7, 10), (2, 9), (10, 7), (2, 8), (9, 8), (4, 4), (2, 10), (10, 1), (0, 4), (4, 3), (10, 0), (0, 3), (3, 4), (1, 1), (7, 2), (4, 0)] (19 points received) find_biggTriang(listOfPoints1) --------> [19, 969, 953, [[0, 1], [7, 10], [10, 0]], 48.5] /// Combinations (19, 3) = 969 (We do not have repeated points) 953 real cases for triangles because the function detected 16 cases when three points are aligned. The function found one triangle [[0, 1], [7, 10], [10, 0]] with its area equals to 49.5/// listOfPoints2 = [(7, 4), (0, 0), (9, 10), (5, 0), (8, 1), (7, 6), (9, 3), (2, 4), (6, 3), (5, 6), (3, 6), (10, 0), (9, 7), (3, 10), (10, 2)] (15 points received) find_biggTriang(listOfPoints2) --------> [15, 455, 446, [[[0, 0], [9, 10], [10, 0]], [[0, 0], [10, 0], [3, 10]]], 50.0] /// Combinations(15, 3) = 455 but there were only 446 real triangles We found two triangles: [[0, 0], [9, 10], [10, 0]] and [[0, 0], [10, 0], [3, 10]] (both in a sorted list. Both triangles have an area of 50.0/// ``` Your code will be tested with lists created randomly up to 70 points. Have a nice moment and enjoy it!!
from itertools import combinations def dist(a, b): return ((a[0]-b[0])**2+(a[1]-b[1])**2)**0.5 def triangle_area(A, B, C): a, b, c = sorted([dist(A, B), dist(A, C), dist(B, C)]) if a+b > c and c-a < b: s = round(((a+b+c)*(a+b-c)*(a+c-b)*(b+c-a))**0.5/4, 1) else: s = None return s def find_biggTriang(listPoints): num_points = len(listPoints) # 1 possible_count = 0 real_count = 0 areas = {} max_area = 0 for x in combinations(listPoints, 3): possible_count += 1 area = triangle_area(*x) if area: areas[x] = area max_area = max(max_area, area) real_count += 1 max_triangles = [list(map(list, k)) for k, v in list(areas.items()) if v == max_area] if len(max_triangles) == 1: max_triangles = max_triangles[0] return [num_points, possible_count, real_count, max_triangles, max_area]
We need a function that may receive a list of an unknown amount of points in the same plane, having each of them, cartesian coordinates of the form (x, y) and may find the biggest triangle (the one with the largest area) formed by all of the possible combinations of groups of three points of that given list. Of course, we will have some combinations of three points that does not form a triangle, because the three points are aligned. The function find_biggTriang(listOfPoints), will output a list with the following data in the order presented bellow: ```python [(1), (2), (3), (4), 5] (1) - Number of points received (You may assume that you will not receive duplicates) (2) - Maximum possible amount of triangles that can be formed with the amount of received points (number in data (1) above). It should be expressed as an integer, (no L for long type variables) (3) - Real Number of triangles that can be formed with the given points. (The function should have a counter for all the cases of three points aligned). It should be expressedas as an integer. (4) - The triangles that have maximum area in a sorted list. If there are two triangles with the biggest area, the result will be presented in this way: [[[xA1, yA1], [xB1, yB1], [xC1, yC1]], [[xA2, yA2], [xB2, yB2], [xC2, yC2]]] But if we have only one triangle with max. area, there is no need of a spare level of braces, so it will be as follows: [[xA1, yA1], [xB1, yB1], [xC1, yC1]] (5) - The value of max. area (absolute value) that was found as a float. As we did not define the units of length for the coordinates, the units for the area will be ignored. ``` It would be useful to apply the expression for the area of a triangle with vertices A, B, and C, is equal to the half of the determinant of the matrix, using the respective coordinates as follows: ```python | xA yA 1| Area Triangle(A, B, C) = 1/2 . | xB yB 1| | xC yC 1| ``` The negative sign for the area should be ignored for the purpose of the exercise, and we will consider the absolute value for all cases. See how to calculate the determinant of a matrix 3 x 3, rule of Sarrus. https://en.wikipedia.org/wiki/Rule_of_Sarrus Using this expression, it would be easy to detect the cases when three points are aligned. Let's see some simple cases. ```python listOfPoints1 = [(0, 1), (7, 3), (9, 0), (7, 10), (2, 9), (10, 7), (2, 8), (9, 8), (4, 4), (2, 10), (10, 1), (0, 4), (4, 3), (10, 0), (0, 3), (3, 4), (1, 1), (7, 2), (4, 0)] (19 points received) find_biggTriang(listOfPoints1) --------> [19, 969, 953, [[0, 1], [7, 10], [10, 0]], 48.5] /// Combinations (19, 3) = 969 (We do not have repeated points) 953 real cases for triangles because the function detected 16 cases when three points are aligned. The function found one triangle [[0, 1], [7, 10], [10, 0]] with its area equals to 49.5/// listOfPoints2 = [(7, 4), (0, 0), (9, 10), (5, 0), (8, 1), (7, 6), (9, 3), (2, 4), (6, 3), (5, 6), (3, 6), (10, 0), (9, 7), (3, 10), (10, 2)] (15 points received) find_biggTriang(listOfPoints2) --------> [15, 455, 446, [[[0, 0], [9, 10], [10, 0]], [[0, 0], [10, 0], [3, 10]]], 50.0] /// Combinations(15, 3) = 455 but there were only 446 real triangles We found two triangles: [[0, 0], [9, 10], [10, 0]] and [[0, 0], [10, 0], [3, 10]] (both in a sorted list. Both triangles have an area of 50.0/// ``` Your code will be tested with lists created randomly up to 70 points. Have a nice moment and enjoy it!!
def area_triangel(i): return abs(1/2*(i[0][0]*i[1][1]+i[0][1]*i[2][0]+i[1][0]*i[2][1]-i[2][0]*i[1][1]-i[2][1]*i[0][0]-i[1][0]*i[0][1])) def find_biggTriang(listPoints): import itertools max_points = [] max_area = -1000 every_valid_point = list(itertools.combinations(listPoints, 3)) num_invalid_points = 0 for j in every_valid_point: area = area_triangel(j) if area == 0: num_invalid_points += 1 elif area > max_area: max_area, max_points = area, [] max_points.append(list(list(x) for x in j)) elif area == max_area: max_points.append(list(list(x) for x in j)) return [len(listPoints), len(every_valid_point), len(every_valid_point)-num_invalid_points, max_points[0] if len(max_points) == 1 else max_points ,max_area]
We need a function that may receive a list of an unknown amount of points in the same plane, having each of them, cartesian coordinates of the form (x, y) and may find the biggest triangle (the one with the largest area) formed by all of the possible combinations of groups of three points of that given list. Of course, we will have some combinations of three points that does not form a triangle, because the three points are aligned. The function find_biggTriang(listOfPoints), will output a list with the following data in the order presented bellow: ```python [(1), (2), (3), (4), 5] (1) - Number of points received (You may assume that you will not receive duplicates) (2) - Maximum possible amount of triangles that can be formed with the amount of received points (number in data (1) above). It should be expressed as an integer, (no L for long type variables) (3) - Real Number of triangles that can be formed with the given points. (The function should have a counter for all the cases of three points aligned). It should be expressedas as an integer. (4) - The triangles that have maximum area in a sorted list. If there are two triangles with the biggest area, the result will be presented in this way: [[[xA1, yA1], [xB1, yB1], [xC1, yC1]], [[xA2, yA2], [xB2, yB2], [xC2, yC2]]] But if we have only one triangle with max. area, there is no need of a spare level of braces, so it will be as follows: [[xA1, yA1], [xB1, yB1], [xC1, yC1]] (5) - The value of max. area (absolute value) that was found as a float. As we did not define the units of length for the coordinates, the units for the area will be ignored. ``` It would be useful to apply the expression for the area of a triangle with vertices A, B, and C, is equal to the half of the determinant of the matrix, using the respective coordinates as follows: ```python | xA yA 1| Area Triangle(A, B, C) = 1/2 . | xB yB 1| | xC yC 1| ``` The negative sign for the area should be ignored for the purpose of the exercise, and we will consider the absolute value for all cases. See how to calculate the determinant of a matrix 3 x 3, rule of Sarrus. https://en.wikipedia.org/wiki/Rule_of_Sarrus Using this expression, it would be easy to detect the cases when three points are aligned. Let's see some simple cases. ```python listOfPoints1 = [(0, 1), (7, 3), (9, 0), (7, 10), (2, 9), (10, 7), (2, 8), (9, 8), (4, 4), (2, 10), (10, 1), (0, 4), (4, 3), (10, 0), (0, 3), (3, 4), (1, 1), (7, 2), (4, 0)] (19 points received) find_biggTriang(listOfPoints1) --------> [19, 969, 953, [[0, 1], [7, 10], [10, 0]], 48.5] /// Combinations (19, 3) = 969 (We do not have repeated points) 953 real cases for triangles because the function detected 16 cases when three points are aligned. The function found one triangle [[0, 1], [7, 10], [10, 0]] with its area equals to 49.5/// listOfPoints2 = [(7, 4), (0, 0), (9, 10), (5, 0), (8, 1), (7, 6), (9, 3), (2, 4), (6, 3), (5, 6), (3, 6), (10, 0), (9, 7), (3, 10), (10, 2)] (15 points received) find_biggTriang(listOfPoints2) --------> [15, 455, 446, [[[0, 0], [9, 10], [10, 0]], [[0, 0], [10, 0], [3, 10]]], 50.0] /// Combinations(15, 3) = 455 but there were only 446 real triangles We found two triangles: [[0, 0], [9, 10], [10, 0]] and [[0, 0], [10, 0], [3, 10]] (both in a sorted list. Both triangles have an area of 50.0/// ``` Your code will be tested with lists created randomly up to 70 points. Have a nice moment and enjoy it!!
from itertools import combinations from numpy.linalg import det def find_biggTriang(listP): lp = list(map(list,listP)) result = [0,0,0,[],0] result[0] = len(lp) lc = list(combinations(lp,3)) result[1] = len(lc) n = 0 for c in lc: l = list(c) m = [[l[0][0],l[0][1],1],[l[1][0],l[1][1],1],[l[2][0],l[2][1],1]] A = round((1/2)*abs(det(m)),1) if A == 0: n += 1 elif A==result[4]: result[3].append(l) elif A>result[4]: result[4] = A result[3].clear() result[3].append(l) result[2] = result[1] - n result[3] = sorted(result[3]) if len(result[3])==1: result[3] = result[3][0] return result
We need a function that may receive a list of an unknown amount of points in the same plane, having each of them, cartesian coordinates of the form (x, y) and may find the biggest triangle (the one with the largest area) formed by all of the possible combinations of groups of three points of that given list. Of course, we will have some combinations of three points that does not form a triangle, because the three points are aligned. The function find_biggTriang(listOfPoints), will output a list with the following data in the order presented bellow: ```python [(1), (2), (3), (4), 5] (1) - Number of points received (You may assume that you will not receive duplicates) (2) - Maximum possible amount of triangles that can be formed with the amount of received points (number in data (1) above). It should be expressed as an integer, (no L for long type variables) (3) - Real Number of triangles that can be formed with the given points. (The function should have a counter for all the cases of three points aligned). It should be expressedas as an integer. (4) - The triangles that have maximum area in a sorted list. If there are two triangles with the biggest area, the result will be presented in this way: [[[xA1, yA1], [xB1, yB1], [xC1, yC1]], [[xA2, yA2], [xB2, yB2], [xC2, yC2]]] But if we have only one triangle with max. area, there is no need of a spare level of braces, so it will be as follows: [[xA1, yA1], [xB1, yB1], [xC1, yC1]] (5) - The value of max. area (absolute value) that was found as a float. As we did not define the units of length for the coordinates, the units for the area will be ignored. ``` It would be useful to apply the expression for the area of a triangle with vertices A, B, and C, is equal to the half of the determinant of the matrix, using the respective coordinates as follows: ```python | xA yA 1| Area Triangle(A, B, C) = 1/2 . | xB yB 1| | xC yC 1| ``` The negative sign for the area should be ignored for the purpose of the exercise, and we will consider the absolute value for all cases. See how to calculate the determinant of a matrix 3 x 3, rule of Sarrus. https://en.wikipedia.org/wiki/Rule_of_Sarrus Using this expression, it would be easy to detect the cases when three points are aligned. Let's see some simple cases. ```python listOfPoints1 = [(0, 1), (7, 3), (9, 0), (7, 10), (2, 9), (10, 7), (2, 8), (9, 8), (4, 4), (2, 10), (10, 1), (0, 4), (4, 3), (10, 0), (0, 3), (3, 4), (1, 1), (7, 2), (4, 0)] (19 points received) find_biggTriang(listOfPoints1) --------> [19, 969, 953, [[0, 1], [7, 10], [10, 0]], 48.5] /// Combinations (19, 3) = 969 (We do not have repeated points) 953 real cases for triangles because the function detected 16 cases when three points are aligned. The function found one triangle [[0, 1], [7, 10], [10, 0]] with its area equals to 49.5/// listOfPoints2 = [(7, 4), (0, 0), (9, 10), (5, 0), (8, 1), (7, 6), (9, 3), (2, 4), (6, 3), (5, 6), (3, 6), (10, 0), (9, 7), (3, 10), (10, 2)] (15 points received) find_biggTriang(listOfPoints2) --------> [15, 455, 446, [[[0, 0], [9, 10], [10, 0]], [[0, 0], [10, 0], [3, 10]]], 50.0] /// Combinations(15, 3) = 455 but there were only 446 real triangles We found two triangles: [[0, 0], [9, 10], [10, 0]] and [[0, 0], [10, 0], [3, 10]] (both in a sorted list. Both triangles have an area of 50.0/// ``` Your code will be tested with lists created randomly up to 70 points. Have a nice moment and enjoy it!!
from itertools import combinations def find_biggTriang(listPoints): s = combinations(listPoints, 3) j = 0 i = 0 ret = [] mx = 0 for a, b, c in s: s = abs((b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1]-a[1])) / 2 if s > mx: mx = s ret = [] if s == mx: ret.append([list(a), list(b), list(c)]) if s > 0: i += 1 j += 1 if len(ret) <= 1: ret = ret[0] return [len(listPoints), j, i, ret, mx]
We need a function that may receive a list of an unknown amount of points in the same plane, having each of them, cartesian coordinates of the form (x, y) and may find the biggest triangle (the one with the largest area) formed by all of the possible combinations of groups of three points of that given list. Of course, we will have some combinations of three points that does not form a triangle, because the three points are aligned. The function find_biggTriang(listOfPoints), will output a list with the following data in the order presented bellow: ```python [(1), (2), (3), (4), 5] (1) - Number of points received (You may assume that you will not receive duplicates) (2) - Maximum possible amount of triangles that can be formed with the amount of received points (number in data (1) above). It should be expressed as an integer, (no L for long type variables) (3) - Real Number of triangles that can be formed with the given points. (The function should have a counter for all the cases of three points aligned). It should be expressedas as an integer. (4) - The triangles that have maximum area in a sorted list. If there are two triangles with the biggest area, the result will be presented in this way: [[[xA1, yA1], [xB1, yB1], [xC1, yC1]], [[xA2, yA2], [xB2, yB2], [xC2, yC2]]] But if we have only one triangle with max. area, there is no need of a spare level of braces, so it will be as follows: [[xA1, yA1], [xB1, yB1], [xC1, yC1]] (5) - The value of max. area (absolute value) that was found as a float. As we did not define the units of length for the coordinates, the units for the area will be ignored. ``` It would be useful to apply the expression for the area of a triangle with vertices A, B, and C, is equal to the half of the determinant of the matrix, using the respective coordinates as follows: ```python | xA yA 1| Area Triangle(A, B, C) = 1/2 . | xB yB 1| | xC yC 1| ``` The negative sign for the area should be ignored for the purpose of the exercise, and we will consider the absolute value for all cases. See how to calculate the determinant of a matrix 3 x 3, rule of Sarrus. https://en.wikipedia.org/wiki/Rule_of_Sarrus Using this expression, it would be easy to detect the cases when three points are aligned. Let's see some simple cases. ```python listOfPoints1 = [(0, 1), (7, 3), (9, 0), (7, 10), (2, 9), (10, 7), (2, 8), (9, 8), (4, 4), (2, 10), (10, 1), (0, 4), (4, 3), (10, 0), (0, 3), (3, 4), (1, 1), (7, 2), (4, 0)] (19 points received) find_biggTriang(listOfPoints1) --------> [19, 969, 953, [[0, 1], [7, 10], [10, 0]], 48.5] /// Combinations (19, 3) = 969 (We do not have repeated points) 953 real cases for triangles because the function detected 16 cases when three points are aligned. The function found one triangle [[0, 1], [7, 10], [10, 0]] with its area equals to 49.5/// listOfPoints2 = [(7, 4), (0, 0), (9, 10), (5, 0), (8, 1), (7, 6), (9, 3), (2, 4), (6, 3), (5, 6), (3, 6), (10, 0), (9, 7), (3, 10), (10, 2)] (15 points received) find_biggTriang(listOfPoints2) --------> [15, 455, 446, [[[0, 0], [9, 10], [10, 0]], [[0, 0], [10, 0], [3, 10]]], 50.0] /// Combinations(15, 3) = 455 but there were only 446 real triangles We found two triangles: [[0, 0], [9, 10], [10, 0]] and [[0, 0], [10, 0], [3, 10]] (both in a sorted list. Both triangles have an area of 50.0/// ``` Your code will be tested with lists created randomly up to 70 points. Have a nice moment and enjoy it!!
import math def area(x,y,z): a = math.hypot(x[0]-y[0],x[1]-y[1]) b = math.hypot(x[0]-z[0],x[1]-z[1]) c = math.hypot(z[0]-y[0],z[1]-y[1]) p = (a+b+c)/2 s = (p*(p-a)*(p-b)*(p-c))**.5 if abs(s)/(a+b+c)<1e-6: return 0 return round(s,6) def find_biggTriang(listPoints): num_of_pts = len(listPoints) num_of_tri = 0 best_area = None best_list = [] for i in range(num_of_pts-2): for j in range(i+1,num_of_pts-1): for k in range(j+1,num_of_pts): a = area(listPoints[i],listPoints[j],listPoints[k]) if a>0: num_of_tri += 1 if best_area is None or best_area<a: best_area = a best_list = [] if a==best_area: best_list.append([list(listPoints[x]) for x in (i,j,k)]) if len(best_list)==1: best_list = best_list[0] return [num_of_pts, num_of_pts*(num_of_pts-1)*(num_of_pts-2)//6,num_of_tri,best_list,best_area]
We need a function that may receive a list of an unknown amount of points in the same plane, having each of them, cartesian coordinates of the form (x, y) and may find the biggest triangle (the one with the largest area) formed by all of the possible combinations of groups of three points of that given list. Of course, we will have some combinations of three points that does not form a triangle, because the three points are aligned. The function find_biggTriang(listOfPoints), will output a list with the following data in the order presented bellow: ```python [(1), (2), (3), (4), 5] (1) - Number of points received (You may assume that you will not receive duplicates) (2) - Maximum possible amount of triangles that can be formed with the amount of received points (number in data (1) above). It should be expressed as an integer, (no L for long type variables) (3) - Real Number of triangles that can be formed with the given points. (The function should have a counter for all the cases of three points aligned). It should be expressedas as an integer. (4) - The triangles that have maximum area in a sorted list. If there are two triangles with the biggest area, the result will be presented in this way: [[[xA1, yA1], [xB1, yB1], [xC1, yC1]], [[xA2, yA2], [xB2, yB2], [xC2, yC2]]] But if we have only one triangle with max. area, there is no need of a spare level of braces, so it will be as follows: [[xA1, yA1], [xB1, yB1], [xC1, yC1]] (5) - The value of max. area (absolute value) that was found as a float. As we did not define the units of length for the coordinates, the units for the area will be ignored. ``` It would be useful to apply the expression for the area of a triangle with vertices A, B, and C, is equal to the half of the determinant of the matrix, using the respective coordinates as follows: ```python | xA yA 1| Area Triangle(A, B, C) = 1/2 . | xB yB 1| | xC yC 1| ``` The negative sign for the area should be ignored for the purpose of the exercise, and we will consider the absolute value for all cases. See how to calculate the determinant of a matrix 3 x 3, rule of Sarrus. https://en.wikipedia.org/wiki/Rule_of_Sarrus Using this expression, it would be easy to detect the cases when three points are aligned. Let's see some simple cases. ```python listOfPoints1 = [(0, 1), (7, 3), (9, 0), (7, 10), (2, 9), (10, 7), (2, 8), (9, 8), (4, 4), (2, 10), (10, 1), (0, 4), (4, 3), (10, 0), (0, 3), (3, 4), (1, 1), (7, 2), (4, 0)] (19 points received) find_biggTriang(listOfPoints1) --------> [19, 969, 953, [[0, 1], [7, 10], [10, 0]], 48.5] /// Combinations (19, 3) = 969 (We do not have repeated points) 953 real cases for triangles because the function detected 16 cases when three points are aligned. The function found one triangle [[0, 1], [7, 10], [10, 0]] with its area equals to 49.5/// listOfPoints2 = [(7, 4), (0, 0), (9, 10), (5, 0), (8, 1), (7, 6), (9, 3), (2, 4), (6, 3), (5, 6), (3, 6), (10, 0), (9, 7), (3, 10), (10, 2)] (15 points received) find_biggTriang(listOfPoints2) --------> [15, 455, 446, [[[0, 0], [9, 10], [10, 0]], [[0, 0], [10, 0], [3, 10]]], 50.0] /// Combinations(15, 3) = 455 but there were only 446 real triangles We found two triangles: [[0, 0], [9, 10], [10, 0]] and [[0, 0], [10, 0], [3, 10]] (both in a sorted list. Both triangles have an area of 50.0/// ``` Your code will be tested with lists created randomly up to 70 points. Have a nice moment and enjoy it!!
def find_biggTriang(P,m=0,c=0): Z,V,l=[],set(),len(P) for i in range(l-2): for j in range(i+1,l-1): for k in range(j+1,l): (x,y),(u,v),(p,q)=P[i],P[j],P[k] s=abs((u-x)*(q-y)-(v-y)*(p-x))/2 if s:V.add((i,j,k)) T=[[x,y],[u,v],[p,q]] if m<s:Z,m=[T],s elif m==s:Z+=[T] c+=1 return[l,c,len(V),1<len(Z)and Z or Z[0],m]
A list of integers is sorted in “Wave” order if alternate items are not less than their immediate neighbors (thus the other alternate items are not greater than their immediate neighbors). Thus, the array `[4, 1, 7, 5, 6, 2, 3]` is in **Wave** order because 4 >= 1, then 1 <= 7, then 7 >= 5, then 5 <= 6, then 6 >= 2, and finally 2 <= 3. The wave-sorted lists has to begin with an element not less than the next, so `[1, 4, 5, 3]` is not sorted in Wave because 1 < 4 Your task is to implement a function that takes a list of integers and sorts it into wave order in place; your function shouldn't return anything. Note: - The resulting array shouldn't necessarily match anyone in the tests, a function just checks if the array is now wave sorted.
def wave_sort(a): a.sort() for i in range(1, len(a), 2): a[i], a[i-1] = a[i-1], a[i]
A list of integers is sorted in “Wave” order if alternate items are not less than their immediate neighbors (thus the other alternate items are not greater than their immediate neighbors). Thus, the array `[4, 1, 7, 5, 6, 2, 3]` is in **Wave** order because 4 >= 1, then 1 <= 7, then 7 >= 5, then 5 <= 6, then 6 >= 2, and finally 2 <= 3. The wave-sorted lists has to begin with an element not less than the next, so `[1, 4, 5, 3]` is not sorted in Wave because 1 < 4 Your task is to implement a function that takes a list of integers and sorts it into wave order in place; your function shouldn't return anything. Note: - The resulting array shouldn't necessarily match anyone in the tests, a function just checks if the array is now wave sorted.
def wave_sort(a): a.sort() for i in range(0, len(a)-1, 2): a[i], a[i+1] = a[i+1], a[i]
A list of integers is sorted in “Wave” order if alternate items are not less than their immediate neighbors (thus the other alternate items are not greater than their immediate neighbors). Thus, the array `[4, 1, 7, 5, 6, 2, 3]` is in **Wave** order because 4 >= 1, then 1 <= 7, then 7 >= 5, then 5 <= 6, then 6 >= 2, and finally 2 <= 3. The wave-sorted lists has to begin with an element not less than the next, so `[1, 4, 5, 3]` is not sorted in Wave because 1 < 4 Your task is to implement a function that takes a list of integers and sorts it into wave order in place; your function shouldn't return anything. Note: - The resulting array shouldn't necessarily match anyone in the tests, a function just checks if the array is now wave sorted.
def wave_sort(a): a.sort() last = len(a) - len(a) % 2 a[1::2], a[:last:2] = a[:last:2], a[1::2]
A list of integers is sorted in “Wave” order if alternate items are not less than their immediate neighbors (thus the other alternate items are not greater than their immediate neighbors). Thus, the array `[4, 1, 7, 5, 6, 2, 3]` is in **Wave** order because 4 >= 1, then 1 <= 7, then 7 >= 5, then 5 <= 6, then 6 >= 2, and finally 2 <= 3. The wave-sorted lists has to begin with an element not less than the next, so `[1, 4, 5, 3]` is not sorted in Wave because 1 < 4 Your task is to implement a function that takes a list of integers and sorts it into wave order in place; your function shouldn't return anything. Note: - The resulting array shouldn't necessarily match anyone in the tests, a function just checks if the array is now wave sorted.
from itertools import chain def wave_sort(a): for i, x in zip(chain(range(1, len(a), 2), range(0, len(a), 2)), sorted(a)): a[i] = x
A list of integers is sorted in “Wave” order if alternate items are not less than their immediate neighbors (thus the other alternate items are not greater than their immediate neighbors). Thus, the array `[4, 1, 7, 5, 6, 2, 3]` is in **Wave** order because 4 >= 1, then 1 <= 7, then 7 >= 5, then 5 <= 6, then 6 >= 2, and finally 2 <= 3. The wave-sorted lists has to begin with an element not less than the next, so `[1, 4, 5, 3]` is not sorted in Wave because 1 < 4 Your task is to implement a function that takes a list of integers and sorts it into wave order in place; your function shouldn't return anything. Note: - The resulting array shouldn't necessarily match anyone in the tests, a function just checks if the array is now wave sorted.
def wave_sort(a): pivot = 0 while pivot < len(a): max_val = max(a[pivot:]) max_val_index = a[pivot:].index(max_val) tmp = a[pivot] a[pivot] = max_val a[max_val_index+pivot] = tmp pivot += 1 if pivot < len(a): min_val = min(a[pivot:]) min_val_index = a[pivot:].index(min_val) tmp = a[pivot] a[pivot] = min_val a[min_val_index+pivot] = tmp pivot += 1
A list of integers is sorted in “Wave” order if alternate items are not less than their immediate neighbors (thus the other alternate items are not greater than their immediate neighbors). Thus, the array `[4, 1, 7, 5, 6, 2, 3]` is in **Wave** order because 4 >= 1, then 1 <= 7, then 7 >= 5, then 5 <= 6, then 6 >= 2, and finally 2 <= 3. The wave-sorted lists has to begin with an element not less than the next, so `[1, 4, 5, 3]` is not sorted in Wave because 1 < 4 Your task is to implement a function that takes a list of integers and sorts it into wave order in place; your function shouldn't return anything. Note: - The resulting array shouldn't necessarily match anyone in the tests, a function just checks if the array is now wave sorted.
def wave_sort(a): a.sort() size,half = len(a), len(a)>>1 for low,high in enumerate(range(0,size,2), half): a[low],a[high] = a[high],a[low] return a
A list of integers is sorted in “Wave” order if alternate items are not less than their immediate neighbors (thus the other alternate items are not greater than their immediate neighbors). Thus, the array `[4, 1, 7, 5, 6, 2, 3]` is in **Wave** order because 4 >= 1, then 1 <= 7, then 7 >= 5, then 5 <= 6, then 6 >= 2, and finally 2 <= 3. The wave-sorted lists has to begin with an element not less than the next, so `[1, 4, 5, 3]` is not sorted in Wave because 1 < 4 Your task is to implement a function that takes a list of integers and sorts it into wave order in place; your function shouldn't return anything. Note: - The resulting array shouldn't necessarily match anyone in the tests, a function just checks if the array is now wave sorted.
def wave_sort(a): a.sort() [a.insert(i+1, a.pop(i)) for i in range(len(a)) if i%2==0] return
A list of integers is sorted in “Wave” order if alternate items are not less than their immediate neighbors (thus the other alternate items are not greater than their immediate neighbors). Thus, the array `[4, 1, 7, 5, 6, 2, 3]` is in **Wave** order because 4 >= 1, then 1 <= 7, then 7 >= 5, then 5 <= 6, then 6 >= 2, and finally 2 <= 3. The wave-sorted lists has to begin with an element not less than the next, so `[1, 4, 5, 3]` is not sorted in Wave because 1 < 4 Your task is to implement a function that takes a list of integers and sorts it into wave order in place; your function shouldn't return anything. Note: - The resulting array shouldn't necessarily match anyone in the tests, a function just checks if the array is now wave sorted.
def wave_sort(a): a1, a2 = sorted(a), sorted(a)[::-1] for i in range(len(a)): if i % 2 == 1: a[i] = a1.pop(0) else: a[i] = a2.pop(0) print(a) return a
A list of integers is sorted in “Wave” order if alternate items are not less than their immediate neighbors (thus the other alternate items are not greater than their immediate neighbors). Thus, the array `[4, 1, 7, 5, 6, 2, 3]` is in **Wave** order because 4 >= 1, then 1 <= 7, then 7 >= 5, then 5 <= 6, then 6 >= 2, and finally 2 <= 3. The wave-sorted lists has to begin with an element not less than the next, so `[1, 4, 5, 3]` is not sorted in Wave because 1 < 4 Your task is to implement a function that takes a list of integers and sorts it into wave order in place; your function shouldn't return anything. Note: - The resulting array shouldn't necessarily match anyone in the tests, a function just checks if the array is now wave sorted.
def wave_sort(a): a.sort() array = [] length = len(a) if len(a) <= 1: return 0 for x in range(0,length//2,1): array.append(a[length-1-x]) array.append(a[x]) if len(a) % 2 != 0: array.insert(length-1, a[int((length/2))]) for x in range(0,length): a[x] = array[x]
A list of integers is sorted in “Wave” order if alternate items are not less than their immediate neighbors (thus the other alternate items are not greater than their immediate neighbors). Thus, the array `[4, 1, 7, 5, 6, 2, 3]` is in **Wave** order because 4 >= 1, then 1 <= 7, then 7 >= 5, then 5 <= 6, then 6 >= 2, and finally 2 <= 3. The wave-sorted lists has to begin with an element not less than the next, so `[1, 4, 5, 3]` is not sorted in Wave because 1 < 4 Your task is to implement a function that takes a list of integers and sorts it into wave order in place; your function shouldn't return anything. Note: - The resulting array shouldn't necessarily match anyone in the tests, a function just checks if the array is now wave sorted.
def wave_sort(a): s = a[:] f = [max, min] for i in range(len(a)): v = f[i%2](s) a[i] = v s.remove(v)
Write function `makeParts` or `make_parts` (depending on your language) that will take an array as argument and the size of the chunk. Example: if an array of size 123 is given and chunk size is 10 there will be 13 parts, 12 of size 10 and 1 of size 3.
def makeParts(arr, csize): return [ arr[i: i + csize] for i in range(0, len(arr), csize)]
Write function `makeParts` or `make_parts` (depending on your language) that will take an array as argument and the size of the chunk. Example: if an array of size 123 is given and chunk size is 10 there will be 13 parts, 12 of size 10 and 1 of size 3.
def makeParts(arr, chunkSize): return [arr[i:i+chunkSize] for i in range(0, len(arr), chunkSize)]
Write function `makeParts` or `make_parts` (depending on your language) that will take an array as argument and the size of the chunk. Example: if an array of size 123 is given and chunk size is 10 there will be 13 parts, 12 of size 10 and 1 of size 3.
def makeParts(arr, chunkSize): r = list() while arr: r.append(arr[0:chunkSize]) arr = arr[chunkSize:] return r
Write function `makeParts` or `make_parts` (depending on your language) that will take an array as argument and the size of the chunk. Example: if an array of size 123 is given and chunk size is 10 there will be 13 parts, 12 of size 10 and 1 of size 3.
def makeParts(arr, chunkSize): lst = [] for i in range(0, len(arr), chunkSize): lst.append(arr[i:i+chunkSize]) return lst
Write function `makeParts` or `make_parts` (depending on your language) that will take an array as argument and the size of the chunk. Example: if an array of size 123 is given and chunk size is 10 there will be 13 parts, 12 of size 10 and 1 of size 3.
def makeParts(arr, size): return [arr[i:i+size] for i in range(0, len(arr), size)]
Write function `makeParts` or `make_parts` (depending on your language) that will take an array as argument and the size of the chunk. Example: if an array of size 123 is given and chunk size is 10 there will be 13 parts, 12 of size 10 and 1 of size 3.
import math def makeParts(arr, size): c = [[] for i in range(math.ceil(len(arr)/size))] for i in range(len(arr)): c[int(i/size)].append(arr[i]) return c
Write function `makeParts` or `make_parts` (depending on your language) that will take an array as argument and the size of the chunk. Example: if an array of size 123 is given and chunk size is 10 there will be 13 parts, 12 of size 10 and 1 of size 3.
def makeParts(arr, chunk_size): return [arr[i:i + chunk_size] for i in range(0, len(arr), chunk_size)]
Write function `makeParts` or `make_parts` (depending on your language) that will take an array as argument and the size of the chunk. Example: if an array of size 123 is given and chunk size is 10 there will be 13 parts, 12 of size 10 and 1 of size 3.
from math import ceil; makeParts=lambda arr, c: [arr[i*c:i*c+c] for i in range(ceil(len(arr)/c))]
Write function `makeParts` or `make_parts` (depending on your language) that will take an array as argument and the size of the chunk. Example: if an array of size 123 is given and chunk size is 10 there will be 13 parts, 12 of size 10 and 1 of size 3.
def makeParts(arr, chunkSize): store = [] while len(arr) >= chunkSize: store.append(arr[:chunkSize]) arr = arr[chunkSize:] if len(arr) > 0: store.append(arr) return store
[XKCD 1609]( http://xkcd.com/1609/) provides us with the following fun fact: ![If anyone tries this on you, the best reply is a deadpan "Oh yeah, that's a common potato chip flavor in Canada."](http://imgs.xkcd.com/comics/food_combinations.png) ### Task: Given an array containing a list of good foods, return a string containing the assertion that any two of the individually good foods are really good when combined. eg: `"You know what's actually really good? Pancakes and relish."` ### Examples: ```python Good_foods = ["Ice cream", "Ham", "Relish", "Pancakes", "Ketchup", "Cheese", "Eggs", "Cupcakes", "Sour cream", "Hot chocolate", "Avocado", "Skittles"] actually_really_good( Good_foods ) # "You know what's actually really good? Pancakes and relish." actually_really_good( ['Peanut butter'] ) # "You know what's actually really good? Peanut butter and more peanut butter." actually_really_good( [] ) # "You know what's actually really good? Nothing!" ``` ### Notes: There are many different valid combinations of 2 foods it doesn't matter which one you choose. But there should be 2 different foods listed **unless** there was only one food given in the input array. Capitalization should be correct, the first given food should be capitalized, but the second should not. The input array should not be modified by the method. The test cases for this kata are fairly complicated, see if you can trick them. (Then let me know about it in the discourse.) The original kata language is *Ruby* ### Bonus: If you thought this kata was easy, try this one: [Testing 'Food combinations'](http://www.codewars.com/kata/testing-food-combinations) in which you get to write a method similar to the one the tests here use to check that a result is valid and returns any errors it has.
OUTPUT = 'You know what\'s actually really good? {}'.format def actually_really_good(foods): foods = list(set(foods)) length = len(foods) if length == 0: return OUTPUT('Nothing!') return OUTPUT('{} and more {}.'.format( foods[0].capitalize(), foods[0 if length == 1 else 1].lower()))
[XKCD 1609]( http://xkcd.com/1609/) provides us with the following fun fact: ![If anyone tries this on you, the best reply is a deadpan "Oh yeah, that's a common potato chip flavor in Canada."](http://imgs.xkcd.com/comics/food_combinations.png) ### Task: Given an array containing a list of good foods, return a string containing the assertion that any two of the individually good foods are really good when combined. eg: `"You know what's actually really good? Pancakes and relish."` ### Examples: ```python Good_foods = ["Ice cream", "Ham", "Relish", "Pancakes", "Ketchup", "Cheese", "Eggs", "Cupcakes", "Sour cream", "Hot chocolate", "Avocado", "Skittles"] actually_really_good( Good_foods ) # "You know what's actually really good? Pancakes and relish." actually_really_good( ['Peanut butter'] ) # "You know what's actually really good? Peanut butter and more peanut butter." actually_really_good( [] ) # "You know what's actually really good? Nothing!" ``` ### Notes: There are many different valid combinations of 2 foods it doesn't matter which one you choose. But there should be 2 different foods listed **unless** there was only one food given in the input array. Capitalization should be correct, the first given food should be capitalized, but the second should not. The input array should not be modified by the method. The test cases for this kata are fairly complicated, see if you can trick them. (Then let me know about it in the discourse.) The original kata language is *Ruby* ### Bonus: If you thought this kata was easy, try this one: [Testing 'Food combinations'](http://www.codewars.com/kata/testing-food-combinations) in which you get to write a method similar to the one the tests here use to check that a result is valid and returns any errors it has.
import random def actually_really_good(foods): if foods == []: return "You know what's actually really good? Nothing!" elif len(foods) == 1: s = random.choice(foods) return "You know what's actually really good? " + s.capitalize() + " and more " + s.lower() + "." else: return "You know what's actually really good? " + random.choice(foods).capitalize() + " and more " + random.choice(foods).lower() + "."
[XKCD 1609]( http://xkcd.com/1609/) provides us with the following fun fact: ![If anyone tries this on you, the best reply is a deadpan "Oh yeah, that's a common potato chip flavor in Canada."](http://imgs.xkcd.com/comics/food_combinations.png) ### Task: Given an array containing a list of good foods, return a string containing the assertion that any two of the individually good foods are really good when combined. eg: `"You know what's actually really good? Pancakes and relish."` ### Examples: ```python Good_foods = ["Ice cream", "Ham", "Relish", "Pancakes", "Ketchup", "Cheese", "Eggs", "Cupcakes", "Sour cream", "Hot chocolate", "Avocado", "Skittles"] actually_really_good( Good_foods ) # "You know what's actually really good? Pancakes and relish." actually_really_good( ['Peanut butter'] ) # "You know what's actually really good? Peanut butter and more peanut butter." actually_really_good( [] ) # "You know what's actually really good? Nothing!" ``` ### Notes: There are many different valid combinations of 2 foods it doesn't matter which one you choose. But there should be 2 different foods listed **unless** there was only one food given in the input array. Capitalization should be correct, the first given food should be capitalized, but the second should not. The input array should not be modified by the method. The test cases for this kata are fairly complicated, see if you can trick them. (Then let me know about it in the discourse.) The original kata language is *Ruby* ### Bonus: If you thought this kata was easy, try this one: [Testing 'Food combinations'](http://www.codewars.com/kata/testing-food-combinations) in which you get to write a method similar to the one the tests here use to check that a result is valid and returns any errors it has.
from random import choice def actually_really_good(foods): res, foods = 'Nothing!', [f.lower() for f in foods] if len(foods)==1: res="{} and more {}.".format(foods[0].capitalize(), foods[0]) elif len(foods)>=2: res="{} and {}.".format(foods[0].capitalize(), choice(foods[1:])) return "You know what's actually really good? {}".format(res)
[XKCD 1609]( http://xkcd.com/1609/) provides us with the following fun fact: ![If anyone tries this on you, the best reply is a deadpan "Oh yeah, that's a common potato chip flavor in Canada."](http://imgs.xkcd.com/comics/food_combinations.png) ### Task: Given an array containing a list of good foods, return a string containing the assertion that any two of the individually good foods are really good when combined. eg: `"You know what's actually really good? Pancakes and relish."` ### Examples: ```python Good_foods = ["Ice cream", "Ham", "Relish", "Pancakes", "Ketchup", "Cheese", "Eggs", "Cupcakes", "Sour cream", "Hot chocolate", "Avocado", "Skittles"] actually_really_good( Good_foods ) # "You know what's actually really good? Pancakes and relish." actually_really_good( ['Peanut butter'] ) # "You know what's actually really good? Peanut butter and more peanut butter." actually_really_good( [] ) # "You know what's actually really good? Nothing!" ``` ### Notes: There are many different valid combinations of 2 foods it doesn't matter which one you choose. But there should be 2 different foods listed **unless** there was only one food given in the input array. Capitalization should be correct, the first given food should be capitalized, but the second should not. The input array should not be modified by the method. The test cases for this kata are fairly complicated, see if you can trick them. (Then let me know about it in the discourse.) The original kata language is *Ruby* ### Bonus: If you thought this kata was easy, try this one: [Testing 'Food combinations'](http://www.codewars.com/kata/testing-food-combinations) in which you get to write a method similar to the one the tests here use to check that a result is valid and returns any errors it has.
def actually_really_good(foods): if len(foods) > 1: good = "{} and {}.".format(foods[0].capitalize(), foods[1].lower()) elif len(foods) == 1: good = "{} and more {}.".format(foods[0].capitalize(), foods[0].lower()) else: good = "Nothing!" return "You know what's actually really good? {}".format(good)
[XKCD 1609]( http://xkcd.com/1609/) provides us with the following fun fact: ![If anyone tries this on you, the best reply is a deadpan "Oh yeah, that's a common potato chip flavor in Canada."](http://imgs.xkcd.com/comics/food_combinations.png) ### Task: Given an array containing a list of good foods, return a string containing the assertion that any two of the individually good foods are really good when combined. eg: `"You know what's actually really good? Pancakes and relish."` ### Examples: ```python Good_foods = ["Ice cream", "Ham", "Relish", "Pancakes", "Ketchup", "Cheese", "Eggs", "Cupcakes", "Sour cream", "Hot chocolate", "Avocado", "Skittles"] actually_really_good( Good_foods ) # "You know what's actually really good? Pancakes and relish." actually_really_good( ['Peanut butter'] ) # "You know what's actually really good? Peanut butter and more peanut butter." actually_really_good( [] ) # "You know what's actually really good? Nothing!" ``` ### Notes: There are many different valid combinations of 2 foods it doesn't matter which one you choose. But there should be 2 different foods listed **unless** there was only one food given in the input array. Capitalization should be correct, the first given food should be capitalized, but the second should not. The input array should not be modified by the method. The test cases for this kata are fairly complicated, see if you can trick them. (Then let me know about it in the discourse.) The original kata language is *Ruby* ### Bonus: If you thought this kata was easy, try this one: [Testing 'Food combinations'](http://www.codewars.com/kata/testing-food-combinations) in which you get to write a method similar to the one the tests here use to check that a result is valid and returns any errors it has.
import random def actually_really_good(foods): if not foods: return "You know what's actually really good? Nothing!" food1, food2 = random.sample(foods, 2) if len(foods) > 1 else foods + ["more {}".format(foods[0])] return "You know what's actually really good? {} and {}.".format(food1.capitalize(), food2.lower())
[XKCD 1609]( http://xkcd.com/1609/) provides us with the following fun fact: ![If anyone tries this on you, the best reply is a deadpan "Oh yeah, that's a common potato chip flavor in Canada."](http://imgs.xkcd.com/comics/food_combinations.png) ### Task: Given an array containing a list of good foods, return a string containing the assertion that any two of the individually good foods are really good when combined. eg: `"You know what's actually really good? Pancakes and relish."` ### Examples: ```python Good_foods = ["Ice cream", "Ham", "Relish", "Pancakes", "Ketchup", "Cheese", "Eggs", "Cupcakes", "Sour cream", "Hot chocolate", "Avocado", "Skittles"] actually_really_good( Good_foods ) # "You know what's actually really good? Pancakes and relish." actually_really_good( ['Peanut butter'] ) # "You know what's actually really good? Peanut butter and more peanut butter." actually_really_good( [] ) # "You know what's actually really good? Nothing!" ``` ### Notes: There are many different valid combinations of 2 foods it doesn't matter which one you choose. But there should be 2 different foods listed **unless** there was only one food given in the input array. Capitalization should be correct, the first given food should be capitalized, but the second should not. The input array should not be modified by the method. The test cases for this kata are fairly complicated, see if you can trick them. (Then let me know about it in the discourse.) The original kata language is *Ruby* ### Bonus: If you thought this kata was easy, try this one: [Testing 'Food combinations'](http://www.codewars.com/kata/testing-food-combinations) in which you get to write a method similar to the one the tests here use to check that a result is valid and returns any errors it has.
def actually_really_good(foods): def formatter(pairFood): return (f(s) for f,s in zip((str.capitalize, str.lower), pairFood)) START = "You know what's actually really good? " return START + ("Nothing!" if not foods else "{1} and {0}{2}.".format("more "*(len(foods)==1), *formatter(foods*2 if len(foods)==1 else foods[:2])))
[XKCD 1609]( http://xkcd.com/1609/) provides us with the following fun fact: ![If anyone tries this on you, the best reply is a deadpan "Oh yeah, that's a common potato chip flavor in Canada."](http://imgs.xkcd.com/comics/food_combinations.png) ### Task: Given an array containing a list of good foods, return a string containing the assertion that any two of the individually good foods are really good when combined. eg: `"You know what's actually really good? Pancakes and relish."` ### Examples: ```python Good_foods = ["Ice cream", "Ham", "Relish", "Pancakes", "Ketchup", "Cheese", "Eggs", "Cupcakes", "Sour cream", "Hot chocolate", "Avocado", "Skittles"] actually_really_good( Good_foods ) # "You know what's actually really good? Pancakes and relish." actually_really_good( ['Peanut butter'] ) # "You know what's actually really good? Peanut butter and more peanut butter." actually_really_good( [] ) # "You know what's actually really good? Nothing!" ``` ### Notes: There are many different valid combinations of 2 foods it doesn't matter which one you choose. But there should be 2 different foods listed **unless** there was only one food given in the input array. Capitalization should be correct, the first given food should be capitalized, but the second should not. The input array should not be modified by the method. The test cases for this kata are fairly complicated, see if you can trick them. (Then let me know about it in the discourse.) The original kata language is *Ruby* ### Bonus: If you thought this kata was easy, try this one: [Testing 'Food combinations'](http://www.codewars.com/kata/testing-food-combinations) in which you get to write a method similar to the one the tests here use to check that a result is valid and returns any errors it has.
actually_really_good=lambda a:"You know what's actually really good? "+(a and"%s and %s."%(a[0],"more "*(a[0]==a[-1])+a[-1])or"Nothing!").capitalize()
[XKCD 1609]( http://xkcd.com/1609/) provides us with the following fun fact: ![If anyone tries this on you, the best reply is a deadpan "Oh yeah, that's a common potato chip flavor in Canada."](http://imgs.xkcd.com/comics/food_combinations.png) ### Task: Given an array containing a list of good foods, return a string containing the assertion that any two of the individually good foods are really good when combined. eg: `"You know what's actually really good? Pancakes and relish."` ### Examples: ```python Good_foods = ["Ice cream", "Ham", "Relish", "Pancakes", "Ketchup", "Cheese", "Eggs", "Cupcakes", "Sour cream", "Hot chocolate", "Avocado", "Skittles"] actually_really_good( Good_foods ) # "You know what's actually really good? Pancakes and relish." actually_really_good( ['Peanut butter'] ) # "You know what's actually really good? Peanut butter and more peanut butter." actually_really_good( [] ) # "You know what's actually really good? Nothing!" ``` ### Notes: There are many different valid combinations of 2 foods it doesn't matter which one you choose. But there should be 2 different foods listed **unless** there was only one food given in the input array. Capitalization should be correct, the first given food should be capitalized, but the second should not. The input array should not be modified by the method. The test cases for this kata are fairly complicated, see if you can trick them. (Then let me know about it in the discourse.) The original kata language is *Ruby* ### Bonus: If you thought this kata was easy, try this one: [Testing 'Food combinations'](http://www.codewars.com/kata/testing-food-combinations) in which you get to write a method similar to the one the tests here use to check that a result is valid and returns any errors it has.
def actually_really_good(foods): return "You know what's actually really good? {}".format('Nothing!' if not foods else '{} and {}.'.format(str.capitalize(foods[0]), (foods[1] if len(foods) > 1 else 'more %s' % foods[0]).lower()))
[XKCD 1609]( http://xkcd.com/1609/) provides us with the following fun fact: ![If anyone tries this on you, the best reply is a deadpan "Oh yeah, that's a common potato chip flavor in Canada."](http://imgs.xkcd.com/comics/food_combinations.png) ### Task: Given an array containing a list of good foods, return a string containing the assertion that any two of the individually good foods are really good when combined. eg: `"You know what's actually really good? Pancakes and relish."` ### Examples: ```python Good_foods = ["Ice cream", "Ham", "Relish", "Pancakes", "Ketchup", "Cheese", "Eggs", "Cupcakes", "Sour cream", "Hot chocolate", "Avocado", "Skittles"] actually_really_good( Good_foods ) # "You know what's actually really good? Pancakes and relish." actually_really_good( ['Peanut butter'] ) # "You know what's actually really good? Peanut butter and more peanut butter." actually_really_good( [] ) # "You know what's actually really good? Nothing!" ``` ### Notes: There are many different valid combinations of 2 foods it doesn't matter which one you choose. But there should be 2 different foods listed **unless** there was only one food given in the input array. Capitalization should be correct, the first given food should be capitalized, but the second should not. The input array should not be modified by the method. The test cases for this kata are fairly complicated, see if you can trick them. (Then let me know about it in the discourse.) The original kata language is *Ruby* ### Bonus: If you thought this kata was easy, try this one: [Testing 'Food combinations'](http://www.codewars.com/kata/testing-food-combinations) in which you get to write a method similar to the one the tests here use to check that a result is valid and returns any errors it has.
from random import shuffle def actually_really_good(foods): if not foods: return "You know what's actually really good? Nothing!" elif len(foods) == 1: return "You know what's actually really good? {0} and more {1}.".format(foods[0].capitalize(), foods[0].lower()) elif len(foods) > 2: shuffle(foods) return "You know what's actually really good? {0} and {1}.".format(foods[0].capitalize(), foods[1].lower())
[XKCD 1609]( http://xkcd.com/1609/) provides us with the following fun fact: ![If anyone tries this on you, the best reply is a deadpan "Oh yeah, that's a common potato chip flavor in Canada."](http://imgs.xkcd.com/comics/food_combinations.png) ### Task: Given an array containing a list of good foods, return a string containing the assertion that any two of the individually good foods are really good when combined. eg: `"You know what's actually really good? Pancakes and relish."` ### Examples: ```python Good_foods = ["Ice cream", "Ham", "Relish", "Pancakes", "Ketchup", "Cheese", "Eggs", "Cupcakes", "Sour cream", "Hot chocolate", "Avocado", "Skittles"] actually_really_good( Good_foods ) # "You know what's actually really good? Pancakes and relish." actually_really_good( ['Peanut butter'] ) # "You know what's actually really good? Peanut butter and more peanut butter." actually_really_good( [] ) # "You know what's actually really good? Nothing!" ``` ### Notes: There are many different valid combinations of 2 foods it doesn't matter which one you choose. But there should be 2 different foods listed **unless** there was only one food given in the input array. Capitalization should be correct, the first given food should be capitalized, but the second should not. The input array should not be modified by the method. The test cases for this kata are fairly complicated, see if you can trick them. (Then let me know about it in the discourse.) The original kata language is *Ruby* ### Bonus: If you thought this kata was easy, try this one: [Testing 'Food combinations'](http://www.codewars.com/kata/testing-food-combinations) in which you get to write a method similar to the one the tests here use to check that a result is valid and returns any errors it has.
def actually_really_good(foods): phrase="You know what's actually really good? " if len(foods)==0:return phrase+"Nothing!" elif len(foods)==1:return phrase+f"{foods[0].capitalize()} and more {foods[0].lower()}." else:return phrase+f"{foods[0].capitalize()} and {foods[1].lower()}."
The goal of this kata is to implement [trie](https://en.wikipedia.org/wiki/Trie) (or prefix tree) using dictionaries (aka hash maps or hash tables), where: 1. the dictionary keys are the prefixes 2. the value of a leaf node is `None` in Python, `nil` in Ruby and `null` in Groovy, JavaScript and Java. 3. the value for empty input is `{}` in Python, Ruby, Javascript and Java (empty map) and `[:]` in Groovy. **Examples:** ```python >>> build_trie() {} >>> build_trie("") {} >>> build_trie("trie") {'t': {'tr': {'tri': {'trie': None}}}} >>> build_trie("tree") {'t': {'tr': {'tre': {'tree': None}}}} >>> build_trie("A","to", "tea", "ted", "ten", "i", "in", "inn") {'A': None, 't': {'to': None, 'te': {'tea': None, 'ted': None, 'ten': None}}, 'i': {'in': {'inn': None}}} >>> build_trie("true", "trust") {'t': {'tr': {'tru': {'true': None, 'trus': {'trust': None}}}}} ``` Happy coding! :)
def build_trie(*words): root = {} for word in words: branch = root length = len(word) for i in range(1, length+1): length -= 1 key = word[:i] if key not in branch: branch[key] = None if length and not branch[key]: branch[key] = {} branch = branch[key] return root
The goal of this kata is to implement [trie](https://en.wikipedia.org/wiki/Trie) (or prefix tree) using dictionaries (aka hash maps or hash tables), where: 1. the dictionary keys are the prefixes 2. the value of a leaf node is `None` in Python, `nil` in Ruby and `null` in Groovy, JavaScript and Java. 3. the value for empty input is `{}` in Python, Ruby, Javascript and Java (empty map) and `[:]` in Groovy. **Examples:** ```python >>> build_trie() {} >>> build_trie("") {} >>> build_trie("trie") {'t': {'tr': {'tri': {'trie': None}}}} >>> build_trie("tree") {'t': {'tr': {'tre': {'tree': None}}}} >>> build_trie("A","to", "tea", "ted", "ten", "i", "in", "inn") {'A': None, 't': {'to': None, 'te': {'tea': None, 'ted': None, 'ten': None}}, 'i': {'in': {'inn': None}}} >>> build_trie("true", "trust") {'t': {'tr': {'tru': {'true': None, 'trus': {'trust': None}}}}} ``` Happy coding! :)
def build_trie(*words): d = {} for word in words: dd = d w, l = "", len(word) for c in word: w += c l -= 1 if w not in dd: dd[w] = None if l and dd[w] is None: dd[w] = {} dd = dd[w] return d
The goal of this kata is to implement [trie](https://en.wikipedia.org/wiki/Trie) (or prefix tree) using dictionaries (aka hash maps or hash tables), where: 1. the dictionary keys are the prefixes 2. the value of a leaf node is `None` in Python, `nil` in Ruby and `null` in Groovy, JavaScript and Java. 3. the value for empty input is `{}` in Python, Ruby, Javascript and Java (empty map) and `[:]` in Groovy. **Examples:** ```python >>> build_trie() {} >>> build_trie("") {} >>> build_trie("trie") {'t': {'tr': {'tri': {'trie': None}}}} >>> build_trie("tree") {'t': {'tr': {'tre': {'tree': None}}}} >>> build_trie("A","to", "tea", "ted", "ten", "i", "in", "inn") {'A': None, 't': {'to': None, 'te': {'tea': None, 'ted': None, 'ten': None}}, 'i': {'in': {'inn': None}}} >>> build_trie("true", "trust") {'t': {'tr': {'tru': {'true': None, 'trus': {'trust': None}}}}} ``` Happy coding! :)
def build_trie(*words): trie = {} for word in words: node = trie l = len(word) for i in range(1, l+1): w = word[:i] node[w] = node = {} if l-i and node.get(w) is None else node.get(w) return trie
The goal of this kata is to implement [trie](https://en.wikipedia.org/wiki/Trie) (or prefix tree) using dictionaries (aka hash maps or hash tables), where: 1. the dictionary keys are the prefixes 2. the value of a leaf node is `None` in Python, `nil` in Ruby and `null` in Groovy, JavaScript and Java. 3. the value for empty input is `{}` in Python, Ruby, Javascript and Java (empty map) and `[:]` in Groovy. **Examples:** ```python >>> build_trie() {} >>> build_trie("") {} >>> build_trie("trie") {'t': {'tr': {'tri': {'trie': None}}}} >>> build_trie("tree") {'t': {'tr': {'tre': {'tree': None}}}} >>> build_trie("A","to", "tea", "ted", "ten", "i", "in", "inn") {'A': None, 't': {'to': None, 'te': {'tea': None, 'ted': None, 'ten': None}}, 'i': {'in': {'inn': None}}} >>> build_trie("true", "trust") {'t': {'tr': {'tru': {'true': None, 'trus': {'trust': None}}}}} ``` Happy coding! :)
build_trie = lambda *words: (cheker(words) or {}) cheker = lambda wos, i=1: None if not wos else {l: cheker(tuple(x for x in wos if x[:i]==l and x!=l), i+1) for l in set(e[:i] for e in wos if e)}
The goal of this kata is to implement [trie](https://en.wikipedia.org/wiki/Trie) (or prefix tree) using dictionaries (aka hash maps or hash tables), where: 1. the dictionary keys are the prefixes 2. the value of a leaf node is `None` in Python, `nil` in Ruby and `null` in Groovy, JavaScript and Java. 3. the value for empty input is `{}` in Python, Ruby, Javascript and Java (empty map) and `[:]` in Groovy. **Examples:** ```python >>> build_trie() {} >>> build_trie("") {} >>> build_trie("trie") {'t': {'tr': {'tri': {'trie': None}}}} >>> build_trie("tree") {'t': {'tr': {'tre': {'tree': None}}}} >>> build_trie("A","to", "tea", "ted", "ten", "i", "in", "inn") {'A': None, 't': {'to': None, 'te': {'tea': None, 'ted': None, 'ten': None}}, 'i': {'in': {'inn': None}}} >>> build_trie("true", "trust") {'t': {'tr': {'tru': {'true': None, 'trus': {'trust': None}}}}} ``` Happy coding! :)
def build_trie(*words): return (cheker(words) or {}) def cheker(words, i=1): doc, selter = {}, set(e[:i] for e in words if e) for fl in selter: doc[fl] = cheker(tuple(e for e in words if e[:i]==fl and e!=fl), i+1) return None if not words else doc
The goal of this kata is to implement [trie](https://en.wikipedia.org/wiki/Trie) (or prefix tree) using dictionaries (aka hash maps or hash tables), where: 1. the dictionary keys are the prefixes 2. the value of a leaf node is `None` in Python, `nil` in Ruby and `null` in Groovy, JavaScript and Java. 3. the value for empty input is `{}` in Python, Ruby, Javascript and Java (empty map) and `[:]` in Groovy. **Examples:** ```python >>> build_trie() {} >>> build_trie("") {} >>> build_trie("trie") {'t': {'tr': {'tri': {'trie': None}}}} >>> build_trie("tree") {'t': {'tr': {'tre': {'tree': None}}}} >>> build_trie("A","to", "tea", "ted", "ten", "i", "in", "inn") {'A': None, 't': {'to': None, 'te': {'tea': None, 'ted': None, 'ten': None}}, 'i': {'in': {'inn': None}}} >>> build_trie("true", "trust") {'t': {'tr': {'tru': {'true': None, 'trus': {'trust': None}}}}} ``` Happy coding! :)
def build_trie(*words): trie={} k='' def recurse(trie,wd,k): for l in wd: k=k+l if k in trie: if trie[k]==None and len(wd)>1: trie[k]={} recurse(trie[k],wd[1:],k) else: trie[k]={} if len(wd)>1 else None recurse(trie[k],wd[1:],k) return trie [recurse(trie,word,'') for word in words] return trie
The goal of this kata is to implement [trie](https://en.wikipedia.org/wiki/Trie) (or prefix tree) using dictionaries (aka hash maps or hash tables), where: 1. the dictionary keys are the prefixes 2. the value of a leaf node is `None` in Python, `nil` in Ruby and `null` in Groovy, JavaScript and Java. 3. the value for empty input is `{}` in Python, Ruby, Javascript and Java (empty map) and `[:]` in Groovy. **Examples:** ```python >>> build_trie() {} >>> build_trie("") {} >>> build_trie("trie") {'t': {'tr': {'tri': {'trie': None}}}} >>> build_trie("tree") {'t': {'tr': {'tre': {'tree': None}}}} >>> build_trie("A","to", "tea", "ted", "ten", "i", "in", "inn") {'A': None, 't': {'to': None, 'te': {'tea': None, 'ted': None, 'ten': None}}, 'i': {'in': {'inn': None}}} >>> build_trie("true", "trust") {'t': {'tr': {'tru': {'true': None, 'trus': {'trust': None}}}}} ``` Happy coding! :)
def build_trie(*words): trie = {} for word in words: node = trie for i in range(1, len(word)+1): prefix = word[:i] if prefix not in node: node[prefix] = None if i < len(word) and node[prefix] is None: node[prefix] = {} node = node[prefix] return trie
The goal of this kata is to implement [trie](https://en.wikipedia.org/wiki/Trie) (or prefix tree) using dictionaries (aka hash maps or hash tables), where: 1. the dictionary keys are the prefixes 2. the value of a leaf node is `None` in Python, `nil` in Ruby and `null` in Groovy, JavaScript and Java. 3. the value for empty input is `{}` in Python, Ruby, Javascript and Java (empty map) and `[:]` in Groovy. **Examples:** ```python >>> build_trie() {} >>> build_trie("") {} >>> build_trie("trie") {'t': {'tr': {'tri': {'trie': None}}}} >>> build_trie("tree") {'t': {'tr': {'tre': {'tree': None}}}} >>> build_trie("A","to", "tea", "ted", "ten", "i", "in", "inn") {'A': None, 't': {'to': None, 'te': {'tea': None, 'ted': None, 'ten': None}}, 'i': {'in': {'inn': None}}} >>> build_trie("true", "trust") {'t': {'tr': {'tru': {'true': None, 'trus': {'trust': None}}}}} ``` Happy coding! :)
def build_trie(*words): trie = {} for word in words: trie = insert(trie, build_branch(word) if word else {}) return trie def build_branch(word, i=0): if i < len(word): return {word[:i+1]: build_branch(word, i+1)} def insert(trie, branch): if branch and trie: k, v = next(iter(list(branch.items()))) if k in trie: trie[k] = insert(trie.get(k, {}), v) else: trie[k] = v return trie or branch
The goal of this kata is to implement [trie](https://en.wikipedia.org/wiki/Trie) (or prefix tree) using dictionaries (aka hash maps or hash tables), where: 1. the dictionary keys are the prefixes 2. the value of a leaf node is `None` in Python, `nil` in Ruby and `null` in Groovy, JavaScript and Java. 3. the value for empty input is `{}` in Python, Ruby, Javascript and Java (empty map) and `[:]` in Groovy. **Examples:** ```python >>> build_trie() {} >>> build_trie("") {} >>> build_trie("trie") {'t': {'tr': {'tri': {'trie': None}}}} >>> build_trie("tree") {'t': {'tr': {'tre': {'tree': None}}}} >>> build_trie("A","to", "tea", "ted", "ten", "i", "in", "inn") {'A': None, 't': {'to': None, 'te': {'tea': None, 'ted': None, 'ten': None}}, 'i': {'in': {'inn': None}}} >>> build_trie("true", "trust") {'t': {'tr': {'tru': {'true': None, 'trus': {'trust': None}}}}} ``` Happy coding! :)
from itertools import accumulate def f(d, word): for c in accumulate(word): if c not in d: d[c] = {} d = d[c] def replace(d): return {key: replace(value) for key, value in d.items()} if d else None def build_trie(*words): d = {} for word in words: f(d, word) return replace(d) or {}
The goal of this kata is to implement [trie](https://en.wikipedia.org/wiki/Trie) (or prefix tree) using dictionaries (aka hash maps or hash tables), where: 1. the dictionary keys are the prefixes 2. the value of a leaf node is `None` in Python, `nil` in Ruby and `null` in Groovy, JavaScript and Java. 3. the value for empty input is `{}` in Python, Ruby, Javascript and Java (empty map) and `[:]` in Groovy. **Examples:** ```python >>> build_trie() {} >>> build_trie("") {} >>> build_trie("trie") {'t': {'tr': {'tri': {'trie': None}}}} >>> build_trie("tree") {'t': {'tr': {'tre': {'tree': None}}}} >>> build_trie("A","to", "tea", "ted", "ten", "i", "in", "inn") {'A': None, 't': {'to': None, 'te': {'tea': None, 'ted': None, 'ten': None}}, 'i': {'in': {'inn': None}}} >>> build_trie("true", "trust") {'t': {'tr': {'tru': {'true': None, 'trus': {'trust': None}}}}} ``` Happy coding! :)
def build_trie(*Q) : R = {'' : {}} for V in Q : for B in range(len(V)) : B = V[:1 + B] if not B in R : if not R[B[:-1]] : R[B[:-2]][B[:-1]] = R[B[:-1]] = {} R[B[:-1]][B] = R[B] = None return R['']
The objective is to write a method that takes two integer parameters and returns a single integer equal to the number of 1s in the binary representation of the greatest common divisor of the parameters. Taken from Wikipedia: "In mathematics, the greatest common divisor (gcd) of two or more integers, when at least one of them is not zero, is the largest positive integer that divides the numbers without a remainder. For example, the GCD of 8 and 12 is 4." For example: the greatest common divisor of 300 and 45 is 15. The binary representation of 15 is 1111, so the correct output would be 4. If both parameters are 0, the method should return 0. The function must be able to handle negative input.
from fractions import gcd def binary_gcd(x, y): return bin(gcd(x, y)).count('1')
The objective is to write a method that takes two integer parameters and returns a single integer equal to the number of 1s in the binary representation of the greatest common divisor of the parameters. Taken from Wikipedia: "In mathematics, the greatest common divisor (gcd) of two or more integers, when at least one of them is not zero, is the largest positive integer that divides the numbers without a remainder. For example, the GCD of 8 and 12 is 4." For example: the greatest common divisor of 300 and 45 is 15. The binary representation of 15 is 1111, so the correct output would be 4. If both parameters are 0, the method should return 0. The function must be able to handle negative input.
def binary_gcd(x, y): import math return bin(math.gcd(x,y)).count('1')
The objective is to write a method that takes two integer parameters and returns a single integer equal to the number of 1s in the binary representation of the greatest common divisor of the parameters. Taken from Wikipedia: "In mathematics, the greatest common divisor (gcd) of two or more integers, when at least one of them is not zero, is the largest positive integer that divides the numbers without a remainder. For example, the GCD of 8 and 12 is 4." For example: the greatest common divisor of 300 and 45 is 15. The binary representation of 15 is 1111, so the correct output would be 4. If both parameters are 0, the method should return 0. The function must be able to handle negative input.
def binary_gcd(x, y): if x==0 and y==0: return 0 def gcd(a, b): if b == 0: return a return gcd(b, a%b) return sum( c == '1' for c in bin(gcd(x, y))[2:] )
The objective is to write a method that takes two integer parameters and returns a single integer equal to the number of 1s in the binary representation of the greatest common divisor of the parameters. Taken from Wikipedia: "In mathematics, the greatest common divisor (gcd) of two or more integers, when at least one of them is not zero, is the largest positive integer that divides the numbers without a remainder. For example, the GCD of 8 and 12 is 4." For example: the greatest common divisor of 300 and 45 is 15. The binary representation of 15 is 1111, so the correct output would be 4. If both parameters are 0, the method should return 0. The function must be able to handle negative input.
from fractions import gcd def binary_gcd(x, y): if not (x or y): bin(max(x,y)).count('1') return bin(gcd(x,y)).count('1')
The objective is to write a method that takes two integer parameters and returns a single integer equal to the number of 1s in the binary representation of the greatest common divisor of the parameters. Taken from Wikipedia: "In mathematics, the greatest common divisor (gcd) of two or more integers, when at least one of them is not zero, is the largest positive integer that divides the numbers without a remainder. For example, the GCD of 8 and 12 is 4." For example: the greatest common divisor of 300 and 45 is 15. The binary representation of 15 is 1111, so the correct output would be 4. If both parameters are 0, the method should return 0. The function must be able to handle negative input.
def binary_gcd(x, y): from fractions import gcd return bin(reduce(gcd, [x, y])).count("1")
The objective is to write a method that takes two integer parameters and returns a single integer equal to the number of 1s in the binary representation of the greatest common divisor of the parameters. Taken from Wikipedia: "In mathematics, the greatest common divisor (gcd) of two or more integers, when at least one of them is not zero, is the largest positive integer that divides the numbers without a remainder. For example, the GCD of 8 and 12 is 4." For example: the greatest common divisor of 300 and 45 is 15. The binary representation of 15 is 1111, so the correct output would be 4. If both parameters are 0, the method should return 0. The function must be able to handle negative input.
import fractions def binary_gcd(x, y): output = bin(fractions.gcd(x,y)) return output.count('1')
The objective is to write a method that takes two integer parameters and returns a single integer equal to the number of 1s in the binary representation of the greatest common divisor of the parameters. Taken from Wikipedia: "In mathematics, the greatest common divisor (gcd) of two or more integers, when at least one of them is not zero, is the largest positive integer that divides the numbers without a remainder. For example, the GCD of 8 and 12 is 4." For example: the greatest common divisor of 300 and 45 is 15. The binary representation of 15 is 1111, so the correct output would be 4. If both parameters are 0, the method should return 0. The function must be able to handle negative input.
def binary_gcd(x, y): while(y): x, y = y, x % y binaryx = bin(abs(x)) #this returns a string bingcd= binaryx.replace('0b', '') return(sum(int(i) for i in bingcd))
The objective is to write a method that takes two integer parameters and returns a single integer equal to the number of 1s in the binary representation of the greatest common divisor of the parameters. Taken from Wikipedia: "In mathematics, the greatest common divisor (gcd) of two or more integers, when at least one of them is not zero, is the largest positive integer that divides the numbers without a remainder. For example, the GCD of 8 and 12 is 4." For example: the greatest common divisor of 300 and 45 is 15. The binary representation of 15 is 1111, so the correct output would be 4. If both parameters are 0, the method should return 0. The function must be able to handle negative input.
def check(n): #求所有除数之和 set1 = set() #创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等 for i in range(1, int(n**0.5)+1): if n%i == 0: set1.add(i) set1.add(n//i) return set1 def binary_gcd(x, y): if x==0 and y==0: return 0 elif x == 0 and y !=0: a = y elif y == 0 and x !=0: a = x else: a = max(check(abs(x)) & check(abs(y))) num = 0 while a != 0: a = a & (a - 1) # 就是这个操作,需要掌握,它的本质含义是抹去了0不考虑 num += 1 return num
The objective is to write a method that takes two integer parameters and returns a single integer equal to the number of 1s in the binary representation of the greatest common divisor of the parameters. Taken from Wikipedia: "In mathematics, the greatest common divisor (gcd) of two or more integers, when at least one of them is not zero, is the largest positive integer that divides the numbers without a remainder. For example, the GCD of 8 and 12 is 4." For example: the greatest common divisor of 300 and 45 is 15. The binary representation of 15 is 1111, so the correct output would be 4. If both parameters are 0, the method should return 0. The function must be able to handle negative input.
from math import gcd def binary_gcd(x, y): return sum(1 for x in bin(gcd(x, y)) if x == '1')
The objective is to write a method that takes two integer parameters and returns a single integer equal to the number of 1s in the binary representation of the greatest common divisor of the parameters. Taken from Wikipedia: "In mathematics, the greatest common divisor (gcd) of two or more integers, when at least one of them is not zero, is the largest positive integer that divides the numbers without a remainder. For example, the GCD of 8 and 12 is 4." For example: the greatest common divisor of 300 and 45 is 15. The binary representation of 15 is 1111, so the correct output would be 4. If both parameters are 0, the method should return 0. The function must be able to handle negative input.
def binary_gcd(x, y): if x == 0 and y == 0: return 0 elif x == 0 or y == 0: return bin(max(abs(x),abs(y))).count('1') for i in range(min(abs(x),abs(y)),0,-1): if (x % i == 0 and y % i == 0): return bin(i).count('1')
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): return filter(str.isdigit, x) if isinstance(x, str) else 'Invalid input !'