Kumite (ko͞omiˌtā) is the practice of taking techniques learned from Kata and applying them through the act of freestyle sparring.
You can create a new kumite by providing some initial code and optionally some test cases. From there other warriors can spar with you, by enhancing, refactoring and translating your code. There is no limit to how many warriors you can spar with.
A great use for kumite is to begin an idea for a kata as one. You can collaborate with other code warriors until you have it right, then you can convert it to a kata.
Goal
Not really sure. But it looks like we're calculating the actual probability of a ruleset and comparing it to the calculated probability.
Fork 1
I changed the testing to use assert_approx_equals
instead of assert_equals
since the implementation was the same, and it makes testing more consistent. Added a zero to the range we're using to increase the odds we will match expected probability, and made a minor optimization to use a comprehension since we're iterating 100,000 times.
I also refactored the funtion to take our alternate ruleset, and run those rules if true. Can't get it to pass the tests though. It's something though.
from random import randint playing_board = [0] * 100 # board is 100 positions long position = 0 # player starts at position 0 on the board while position < 100: # end when position moves off board playing_board[position] = 1 # player was here position += randint(1, 6) # throw a die and move # what's the probability that playing_board[n] == 1? # there is a prize if you land on position n # but a cost for playing the game # let's run N times def probability(other_rule=False): successes = [0] * 100 if not other_rule: for n in range(100000): # maybe this isn't big enough # maybe it is now? playing_board = [0] * 100 position = 0 while position < 100: successes[position] += 1 position += randint(1, 6) return [s / n for s in successes] # what if we add a rule # if the player lands on square 99, they teleport back to 0 for n in range(100000): playing_board = [0] * 100 # board is 100 positions long position = 0 # player starts at position 0 on the board while position < 100: # end when position moves off board successes[position] += 1 # player was here position += randint(1, 6) # throw a die and move if position == 99: position = 0 # snakey snake return [s / n for s in successes] # can you calculate the probability of the prize now?
- from random import randint
- playing_board = [0] * 100 # board is 100 positions long
- position = 0 # player starts at position 0 on the board
- while position < 100: # end when position moves off board
- playing_board[position] = 1 # player was here
- position += randint(1, 6) # throw a die and move
- # what's the probability that playing_board[n] == 1?
- # there is a prize if you land on position n
- # but a cost for playing the game
- # let's run N times
def probability():N = 10000 # maybe this isn't big enough- def probability(other_rule=False):
- successes = [0] * 100
for _ in range(N):playing_board = [0] * 100position = 0while position < 100:successes[position] += 1position += randint(1, 6)ret = []for s in successes:ret.append(s / N)return ret- if not other_rule:
- for n in range(100000): # maybe this isn't big enough # maybe it is now?
- playing_board = [0] * 100
- position = 0
- while position < 100:
- successes[position] += 1
- position += randint(1, 6)
- return [s / n for s in successes]
- # what if we add a rule
- # if the player lands on square 99, they teleport back to 0
- for n in range(100000):
- playing_board = [0] * 100 # board is 100 positions long
- position = 0 # player starts at position 0 on the board
- while position < 100: # end when position moves off board
- successes[position] += 1 # player was here
- position += randint(1, 6) # throw a die and move
- if position == 99: position = 0 # snakey snake
- return [s / n for s in successes]
# what if we add a rule# if the player lands on square 99, they teleport back to 0playing_board = [0] * 100 # board is 100 positions longposition = 0 # player starts at position 0 on the boardwhile position < 100: # end when position moves off boardplaying_board[position] = 1 # player was hereposition += randint(1, 6) # throw a die and moveif position == 99: position = 0 # snakey snake- # can you calculate the probability of the prize now?
import codewars_test as test from solution import probability default = [1] for _ in range(99): default.append(sum(default[-6:]) / 6) other = [1.28571428571428753] for _ in range(99): other.append(sum(other[-6:]) / 6) # test.assert_equals(actual, expected, [optional] message) # this should be used for strict equals # test.assert_approx_equals(actual, expected, margin=1e-9, message=None, allow_raise=False) # we use this instead @test.describe("Get close enough") def test_group(): @test.it("Stay within 1 d.p. of accuracy, default rule") def test_case(): user_probs = probability() for n in range(100): test.assert_approx_equals(user_probs[n], default[n], margin=0.1) @test.it("Stay within 2 d.p. of accuracy, default rule") def test_case(): user_probs = probability() for n in range(100): test.assert_approx_equals(user_probs[n], default[n], margin=0.01) @test.it("Stay within 1 d.p. of accuracy, other rule") def test_case(): user_probs = probability(True) for n in range(100): test.assert_approx_equals(user_probs[n], other[n], margin=0.1) @test.it("Stay within 2 d.p. of accuracy, other rule") def test_case(): user_probs = probability(True) for n in range(100): test.assert_approx_equals(user_probs[n], other[n], margin=0.01)
- import codewars_test as test
- from solution import probability
probabilities = [1]- default = [1]
- for _ in range(99):
probabilities.append(sum(probabilities[-6:]) / 6)- default.append(sum(default[-6:]) / 6)
- other = [1.28571428571428753]
- for _ in range(99):
- other.append(sum(other[-6:]) / 6)
# test.assert_equals(actual, expected, [optional] message)- # test.assert_equals(actual, expected, [optional] message) # this should be used for strict equals
- # test.assert_approx_equals(actual, expected, margin=1e-9, message=None, allow_raise=False) # we use this instead
- @test.describe("Get close enough")
- def test_group():
@test.it("Say within 1 d.p. of accuracy")- @test.it("Stay within 1 d.p. of accuracy, default rule")
- def test_case():
- user_probs = probability()
- for n in range(100):
test.assert_equals(abs(user_probs[n] - probabilities[n]) < 0.1, True, "The error was " + str(abs(user_probs[n] - probabilities[n])))@test.it("Say within 2 d.p. of accuracy")- test.assert_approx_equals(user_probs[n], default[n], margin=0.1)
- @test.it("Stay within 2 d.p. of accuracy, default rule")
- def test_case():
- user_probs = probability()
- for n in range(100):
test.assert_equals(abs(user_probs[n] - probabilities[n]) < 0.01, True, "The error was " + str(abs(user_probs[n] - probabilities[n])))- test.assert_approx_equals(user_probs[n], default[n], margin=0.01)
- @test.it("Stay within 1 d.p. of accuracy, other rule")
- def test_case():
- user_probs = probability(True)
- for n in range(100):
- test.assert_approx_equals(user_probs[n], other[n], margin=0.1)
- @test.it("Stay within 2 d.p. of accuracy, other rule")
- def test_case():
- user_probs = probability(True)
- for n in range(100):
- test.assert_approx_equals(user_probs[n], other[n], margin=0.01)
The goal of this kumite is to separate each adjacient pair of characters in the original string by an additional space (' '
) character.
Original
Used std::accumulate
to achieve this
Fork 1
- if the string is empty, return empty string (next steps require the string to be nonempty)
- preallocate a buffer of size
2*string.length()-1
filled with space characters - map each each character of original string from position
i
to position2*i
in the buffer
#include <string> std::string digest(const std::string& str) { if(str.empty()) return ""; std::string buff (str.size()*2-1, ' '); for(std::size_t i = 0; i < str.size(); ++i) buff[2*i] = str[i]; return buff; }
- #include <string>
#include <numeric>std::string digest(const std::string& param) {return param.empty()?param: std::accumulate(std::next(param.cbegin()),param.cend(),std::string(1,param[0]),[](auto &s, auto c) {return s.append(" ").append(1,c);});- std::string digest(const std::string& str) {
- if(str.empty())
- return "";
- std::string buff (str.size()*2-1, ' ');
- for(std::size_t i = 0; i < str.size(); ++i)
- buff[2*i] = str[i];
- return buff;
- }
// TODO: Replace examples and use TDD by writing your own tests Describe(any_group_name_you_want) { It(should_do_something) { Assert::That(digest("Burger"), Equals("B u r g e r")); Assert::That(digest("FoEMfIp"), Equals("F o E M f I p")); Assert::That(digest("Haggis"), Equals("H a g g i s")); Assert::That(digest("chitlins"), Equals("c h i t l i n s")); Assert::That(digest("SPAM"), Equals("S P A M")); Assert::That(digest("S 1P 2A 3M"), Equals("S 1 P 2 A 3 M")); Assert::That(digest("1234567"), Equals("1 2 3 4 5 6 7")); Assert::That(digest("{1,2,3,4,5,6,7}"), Equals("{ 1 , 2 , 3 , 4 , 5 , 6 , 7 }")); Assert::That(digest("{1:'a',2:'b',3:'c'}"), Equals("{ 1 : ' a ' , 2 : ' b ' , 3 : ' c ' }")); // Check for the two special cases !! Assert::That(digest("B"), Equals("B")); Assert::That(digest(""), Equals("")); } };
- // TODO: Replace examples and use TDD by writing your own tests
- Describe(any_group_name_you_want)
- {
- It(should_do_something)
- {
- Assert::That(digest("Burger"), Equals("B u r g e r"));
- Assert::That(digest("FoEMfIp"), Equals("F o E M f I p"));
- Assert::That(digest("Haggis"), Equals("H a g g i s"));
- Assert::That(digest("chitlins"), Equals("c h i t l i n s"));
- Assert::That(digest("SPAM"), Equals("S P A M"));
- Assert::That(digest("S 1P 2A 3M"), Equals("S 1 P 2 A 3 M"));
- Assert::That(digest("1234567"), Equals("1 2 3 4 5 6 7"));
// Assert::That(digest("{1,2,3,4,5,6,7}"), Equals("{ 1 , 2 , 3 , 4 , 5 , 6 , 7 }"));// Assert::That(digest("{1:'a',2:'b',3:'c'}"), Equals("{ 1 : ' a ' , 2 : ' b ' , 3 : ' c ' }"));- Assert::That(digest("{1,2,3,4,5,6,7}"), Equals("{ 1 , 2 , 3 , 4 , 5 , 6 , 7 }"));
- Assert::That(digest("{1:'a',2:'b',3:'c'}"), Equals("{ 1 : ' a ' , 2 : ' b ' , 3 : ' c ' }"));
- // Check for the two special cases !!
- Assert::That(digest("B"), Equals("B"));
- Assert::That(digest(""), Equals(""));
- }
- };
Goal
Write a function matrix()
that takes a 2D array, an operation, a target location, and an optional write_data as an input.
def matrix(matrice=[[1,2,3],
[4,5,6],
[7,8,9]], operation="write", location=(0, 1), write_data=7)
Your function should catch any IndexError that occers. Return values should be:
- if write: The new matrix, after adding write_data in the location given.
- if read: The existing data at the requested location.
- if neither: raise an AttributeError with any message.
Fork 1
Cleaned up some of the error checking to use best practices. Added testing for the error checking. Added random testing with basic matricies from numpy.
The random tests are honestly scuffed beyond belief. I've never worked with numpy before, and this is probably a bad first experience. I would love to see someone fix the mess that I've made lol... sorry in advance. I decided to cap the size of random tests at 100 since this isn't really meant to be a preformance type kumite. Ran a couple times and seems like a good upper limit imo.
def matrix(matrice=list, operation=str, location=tuple, write_data=None): if operation == "read": try: return matrice[location[0]][location[1]] except IndexError as e: print(e) return 0 elif operation == "write": try: matrice[location[0]][location[1]] = write_data return matrice except IndexError as e: print(e) return 0 else: raise AttributeError("That is not a valid operation for this system.")
def matrix(matrice=list, operation=str, location=tuple, writedata=None):- def matrix(matrice=list, operation=str, location=tuple, write_data=None):
- if operation == "read":
try:- try:
- return matrice[location[0]][location[1]]
except Exception as e:- except IndexError as e:
- print(e)
- return 0
- elif operation == "write":
- try:
matrice[location[0]][location[1]] = writedata- matrice[location[0]][location[1]] = write_data
- return matrice
except Exception as e:- except IndexError as e:
- print(e)
- return 0
- else:
raise OperationError("That is not a valid operation for this system.")- raise AttributeError("That is not a valid operation for this system.")
import codewars_test as test from solution import matrix import numpy import random # Working solution def working_matrix(mx, op, loc, wd=None): if op == "read": try: return mx[loc[0]][loc[1]] except IndexError as e: return 0 elif op == "write": try: mx[loc[0]][loc[1]] = wd return mx except IndexError as e: return 0 else: raise AttributeError("That is not a valid operation for this system.") def get_rand_matrix(size): return [i for i in numpy.random.randint(0, 100, (size, size))] # Start of testing @test.describe("Example") def test_group(): @test.it("Fixed Tests") def test_case(): test.assert_equals(matrix([[1,2,3], [4,5,6], [7,8,9]], "read", (0,1)), 2) test.assert_equals(matrix([[1,2,3], [4,5,6], [7,8,9]], "write", (0,1), 7), [[1,7,3], [4,5,6], [7,8,9]]) test.assert_equals(matrix([[1,2,3], [4,5,6], [7,8,9]], "read", (1,2)), 6) test.assert_equals(matrix([[1,2,3], [4,5,6], [7,8,9]], "write", (1,2), 7), [[1,2,3], [4,5,7], [7,8,9]]) @test.it("Test Error Catching") def test_case(): try: matrix([[1,2,3],[1,2,3]], 'copy', (0,1)) test.fail('Your function did not raise the correct error.') except AttributeError as e: test.pass_() try: test.assert_equals(matrix([[1,2,3],[1,2,3]], 'read', (2,4)), 0) except IndexError as e: test.fail('Your function allowed for an IndexError. Expected 0') try: test.assert_equals(matrix([[1,2,3],[1,2,3]], 'write', (2,4)), 0) except IndexError as e: test.fail('Your function allowed for an IndexError. Expected 0') test.assert_equals(matrix([[1,2,3],[1,2,3]], 'write', (1, 1)), [[1, 2, 3], [1, None, 3]]) @test.describe('Random Tests') def random_time(): @test.it('Small Tests') def small_rand(): for i in range(25): length = random.randrange(3, 10) test_matrix = get_rand_matrix(length) user_test = test_matrix.copy() rand_index = (random.randrange(-length, length + 2), random.randrange(-length, length + 2)) if i % 2: data = random.randrange(0, 100) sol = working_matrix(test_matrix, 'write', rand_index, data) test.assert_equals(matrix(user_test, 'write', rand_index, data), sol) else: sol = working_matrix(test_matrix, 'read', rand_index) test.assert_equals(matrix(user_test, 'read', rand_index), sol) @test.it('Medium Tests') def medium_rand(): for i in range(25): length = random.randrange(10, 50) test_matrix = get_rand_matrix(length) user_test = test_matrix.copy() rand_index = (random.randrange(-length, length + 2), random.randrange(-length, length + 2)) if i % 2: data = random.randrange(0, 100) sol = working_matrix(test_matrix, 'write', rand_index, data) test.assert_equals(matrix(user_test, 'write', rand_index, data), sol) else: sol = working_matrix(test_matrix, 'read', rand_index) test.assert_equals(matrix(user_test, 'read', rand_index), sol) @test.it('Large Tests') def large_rand(): for i in range(25): length = random.randrange(50, 100) test_matrix = get_rand_matrix(length) user_test = test_matrix.copy() rand_index = (random.randrange(-length, length + 2), random.randrange(-length, length + 2)) if i % 2: data = random.randrange(0, 100) sol = working_matrix(test_matrix, 'write', rand_index, data) test.assert_equals(matrix(user_test, 'write', rand_index, data), sol) else: sol = working_matrix(test_matrix, 'read', rand_index) test.assert_equals(matrix(user_test, 'read', rand_index), sol)
- import codewars_test as test
# TODO Write testsfrom solution import matrix # or from solution import example- from solution import matrix
# test.assert_equals(actual, expected, [optional] message)- import numpy
- import random
- # Working solution
- def working_matrix(mx, op, loc, wd=None):
- if op == "read":
- try: return mx[loc[0]][loc[1]]
- except IndexError as e:
- return 0
- elif op == "write":
- try:
- mx[loc[0]][loc[1]] = wd
- return mx
- except IndexError as e:
- return 0
- else:
- raise AttributeError("That is not a valid operation for this system.")
- def get_rand_matrix(size):
- return [i for i in numpy.random.randint(0, 100, (size, size))]
- # Start of testing
- @test.describe("Example")
- def test_group():
@test.it("test case")- @test.it("Fixed Tests")
- def test_case():
- test.assert_equals(matrix([[1,2,3],
- [4,5,6],
- [7,8,9]], "read", (0,1)), 2)
- test.assert_equals(matrix([[1,2,3],
- [4,5,6],
- [7,8,9]], "write", (0,1), 7), [[1,7,3],
- [4,5,6],
- [7,8,9]])
- test.assert_equals(matrix([[1,2,3],
- [4,5,6],
- [7,8,9]], "read", (1,2)), 6)
- test.assert_equals(matrix([[1,2,3],
- [4,5,6],
- [7,8,9]], "write", (1,2), 7), [[1,2,3],
- [4,5,7],
- [7,8,9]])
- @test.it("Test Error Catching")
- def test_case():
- try:
- matrix([[1,2,3],[1,2,3]], 'copy', (0,1))
- test.fail('Your function did not raise the correct error.')
- except AttributeError as e:
- test.pass_()
- try:
- test.assert_equals(matrix([[1,2,3],[1,2,3]], 'read', (2,4)), 0)
- except IndexError as e:
- test.fail('Your function allowed for an IndexError. Expected 0')
- try:
- test.assert_equals(matrix([[1,2,3],[1,2,3]], 'write', (2,4)), 0)
- except IndexError as e:
- test.fail('Your function allowed for an IndexError. Expected 0')
- test.assert_equals(matrix([[1,2,3],[1,2,3]], 'write', (1, 1)), [[1, 2, 3], [1, None, 3]])
- @test.describe('Random Tests')
- def random_time():
- @test.it('Small Tests')
- def small_rand():
- for i in range(25):
- length = random.randrange(3, 10)
- test_matrix = get_rand_matrix(length)
- user_test = test_matrix.copy()
- rand_index = (random.randrange(-length, length + 2), random.randrange(-length, length + 2))
- if i % 2:
- data = random.randrange(0, 100)
- sol = working_matrix(test_matrix, 'write', rand_index, data)
- test.assert_equals(matrix(user_test, 'write', rand_index, data), sol)
- else:
- sol = working_matrix(test_matrix, 'read', rand_index)
- test.assert_equals(matrix(user_test, 'read', rand_index), sol)
- @test.it('Medium Tests')
- def medium_rand():
- for i in range(25):
- length = random.randrange(10, 50)
- test_matrix = get_rand_matrix(length)
- user_test = test_matrix.copy()
- rand_index = (random.randrange(-length, length + 2), random.randrange(-length, length + 2))
- if i % 2:
- data = random.randrange(0, 100)
- sol = working_matrix(test_matrix, 'write', rand_index, data)
- test.assert_equals(matrix(user_test, 'write', rand_index, data), sol)
- else:
- sol = working_matrix(test_matrix, 'read', rand_index)
- test.assert_equals(matrix(user_test, 'read', rand_index), sol)
- @test.it('Large Tests')
- def large_rand():
- for i in range(25):
- length = random.randrange(50, 100)
- test_matrix = get_rand_matrix(length)
- user_test = test_matrix.copy()
- rand_index = (random.randrange(-length, length + 2), random.randrange(-length, length + 2))
- if i % 2:
- data = random.randrange(0, 100)
- sol = working_matrix(test_matrix, 'write', rand_index, data)
- test.assert_equals(matrix(user_test, 'write', rand_index, data), sol)
- else:
- sol = working_matrix(test_matrix, 'read', rand_index)
- test.assert_equals(matrix(user_test, 'read', rand_index), sol)
Goal
You are collecting data that fits a wave signal. Your must determine witch mathematical expression fits the signal. You will receive an array of numbers into your function called find_signal()
All numbers in the array will obey one of these expressions:
y = sin x,
y = cos x,
y = sin x + cos x
The given y values will always correspond to x input values of 0, 1, 2, ... n where n is the length of the array - 1. Your function will identify which signal is coming in and return string: 'sin x', 'cos x' or 'sin x + cos x'. Otherwise, None
All inputs will have at least 2 numbers to indicate a clear answer.
Fork 1
Removed duplicate tests. Added more precise floating point values instead of rounded numbers. (I think its best practice to avoid rounding where it is not absolutely necessary? Either way, it makes the random tests easier to build, and the actual code more accurate). Added random tests
In addition to what's above, I refactored pretty much the whole code to accept more than just 4 numbers. The random tests will give an array of size 2 <= n <= 1000
. We start at 2 to avoid edge cases between cos, and sin + cos. I'm sure someone smarter than I could find a way to include those as well, but I think this is good enough for a pretty simple problem like this.
import math as m def find_signal(wave): sinx = ('sin x', [i for i in range(len(wave)) if wave[i] == m.sin(i)]) cosx = ('cos x', [i for i in range(len(wave)) if wave[i] == m.cos(i)]) cossin = ('sin x + cos x', [i for i in range(len(wave)) if wave[i] == m.cos(i) + m.sin(i)]) final = max([sinx, cosx, cossin], key=lambda x : sum(x[1])) return final[0] if sum(final[1]) == sum([i for i in range(len(wave))]) else None
- import math as m
def find_signal(s):k=0; k1=0; k2=0for i in range(4):if s[i]==round(m.sin(i),2):k=k+1if k==4:return('sin x')if s[i]==round(m.cos(i),2):k1=k1+1if k1==4:return('cos x')if s[i]==round(m.cos(i)+m.sin(i),2):k2=k2+1if k2==4:return('sin x + cos x')- def find_signal(wave):
- sinx = ('sin x', [i for i in range(len(wave)) if wave[i] == m.sin(i)])
- cosx = ('cos x', [i for i in range(len(wave)) if wave[i] == m.cos(i)])
- cossin = ('sin x + cos x', [i for i in range(len(wave)) if wave[i] == m.cos(i) + m.sin(i)])
- final = max([sinx, cosx, cossin], key=lambda x : sum(x[1]))
- return final[0] if sum(final[1]) == sum([i for i in range(len(wave))]) else None
import codewars_test as test from solution import find_signal import math import random # Working solution def found_signal(wave): sinx = ('sin x', [i for i in range(len(wave)) if wave[i] == math.sin(i)]) cosx = ('cos x', [i for i in range(len(wave)) if wave[i] == math.cos(i)]) cossin = ('sin x + cos x', [i for i in range(len(wave)) if wave[i] == math.cos(i) + math.sin(i)]) final = max([sinx, cosx, cossin], key=lambda x : sum(x[1])) return final[0] if sum(final[1]) == sum([i for i in range(len(wave))]) else None # Generate random tests def get_random(): waves = ['math.sin(i)', 'math.cos(i)', '(math.sin(i) + math.cos(i))', '(math.tan(i))'] expression = random.choice(waves) array = eval(f'[{expression} for i in range(random.randrange(2, 1000))]') return array # Start of testing @test.describe("Fixed Tests") def test_group(): @test.it("Standard Tests") def test_case(): test.assert_equals(find_signal([0.0, 0.8414709848078965, 0.9092974268256817, 0.1411200080598672]), 'sin x') test.assert_equals(find_signal([1.0, 0.5403023058681398, -0.4161468365471424, -0.9899924966004454]), 'cos x') test.assert_equals(find_signal([1.0, 1.3817732906760363, 0.4931505902785393, -0.8488724885405782]), 'sin x + cos x') test.assert_equals(find_signal([0, 0, 0, 0.14]), None) @test.describe('Random Tests') def rand_tests(): for _ in range(100): seed = get_random() exp = found_signal(seed) @test.it(f'Expression: {exp} \nLength of array: {len(seed)}') def test_random_edition(): test.assert_equals(find_signal(seed), exp)
- import codewars_test as test
# TODO Write testsfrom solution import find_signal # or from solution import example- from solution import find_signal
# test.assert_equals(actual, expected, [optional] message)@test.describe("Example")- import math
- import random
- # Working solution
- def found_signal(wave):
- sinx = ('sin x', [i for i in range(len(wave)) if wave[i] == math.sin(i)])
- cosx = ('cos x', [i for i in range(len(wave)) if wave[i] == math.cos(i)])
- cossin = ('sin x + cos x', [i for i in range(len(wave)) if wave[i] == math.cos(i) + math.sin(i)])
- final = max([sinx, cosx, cossin], key=lambda x : sum(x[1]))
- return final[0] if sum(final[1]) == sum([i for i in range(len(wave))]) else None
- # Generate random tests
- def get_random():
- waves = ['math.sin(i)', 'math.cos(i)', '(math.sin(i) + math.cos(i))', '(math.tan(i))']
- expression = random.choice(waves)
- array = eval(f'[{expression} for i in range(random.randrange(2, 1000))]')
- return array
- # Start of testing
- @test.describe("Fixed Tests")
- def test_group():
@test.it("test case")- @test.it("Standard Tests")
- def test_case():
test.assert_equals(find_signal([0,.84,.91,.14]),'sin x')test.assert_equals(find_signal([1,.54,-.42,-.99]),'cos x')test.assert_equals(find_signal([1,1.38,.49,-.85]),'sin x + cos x')test.assert_equals(find_signal([0,.84,.91,.14]),'sin x')test.assert_equals(find_signal([0,.84,.91,.14]),'sin x')test.assert_equals(find_signal([1,.54,-.42,-.99]),'cos x')test.assert_equals(find_signal([1,1.38,.49,-.85]),'sin x + cos x')test.assert_equals(find_signal([0,0,0,.14]),None)- test.assert_equals(find_signal([0.0, 0.8414709848078965, 0.9092974268256817, 0.1411200080598672]), 'sin x')
- test.assert_equals(find_signal([1.0, 0.5403023058681398, -0.4161468365471424, -0.9899924966004454]), 'cos x')
- test.assert_equals(find_signal([1.0, 1.3817732906760363, 0.4931505902785393, -0.8488724885405782]), 'sin x + cos x')
- test.assert_equals(find_signal([0, 0, 0, 0.14]), None)
- @test.describe('Random Tests')
- def rand_tests():
- for _ in range(100):
- seed = get_random()
- exp = found_signal(seed)
- @test.it(f'Expression: {exp} \nLength of array: {len(seed)}')
- def test_random_edition():
- test.assert_equals(find_signal(seed), exp)
using System; namespace Solution { public class BlockBuilder { public static int[][] BuildATower(int[] bag) { return new int[][] {new int[] {1}}; // Code goes here ... } } }
- using System;
- namespace Solution
- {
- public class BlockBuilder
- {
public static int[,] BuildATower(int[] bag)- public static int[][] BuildATower(int[] bag)
- {
return new int[,] { { 1 } }; // Code goes here ...- return new int[][] {new int[] {1}}; // Code goes here ...
- }
- }
- }
using System; using NUnit.Framework; namespace Solution { [TestFixture] public class SolutionTest { [Test] public void ExampleTest() { Assert.AreEqual(new int[][] {new int[] {1}}, BlockBuilder.BuildATower(new int[] {1})); Assert.AreEqual(new int[][] {new int[] {1}}, BlockBuilder.BuildATower(new int[] {1, 1})); Assert.AreEqual(new int[][] {new int[] {1}, new int[] {1, 1}}, BlockBuilder.BuildATower(new int[] {1, 1, 1})); Assert.AreEqual(new int[][] {new int[] {1}, new int[] {2}, new int[] {3}}, BlockBuilder.BuildATower(new int[] {1, 2, 3})); } } }
- using System;
- using NUnit.Framework;
- namespace Solution
- {
- [TestFixture]
- public class SolutionTest
- {
- [Test]
- public void ExampleTest()
- {
int[,] expectedArray = { { 1 } };int[,] actualResult = BlockBuilder.BuildATower(new int[] { 1 });Assert.AreEqual(expectedArray, actualResult);- Assert.AreEqual(new int[][] {new int[] {1}}, BlockBuilder.BuildATower(new int[] {1}));
- Assert.AreEqual(new int[][] {new int[] {1}}, BlockBuilder.BuildATower(new int[] {1, 1}));
- Assert.AreEqual(new int[][] {new int[] {1}, new int[] {1, 1}}, BlockBuilder.BuildATower(new int[] {1, 1, 1}));
- Assert.AreEqual(new int[][] {new int[] {1}, new int[] {2}, new int[] {3}}, BlockBuilder.BuildATower(new int[] {1, 2, 3}));
- }
- }
- }
Compact, can't be taking up too much storage space!
class Greeting: def __init__(self, name, rank=None, formal=False): self.name = name self.rank = rank self.formal = formal def __call__(self): return f'He{["y","llo"][self.formal]}, {[str(self.rank)+" ",""][self.rank is None or not self.formal]}{self.name}{chr(33+self.formal*13)}'
- class Greeting:
- def __init__(self, name, rank=None, formal=False):
- self.name = name
- self.rank = rank
- self.formal = formal
- def __call__(self):
if self.formal: return f'Hello,{" " + self.rank if self.rank is not None else ""} {self.name}.'else: return f'Hey, {self.name}!'- return f'He{["y","llo"][self.formal]}, {[str(self.rank)+" ",""][self.rank is None or not self.formal]}{self.name}{chr(33+self.formal*13)}'
It will be faster, if you use bit operation