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.
public async Task CreateUser(User userInput)
{
var validUserTypes = new string[] { "regular", "premium", "trial" };
if (!validUserTypes.Contains(userInput.UserType))
{
throw new ArgumentOutOfRangeException(
nameof(userInput.UserType),
"Invalid user type. Must be one of: " + string.Join(", ", validUserTypes)
);
}
User user = userInput.UserType switch
{
"regular" => new User(userInput.Username),
"premium" => new User(userInput.Username, new List<Permission>
{
"PremiumFeature.Read",
"PremiumFeature.Create"
})
{
IsPremium = true
},
"trial" => new User(userInput.Username) { IsOnTrial = true },
_ => throw new ArgumentOutOfRangeException(
nameof(userInput.UserType),
"Invalid user type. Must be one of: " + string.Join(", ", validUserTypes)
)
};
return await repository.CreateAsync(user);
}
public async Task<bool> CreateUser(User userInput) { var validUserTypes = new string[] { "regular", "premium", "trial" }; if (!validUserTypes.Contains(userInput.UserType)) { throw new ArgumentOutOfRangeException( nameof(userInput.UserType), "Invalid user type. Must be one of: " + string.Join(", ", validUserTypes) ); } User user = userInput.UserType switch { "regular" => new User(userInput.Username), "premium" => new User(userInput.Username, new List<Permission> { "PremiumFeature.Read", "PremiumFeature.Create" }) { IsPremium = true }, "trial" => new User(userInput.Username) { IsOnTrial = true }, _ => throw new ArgumentOutOfRangeException( nameof(userInput.UserType), "Invalid user type. Must be one of: " + string.Join(", ", validUserTypes) ) }; return await repository.CreateAsync(user); }
public async Task<bool> CreateUser(User userInput) {var validUserTypes = new string[] {"regular", "premium", "trial"} ;var user = userInput.UserType switch {"regular" => new User(userInput.Username),"premium" => new User(userInput.Username,new List<Permission> {"PremiumFeature.Read","PremiumFeature.Create",}){IsPremium = true},"trial" => new User(input.Username) {IsOnTrial = true},_ => new ArgumentOutOfRangeException("Invalid user type. Must be on of the following {string.Join(" ")"nameof(input.usertype))};- public async Task<bool> CreateUser(User userInput)
- {
- var validUserTypes = new string[] { "regular", "premium", "trial" };
- if (!validUserTypes.Contains(userInput.UserType))
- {
- throw new ArgumentOutOfRangeException(
- nameof(userInput.UserType),
- "Invalid user type. Must be one of: " + string.Join(", ", validUserTypes)
- );
- }
- User user = userInput.UserType switch
- {
- "regular" => new User(userInput.Username),
- "premium" => new User(userInput.Username, new List<Permission>
- {
- "PremiumFeature.Read",
- "PremiumFeature.Create"
- })
- {
- IsPremium = true
- },
- "trial" => new User(userInput.Username) { IsOnTrial = true },
- _ => throw new ArgumentOutOfRangeException(
- nameof(userInput.UserType),
- "Invalid user type. Must be one of: " + string.Join(", ", validUserTypes)
- )
- };
- return await repository.CreateAsync(user);
eval(compile((_:=__import__("ast")).fix_missing_locations(_.Module(body=[_.Import(names=[_.alias(name='string')]), _.Assign(targets=[_.Name(id='ceasar', ctx=_.Store())], value=_.Lambda(args=_.arguments(posonlyargs=[], args=[_.arg(arg='s'), _.arg(arg='n')], kwonlyargs=[], kw_defaults=[], defaults=[]), body=_.Call(func=_.Attribute(value=_.Constant(value=''), attr='join', ctx=_.Load()), args=[_.ListComp(elt=_.Name(id='c', ctx=_.Load()), generators=[_.comprehension(target=_.Name(id='c', ctx=_.Store()), iter=_.Call(func=_.Name(id='map', ctx=_.Load()), args=[_.Lambda(args=_.arguments(posonlyargs=[], args=[_.arg(arg='c')], kwonlyargs=[], kw_defaults=[], defaults=[]), body=_.IfExp(test=_.BoolOp(op=_.Or(), values=[_.Compare(left=_.Name(id='c', ctx=_.Load()), ops=[_.In()], comparators=[_.BinOp(left=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_lowercase', ctx=_.Load()), slice=_.Slice(lower=_.Name(id='n', ctx=_.Load())), ctx=_.Load()), op=_.Add(), right=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_lowercase', ctx=_.Load()), slice=_.Slice(upper=_.Name(id='n', ctx=_.Load())), ctx=_.Load()))]), _.BoolOp(op=_.And(), values=[_.Compare(left=_.Name(id='c', ctx=_.Load()), ops=[_.In()], comparators=[_.BinOp(left=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_uppercase', ctx=_.Load()), slice=_.Slice(lower=_.Name(id='n', ctx=_.Load())), ctx=_.Load()), op=_.Add(), right=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_uppercase', ctx=_.Load()), slice=_.Slice(upper=_.Name(id='n', ctx=_.Load())), ctx=_.Load()))]), _.Call(func=_.Attribute(value=_.Name(id='c', ctx=_.Load()), attr='islower', ctx=_.Load()), args=[], keywords=[])])]), body=_.Subscript(value=_.BinOp(left=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_lowercase', ctx=_.Load()), slice=_.Slice(lower=_.Name(id='n', ctx=_.Load())), ctx=_.Load()), op=_.Add(), right=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_lowercase', ctx=_.Load()), slice=_.Slice(upper=_.Name(id='n', ctx=_.Load())), ctx=_.Load())), slice=_.BinOp(left=_.Call(func=_.Name(id='ord', ctx=_.Load()), args=[_.Name(id='c', ctx=_.Load())], keywords=[]), op=_.Sub(), right=_.Constant(value=97)), ctx=_.Load()), orelse=_.IfExp(test=_.BoolOp(op=_.Or(), values=[_.Compare(left=_.Name(id='c', ctx=_.Load()), ops=[_.In()], comparators=[_.BinOp(left=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_lowercase', ctx=_.Load()), slice=_.Slice(lower=_.Name(id='n', ctx=_.Load())), ctx=_.Load()), op=_.Add(), right=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_lowercase', ctx=_.Load()), slice=_.Slice(upper=_.Name(id='n', ctx=_.Load())), ctx=_.Load()))]), _.BoolOp(op=_.And(), values=[_.Compare(left=_.Name(id='c', ctx=_.Load()), ops=[_.In()], comparators=[_.BinOp(left=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_uppercase', ctx=_.Load()), slice=_.Slice(lower=_.Name(id='n', ctx=_.Load())), ctx=_.Load()), op=_.Add(), right=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_uppercase', ctx=_.Load()), slice=_.Slice(upper=_.Name(id='n', ctx=_.Load())), ctx=_.Load()))]), _.Call(func=_.Attribute(value=_.Name(id='c', ctx=_.Load()), attr='isupper', ctx=_.Load()), args=[], keywords=[])])]), body=_.Subscript(value=_.BinOp(left=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_uppercase', ctx=_.Load()), slice=_.Slice(lower=_.Name(id='n', ctx=_.Load())), ctx=_.Load()), op=_.Add(), right=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_uppercase', ctx=_.Load()), slice=_.Slice(upper=_.Name(id='n', ctx=_.Load())), ctx=_.Load())), slice=_.BinOp(left=_.Call(func=_.Name(id='ord', ctx=_.Load()), args=[_.Name(id='c', ctx=_.Load())], keywords=[]), op=_.Sub(), right=_.Constant(value=65)), ctx=_.Load()), orelse=_.Name(id='c', ctx=_.Load())))), _.Name(id='s', ctx=_.Load())], keywords=[]), ifs=[], is_async=0)])], keywords=[])))], type_ignores=[])), "", "exec"))
def ceasar(string, pos):bet = 'abcdefghijklmnopqrstuvwxyz'new = bet[pos:] + bet[:pos]word = ''for char in string:if char.lower() in bet: word += new[bet.index(char.lower())].upper() if char.isupper() else new[bet.index(char)]else: word += charreturn word- eval(compile((_:=__import__("ast")).fix_missing_locations(_.Module(body=[_.Import(names=[_.alias(name='string')]), _.Assign(targets=[_.Name(id='ceasar', ctx=_.Store())], value=_.Lambda(args=_.arguments(posonlyargs=[], args=[_.arg(arg='s'), _.arg(arg='n')], kwonlyargs=[], kw_defaults=[], defaults=[]), body=_.Call(func=_.Attribute(value=_.Constant(value=''), attr='join', ctx=_.Load()), args=[_.ListComp(elt=_.Name(id='c', ctx=_.Load()), generators=[_.comprehension(target=_.Name(id='c', ctx=_.Store()), iter=_.Call(func=_.Name(id='map', ctx=_.Load()), args=[_.Lambda(args=_.arguments(posonlyargs=[], args=[_.arg(arg='c')], kwonlyargs=[], kw_defaults=[], defaults=[]), body=_.IfExp(test=_.BoolOp(op=_.Or(), values=[_.Compare(left=_.Name(id='c', ctx=_.Load()), ops=[_.In()], comparators=[_.BinOp(left=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_lowercase', ctx=_.Load()), slice=_.Slice(lower=_.Name(id='n', ctx=_.Load())), ctx=_.Load()), op=_.Add(), right=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_lowercase', ctx=_.Load()), slice=_.Slice(upper=_.Name(id='n', ctx=_.Load())), ctx=_.Load()))]), _.BoolOp(op=_.And(), values=[_.Compare(left=_.Name(id='c', ctx=_.Load()), ops=[_.In()], comparators=[_.BinOp(left=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_uppercase', ctx=_.Load()), slice=_.Slice(lower=_.Name(id='n', ctx=_.Load())), ctx=_.Load()), op=_.Add(), right=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_uppercase', ctx=_.Load()), slice=_.Slice(upper=_.Name(id='n', ctx=_.Load())), ctx=_.Load()))]), _.Call(func=_.Attribute(value=_.Name(id='c', ctx=_.Load()), attr='islower', ctx=_.Load()), args=[], keywords=[])])]), body=_.Subscript(value=_.BinOp(left=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_lowercase', ctx=_.Load()), slice=_.Slice(lower=_.Name(id='n', ctx=_.Load())), ctx=_.Load()), op=_.Add(), right=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_lowercase', ctx=_.Load()), slice=_.Slice(upper=_.Name(id='n', ctx=_.Load())), ctx=_.Load())), slice=_.BinOp(left=_.Call(func=_.Name(id='ord', ctx=_.Load()), args=[_.Name(id='c', ctx=_.Load())], keywords=[]), op=_.Sub(), right=_.Constant(value=97)), ctx=_.Load()), orelse=_.IfExp(test=_.BoolOp(op=_.Or(), values=[_.Compare(left=_.Name(id='c', ctx=_.Load()), ops=[_.In()], comparators=[_.BinOp(left=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_lowercase', ctx=_.Load()), slice=_.Slice(lower=_.Name(id='n', ctx=_.Load())), ctx=_.Load()), op=_.Add(), right=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_lowercase', ctx=_.Load()), slice=_.Slice(upper=_.Name(id='n', ctx=_.Load())), ctx=_.Load()))]), _.BoolOp(op=_.And(), values=[_.Compare(left=_.Name(id='c', ctx=_.Load()), ops=[_.In()], comparators=[_.BinOp(left=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_uppercase', ctx=_.Load()), slice=_.Slice(lower=_.Name(id='n', ctx=_.Load())), ctx=_.Load()), op=_.Add(), right=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_uppercase', ctx=_.Load()), slice=_.Slice(upper=_.Name(id='n', ctx=_.Load())), ctx=_.Load()))]), _.Call(func=_.Attribute(value=_.Name(id='c', ctx=_.Load()), attr='isupper', ctx=_.Load()), args=[], keywords=[])])]), body=_.Subscript(value=_.BinOp(left=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_uppercase', ctx=_.Load()), slice=_.Slice(lower=_.Name(id='n', ctx=_.Load())), ctx=_.Load()), op=_.Add(), right=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_uppercase', ctx=_.Load()), slice=_.Slice(upper=_.Name(id='n', ctx=_.Load())), ctx=_.Load())), slice=_.BinOp(left=_.Call(func=_.Name(id='ord', ctx=_.Load()), args=[_.Name(id='c', ctx=_.Load())], keywords=[]), op=_.Sub(), right=_.Constant(value=65)), ctx=_.Load()), orelse=_.Name(id='c', ctx=_.Load())))), _.Name(id='s', ctx=_.Load())], keywords=[]), ifs=[], is_async=0)])], keywords=[])))], type_ignores=[])), "", "exec"))
/* __uint128_t solution(char *str1, char *str2) { return *(uint64_t *)str1 | ( (__uint128_t) *(uint64_t *)str2 << 64 ); } 48 8b 07 mov rax, [rdi] 48 8b 16 mov rdx, [rsi] c3 ret */ const long solution = 54912407923297096;
__uint128_t solution(char* str1, char* str2) {__uint128_t result = 0;for (unsigned long i = 0; i < 7; ++i) {result +=(((__uint128_t) str1[i]) << (8*(i + 0))) +(((__uint128_t) str2[i]) << (8*(i + 8)));- /*
- __uint128_t solution(char *str1, char *str2) {
- return *(uint64_t *)str1 | ( (__uint128_t) *(uint64_t *)str2 << 64 );
- }
return result;}- 48 8b 07 mov rax, [rdi]
- 48 8b 16 mov rdx, [rsi]
- c3 ret
- */
- const long solution = 54912407923297096;
Goal
Get dice roll results from multiple dice of the same type.
Dice notation
Dice are entered as strings such as "2d6" where the first number indicates the quantity of dice thrown and the last number indicates the number of sides on the dice. Assume input is "XdN"
where 1 <= X <= 250
and <= N <= 5000
e.g. "2d6" means 2 dice are thrown. Each dice is a 6 sided dice with values 1-6.
2d6 should have results such as [2,5] or [1,6] or [3,3]
e.g. 3d500 (after setting random.seed(444) should result in [159,148,7]
Fork 1
Solved the problem, and added random testing. Currently the random tests will use any dice noted here and then each multiple of 50 above that.Calculating which number
import random def roll_dice(dice): return [random.randint(1, int(dice[dice.index('d') + 1:])) for _ in range(int(dice[:dice.index('d')]))]
- import random
def roll_dice(dice_text:str):#this returns the correct value for roll_dice("2d1000")return [random.randint(1,1000), random.randint(1,1000)]- def roll_dice(dice):
- return [random.randint(1, int(dice[dice.index('d') + 1:])) for _ in range(int(dice[:dice.index('d')]))]
import codewars_test as test from solution import roll_dice import random def get_dice(dice): return [random.randint(1, int(dice[dice.index('d') + 1:])) for _ in range(int(dice[:dice.index('d')]))] def gen_dice(num1, num2): random.seed() sizes = [1, 2, 3, 4, 5, 6, 7, 12, 14, 16, 18, 20, 24, 30, 34, 48, 50, 60, 100, 120] + [i for i in range(150, 5001, 50)] r_seed = random.randint(0, 1000) return (r_seed, f'{random.randint(num1, num2)}d{random.choice(sizes)}') @test.describe("Example Test Cases") def test_group(): @test.it("Known Seeded Random Values") def test_case(): random.seed(444) test.assert_equals(roll_dice("2d1000"), [317, 295]) random.seed(444) test.assert_equals(roll_dice("3d500"), [159, 148, 7]) @test.describe("Small Random Test Cases") def test_group(): for _ in range(25): dice = gen_dice(1, 10) random.seed(dice[0]) sol = get_dice(dice[1]) @test.it(f"Seed: {dice[0]} Dice: {dice[1]}") def test_case(): random.seed(dice[0]) test.assert_equals(roll_dice(dice[:][1]), sol) @test.describe("Medium Random Test Cases") def test_group(): for _ in range(25): dice = gen_dice(10, 25) random.seed(dice[0]) sol = get_dice(dice[1]) @test.it(f"Seed: {dice[0]} Dice: {dice[1]}") def test_case(): random.seed(dice[0]) test.assert_equals(roll_dice(dice[:][1]), sol) @test.describe("Large Random Test Cases") def test_group(): for _ in range(25): dice = gen_dice(25, 100) random.seed(dice[0]) sol = get_dice(dice[1]) @test.it(f"Seed: {dice[0]} Dice: {dice[1]}") def test_case(): random.seed(dice[0]) test.assert_equals(roll_dice(dice[:][1]), sol) @test.describe("Largest Random Test Cases") def test_group(): for _ in range(25): dice = gen_dice(100, 250) random.seed(dice[0]) sol = get_dice(dice[1]) @test.it(f"Seed: {dice[0]} Dice: {dice[1]}") def test_case(): random.seed(dice[0]) test.assert_equals(roll_dice(dice[:][1]), sol)
- import codewars_test as test
import random- from solution import roll_dice
- import random
- def get_dice(dice):
- return [random.randint(1, int(dice[dice.index('d') + 1:])) for _ in range(int(dice[:dice.index('d')]))]
- def gen_dice(num1, num2):
- random.seed()
- sizes = [1, 2, 3, 4, 5, 6, 7, 12, 14, 16, 18, 20,
- 24, 30, 34, 48, 50, 60, 100, 120] + [i for i in range(150, 5001, 50)]
- r_seed = random.randint(0, 1000)
- return (r_seed, f'{random.randint(num1, num2)}d{random.choice(sizes)}')
# test.assert_equals(actual, expected, [optional] message)- @test.describe("Example Test Cases")
- def test_group():
@test.it("Seeded random values (return correct values for known seeded 'random' results)")- @test.it("Known Seeded Random Values")
- def test_case():
- random.seed(444)
- test.assert_equals(roll_dice("2d1000"), [317, 295])
- random.seed(444)
- test.assert_equals(roll_dice("3d500"), [159, 148, 7])
@test.it("Quantity of dice in list")def test_case():random.seed(444)test.assert_equals(len(roll_dice("2d1000")), 2)random.seed(444)test.assert_equals(len(roll_dice("3d500")), 3)- @test.describe("Small Random Test Cases")
- def test_group():
- for _ in range(25):
- dice = gen_dice(1, 10)
- random.seed(dice[0])
- sol = get_dice(dice[1])
- @test.it(f"Seed: {dice[0]} Dice: {dice[1]}")
- def test_case():
- random.seed(dice[0])
- test.assert_equals(roll_dice(dice[:][1]), sol)
- @test.describe("Medium Random Test Cases")
- def test_group():
- for _ in range(25):
- dice = gen_dice(10, 25)
- random.seed(dice[0])
- sol = get_dice(dice[1])
- @test.it(f"Seed: {dice[0]} Dice: {dice[1]}")
- def test_case():
- random.seed(dice[0])
- test.assert_equals(roll_dice(dice[:][1]), sol)
- @test.describe("Large Random Test Cases")
- def test_group():
- for _ in range(25):
- dice = gen_dice(25, 100)
- random.seed(dice[0])
- sol = get_dice(dice[1])
- @test.it(f"Seed: {dice[0]} Dice: {dice[1]}")
- def test_case():
- random.seed(dice[0])
- test.assert_equals(roll_dice(dice[:][1]), sol)
- @test.describe("Largest Random Test Cases")
- def test_group():
- for _ in range(25):
- dice = gen_dice(100, 250)
- random.seed(dice[0])
- sol = get_dice(dice[1])
- @test.it(f"Seed: {dice[0]} Dice: {dice[1]}")
- def test_case():
- random.seed(dice[0])
- test.assert_equals(roll_dice(dice[:][1]), sol)
Goal
write a function that will return the integer of a string evaluation. Your function should catch any errors related to this process. If it does catch and error, it should return a string: "Invalid Input"
Fork 1
Added testing, and error checking. I think random tests should cover all realistic inputs that don't try to intentionally break the function. For example, KeyError would be pretty easy to create here, but why would you put something as complicated as a dictionary into this function without already knowing the keys?
def calc(string): try: return int(eval(string)) except (NameError, SyntaxError, TypeError, ValueError, ZeroDivisionError) as e: print(e) return 'Invalid Input'
- def calc(string):
return int(eval(string))- try: return int(eval(string))
- except (NameError, SyntaxError, TypeError, ValueError, ZeroDivisionError) as e:
- print(e)
- return 'Invalid Input'
import codewars_test as test from solution import calc import random # Working Solution def calc_expression(string): try: return int(eval(string)) except (NameError, SyntaxError, TypeError, ValueError, ZeroDivisionError) as e: print('Error Recieved: ', type(e), e) return 'Invalid Input' # Random Generator def get_rand_expression(): math_dict = {"a" : "+", "s" : "-", "m" : "*", "d" : "/", "mod" : "%", "p" : "**",} expressions = ["a", "s", "m", "d", "mod", "p", "4 ^ 2", "2 << 3", "8 >> 2", "9 | 5", "7 & 3", "-5", "+5", "1 / 0", "1 / 1", "1 // 0", "1 % 0", "1.5 + 2.5", "3.0 / 1.5", 'one + one', 'variable', 'True', "4.2 * 5.5", "-1.2", "+0.0", "-0.0", "0.1 + 0.2", "1 / 3", "0.1 + 0.1 + 0.1", "0b1101 + 0b1011", "0o755 - 0o644", "0x1A * 0x2F", "0b1010 / 0o12", "0x1A >> 2", "0b101 & 0o74", "-0b1101", 'False', "+0o777", "-0xABC", "1 / '0'", "2 + '2'", "'1' + '2'", "'Hello' * 3", "'Python'[1]", 'None', "'543 + 210'.replace('+', '*')", '3 + 4j', '1 - 2j', 'None', '1.2e10^8', '7 + 3 * 2', f'pow({random.randint(1, 100)}, {random.randint(1, 100)})', 'abs(-7.5)', '7 * (3 + 2)', f'min([i for i in range({random.randint(0, 1000)}, {random.randint(0, 1000)})])', f'round({random.randint(1, 100)} + {random.random()})', f'len([i for i in range({random.randint(0, 1000)})])', f'sum([i for i in range({random.randint(0, 1000)})])', f'sum([i + i // 10 for i in range({random.randint(0, 1000)})])'] rand = random.choice(expressions) if rand in math_dict: if rand != 'p': return f'{random.randint(-10000, 10000)} {math_dict[rand]} {random.randint(-10000, 10000)}' return f'{random.randint(-100, 100)} {math_dict[rand]} {random.randint(-100, 100)}' return rand # Start of Testing @test.describe("Standard Operations") def test_group(): @test.it("Addition") def test_add(): test.assert_equals(calc('1 + 1'), 2) @test.it("Subtraction") def test_sub(): test.assert_equals(calc('1 - 1'), 0) @test.it("Multiplication") def test_mult(): test.assert_equals(calc('2 * 3'), 6) @test.it("Division") def test_div(): test.assert_equals(calc('6 // 2'), 3) @test.it("Modulous") def test_mod(): test.assert_equals(calc('6 % 2'), 0) @test.describe("Edge Case Expressions") def test_edge_group(): @test.it("") def test_edge(): test.assert_equals(calc('7 / 2'), 3) test.assert_equals(calc('7*7+7-7*7/7'), 49) test.assert_equals(calc('5.1234 + 1.1234'), 6) test.assert_equals(calc('one plus one'), 'Invalid Input', 'Your function did not catch the error correctly') test.assert_equals(calc('one + one'), 'Invalid Input', 'Your function did not catch the error correctly') test.assert_equals(calc('5 if 1 == 1 else 0'), 5) test.assert_equals(calc('"Uh-Oh" if True else 0'), 'Invalid Input', 'Your function did not catch the error correctly') test.assert_equals(calc('"Uh-Oh" + 5'), 'Invalid Input', 'Your function did not catch the error correctly') @test.describe("Simple Random Tests") def test_random(): for _ in range(100): random_exp = get_rand_expression() @test.it(f"{random_exp}") def test_random_edition(): test.assert_equals(calc(random_exp), calc_expression(random_exp)) @test.describe("Complex Random Tests") def test_random(): for _ in range(100): rand_exp = get_rand_expression() + random.choice([' + ', ' - ', ' * ', ' / ', ' % ']) + get_rand_expression() @test.it(f"{rand_exp}") def test_random_edition(): test.assert_equals(calc(rand_exp), calc_expression(rand_exp))
- import codewars_test as test
# TODO Write testsimport solution # or from solution import example- from solution import calc
- import random
# test.assert_equals(actual, expected, [optional] message)@test.describe("Easy")- # Working Solution
- def calc_expression(string):
- try: return int(eval(string))
- except (NameError, SyntaxError, TypeError, ValueError, ZeroDivisionError) as e:
- print('Error Recieved: ', type(e), e)
- return 'Invalid Input'
- # Random Generator
- def get_rand_expression():
- math_dict = {"a" : "+", "s" : "-", "m" : "*", "d" : "/", "mod" : "%", "p" : "**",}
- expressions = ["a", "s", "m", "d", "mod", "p", "4 ^ 2", "2 << 3", "8 >> 2", "9 | 5", "7 & 3", "-5", "+5",
- "1 / 0", "1 / 1", "1 // 0", "1 % 0", "1.5 + 2.5", "3.0 / 1.5", 'one + one', 'variable', 'True',
- "4.2 * 5.5", "-1.2", "+0.0", "-0.0", "0.1 + 0.2", "1 / 3", "0.1 + 0.1 + 0.1", "0b1101 + 0b1011",
- "0o755 - 0o644", "0x1A * 0x2F", "0b1010 / 0o12", "0x1A >> 2", "0b101 & 0o74", "-0b1101", 'False',
- "+0o777", "-0xABC", "1 / '0'", "2 + '2'", "'1' + '2'", "'Hello' * 3", "'Python'[1]", 'None',
- "'543 + 210'.replace('+', '*')", '3 + 4j', '1 - 2j', 'None', '1.2e10^8', '7 + 3 * 2',
- f'pow({random.randint(1, 100)}, {random.randint(1, 100)})', 'abs(-7.5)', '7 * (3 + 2)',
- f'min([i for i in range({random.randint(0, 1000)}, {random.randint(0, 1000)})])',
- f'round({random.randint(1, 100)} + {random.random()})',
- f'len([i for i in range({random.randint(0, 1000)})])',
- f'sum([i for i in range({random.randint(0, 1000)})])',
- f'sum([i + i // 10 for i in range({random.randint(0, 1000)})])']
- rand = random.choice(expressions)
- if rand in math_dict:
- if rand != 'p':
- return f'{random.randint(-10000, 10000)} {math_dict[rand]} {random.randint(-10000, 10000)}'
- return f'{random.randint(-100, 100)} {math_dict[rand]} {random.randint(-100, 100)}'
- return rand
- # Start of Testing
- @test.describe("Standard Operations")
- def test_group():
@test.it("test case")def test_case():test.assert_equals(solution.calc('1 + 1'), 2)- @test.it("Addition")
- def test_add():
- test.assert_equals(calc('1 + 1'), 2)
- @test.it("Subtraction")
- def test_sub():
- test.assert_equals(calc('1 - 1'), 0)
- @test.it("Multiplication")
- def test_mult():
- test.assert_equals(calc('2 * 3'), 6)
- @test.it("Division")
- def test_div():
- test.assert_equals(calc('6 // 2'), 3)
- @test.it("Modulous")
- def test_mod():
- test.assert_equals(calc('6 % 2'), 0)
- @test.describe("Edge Case Expressions")
- def test_edge_group():
- @test.it("")
- def test_edge():
- test.assert_equals(calc('7 / 2'), 3)
- test.assert_equals(calc('7*7+7-7*7/7'), 49)
- test.assert_equals(calc('5.1234 + 1.1234'), 6)
- test.assert_equals(calc('one plus one'), 'Invalid Input', 'Your function did not catch the error correctly')
- test.assert_equals(calc('one + one'), 'Invalid Input', 'Your function did not catch the error correctly')
- test.assert_equals(calc('5 if 1 == 1 else 0'), 5)
- test.assert_equals(calc('"Uh-Oh" if True else 0'), 'Invalid Input', 'Your function did not catch the error correctly')
- test.assert_equals(calc('"Uh-Oh" + 5'), 'Invalid Input', 'Your function did not catch the error correctly')
- @test.describe("Simple Random Tests")
- def test_random():
- for _ in range(100):
- random_exp = get_rand_expression()
- @test.it(f"{random_exp}")
- def test_random_edition():
- test.assert_equals(calc(random_exp), calc_expression(random_exp))
- @test.describe("Complex Random Tests")
- def test_random():
- for _ in range(100):
- rand_exp = get_rand_expression() + random.choice([' + ', ' - ', ' * ', ' / ', ' % ']) + get_rand_expression()
- @test.it(f"{rand_exp}")
- def test_random_edition():
- test.assert_equals(calc(rand_exp), calc_expression(rand_exp))
Story
The pandemic has spread to all countries of the world, and Berland is no exception. Even at the All-Berland Olympiad in Computer Science, antiviral measures were introduced. In total, n
people participate in the Olympiad, and in order to comply with all the instructions of the management, the Olympiad jury decided to invite participants to the tour one at a time with an interval of x
minutes. Thus, the first participant will start the tour at time 0, the second participant will start the tour at time x
, the third — at time 2x
and so on.
Despite the different start times, the duration of the tour for each participant is exactly t
minutes. Because of this, some participants finish writing the tour before the rest. When a participant finishes writing a tour, the amount of dissatisfaction with the organization of the Olympiad for this participant is equal to the number of other participants who are currently still writing or just starting to write a tour, but have not finished it yet.
Goal
Help the organizers of the Olympiad to find out what the total dissatisfaction of all participants of the Olympiad is equal to.
Input:
A single integer n is entered in the first line 1<=n<=2 * 10^9 — the number of participants of the Olympiad.
A single integer x is entered in the second line 1<=x<=2 * 10^9 — the interval in minutes between the start times of the tour for participants.
In the third line, a single integer t is entered 1<=t<=2 * 10^9 — duration of the tour.
Output:
In a single line, return one number — the total dissatisfaction of all participants of the Olympiad.
Examples
def satisfaction(4, 2, 5) --> 5
def satisfaction(3, 1, 2) --> 3
def satisfaction(3, 3, 10) --> 3
-
In the first example , the first participant will start writing the tour at time 0 and finish at time 5. By this time, the second and third participants will already start writing the tour, so the dissatisfaction of the first participant will be equal to 2. The second participant will start writing at time 2 and finish at time 7. By this point, the third and fourth participants will already start writing the tour, so the dissatisfaction of the second will be equal to 2. The third participant will start writing the tour at time 4 and finish at time 9. By this time, the fourth participant will already start writing the tour, so the dissatisfaction of the third will be equal to 1. The fourth participant will start writing the tour at time 6 and finish at time 11. At time 9 no one will write a tour anymore, so the dissatisfaction of the fourth will be equal to 0. Thus, the total dissatisfaction of all participants will be equal to 2+2+1+0=5.
-
In the second example , the first participant will start writing the tour at time 0 and finish at time 2. By this point, the second participant will already be writing the tour, and the third participant will just start at time 2. Therefore , the dissatisfaction of the first participant will be equal to 2. The second participant will start at time 1and finish at time 3. By this point, only the third participant will still be writing the tour. Thus, the total dissatisfaction of all participants will be equal to 2+1=3.
Fork 1
I think I met the bid here. I wrote some edge cases that you should check to make sure that they follow the rules as well, but I've been treating all comparisons as <= since you said:
currently still writing or just starting to write a tour, but have not finished it yet.
Either way, really fun challenge! If this is looking good for you, just add some random tests and this will be ready for a kata IMO. This was a really fun puzzle to figure out because it's not just math that helps you get to the right solution, but clever coding logic as well. This would be a really fun kata when you're satisfied... get it?
def satisfaction(n, x, t): start_times = [i * x for i in range(n)] finish_times = [(i * x) + t for i in range(n)] upset_factor = 0 for i, writer in enumerate(finish_times): for j, others in enumerate(start_times): if others <= writer and i < j: upset_factor += 1 print(start_times, finish_times) return upset_factor
def qwerty(n, x, t):time_finish_before_start = t + x * (n - 1)time_start_before_finish = t + x * (n - 2)dissatisfaction_finish_before_start = min(n - 1, time_finish_before_start // x)dissatisfaction_start_before_finish = max(0, n - 2 - dissatisfaction_finish_before_start)total_dissatisfaction = dissatisfaction_finish_before_start * dissatisfaction_start_before_finishreturn total_dissatisfaction- def satisfaction(n, x, t):
- start_times = [i * x for i in range(n)]
- finish_times = [(i * x) + t for i in range(n)]
- upset_factor = 0
- for i, writer in enumerate(finish_times):
- for j, others in enumerate(start_times):
- if others <= writer and i < j:
- upset_factor += 1
- print(start_times, finish_times)
- return upset_factor
import codewars_test as test from solution import satisfaction @test.describe("Example Tests") def test_group(): @test.it("Example One") def example_one(): test.assert_equals(satisfaction(4, 2, 5), 5) @test.it("Example Two") def example_two(): test.assert_equals(satisfaction(3, 1, 2), 3) @test.it("Example Three") def example_three(): test.assert_equals(satisfaction(3, 3, 10), 3) @test.describe("Fixed Tests") def test_group(): @test.it("Fixed Tests") def test_fixed_edition(): test.assert_equals(satisfaction(1, 1, 1), 0) test.assert_equals(satisfaction(1, 10, 10), 0) test.assert_equals(satisfaction(10, 1, 10), 45) test.assert_equals(satisfaction(1, 10, 10), 0)
- import codewars_test as test
# TODO Write testsimport solution # or from solution import example- from solution import satisfaction
# test.assert_equals(actual, expected, [optional] message)@test.describe("Example")- @test.describe("Example Tests")
- def test_group():
@test.it("test case")def test_case():test.assert_equals(1 + 1, 2)- @test.it("Example One")
- def example_one():
- test.assert_equals(satisfaction(4, 2, 5), 5)
- @test.it("Example Two")
- def example_two():
- test.assert_equals(satisfaction(3, 1, 2), 3)
- @test.it("Example Three")
- def example_three():
- test.assert_equals(satisfaction(3, 3, 10), 3)
- @test.describe("Fixed Tests")
- def test_group():
- @test.it("Fixed Tests")
- def test_fixed_edition():
- test.assert_equals(satisfaction(1, 1, 1), 0)
- test.assert_equals(satisfaction(1, 10, 10), 0)
- test.assert_equals(satisfaction(10, 1, 10), 45)
- test.assert_equals(satisfaction(1, 10, 10), 0)