Start a new Kumite
AllAgda (Beta)BF (Beta)CCFML (Beta)ClojureCOBOL (Beta)CoffeeScriptCommonLisp (Beta)CoqC++CrystalC#D (Beta)DartElixirElm (Beta)Erlang (Beta)Factor (Beta)Forth (Beta)Fortran (Beta)F#GoGroovyHaskellHaxe (Beta)Idris (Beta)JavaJavaScriptJulia (Beta)Kotlinλ Calculus (Beta)LeanLuaNASMNim (Beta)Objective-C (Beta)OCaml (Beta)Pascal (Beta)Perl (Beta)PHPPowerShell (Beta)Prolog (Beta)PureScript (Beta)PythonR (Beta)RacketRaku (Beta)Reason (Beta)RISC-V (Beta)RubyRustScalaShellSolidity (Beta)SQLSwiftTypeScriptVB (Beta)
Show only mine

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.

Ad
Ad

Hello Everybody I would like your help to improve the code quality of this very old, simple and scrappy code I made when I started to code as a hobby.

import random


def code():
    print('Guess a number between 1 and 25')

    # secret number
    secret_number = random.randint(1, 25)

    guess_count = 0
    guess_limit = 5

    # mainloop
    while guess_count < guess_limit:
        try:
            guess = int(input('\nGuess: '))
            guess_count += 1

        except ValueError:
            print("\nInvalid Input!")
            continue

        if guess > secret_number:
            print('\nNo, too big.')
            guess_count += 1

        elif guess < secret_number:
            print('\nNo, too small.')
            guess_count += 1

        elif guess == secret_number:
            print('\nWow, you are a actully are a true mind reader!')
            print(f"The number was {secret_number} indeed! ")
            reply = input('\nDo you want to play guess again? (yes/no) - ')
            if reply == 'yes':
                code()
            else:
                exit()

        if guess_count == 5:
            print('\nSorry, you have failed:(')
            print(f'\nThe secret number was {secret_number}.')

            replay = input('\nDo you want to play Guess game again? (yes/no) - ')
            if replay == 'yes':
                code()
            elif replay == 'no':
                exit()
            else:
                print("I don't understand")


code()

A customer pays a goods for 100 (price) and they must pay additonal tax 10 (VAT rate 10%). The final price will be 110.

If the customer pays goods with price greater than or equal 1000, the customers will pay additional luxury tax with rate 30%.

We need your help to make a formula to calculate the final price (include tax).

Information:
VAT rate = 10%
Luxury tax rate* = 30%
*imposed only if the goods and services price greater than or equal 1000

function finalPrice(price) {
  var vat = 0.1
  var lux = 0.3
  
  if(price >= 1000) {
  return Math.floor(price * (1+vat+lux))
    } else {
      return Math.floor(price * (1+vat))
    }
}

Restaurant have to calcute the final price which include Value Added Tax(VAT) and service charge.

Service charge only calculated for dine in.

We need your help to make a function to calculate the final price.

Note:
-VAT rate is 10%
-service charge rate is 5%
-service charge is taxable
-the final price should be round down.

Example:
-if the price is 100 and take away, the final price would be 110
-if the price is 100 and dine in, the final price would be 105

function finalPrice(price,dineIn) {
  var service = 0.05
  var VAT = 0.1
  
  if(dineIn == true) {
    return Math.floor(price * (1 +service) * (1+ VAT)) }
  else {
    return Math.floor(price * (1+ VAT))
  }
   
  
}

תרגול טיפוסי נתונים מורכבים
במסעדה של טוויטי רוצים לעקוב אחרי העובדים במסעדה ואחרי הגילאים שלהם על מנת לנהל את השכר שלהם בצורה מדויקת וטובה. כאן בדיוק אתם נכנסים לתמונה: עליכם לכתוב אפליקציה בת שתי מחלקות שתנהל את רשימות העובדים במסעדה.
מחלקת ה-Main
מחלקה זו תכיל את את השגרה הראשית main והיא תציג תפריט למשתמש עד אשר הוא יבחר לצאת. כל פעם שהמשתמש בוחר פעולה מהתפריט יש להפעיל את המתודות המתאימות.
התפריט יכיל את האופציות הבאות:

  1. הוספת עובד
  2. הסרת עובד
  3. בדיקה האם עובד קיים ברשימות העובדים
  4. הדפסת כל העובדים במסעדה
  5. שינוי גיל של עובד
    יש להגדיר קבועים לייצוג האפשרויות האלו

מחלקת המסעדה – Restaurant
למחלקה זו data member אחד:
private HashMap<String, Integer> emploees;
ה Data Member שלנו הוא מטיפוס HashMap.
מתודות:
הוספת עובד
public boolean addEmployee(String name, int age)
ערך החזר:
האם הצלחנו להוסיף את העובד.
הפרמטרים המתקבלים:
שם העובד
גל העובד
שני נתונים אלו ישמרו בתוך הרשימה שלנו.
כיצד ניתן לשמור את שניהם יחדיו? כנראה שאחד מהערכים יהיה המפתח (הממוין), והשני יהיה הערך הנשמר. חישבו היטב מה יהיה ממוין ומה יהיה הערך.
כאשר אנו קולטים את שני הנתונים הללו יש לבדוק את הדברים הבאים:
השדות הללו מכילים ערכים – הרי לא הגיוני שנקלוט עובד שאין לו שם.
לא קיים עובד עם שם כזה במערכת – כי אם הוא כבר קיים המערכת תספוג תעופה

פיטור עובד
public boolean removeEmployee(String name)
הסרה מהמסעדה של העובד
יש לבדוק שהעובד באמת קיים במערכת

בדיקה האם קיים עובד במערכת
private boolean isEmployeeExist(String name)
מקבלת שם עובד ובודקת האם הוא קיים ברשימה
זוהי מתודה פרטית למחלקת המסעדה, חישבו היכן היא תהיה שימושית.

הדפסת רשימת העובדים
public void printEmployees()

יש לטפל במקרה ולא קיימים עובדים במסעדה באמצעות הדפסה מיוחדת.

import java.util.InputMismatchException;
import java.util.Scanner;

public class Main {
    private static Scanner input = new Scanner(System.in);
    private static final int EXIT = -999;
    public static Restaurant restaurant;
    final static int ADD_EMPLOYEE = 1;
    final static int REMOVE_EMPLOYEE = 2;
    final static int IS_EMPLOYEE_EXIST = 3;
    final static int PRINT_EMPLOYEES = 4;
    final static int CHANGE_EMPLOYEE_AGE = 5;

    public static void main(String[] args) {
        System.out.println("Choose your option from the list below or if you want to stop enter -999");
        System.out.println("Press "+ADD_EMPLOYEE+" to add employee");
        System.out.println("Press "+REMOVE_EMPLOYEE+" to remove employee");
        System.out.println("Press "+IS_EMPLOYEE_EXIST+" to check if employee exist");
        System.out.println("Press "+PRINT_EMPLOYEES+" to print employees");
        System.out.println("Press "+CHANGE_EMPLOYEE_AGE+" to change age");

        int option = input.nextInt();
        while (option > 5 || (option < 1  && option!= EXIT )) {
            System.out.println("Wrong option number choose your option again");
            option = input.nextInt();
        }

        restaurant = new Restaurant();

        while (option != EXIT) {
            turn(option);

            System.out.println("Choose your option if you want to stop enter -999");
            option = input.nextInt();
            while (option > 5 || (option < 1  && option!= EXIT )) {
                System.out.println("Wrong option number choose your option again");
                option = input.nextInt();
            }
        }

    }

    private static void turn(int option) {
        switch (option) {
            case ADD_EMPLOYEE:
                addEmployee();

                break;
            case REMOVE_EMPLOYEE:
                removeEmployee();

                break;
            case IS_EMPLOYEE_EXIST:
                isEmployeeExist();

                break;
            case PRINT_EMPLOYEES:
                restaurant.printEmployees();

                break;
            case CHANGE_EMPLOYEE_AGE:
                changeEmployeeAge();

                break;
            default:
                break;
        }
    }

    private static void addEmployee() {
        String name;
        int age;

        System.out.println("Enter employee's name");
        name = input.next();
        System.out.println("Enter employee's age");
        age = input.nextInt();
        if (restaurant.addEmployee(name, age)) {
            System.out.println("You added the employee name to " + name + " and age to " + age);
        } else {
            if (name.isEmpty()) {
                System.out.println("You did not entered a name");
            } else {
                System.out.println("The employee " + name + " already exist");
            }
        }
    }

    private static void removeEmployee() {
        String name;

        System.out.println("Enter employee's name");
        name = input.next();
        if (restaurant.removeEmployee(name)) {
            System.out.println("You remvoed the employee " + name);
        } else {
            System.out.println("The employee " + name + " does not exist");
        }
    }

    private static void isEmployeeExist() {
        String name;

        System.out.println("Enter employee's name");
        name = input.next();
        if (restaurant.isEmployeeExist(name)) {
            System.out.println("Employee " + name + " exist");
        } else {
            System.out.println("Employee " + name + "  does not exist");
        }

    }

    private static void changeEmployeeAge() {
        String name;
        int age;

        System.out.println("Enter employee's name");
        name = input.next();
        System.out.println("Enter employee's age");
        age = input.nextInt();
        if (restaurant.setAge(name, age)) {
            System.out.println("You updated the employee " + name + " age to " + age);
        } else {
            System.out.println("The employee " + name + " does not exist");
        }
    }
}

import java.util.HashMap;

public class Restaurant {
    private HashMap<String, Integer> emploees;
    public Restaurant(){
        emploees = new HashMap<String, Integer>();
    }

    public boolean addEmployee(String name, int age) {
        if (this.isEmployeeExist(name) || name.isEmpty()) {
            return false;
        } else {
            this.emploees.put(name, age);
            return true;
        }
    }

    public boolean removeEmployee(String name) {
        if(this.isEmployeeExist(name)){
            this.emploees.remove(name);
            return true;
        }
        return false;
    }

    public boolean isEmployeeExist(String name){
        return (this.emploees.containsKey(name));
    }

    public void printEmployees() {
        if(this.emploees.isEmpty()){
            System.out.println("This restaurant has no workers");
        }
        else{
            for(String key : this.emploees.keySet()){
                System.out.println(key+" "+ this.emploees.get(key));

            }
        }

    }

    public boolean setAge(String name,int age){
        if(this.emploees.containsKey(name)){
            this.emploees.replace(name,age);
            return true;
        }
        return false;


    }



}
Algorithms
Logic
Lists
Data Structures

Given an input list. Example [1,2,3,4,5,6] split it into a new list, where the items contained are split into longer and longer length lists in the parent list. Like: [[1], [2, 3], [4, 5, 6]].

If the list does not fill the chunk completly, fill it up party. [1,2,3,4] => [[1], [2, 3], [4]]

More examples:

[1, 2, 3, 4, 5, 6] => [[1], [2, 3], [4, 5, 6]]

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] => [[1], [2, 3], [4, 5, 6], [7, 8, 9, 10], [11, 12, 13, 14, 15], [16]]

def variable_chunks(lst):
    if lst == []:
        return [[]]
    result = []
    y = 0
    for x in range(1, len(lst) + 1):
        result.append(lst[y:y+x])
        y = y+x
    return [x for x in result if x != []]
// The operation with the number "1" goes first
var add1 = 0
var add2 = 0

var minus1 = 0
var minus2 = 0

var divide1 = 0
var divide2 = 0

var times1 = 0
var times2 = 0
//change the numbers in the varibles above

console.log("Addition" , add1 + add2) //Addition

console.log("Subtraction", minus1-minus2) //Subtraction

console.log("Division" , divide1/divide2) //Division

console.log("Multiplication" , times1*times2) //Multiplication

Make a file get downloaded.

function download(filename, text) {
          var element = document.createElement("a");
          element.setAttribute(
            "href",
            "data:text/plain;charset=utf-8," + encodeURIComponent(text)
          );
          element.setAttribute("download", filename);

          element.style.display = "none";
          document.body.appendChild(element);

          element.click();

          document.body.removeChild(element);
        }

        window.onload = function() {
            var text = "downloaded file";
            var filenames = "file";
            var filename = filenames + ".txt";

            download(filename, text);
        }

You are building a calendar app. You have the following task assigned to you:

Build a function that receives a single parameter - a list of time intervals when the user is not available - and returns a list of the intervals when the user will be free in the same day. Consider that all times are restricted to 30 minutes increments, eg “12:00”, “00:30”, “17:30”. No input validation is necessary.

Both the parameter and the return value should be a list of tuples, for example, the following list:

[(“12:00”, “13:00”), (“14:00”, “17:00”)]

Means that the user is busy from 12:00 to 13:00 (let’s say it’s his lunch time) and from 14:00 to 17:00 (let’s say he’ll be in a long meeting). Calling the function with the arguments, like:

Should return the time intervals when the user is available, so, in this case, it would be:

[(“00:00”,“12:00”), (“13:00”, “14:00”), (“17:00”, “24:00”)]

def get_available_times(hours):
    available_times = {}
    i = 0
    for i in range(0, len(hours)):
        if hours[i][0] == '00:00':
            continue
        if i == 0:
            available_times['00:00'] = hours[i][0]
        else:
            available_times[hours[i-1][1]] = hours[i][0]
        if i == (len(hours) - 1) and hours[i][1] != '24:00':
            available_times[hours[i][1]] = '24:00'
    return list(available_times.items())
Logic
Arrays
Data Types
Objects

The function must receive three parameters: array, order, and key. The key must determine the order of the array, as in the example:

let arr = [
{id: 5, name: 'Hugo'},
{id: 2, name: 'Julian'},
{id: 3, name: 'Anne'},
{id: 1, name: 'April'},
{id: 4, name: 'John'}
];

let order = [1, 2, 3, 4, 5];

mapOrder(arr, order, 'id');

must return:

0: {id: 1, name: "April"}
1: {id: 2, name: "Julian"}
2: {id: 3, name: "Anne"}
3: {id: 4, name: "John"}
4: {id: 5, name: "Hugo"}

function mapOrder(array, order, key) {
  if (typeof array !== 'object' || typeof order !==  'object' || typeof key !== 'string') return [];
  
  array.sort((a, b) => {
    let A = a[key], B = b[key];

    if (order.indexOf(A) > order.indexOf(B)) {
        return 1;
    } else return -1;
  });

  return array;
}

Whether you're a kata solver or a kata author, Codewars allows you to embed client-side
HTML, CSS, and JavaScript in your outputs.

This goes well beyond ASCII art. The door is open to more sophisticated debugging and visualization techniques. For a contrived and sloppily coded example, run this kata; in the output panel there should be a snake which, if luck will have it, you can control via the arrow keys on your keyboard.

Some JavaScript methods are disabled in this environment, but even so, for kata authors with JavaScript+CSS experience and full DOM control, the sky's the limit.

// The client-side stuff that this demo is made of is
// in the preloaded section, but it's not pretty or necessary
// to look at so I'm leaving it out of the main code view.
// The purpose of this kumite isn't to demonstrate *how* to embed HTML.
// That's as trivial as console.log(). The point, rather, is
// to make a public service anouncement to remind everyone
// that HTML, CSS, and JavaScript are available, and when
// deployed appropriately they can improve your katas.