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.
create a pop_first and pop_last functions which will delete first/last element from vector and then return it
#include<vector>
template <typename T>
T
pop_last(std::vector<T>* v) {
T result = (*v)[v->size() - 1];
v->pop_back();
return result;
}
template <typename T>
T
pop_first(std::vector<T>* v) {
T result = (*v)[0];
v->erase(v->begin());
return result;
}
template int pop_last(std::vector<int>*);
template int pop_first(std::vector<int>*);
#include<vector>
template <typename T> T pop_last(std::vector<T>* v);
template <typename T> T pop_first(std::vector<T>* v);
Describe(pop)
{
It(_pop_last_)
{
std::vector<int> vec = {1,2,3,4};
Assert::That(pop_last(&vec), Equals(4));
Assert::That(pop_last(&vec), Equals(3));
Assert::That(pop_last(&vec), Equals(2));
Assert::That(pop_last(&vec), Equals(1));
}
It(_pop_first_)
{
std::vector<int> vec2 = {1,2,3,4};
Assert::That(pop_first(&vec2), Equals(1));
Assert::That(pop_first(&vec2), Equals(2));
Assert::That(pop_first(&vec2), Equals(3));
Assert::That(pop_first(&vec2), Equals(4));
}
};
SQLite
is a lightweight disk-based database that doesn’t require a server process and allows accessing the database using a nonstandard variant of the SQL
.
Objective
- Build a survey application that utilizes Python's built-in
sqlite3
module.
Scenario
What is your favorite programming language? This Survey
application prompts a user to enter their username
, and favorite programming_language
. It saves the results to a sqlite3
database, and displays the results afterwards.
import sqlite3
import os
# constants:
CREATE_SURVEY_TABLE = """
CREATE TABLE IF NOT EXISTS Survey_tb (
id INTEGER,
username VARCHAR(50) UNIQUE,
language VARCHAR(20),
PRIMARY KEY(id)
);"""
INSERT_INTO_SURVEY = """
INSERT INTO Survey_tb (username, language) VALUES(?,?);
"""
DISPLAY_RESULTS = """
SELECT * FROM Survey_tb;
"""
MENU_PROMPT = """ -- Favorite Programming Language Survey!--"""
class SurveyConnection:
"""SQLite3 Survey connection class"""
def __init__(self):
self.conn = sqlite3.connect(os.path.join(os.getcwd(), 'survey.db'))
self.curr = self.conn.cursor()
self.__create_table()
def __create_table(self):
"""Creates tables used to store survey results."""
with self.conn:
self.conn.execute(CREATE_SURVEY_TABLE)
def save_to_db(self, username, language):
"""This function saves survey results to database."""
try:
with self.conn:
self.conn.execute(INSERT_INTO_SURVEY, (username, language))
return 'Your results have been saved successfully!'
except sqlite3.IntegrityError:
print("You have already taken the survey")
return False
class Survey:
"""A survey class with a sqlite3 connection class."""
def __init__(self, connection):
self.connection = connection
def take_survey(self):
"""Prompts user for username, and favorite programming language, and save results to database."""
print(MENU_PROMPT)
username = input('Enter your username:\n> ')
language = input('What is your favorite programming?:\n> ')
self.connection.save_to_db(username, language)
self.connection.conn.commit()
def show_survey_results(self):
"""Displays results of database."""
row = self.connection.curr.execute(DISPLAY_RESULTS).fetchall()
for result in row:
print(result)
def main():
connection = SurveyConnection()
survey = Survey(connection)
survey.take_survey()
survey.show_survey_results()
if __name__ == '__main__':
main()
import codewars_test as test
import os
from solution import SurveyConnection, Survey
@test.describe("Example")
def test_group():
@test.it("test case 1: Ensuring local databse file was created successfully, and database connection.")
def test_case():
connection = SurveyConnection()
database_created = os.path.exists(os.path.join(os.getcwd(),'survey.db'))
test.assert_equals(database_created, True)
@test.it('test case 2: Inserting record into database using the "save_to_db" method.')
def test_case():
connection = SurveyConnection()
result = connection.save_to_db('seraph776', 'Python')
test.assert_equals(result, 'Your results have been saved successfully!')
@test.it("test case 3: Querying the previously inserted record, ensuring it was saved to the database successfully.")
def test_case():
connection = SurveyConnection()
record = len(connection.curr.execute("SELECT username FROM Survey_tb WHERE username = ?", ('seraph776',)).fetchone())
test.assert_equals(record, True)
@test.it('test case 4: Testing UNIQUE contraint of username.')
def test_case():
connection = SurveyConnection()
test.assert_equals(connection.save_to_db('seraph776', 'Python'),False )
@test.it("test case 5: Database has been successfully deleted...")
def test_case():
# deleting database after testing.
os.remove(os.path.join(os.getcwd(), 'survey.db'))
database_created = os.path.exists(os.path.join(os.getcwd(),'survey.db'))
test.assert_equals(database_created, False)
int main;
#include<criterion/criterion.h>
import socket
def setup():
print('setup done')
def http_server(port = 80):
with socket.create_server(('127.0.0.1',port)) as my_server:
with my_server.accept()[0] as con:
packet = con.recv(1024).decode()
con.send(b'sent mssg')
def close():
pass
import os, sys, json, threading, socket, time
import codewars_test as test
import preloaded
preloaded.make_dir()
import importlib
importlib.invalidate_caches()
time.sleep(0.01)
# prevent automated solution import
class fake_solution:
pass
sys.modules["solution"] = fake_solution
import solution
del sys.modules["solution"]
base_path = os.path.dirname(os.path.abspath(__file__))
webroot_path = f'{base_path}/server_folder/webroot'
import shutil
shutil.copy(f'{base_path}/solution.py', f'{base_path}/server_folder/solution.py')
print(os.listdir(f'{base_path}'))
print(os.listdir(f'{base_path}/server_folder'))
import server_folder.solution as solution
solution.setup()
server_thread = threading.Thread(target = solution.http_server, args = [1111])
server_thread.start()
with socket.create_connection(('127.0.0.1',1111)) as a:
a.send(b'GET / HTTP/1.1')
b = a.recv(2048).decode().replace('<', '< ')
print(b)
solution.close()
server_thread.join()
Description: Write a function number_sum that takes a list of integers as input and returns the sum of all positive numbers in the list. If the list contains only negative numbers or is empty, the function should return 0.
Function signature: def number_sum(numbers: List[int]) -> int:
Example
number_sum([1, 2, 3, -4, -5]) # returns 6 (1 + 2 + 3)
number_sum([-1, -2, -3]) # returns 0
from typing import List
def number_sum(numbers: List[int]) -> int:
return sum(num for num in numbers if num > 0)
# Example usage
print(number_sum([1, -2, 3, -4, 5])) # Output: 9
print(number_sum([-1, -2, -3])) # Output: 0
import codewars_test as test
# TODO Write tests
import solution # or from solution import example
# test.assert_equals(actual, expected, [optional] message)
@test.describe("Example")
def test_group():
@test.it("test case")
def test_case():
test.assert_equals(1 + 1, 2)
Write a function that will have one argument which will be a string (sentence) and you have to capitalize every words first letter in that sentence. For example: if the input is "i am a javascript programmer" then the output shoud come "I Am A Javascript Programmer"
function capitalize(sentence) {
let words = sentence.split(' ');
const length = words.length;
for (let i = 0; i < length; ++i) {
words[i] = words[i][0].toUpperCase() + words[i].substr(1)
}
return words.join(' ');
}
console.log(capitalize("i am a javascript programmer"));
// Since Node 10, we're using Mocha.
// You can use `chai` for assertions.
const chai = require("chai");
const assert = chai.assert;
// Uncomment the following line to disable truncating failure messages for deep equals, do:
// chai.config.truncateThreshold = 0;
// Since Node 12, we no longer include assertions from our deprecated custom test framework by default.
// Uncomment the following to use the old assertions:
// const Test = require("@codewars/test-compat");
describe("Solution", function() {
it("should test for something", function() {
// Test.assertEquals(1 + 1, 2);
// assert.strictEqual(1 + 1, 2);
});
});
from random import randint
quotes= ["Captain Teemo on duty.","Yes, sir!", "Armed and ready.","Reporting in.","Hut, two, three, four.","I'll scout ahead!","Swiftly!","That's gotta sting.","Never underestimate the power of the Scout's code.","Size doesn't mean everything."]
def motivation():
return quotes[randint(0,len(quotes)-1)]
import codewars_test as test
# TODO Write tests
import solution # or from solution import example
print(motivation())
# test.assert_equals(actual, expected, [optional] message)
@test.describe("Example")
def test_group():
@test.it("test case")
def test_case():
test.assert_equals(1 + 1, 2)
Task
- Debug the
authenticated_request
function. There are several bugs in this code preventing it from executing correctly. If properly debugged, it will autheniticate the request to the given url, and return a200
HTTP response status code (which means there was a successfful response).
Rule
- Do not edit the
URL
constant in theCode
orPreloaded
tab. The purpose of this kumite is to debug the code within theauthenticated_request
method, and generated a200
response code to this given url.
Hint
Click to view
- You must look at the
URL
constant in thePreloaded
tab to successfully debug this. - There is an incorrect:
data structure
,method
, andparameter
.
import requests
def authenticated_request():
credentials = {'username': 'seraph', 'password': 'secret'}
try:
response = requests.post(url=URL, data=credentials)
except (ValueError, NameError, TypeError) as e:
return False
else:
return response.status_code == 200
import codewars_test as test
from solution import authenticated_request
@test.describe("Example")
def test_group():
@test.it("test case")
def test_case():
test.assert_equals(authenticated_request(), True)
def get_of_my_lawn(on_my_lawn):
if on_my_lawn:
return "get of my lawn"
import codewars_test as test
# TODO Write tests
import solution # or from solution import example
# test.assert_equals(actual, expected, [optional] message)
@test.describe("Example")
def test_group():
@test.it("test case")
def test_case():
test.assert_equals(1 + 1, 2)
Background information
Time is measured differently on each planet. One Earth year is equivalent to the amount of
time it takes for Earth to orbit the sun. On other planets, this orbital time is shorter or longer.
Planet | Rotation period (hours) | Orbit period (days) |
---|---|---|
Mercury | 58.6 | 88.0 |
Venus | 243 | 224.7 |
Earth | .99 | 365.25 |
Mars | 1.03 | 687 |
Jupiter | .41 | 4331 |
Saturn | .45 | 10747 |
Uranus | .72 | 30589 |
Neptune | .67 | 59800 |
Pluto | 6.39 | 90560 |
- Source : nasa.org
Task
Create a function named planetary_age
that takes two parameters, planet
, and age
which are str
, and int
respectively. The function should calculate your age on other planets.
def planetary_age(planet, age):
hashmap = {
'mercury': {'rotation': 58.6, 'revolution': 88.0},
'venus': {'rotation': 243, 'revolution': 224.7},
'earth': {'rotation': .99, 'revolution': 365.25},
'mars': {'rotation': 1.03, 'revolution': 687},
'jupiter': {'rotation': .41, 'revolution': 4331},
'saturn': {'rotation': .45, 'revolution': 10747},
'uranus': {'rotation': .72, 'revolution': 30589},
'neptune': {'rotation': .67, 'revolution': 59800},
'pluto': {'rotation': 6.39, 'revolution': 90560}
}
earth_days = age * hashmap['earth']['revolution']
planet_age = earth_days / hashmap[planet]['revolution']
days = earth_days / hashmap[planet]['rotation']
return planet_age, days
import codewars_test as test
from solution import planetary_age
import random
@test.describe("Example")
def test_group():
@test.it("test case: testing ages (13, 20, 55, 76) against all 12 planets")
def test_case():
planets = ('mercury', 'venus', 'earth', 'mars', 'jupiter', 'saturn', 'uranus', 'neptune', 'pluto')
age = 13
s1 = ((53.95738636363637, 81.02815699658703),
(21.13150867823765, 19.540123456790123),
(13.0, 4796.212121212121),
(6.9115720524017465, 4609.9514563106795),
(1.0963403371045948, 11581.09756097561),
(0.44182097329487297, 10551.666666666666),
(0.1552273693157671, 6594.791666666667),
(0.07940217391304348, 7086.940298507462),
(0.052432089222614844, 743.075117370892),)
for planet, expected in zip(planets, s1):
test.assert_equals(planetary_age(planet, age), expected)
age = 20
s2 = ((83.01136363636364, 124.65870307167235),
(32.510013351134845, 30.061728395061728),
(20.0, 7378.787878787879),
(10.633187772925764, 7092.233009708738),
(1.6866774416993766, 17817.07317073171),
(0.6797245742998046, 16233.333333333332),
(0.23881133740887248, 10145.833333333334),
(0.12215719063545151, 10902.985074626866),
(0.08066475265017668, 1143.192488262911),)
for planet, expected in zip(planets, s2):
test.assert_equals(planetary_age(planet, age), expected)
age = 55
s3 = ((228.28125, 342.811433447099),
(89.40253671562083, 82.66975308641975),
(55.0, 20291.666666666668),
(29.24126637554585, 19503.640776699027),
(4.638362964673286, 48996.9512195122),
(1.8692425793244627, 44641.666666666664),
(0.6567311778743993, 27901.041666666668),
(0.3359322742474916, 29983.20895522388),
(0.22182806978798586, 3143.779342723005),)
for planet, expected in zip(planets, s3):
test.assert_equals(planetary_age(planet, age), expected)
age = 76
s4 = ((315.4431818181818, 473.70307167235495),
(123.53805073431242, 114.23456790123457),
(76.0, 28039.39393939394),
(40.4061135371179, 26950.485436893203),
(6.409374278457631, 67704.87804878049),
(2.5829533823392574, 61686.666666666664),
(0.9074830821537154, 38554.16666666667),
(0.46419732441471573, 41431.343283582086),
(0.3065260600706714, 4344.131455399061),)
for planet, expected in zip(planets, s4):
test.assert_equals(planetary_age(planet, age), expected)