#include <ctype.h>
#include <string.h>
void drop_caps(char *dest, const char *src) {
unsigned in_word = 0;
for (unsigned i = 0; i < strlen(src) + 1000; i++, src++, dest++) {
if (*src == ' ' || (!in_word && strcspn(src, " ") <= 2)) in_word = 0, *dest = *src;
else if (in_word) *dest = tolower(*src);
else in_word = 1, *dest = toupper(*src);
}
*dest = '\0';
}
#include <criterion/criterion.h>
void drop_caps(char *, const char *);
void do_one_test(const char *input, const char *expected, char *buffer) {
drop_caps(buffer, input);
cr_assert_str_eq(buffer, expected);
}
#define sample_test(input, expected) do_one_test(input, expected, (char[sizeof expected]){'@'})
Test(tests_suite, sample_tests) {
sample_test("Apple Banana", "Apple Banana");
sample_test("Apple", "Apple");
sample_test("", "");
sample_test("of", "of");
sample_test(" leading spaces", " Leading Spaces");
sample_test("trailing spaces ", "Trailing Spaces ");
sample_test("ALL CAPS CRAZINESS", "All Caps Craziness");
sample_test("rAnDoM CaPs CrAzInEsS", "Random Caps Craziness");
}
Fundamentals
def regex(s): import re return re.sub(r"[0-9]", "", s) def regex_plus(s): import re return re.sub(r"[0-9]+", "", s) def isnumeric(s): from itertools import filterfalse return "".join(filterfalse(str.isnumeric, s)) def filter_digits(x): from itertools import filterfalse return "".join(filterfalse("0123456789".__contains__, x)) def translate(s): return s.translate(str.maketrans("", "", "0123456789"))
from itertools import filterfalsedigits = "0123456789".__contains__- def regex(s):
- import re
- return re.sub(r"[0-9]", "", s)
remove_numbers=lambda x:''.join(filterfalse(digits, x))- def regex_plus(s):
- import re
- return re.sub(r"[0-9]+", "", s)
- def isnumeric(s):
- from itertools import filterfalse
- return "".join(filterfalse(str.isnumeric, s))
- def filter_digits(x):
- from itertools import filterfalse
- return "".join(filterfalse("0123456789".__contains__, x))
- def translate(s):
- return s.translate(str.maketrans("", "", "0123456789"))
from time import perf_counter from solution import * a = ( ("none", "aaaaaaaaaaaaaaaaaaaa" * 100_000), ("half", "aaaaaaaaaa0123456789" * 100_000), ("all ", "01234567890123456789" * 100_000) ) for header, s in a: print(header) for f in (regex, regex_plus, isnumeric, filter_digits, translate): start = perf_counter() f(s) end = perf_counter() print(f" {f.__name__:<15} - {end - start:.6f}") print()
import codewars_test as test# TODO Write testsimport solution # or from solution import example- from time import perf_counter
- from solution import *
# test.assert_equals(actual, expected, [optional] message)@test.describe("Example")def test_group():@test.it("Tests")def test_case():test.assert_equals(remove_numbers("1234567890__A1234567890"), "__A")test.assert_equals(remove_numbers("Hello world!"), "Hello world!")test.assert_equals(remove_numbers("2 times 2 is 4"), " times is ")test.assert_equals(remove_numbers("this is the year 2021"), "this is the year ")- a = (
- ("none", "aaaaaaaaaaaaaaaaaaaa" * 100_000),
- ("half", "aaaaaaaaaa0123456789" * 100_000),
- ("all ", "01234567890123456789" * 100_000)
- )
- for header, s in a:
- print(header)
- for f in (regex, regex_plus, isnumeric, filter_digits, translate):
- start = perf_counter()
- f(s)
- end = perf_counter()
- print(f" {f.__name__:<15} - {end - start:.6f}")
- print()
""" import cmath as c;f=lambda a,b=None:c.pi*a if b==None else getattr(c,"a"*(b<0)+["sin","cos","tan"][abs(b)%4-1]+"h"*(abs(b)>4))(a) import cmath as c;f=lambda a,b=None:getattr(c,"a"*(b<0)+["sin","cos","tan"][abs(b)%4-1]+"h"*(abs(b)>4))(a)if b!=None else c.pi*a import cmath as c;f=lambda a,b="":getattr(c,"a"*(b<0)+["sin","cos","tan"][abs(b)%4-1]+"h"*(abs(b)>4))(a)if b!=""else c.pi*a import cmath as c;f=lambda a,b="":getattr(c,"a"[b:]+["sin","cos","tan"][abs(b)%4-1]+"h"*(abs(b)>4))(a)if b!=""else c.pi*a import cmath as c;f=lambda a,b="":getattr(c,"a"[b:]+["sin","cos","tan"][abs(b)%4-1]+"h"[-4<b<4:])(a)if b!=""else c.pi*a """ from cmath import*;f=lambda a,b=0:globals()["a"[b:]+"sctioansn"[abs(b)%4-1::3]+"h"[-4<b<4:]](a)if b else pi*a
- """
- import cmath as c;f=lambda a,b=None:c.pi*a if b==None else getattr(c,"a"*(b<0)+["sin","cos","tan"][abs(b)%4-1]+"h"*(abs(b)>4))(a)
- import cmath as c;f=lambda a,b=None:getattr(c,"a"*(b<0)+["sin","cos","tan"][abs(b)%4-1]+"h"*(abs(b)>4))(a)if b!=None else c.pi*a
- import cmath as c;f=lambda a,b="":getattr(c,"a"*(b<0)+["sin","cos","tan"][abs(b)%4-1]+"h"*(abs(b)>4))(a)if b!=""else c.pi*a
- import cmath as c;f=lambda a,b="":getattr(c,"a"[b:]+["sin","cos","tan"][abs(b)%4-1]+"h"*(abs(b)>4))(a)if b!=""else c.pi*a
"""- import cmath as c;f=lambda a,b="":getattr(c,"a"[b:]+["sin","cos","tan"][abs(b)%4-1]+"h"[-4<b<4:])(a)if b!=""else c.pi*a
- """
- from cmath import*;f=lambda a,b=0:globals()["a"[b:]+"sctioansn"[abs(b)%4-1::3]+"h"[-4<b<4:]](a)if b else pi*a
Dictionary
Data Structures
def nested_dic(*args): a = list(args) r = a.pop() for x in reversed(a): r = [{y: z} for y, z in zip(x, r)] return r
def nested_dic(*args, i0 = None, i1 = None):if i0 != None:if i0 < len(args) - 1:return {args[i0][i1]: nested_dic(*args, i0 = i0 + 1, i1 = i1)}else:return args[len(args) - 1][i1]return [{args[0][i1]: nested_dic(*args, i0 = 1, i1 = i1)} for i1 in range(len(args[0]))]- def nested_dic(*args):
- a = list(args)
- r = a.pop()
- for x in reversed(a):
- r = [{y: z} for y, z in zip(x, r)]
- return r
import codewars_test as test from solution import nested_dic @test.it("Test") def _(): faces = [":)", ":(", ";|", ":P"] keys = ["S001", "S002", "S003", "S004"] names = ["Kate", "Toni", "Dany", "John"] ages = [23, 15, 89, 69] actual = nested_dic(faces, keys, names, ages) expected = [ {":)": {"S001": {"Kate": 23}}}, {":(": {"S002": {"Toni": 15}}}, {";|": {"S003": {"Dany": 89}}}, {":P": {"S004": {"John": 69}}}, ] test.assert_equals(actual, expected)
- import codewars_test as test
# TODO Write testsimport solution # or from solution import example- from solution import nested_dic
keys = ['S001', 'S002', 'S003', 'S004']names = ['Kate', 'Toni', 'Dany', 'Sam']ages = [23, 15, 89, 69]# test.assert_equals(actual, expected, [optional] message)@test.describe("Example")def test_group():@test.it("test case")def test_case():test.assert_equals(nested_dic(['S001', 'S002', 'S003', 'S004'], ['Kate', 'Toni', 'Dany', 'Sam'], [23, 15, 89, 69]), [{'S001': {'Kate': 23}}, {'S002': {'Toni': 15}}, {'S003': {'Dany': 89}}, {'S004': {'Sam': 69}}])- @test.it("Test")
- def _():
- faces = [":)", ":(", ";|", ":P"]
- keys = ["S001", "S002", "S003", "S004"]
- names = ["Kate", "Toni", "Dany", "John"]
- ages = [23, 15, 89, 69]
- actual = nested_dic(faces, keys, names, ages)
- expected = [
- {":)": {"S001": {"Kate": 23}}},
- {":(": {"S002": {"Toni": 15}}},
- {";|": {"S003": {"Dany": 89}}},
- {":P": {"S004": {"John": 69}}},
- ]
- test.assert_equals(actual, expected)
Algorithms
Logic
Lists
Data Structures
from math import ceil def variable_chunks(a): n = 0 return [a[n:(n := n + i)] for i in range(1, ceil(((1 + 8 * len(a))**0.5 + 1) / 2))]
def variable_chunks(given):i, chunks = 0, []while given := given[i:]:chunks.append(given[:(i := i + 1)])return chunks- from math import ceil
- def variable_chunks(a):
- n = 0
- return [a[n:(n := n + i)] for i in range(1, ceil(((1 + 8 * len(a))**0.5 + 1) / 2))]
t = str.maketrans("ACGTacgt", "TGCATGCA") reverse_compliment = lambda dna: "".join(chr(t[ord(x)]) for x in reversed(dna))
reverse_compliment = lambda dna: dna[::-1].translate(str.maketrans("ACGTacgt", "TGCATGCA"))- t = str.maketrans("ACGTacgt", "TGCATGCA")
- reverse_compliment = lambda dna: "".join(chr(t[ord(x)]) for x in reversed(dna))
Variables
Basic Language Features
Fundamentals
Conditional Statements
Control Flow
Loops
Arrays
Data Types
def get_primes(n): a = [1] * n a[0] = a[1] = 0 for i in range(2, n): if a[i]: x, y = divmod(n - i**2, i) a[i**2:n:i] = [0] * (x + bool(y)) return [i for i, x in enumerate(a) if x]
from math import sqrtdef is_prime(num):for newnum in range(2, int(sqrt(num)) + 1):if num % newnum == 0:return Falsereturn Truedef get_primes(num):return [n for n in range(2, num + 1) if is_prime(n)]- def get_primes(n):
- a = [1] * n
- a[0] = a[1] = 0
- for i in range(2, n):
- if a[i]:
- x, y = divmod(n - i**2, i)
- a[i**2:n:i] = [0] * (x + bool(y))
- return [i for i, x in enumerate(a) if x]
test.assert_equals(get_primes(10), [2, 3, 5, 7]) test.assert_equals(get_primes(50), [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]) test.assert_equals(get_primes(100), [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]) test.assert_equals(len(get_primes(10_000)), 1229) test.assert_equals(len(get_primes(1_000_000)), 78498) test.assert_equals(len(get_primes(10_000_000)), 664579)
- test.assert_equals(get_primes(10), [2, 3, 5, 7])
- test.assert_equals(get_primes(50), [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47])
- test.assert_equals(get_primes(100), [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97])
test.assert_equals(len(get_primes(10000)), 1229)test.assert_equals(len(get_primes(1000000)), 78498)- test.assert_equals(len(get_primes(10_000)), 1229)
- test.assert_equals(len(get_primes(1_000_000)), 78498)
- test.assert_equals(len(get_primes(10_000_000)), 664579)
Performance
divisors=lambda n,r=[]:r.clear()or[d-n//d and r.append(n//d)or d for d in range(1,int(n**.5+1))if n%d<1]+r[::-1]
divisors=lambda n,r=[]:r.clear()or[d for d in range(1,int(n**.5+1))if n%d<1 and(d-n//d and r.append(n//d)or 1)]+r[::-1]- divisors=lambda n,r=[]:r.clear()or[d-n//d and r.append(n//d)or d for d in range(1,int(n**.5+1))if n%d<1]+r[::-1]
from random import randint test.assert_equals(divisors(60), [1,2,3,4,5,6,10,12,15,20,30,60]) test.assert_equals(divisors(4), [1,2,4]) test.assert_equals(divisors(15), [1,3,5,15]) test.assert_equals(divisors(101), [1,101]) @test.describe('Random') def random_tests(): for i in range(100): divisors(randint(1000000,2000000)) Test.pass_()
- from random import randint
def example(n):res=[]for i in range(1,n):if i in res: breakif n % i == 0:res.append(i)res.append(int(n / i))return sorted(list(set(res)))test.assert_equals(divisors (5*4*3), [1,2,3,4,5,6,10,12,15,20,30,60])test.assert_equals(divisors (4), [1,2,4])test.assert_equals(divisors (5*3), [1,3,5,15])test.assert_equals(divisors (101), [1,101])- test.assert_equals(divisors(60), [1,2,3,4,5,6,10,12,15,20,30,60])
- test.assert_equals(divisors(4), [1,2,4])
- test.assert_equals(divisors(15), [1,3,5,15])
- test.assert_equals(divisors(101), [1,101])
- @test.describe('Random')
- def random_tests():
- for i in range(100):
rand = randint(1000000,2000000)test.assert_equals(divisors(rand),example(rand))- divisors(randint(1000000,2000000))
- Test.pass_()
-- code which does not return anything
def compare(actual, expected, header)
actual = DB[actual].to_a if actual.is_a?(String)
expected = DB[expected].to_a if expected.is_a?(String)
if actual != expected
Display.table(actual, label: "Actual (#{header})")
Display.table(expected, label: "Expected (#{header})", tab: true)
end
it header do
expect(actual).to eq expected
end
end
describe "Fixed tests" do
compare(
"SELECT * FROM items WHERE id = 1",
"SELECT * FROM items WHERE id = 1",
"Correct"
)
compare(
"SELECT * FROM items WHERE id < 3",
"SELECT * FROM items WHERE id > 2",
"Wrong"
)
end
int nbDaysInMonth(int n, bool m) { return n == 2 ? 28 + m : 30 + (n + (n > 7) & 1); }
int nbDaysInMonth(int month, bool leap) {int days[12] = {31,28,31,30,31,30,31,31,30,31,30,31};return days[month - 1] + (month == 2 && leap);- int nbDaysInMonth(int n, bool m) {
- return n == 2 ? 28 + m : 30 + (n + (n > 7) & 1);
- }
Algorithms
Logic
Arrays
Data Types
Mathematics
Numbers
Statistics
Data
function mad(a) { if (!a.length) return null; let n = a.reduce((x, y) => x + y, 0) / a.length; return a.reduce((x, y) => x + Math.abs(y - n), 0) / a.length; }
function mad(array) {if(array.length === 0){return null}if(array.length === 1){return 0}let average = (array.reduce((acc, cV) => acc + cV))/array.lengthlet array2 = array.map((item,index,arr)=> Math.abs(item-average))return (array2.reduce((acc, cV) => acc + cV))/array2.length;- function mad(a) {
- if (!a.length) return null;
- let n = a.reduce((x, y) => x + y, 0) / a.length;
- return a.reduce((x, y) => x + Math.abs(y - n), 0) / a.length;
- }
const {assert} = require("chai"); describe("Solution", function() { it("Simple and Edge Cases", function() { assert.equal(mad([1,1,4,6]), 2); assert.equal(mad([2,2,4,4]), 1); }); it("Variable Length Arrays", function() { assert.equal(mad([4,6]), 1); assert.equal(mad([2,2,2,4,4,4]), 1); assert.equal(mad([]), null); assert.equal(mad([5223]),0); }); }); function solution(array) { if(array.length === 0){return null} if(array.length === 1){return 0} let average = (array.reduce((acc, cV) => acc + cV))/array.length let array2 = array.map((item,index,arr)=> Math.abs(item-average)) return (array2.reduce((acc, cV) => acc + cV))/array2.length; } const randint = require("lodash/random"); describe("Random tests", function() { it("Random Test", function() { for (let i = 0; i < 100; i++) { let arr = Array.from({length: randint(0, 50)}, _ => randint(0, 99)); let expected = solution(arr); assert.equal(mad(arr), expected, 1e-9); } }); });
const assert = require("chai").assert;// If the failure output for deep equality is truncated, `chai.config.truncateThreshold` can be adjusted.- const {assert} = require("chai");
- describe("Solution", function() {
- it("Simple and Edge Cases", function() {
Test.assertDeepEquals(mad([1,1,4,6]), 2);Test.assertDeepEquals(mad([2,2,4,4]), 1);- assert.equal(mad([1,1,4,6]), 2);
- assert.equal(mad([2,2,4,4]), 1);
- });
it("Variable Length Arrays", function() {Test.assertDeepEquals(mad([4,6]), 1);Test.assertDeepEquals(mad([2,2,2,4,4,4]), 1);Test.assertDeepEquals(mad([]), null);Test.assertDeepEquals(mad([5223]),0);- it("Variable Length Arrays", function() {
- assert.equal(mad([4,6]), 1);
- assert.equal(mad([2,2,2,4,4,4]), 1);
- assert.equal(mad([]), null);
- assert.equal(mad([5223]),0);
- });
- });
it("Random Test", function() {function madTest(array) {if(array.length === 0){return null}if(array.length === 1){return 0}let average = (array.reduce((acc, cV) => acc + cV))/array.lengthlet array2 = array.map((item,index,arr)=> Math.abs(item-average))return (array2.reduce((acc, cV) => acc + cV))/array2.length;- function solution(array) {
- if(array.length === 0){return null}
- if(array.length === 1){return 0}
- let average = (array.reduce((acc, cV) => acc + cV))/array.length
- let array2 = array.map((item,index,arr)=> Math.abs(item-average))
- return (array2.reduce((acc, cV) => acc + cV))/array2.length;
- }
for (let i=0;i<100;i++){arrLen=1+Math.floor(Math.random()*100)let testArray=[]for(let j=0;j<arrLen;j++){testArray.push(Math.floor(Math.random()*100))- const randint = require("lodash/random");
- describe("Random tests", function() {
- it("Random Test", function() {
- for (let i = 0; i < 100; i++) {
- let arr = Array.from({length: randint(0, 50)}, _ => randint(0, 99));
- let expected = solution(arr);
- assert.equal(mad(arr), expected, 1e-9);
- }
console.log('testing...',testArray)Test.assertDeepEquals(mad(testArray), madTest(testArray));};- });
});- });
#include <functional> #include <string> std::string calculator(int op, int x, int y) { static std::array<std::function<int(int, int)>, 5> ops{ std::plus<int>(), std::minus<int>(), std::multiplies<int>(), std::divides<int>(), std::modulus<int>(), }; if (op < 1 || op > 5 || (!y && (op == 4 || op == 5))) return "Invalid Input!"; return std::to_string(ops[op-1](x, y)); }
#include <iostream>using namespace std;- #include <functional>
- #include <string>
string die() {return "Invalid Input!";}string Calculator(int choice, int x, int y) {string answer;if (choice == 1 || choice == 2 || choice == 3 || choice == 4 || choice == 5){switch (choice) {case 1:answer = std::to_string(x + y);break;case 2:answer = std::to_string(x - y);break;case 3:answer = std::to_string(x * y);break;case 4:answer = std::to_string(x / y);break;case 5:answer = std::to_string(x % y);break;}}else { return die(); }return answer;- std::string calculator(int op, int x, int y) {
- static std::array<std::function<int(int, int)>, 5> ops{
- std::plus<int>(),
- std::minus<int>(),
- std::multiplies<int>(),
- std::divides<int>(),
- std::modulus<int>(),
- };
- if (op < 1 || op > 5 || (!y && (op == 4 || op == 5))) return "Invalid Input!";
- return std::to_string(ops[op-1](x, y));
- }
Describe(Sample_Tests) { It(Test) { Assert::That(calculator(0, 420, 420), Equals("Invalid Input!")); Assert::That(calculator(1, 1, 1), Equals("2")); Assert::That(calculator(1, 16, 9), Equals("25")); Assert::That(calculator(2, 1, 1), Equals("0")); Assert::That(calculator(2, 57, 62), Equals("-5")); Assert::That(calculator(3, -10, 10), Equals("-100")); Assert::That(calculator(3, -12, -12), Equals("144")); Assert::That(calculator(4, 2, 4), Equals("0")); Assert::That(calculator(4, 4, 2), Equals("2")); Assert::That(calculator(4, 1, 0), Equals("Invalid Input!")); Assert::That(calculator(5, 3, 5), Equals("3")); Assert::That(calculator(5, 5, 3), Equals("2")); Assert::That(calculator(6, 69, 69), Equals("Invalid Input!")); } };
// TODO: Replace examples and use TDD by writing your own testsDescribe(Sample_Tests){It(Test){Assert::That(Calculator(0, 420, 420), Equals("Invalid Input!"));Assert::That(Calculator(1, 1, 1), Equals("2"));Assert::That(Calculator(1, 16, 9), Equals("25"));Assert::That(Calculator(2, 1, 1), Equals("0"));Assert::That(Calculator(2, 57, 62), Equals("-5"));Assert::That(Calculator(3, -10, 10), Equals("-100"));Assert::That(Calculator(3, -12, -12), Equals("144"));Assert::That(Calculator(4, 2, 4), Equals("0"));Assert::That(Calculator(4, 4, 2), Equals("2"));Assert::That(Calculator(4, 1, 0), Equals("Invalid Input!"));Assert::That(Calculator(5, 3, 5), Equals("3"));Assert::That(Calculator(5, 5, 3), Equals("2"));Assert::That(Calculator(6, 69, 69), Equals("Invalid Input!"));}- Describe(Sample_Tests) {
- It(Test) {
- Assert::That(calculator(0, 420, 420), Equals("Invalid Input!"));
- Assert::That(calculator(1, 1, 1), Equals("2"));
- Assert::That(calculator(1, 16, 9), Equals("25"));
- Assert::That(calculator(2, 1, 1), Equals("0"));
- Assert::That(calculator(2, 57, 62), Equals("-5"));
- Assert::That(calculator(3, -10, 10), Equals("-100"));
- Assert::That(calculator(3, -12, -12), Equals("144"));
- Assert::That(calculator(4, 2, 4), Equals("0"));
- Assert::That(calculator(4, 4, 2), Equals("2"));
- Assert::That(calculator(4, 1, 0), Equals("Invalid Input!"));
- Assert::That(calculator(5, 3, 5), Equals("3"));
- Assert::That(calculator(5, 5, 3), Equals("2"));
- Assert::That(calculator(6, 69, 69), Equals("Invalid Input!"));
- }
- };
def convert(s): return "".join(x.lower() if i & 1 else x.upper() for i, x in enumerate(filter(str.isalpha, s)))
import stringdef HeLlOwOrLddddd(strng):strng = [x for x in strng if x in string.ascii_letters]return "".join([strng[x].upper() if x % 2 == 0 else strng[x].lower() for x in range(len(strng))])- def convert(s):
- return "".join(x.lower() if i & 1 else x.upper() for i, x in enumerate(filter(str.isalpha, s)))
Test.assert_equals(convert("Hello World"), "HeLlOwOrLd") Test.assert_equals(convert(" Ola QueAse"), "OlAqUeAsE") Test.assert_equals(convert("Ola QueAse "), "OlAqUeAsE") Test.assert_equals(convert("H^*@kJpcni(!0dcmniwp"), "HkJpCnIdCmNiWp")
import stringfrom random import randintTest.describe("Basic Tests")test.assert_equals(HeLlOwOrLddddd("Hello World"), "HeLlOwOrLd")test.assert_equals(HeLlOwOrLddddd(" Ola QueAse"), "OlAqUeAsE")test.assert_equals(HeLlOwOrLddddd(" Ola QueAse"), "OlAqUeAsE")Test.describe("Complex Tests")test.assert_equals(HeLlOwOrLddddd(" "), "")test.assert_equals(HeLlOwOrLddddd("H^*@kJpcni(!0dcmniwp"), "HkJpCnIdCmNiWp")Test.describe("Random Tests")for x in range(100):alpha = string.ascii_letters + string.punctuationstrng = "".join([alpha[randint(0, 83)] for x in range(randint(100, 150))])proper_strng = [x for x in strng if x in string.ascii_letters]proper_strng = "".join([proper_strng[x].upper() if x % 2 == 0 else proper_strng[x].lower() for x in range(len(proper_strng))])test.assert_equals(HeLlOwOrLddddd(strng), proper_strng)- Test.assert_equals(convert("Hello World"), "HeLlOwOrLd")
- Test.assert_equals(convert(" Ola QueAse"), "OlAqUeAsE")
- Test.assert_equals(convert("Ola QueAse "), "OlAqUeAsE")
- Test.assert_equals(convert("H^*@kJpcni(!0dcmniwp"), "HkJpCnIdCmNiWp")
public class HeLlOwOrLddddd { public static String convert(String s) { StringBuilder sb = new StringBuilder(); boolean f = false; for (char x : s.toCharArray()) if (Character.isLetter(x)) sb.append((f = !f) ? Character.toUpperCase(x) : Character.toLowerCase(x)); return sb.toString(); } }
- public class HeLlOwOrLddddd {
public static String convert(String input) {String salida = "";boolean mayus = true;for (int i=0;i<input.length();i++){if (Character.isLetter(input.charAt(i))){if (mayus){salida+=Character.toUpperCase(input.charAt(i));mayus=false;}else{salida+=Character.toLowerCase(input.charAt(i));mayus=true;}}}return salida;- public static String convert(String s) {
- StringBuilder sb = new StringBuilder();
- boolean f = false;
- for (char x : s.toCharArray())
- if (Character.isLetter(x))
- sb.append((f = !f) ? Character.toUpperCase(x) : Character.toLowerCase(x));
- return sb.toString();
- }
- }
import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class SolutionTest { @Test public void testSomething() { assertEquals("HeLlOwOrLd", HeLlOwOrLddddd.convert("Hello World")); assertEquals("OlAqUeAsE", HeLlOwOrLddddd.convert(" Ola QueAse")); } }
- import org.junit.Test;
- import static org.junit.Assert.assertEquals;
- import org.junit.runners.JUnit4;
// TODO: Replace examples and use TDD development by writing your own tests- public class SolutionTest {
- @Test
- public void testSomething() {
// assertEquals("expected", "actual");- assertEquals("HeLlOwOrLd", HeLlOwOrLddddd.convert("Hello World"));
- assertEquals("OlAqUeAsE", HeLlOwOrLddddd.convert(" Ola QueAse"));
- }
- }