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.
"""Test equipment positions.""" from __future__ import annotations from collections import Counter, defaultdict import datetime as dt import math import numpy as np import pandas as pd from typing import Any def data_dict() -> defaultdict[str, Any]: """Return all equipment positions.""" d = defaultdict(list) d["T123"].append({"position": {"x": 42, "y": 24, "z": 0.42}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=0)}) d["T456"].append({"position": {"x": 21.0, "y": 34, "z": 0.289}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=0)}) d["T789"].append({"position": {"x": 17, "y": 39, "z": 0.789}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=0)}) d["T456"].append({"position": {"x": 91.0, "y": 114, "z": 0.489}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=3)}) d["T123"].append({"position": {"x": 43, "y": 25, "z": 0.43}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=1)}) d["T789"].append({"position": {"x": 19., "y": 79, "z": 0.991}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=6)}) d["T123"].append({"position": {"x": 46, "y": 29, "z": 0.44}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=2)}) d["T456"].append({"position": {"x": 24.0, "y": 37, "z": 0.297}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=4)}) d["T123"].append({"position": {"x": 49.0, "y": 32, "z": 0.451}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=3)}) d["T789"].append({"position": {"x": 23., "y": 81, "z": 1.103}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=7)}) return d def latest_snapshot() -> dict[str, Any]: """Return a snapshot of latest equipment.""" return { "T123": {"position": {"x": 49.0, "y": 32, "z": 0.451}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=3)}, "T456": {"position": {"x": 24.0, "y": 37, "z": 0.297}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=4)}, "T789": {"position": {"x": 23.0, "y": 81, "z": 1.103}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=7)}, } def counts() -> dict[str, int]: """Return counts per equipment.""" return { "T123": 4, "T456": 3, "T789": 3 } def speeds() -> defaultdict[str, Any]: """Return speeds of equipment.""" d = defaultdict(list) d["T123"].append({"speed": 4.242654947082074, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=3)}) d["T123"].append({"speed": 5.00000999999, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=2)}) d["T123"].append({"speed": 1.4142489172702237, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=1)}) d["T123"].append({"speed": None, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=0)}) d["T456"].append({"speed": 102.0687849638664, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=4)}) d["T456"].append({"speed": 35.43388209045123, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=3)}) d["T456"].append({"speed": None, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=0)}) d["T789"].append({"speed": 4.473538196997986, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=7)}) d["T789"].append({"speed": 6.6750796998987205, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=6)}) d["T789"].append({"speed": None, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=0)}) return d def find_furthest_west(d: defaultdict) -> str: """ Find the name of the truck that is furthest west. That is, the truck with the smallest easting position component. """ latest = get_latest_snapshot(d) truck_furthest_west = "" x = latest[list(latest.keys())[0]]['position']['x'] for item in latest: if latest[item]['position']['x'] < x: x = latest[item]['position']['x'] truck_furthest_west = item return truck_furthest_west def get_latest_snapshot(d: defaultdict) -> dict[str, Any]: """ Return a snapshot of the latest positional updates for the equipment. """ temp = defaultdict(list) for item in d: df = pd.DataFrame(d[item]) temp[item] = df.iloc[-1].to_dict() return temp def get_counts(d: defaultdict) -> dict[str, int]: """Return a dict of trucks and the times they have provided updates.""" temp = defaultdict(list) for item in d: temp[item] = len(d[item]) return temp def calculate_speeds(d: defaultdict) -> defaultdict[str, Any]: """Return a dict of equipment and the speeds they are travelling at.""" df = pd.json_normalize(d, sep='_') temp = defaultdict(list) for item in d: df = pd.json_normalize(d[item], sep='_') diff = df.diff() coords = [c for c in df.columns if not 'timestamp' in c] df['speed'] = np.linalg.norm(diff[coords], axis=1)/diff['timestamp'].dt.seconds temp[item] = df[['timestamp', 'speed']] print(temp) pass
- """Test equipment positions."""
- from __future__ import annotations
- from collections import Counter, defaultdict
- import datetime as dt
- import math
- import numpy as np
- import pandas as pd
- from typing import Any
- def data_dict() -> defaultdict[str, Any]:
- """Return all equipment positions."""
- d = defaultdict(list)
- d["T123"].append({"position": {"x": 42, "y": 24, "z": 0.42}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=0)})
- d["T456"].append({"position": {"x": 21.0, "y": 34, "z": 0.289}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=0)})
- d["T789"].append({"position": {"x": 17, "y": 39, "z": 0.789}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=0)})
- d["T456"].append({"position": {"x": 91.0, "y": 114, "z": 0.489}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=3)})
- d["T123"].append({"position": {"x": 43, "y": 25, "z": 0.43}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=1)})
- d["T789"].append({"position": {"x": 19., "y": 79, "z": 0.991}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=6)})
- d["T123"].append({"position": {"x": 46, "y": 29, "z": 0.44}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=2)})
- d["T456"].append({"position": {"x": 24.0, "y": 37, "z": 0.297}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=4)})
- d["T123"].append({"position": {"x": 49.0, "y": 32, "z": 0.451}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=3)})
- d["T789"].append({"position": {"x": 23., "y": 81, "z": 1.103}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=7)})
- return d
- def latest_snapshot() -> dict[str, Any]:
- """Return a snapshot of latest equipment."""
- return {
- "T123": {"position": {"x": 49.0, "y": 32, "z": 0.451}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=3)},
- "T456": {"position": {"x": 24.0, "y": 37, "z": 0.297}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=4)},
- "T789": {"position": {"x": 23.0, "y": 81, "z": 1.103}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=7)},
- }
- def counts() -> dict[str, int]:
- """Return counts per equipment."""
- return {
- "T123": 4,
- "T456": 3,
- "T789": 3
- }
- def speeds() -> defaultdict[str, Any]:
- """Return speeds of equipment."""
- d = defaultdict(list)
- d["T123"].append({"speed": 4.242654947082074, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=3)})
- d["T123"].append({"speed": 5.00000999999, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=2)})
- d["T123"].append({"speed": 1.4142489172702237, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=1)})
- d["T123"].append({"speed": None, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=0)})
- d["T456"].append({"speed": 102.0687849638664, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=4)})
- d["T456"].append({"speed": 35.43388209045123, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=3)})
- d["T456"].append({"speed": None, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=0)})
- d["T789"].append({"speed": 4.473538196997986, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=7)})
- d["T789"].append({"speed": 6.6750796998987205, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=6)})
- d["T789"].append({"speed": None, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=0)})
- return d
- def find_furthest_west(d: defaultdict) -> str:
- """
- Find the name of the truck that is furthest west. That is,
- the truck with the smallest easting position component.
- """
pass- latest = get_latest_snapshot(d)
- truck_furthest_west = ""
- x = latest[list(latest.keys())[0]]['position']['x']
- for item in latest:
- if latest[item]['position']['x'] < x:
- x = latest[item]['position']['x']
- truck_furthest_west = item
- return truck_furthest_west
- def get_latest_snapshot(d: defaultdict) -> dict[str, Any]:
- """
- Return a snapshot of the latest positional updates for the
- equipment.
- """
pass- temp = defaultdict(list)
- for item in d:
- df = pd.DataFrame(d[item])
- temp[item] = df.iloc[-1].to_dict()
- return temp
- def get_counts(d: defaultdict) -> dict[str, int]:
- """Return a dict of trucks and the times they have provided updates."""
pass- temp = defaultdict(list)
- for item in d:
- temp[item] = len(d[item])
- return temp
- def calculate_speeds(d: defaultdict) -> defaultdict[str, Any]:
- """Return a dict of equipment and the speeds they are travelling at."""
- df = pd.json_normalize(d, sep='_')
- temp = defaultdict(list)
- for item in d:
- df = pd.json_normalize(d[item], sep='_')
- diff = df.diff()
- coords = [c for c in df.columns if not 'timestamp' in c]
- df['speed'] = np.linalg.norm(diff[coords], axis=1)/diff['timestamp'].dt.seconds
- temp[item] = df[['timestamp', 'speed']]
- print(temp)
- pass
Non-Regex solution because I have an irrational distaste for Regex.
- length < 15 check omitted because a correct string already has a minimum length of: 8 (date) + 3 (uppercase) + 3 (month) + 1 (special) + 2 (length) = 17
- lowercase character check omitted because the month abbreviation already requires it
- digit character check omitted because the both the date and length already require it
use std::convert::identity; use chrono::Local; const MONTHS: [&str; 12] = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"]; fn validate_password(password: &str) -> bool { let len = password.len(); let conditions = [ len <= 40, !(2..=len/2).any(|i| len % i == 0), password.chars().filter(char::is_ascii_uppercase).count() >= 3, !password.chars().all(char::is_alphanumeric), password.chars().flat_map(|c| c.to_digit(10)).sum::<u32>() >= 25, MONTHS.iter().any(|month| password.contains(month)), password.contains(&Local::now().format("%Y%m%d").to_string()), password.split(char::is_alphanumeric).map(str::len).max().unwrap_or(0) <= 1, password.contains(&len.to_string()) ]; conditions.into_iter().all(identity) }
use regex::Regex;use chrono::prelude::*;- use std::convert::identity;
- use chrono::Local;
- const MONTHS: [&str; 12] = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
- fn validate_password(password: &str) -> bool {
let mut regexps = vec![r"^.{17}|.{19}|.{23}|.{29}|.{31}|.{37}$", // The maximum length of the password is 40 characters,// The minimum length of the password is 15 characters// The length of the password must be a prime numberr"[a-z]", // Must at least 1 lower caser"[A-Z].*[A-Z].*[A-Z]", // and 3 upper case letter,r"[\d]", // 1 number,r"[^\w^\s]", // 1 special characterr"jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec", //Must have the diminituve of a month- let len = password.len();
- let conditions = [
- len <= 40,
- !(2..=len/2).any(|i| len % i == 0),
- password.chars().filter(char::is_ascii_uppercase).count() >= 3,
- !password.chars().all(char::is_alphanumeric),
- password.chars().flat_map(|c| c.to_digit(10)).sum::<u32>() >= 25,
- MONTHS.iter().any(|month| password.contains(month)),
- password.contains(&Local::now().format("%Y%m%d").to_string()),
- password.split(char::is_alphanumeric).map(str::len).max().unwrap_or(0) <= 1,
- password.contains(&len.to_string())
- ];
let date = Local::now().format("%Y%m%d").to_string(); //Must have today's dateregexps.push(&date);let len = password.len().to_string(); //The length of the password must be inside the passwordregexps.push(&len);let not_match = Regex::new(r"[^\w^\s]{2}").unwrap(); //2 special characters can't be together!not_match.is_match(password) && regexps.iter().all(|r|Regex::new(r).unwrap().is_match(password))- conditions.into_iter().all(identity)
- }
#[cfg(test)] mod tests { use super::*; #[test] fn test_correct() { assert!(validate_password(&(date() + "19jan#NAN99"))); } #[test] fn test_too_long() { assert!(!validate_password(&(date() + "53jan#NANabcdefghijklmnopqrstuvwxyz0123456789"))); } #[test] fn non_prime_length() { assert!(!validate_password(&(date() + "20jan#NAN999"))); } #[test] fn insufficient_capitals() { assert!(!validate_password(&(date() + "19jan#NAn99"))); } #[test] fn no_special_characters() { assert!(!validate_password(&(date() + "19janNANA99"))); } #[test] fn missing_month() { assert!(!validate_password(&(date() + "19jab#NAN99"))); } #[test] fn missing_date() { assert!(!validate_password("17jan#NAN12345678")); } #[test] fn adjacent_special_characters() { assert!(!validate_password(&(date() + "23jan#.NAN99999"))); } #[test] fn wrong_length() { assert!(!validate_password(&(date() + "19jan#NAN"))); } fn date() -> String { Local::now().format("%Y%m%d").to_string() } }
- #[cfg(test)]
- mod tests {
- use super::*;
- #[test]
fn test_add() {assert!(!validate_password(&"abcdedfghijlkmn"));let password = Local::now().format("%Y%m%d").to_string() + &"17jan#NAN";assert!(validate_password(&password));- fn test_correct() {
- assert!(validate_password(&(date() + "19jan#NAN99")));
- }
- #[test]
- fn test_too_long() {
- assert!(!validate_password(&(date() + "53jan#NANabcdefghijklmnopqrstuvwxyz0123456789")));
- }
- #[test]
- fn non_prime_length() {
- assert!(!validate_password(&(date() + "20jan#NAN999")));
- }
- #[test]
- fn insufficient_capitals() {
- assert!(!validate_password(&(date() + "19jan#NAn99")));
- }
- #[test]
- fn no_special_characters() {
- assert!(!validate_password(&(date() + "19janNANA99")));
- }
- #[test]
- fn missing_month() {
- assert!(!validate_password(&(date() + "19jab#NAN99")));
- }
- #[test]
- fn missing_date() {
- assert!(!validate_password("17jan#NAN12345678"));
- }
- #[test]
- fn adjacent_special_characters() {
- assert!(!validate_password(&(date() + "23jan#.NAN99999")));
- }
- #[test]
- fn wrong_length() {
- assert!(!validate_password(&(date() + "19jan#NAN")));
- }
- fn date() -> String {
- Local::now().format("%Y%m%d").to_string()
- }
- }
-2 chars
//who needs dyn for that? enum Animal { Dog, Cat, Rat, } impl Animal { //moved from create_animal fn new(animal_type: &str) -> Animal { match animal_type { "dog" => Animal::Dog, "cat" => Animal::Cat, "rat" => Animal::Rat, _ => panic!("Unknown animal {animal_type}"), } } fn speak(&self) -> &'static str { match self { Animal::Dog => "Woof!", Animal::Cat => "Meow!", _ => unimplemented!(), } } } //next: implement Result to avoid panicing
trait Animal {fn speak(&self) -> &'static str {unimplemented!();}- //who needs dyn for that?
- enum Animal {
- Dog,
- Cat,
- Rat,
- }
struct Dog;impl Animal for Dog {fn speak(&self) -> &'static str {"Woof!"- impl Animal {
- //moved from create_animal
- fn new(animal_type: &str) -> Animal {
- match animal_type {
- "dog" => Animal::Dog,
- "cat" => Animal::Cat,
- "rat" => Animal::Rat,
- _ => panic!("Unknown animal {animal_type}"),
- }
- }
}struct Cat;impl Animal for Cat {- fn speak(&self) -> &'static str {
"Meow!"- match self {
- Animal::Dog => "Woof!",
- Animal::Cat => "Meow!",
- _ => unimplemented!(),
- }
- }
- }
struct Rat;impl Animal for Rat {}fn create_animal(animal_type: &str) -> Box<dyn Animal> {match animal_type {"dog" => Box::new(Dog),"cat" => Box::new(Cat),"rat" => Box::new(Rat),_ => panic!()}}- //next: implement Result to avoid panicing
#[cfg(test)] mod tests { use super::*; #[test] fn test_implemented() { let dog = Animal::new("dog"); let cat = Animal::new("cat"); assert_eq!(dog.speak(), "Woof!"); assert_eq!(cat.speak(), "Meow!"); } #[test] #[should_panic] fn test_unimplemented() { let rat = Animal::new("rat"); rat.speak(); } #[test] #[should_panic] fn test_wrong_input() { let kangaroo = Animal::new("kangaroo"); kangaroo.speak(); } }
- #[cfg(test)]
- mod tests {
- use super::*;
- #[test]
- fn test_implemented() {
let dog = create_animal("dog");let cat = create_animal("cat");- let dog = Animal::new("dog");
- let cat = Animal::new("cat");
- assert_eq!(dog.speak(), "Woof!");
- assert_eq!(cat.speak(), "Meow!");
- }
- #[test]
- #[should_panic]
- fn test_unimplemented() {
let rat = create_animal("rat");- let rat = Animal::new("rat");
- rat.speak();
- }
- #[test]
- #[should_panic]
- fn test_wrong_input() {
- let kangaroo = Animal::new("kangaroo");
- kangaroo.speak();
- }
- }
test cases
import codewars_test as test from solution import Greeting import random def get_greeting(name, rank=None, formal=False): print(f'Hello,{" " + rank if rank is not None else ""} {name}.' if formal else f'Hey, {name}!') return f'Hello,{" " + rank if rank is not None else ""} {name}.' if formal else f'Hey, {name}!' names = [ 'Lisa', 'Skylar', 'Dylan', 'Harper', 'Susan', 'Kenneth', 'Quinn', 'Kevin', 'Morgan', 'Jordan', 'Finley', 'Karen', 'Michael', 'Emerson', 'Daniel', 'Avery', 'William', 'Michelle', 'Justice', 'David', 'Donald', 'Richard', 'Jennifer', 'Robert', 'Payton', 'John', 'James', 'Ariel', 'Skyler', 'Dorothy', 'Charles', 'Paul', 'Drew', 'Rory', 'Steven', 'Riley', 'Reese', 'Robin', 'Cameron', 'Mark', 'Jamie', 'Sarah', 'Jessica', 'Nancy', 'Anthony', 'Brian', 'Sandra', 'George', 'Helen', 'Melissa', 'Dakota', 'Mary', 'Alexis', 'Peyton', 'Alex', 'Charlie', 'Matthew', 'Patricia', 'Christopher', 'Edward', 'Elizabeth', 'Amanda', 'Sawyer', 'Margaret', 'Donna', 'Emily', 'Thomas', 'Bailey', 'Hayden', 'Rowan', 'Harley', 'Kai', 'Carol', 'Laura', 'Linda', 'Casey', 'Parker', 'Andrew', 'Joseph', 'Reagan', 'Emery', 'Phoenix', 'Taylor', 'Betty' ] titles = [ 'Duchess', 'Ambassador', 'Mistress', 'Executive', 'Sultan', 'Pharaoh', 'Baron', 'Mayor', 'Magistrate', 'Sergeant', 'Doctor', 'Sir', 'Lord', 'Vice President', 'Baroness', 'Cardinal', 'Officer', 'Archbishop', 'Duke', 'Agent', 'Madam', 'Queen', 'Minister', 'King', 'Captain', 'Pope', 'Master', 'Admiral', 'Princess', 'Lieutenant', 'Director', 'President', 'Governor', 'Commander', 'Prince', 'Detective', 'Professor', 'Sheikh', 'Bishop', 'Chancellor', 'Countess', 'Empress', 'Chief', 'Senator', 'Counselor', 'Emperor', 'Judge', 'General', 'Count' ] @test.describe("Fixed Tests") def test_group(): @test.it("Tests") def test_case(): test.assert_equals(Greeting('John'), 'Hey, John!') test.assert_equals(Greeting('Churchill', 'Sir', True), 'Hello, Sir Churchill.') test.assert_equals(Greeting('Einstein', 'Proffessor', False), 'Hey, Einstein!') test.assert_equals(Greeting('Jane', formal=True), 'Hello, Jane.') @test.describe("Random Tests") def random(): for test_number in range(100): qname = names[random.randint(0,len(names)-1)] qrank = titles[random.randint(0,len(titles)-1)] if random.randint(0,1)==1 else '' f = bool(random.randint(0,1)==0) @test.it(f'Random Test #{str(test_number+1)}: {qname}{", rank="+qrank if not qrank=="" else ""}, formal={f}') def _(): expected = f'Hello,{" "if not qrank=="" else ""}{qrank} {qname}.' if f else f'Hey, {qname}!' print(f'Expected Answer: "{expected}". Your Answer: "{Greeting(qname, qrank, f)}"') test.assert_equals(Greeting(qname, qrank, f), expected)
- import codewars_test as test
- from solution import Greeting
- import random
# Working solution / random generator- def get_greeting(name, rank=None, formal=False):
- print(f'Hello,{" " + rank if rank is not None else ""} {name}.' if formal else f'Hey, {name}!')
- return f'Hello,{" " + rank if rank is not None else ""} {name}.' if formal else f'Hey, {name}!'
def get_person():names = [- names = [
- 'Lisa', 'Skylar', 'Dylan', 'Harper', 'Susan', 'Kenneth', 'Quinn', 'Kevin', 'Morgan', 'Jordan', 'Finley',
- 'Karen', 'Michael', 'Emerson', 'Daniel', 'Avery', 'William', 'Michelle', 'Justice', 'David', 'Donald',
- 'Richard', 'Jennifer', 'Robert', 'Payton', 'John', 'James', 'Ariel', 'Skyler', 'Dorothy', 'Charles', 'Paul',
- 'Drew', 'Rory', 'Steven', 'Riley', 'Reese', 'Robin', 'Cameron', 'Mark', 'Jamie', 'Sarah', 'Jessica', 'Nancy',
- 'Anthony', 'Brian', 'Sandra', 'George', 'Helen', 'Melissa', 'Dakota', 'Mary', 'Alexis', 'Peyton', 'Alex',
- 'Charlie', 'Matthew', 'Patricia', 'Christopher', 'Edward', 'Elizabeth', 'Amanda', 'Sawyer', 'Margaret',
- 'Donna', 'Emily', 'Thomas', 'Bailey', 'Hayden', 'Rowan', 'Harley', 'Kai', 'Carol', 'Laura', 'Linda', 'Casey',
- 'Parker', 'Andrew', 'Joseph', 'Reagan', 'Emery', 'Phoenix', 'Taylor', 'Betty'
- ]
titles = [- titles = [
- 'Duchess', 'Ambassador', 'Mistress', 'Executive', 'Sultan', 'Pharaoh', 'Baron', 'Mayor', 'Magistrate',
- 'Sergeant', 'Doctor', 'Sir', 'Lord', 'Vice President', 'Baroness', 'Cardinal', 'Officer', 'Archbishop',
- 'Duke', 'Agent', 'Madam', 'Queen', 'Minister', 'King', 'Captain', 'Pope', 'Master', 'Admiral', 'Princess',
- 'Lieutenant', 'Director', 'President', 'Governor', 'Commander', 'Prince', 'Detective', 'Professor',
- 'Sheikh', 'Bishop', 'Chancellor', 'Countess', 'Empress', 'Chief', 'Senator', 'Counselor', 'Emperor', 'Judge',
- 'General', 'Count'
- ]
rand_num = random.randrange(1, 4)if rand_num == 1:return random.choice(names)if rand_num == 2:rand_name = random.choice(names)title_or_formal = random.choice([(random.choice(titles)), (random.randrange(1, 10) % 2 == 0)])return rand_name, title_or_formalrand_name = random.choice(names)rand_title = random.choice(titles)form = random.randrange(1, 10) % 2 == 0return rand_name, rand_title, form# START OF TESTING@test.describe("Example")- @test.describe("Fixed Tests")
- def test_group():
@test.it("Test case")- @test.it("Tests")
- def test_case():
# Corrected function calls- test.assert_equals(Greeting('John'), 'Hey, John!')
- test.assert_equals(Greeting('Churchill', 'Sir', True), 'Hello, Sir Churchill.')
- test.assert_equals(Greeting('Einstein', 'Proffessor', False), 'Hey, Einstein!')
- test.assert_equals(Greeting('Jane', formal=True), 'Hello, Jane.')
- @test.describe("Random Tests")
def random_stuff():for _ in range(100):person = get_person()@test.it(f"Testing: {person}")def test_random():if isinstance(person, tuple):if len(person) == 2:if isinstance(person[1], str):test.assert_equals(Greeting(person[0], rank=person[1]), get_greeting(person[0], rank=person[1]))else:test.assert_equals(Greeting(person[0], formal=person[1]), get_greeting(person[0], formal=person[1]))else:test.assert_equals(Greeting(*person), get_greeting(*person))else:test.assert_equals(Greeting(person), f'Hey, {person}!')- def random():
- for test_number in range(100):
- qname = names[random.randint(0,len(names)-1)]
- qrank = titles[random.randint(0,len(titles)-1)] if random.randint(0,1)==1 else ''
- f = bool(random.randint(0,1)==0)
- @test.it(f'Random Test #{str(test_number+1)}: {qname}{", rank="+qrank if not qrank=="" else ""}, formal={f}')
- def _():
- expected = f'Hello,{" "if not qrank=="" else ""}{qrank} {qname}.' if f else f'Hey, {qname}!'
- print(f'Expected Answer: "{expected}". Your Answer: "{Greeting(qname, qrank, f)}"')
- test.assert_equals(Greeting(qname, qrank, f), expected)