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

Se va a simular el estilo de puntuacion de una liga de futbol en la cual :

  • Si juegas en casa tus goles marcados se reflejan a la izquierda del guion.
  • Si juegas fuera tus goles marcados se reflejan a la derecha del guion.
  • Los goles encajados se reflejan en la parte contraria a los marcados eg;
    • {3-0} Partido en casa ganado 3 goles marcados.
    • {0-3} Partido fuera ganado 3 goles marcados.
    • {1-2} Partido en casa perdido 1 gol marcado 2 encajados.
  • Los partidos se deciden si son fuera o en casa mediante alternancia.
    • Uno fuera uno en casa ,dependiendo de el parametro booleano que se le pasa como parametro a la funcion.
    • El parametro pasado , si es true es que el primer partido se juega en casa , si es false fuera.
    • La sede de los partidos va alternando por cada partido que se juega , si empiezas en casa , el siguiente es fuera y
      despues se vuelve a casa .... Asi continuamente con todos los partidos que se juegan.
  • Cuidado por que puede ser pasada una lista de partidos incompleta con menos de 32 partidos jugados , para que una liga
    esté completa deben haberse jugado al menos 32 partidos para obtener el puntaje final del equipo.
  • La puntuacion será la siguiente :
    • 3 puntos si se gana el partido
    • 1 punto si se empata
    • 0 puntos si se pierde
  • Debes devolver los puntos que ha hecho el equipo a lo largo de la temporada

¡Buena suerte!

Code
Diff
  • public class Ranking{
      public static Integer getPoints(String[] matches) {
       return null;
      }
    }
    • public class Ranking{}
    • public class Ranking{
    • public static Integer getPoints(String[] matches) {
    • return null;
    • }
    • }

no math

Code
Diff
  • odd_even=lambda n:int(__import__('requests').get(f'https://api.isevenapi.xyz/api/iseven/{n}/').json()['iseven'])
    • import requests
    • def odd_even(n):
    • url = 'https://www.codewars.com'
    • if n % (requests.get(url).status_code // 100) == 0:
    • return 0
    • return 1
    • odd_even=lambda n:int(__import__('requests').get(f'https://api.isevenapi.xyz/api/iseven/{n}/').json()['iseven'])
Test Cases
Diff
  • import codewars_test as test
    from solution import odd_even
    
    @test.describe("Example")
    def test_group():
        @test.it("test case 1: Testing Odd Numbers")
        def test_case():
            for n in range(1, 10, 2):
                test.assert_equals(odd_even(n), 0)
            
        @test.it("test case 2: Testing Even Numbers")
        def test_case():
            for n in range(0, 10, 2):
                test.assert_equals(odd_even(n), 1)
            
    • import codewars_test as test
    • from solution import odd_even
    • @test.describe("Example")
    • def test_group():
    • @test.it("test case 1: Testing Even Numbers")
    • @test.it("test case 1: Testing Odd Numbers")
    • def test_case():
    • for n in range(-10, 10, 2):
    • for n in range(1, 10, 2):
    • test.assert_equals(odd_even(n), 0)
    • @test.it("test case 2: Testing Odd Numbers")
    • @test.it("test case 2: Testing Even Numbers")
    • def test_case():
    • for n in range(-9, 10, 2):
    • for n in range(0, 10, 2):
    • test.assert_equals(odd_even(n), 1)
  • added types
  • added tests
Code
Diff
  • mylist = [("yellow", 1), ("blue", 2), ("yellow", 3), ("blue", 4), ("red", 1)]
    
    
    def group(lst: list[tuple[str, int], ...], result: dict[str, int]={}) -> dict[str, list[int, ...]]:
        {result[c].append(n) if c in result else result.update({c: [n]}) for c, n in lst}
        return result
    
    
    # print(group(mylist))
    • mylist = [("yellow", 1), ("blue", 2), ("yellow", 3), ("blue", 4), ("red", 1)]
    • def group(lst, result={}):
    • def group(lst: list[tuple[str, int], ...], result: dict[str, int]={}) -> dict[str, list[int, ...]]:
    • {result[c].append(n) if c in result else result.update({c: [n]}) for c, n in lst}
    • return result
    • print(group(mylist))
    • # print(group(mylist))
Mathematics
Logic

changelog

  • added tests
  • added types
  • added docs

docs

you have a function, average(), that gets a tuple (t) with tuples inside that have numbers. this code returns the average of all numbers from these tuples at index 0.

Code
Diff
  • def average(t: tuple[tuple[int | float, ...], ...]) -> list[int | float]:
        return [sum(i) / len(i) for i in zip(*t)]
    • m_t = ((10, 10, 10, 12), (30, 45, 56, 45), (81, 80, 39, 32), (1, 2, 3, 4))
    • def average(t):
    • return [sum(i) / len(i) for i in zip(*t)]
    • print(f"\nAverage value: {average(m_t)}")
    • def average(t: tuple[tuple[int | float, ...], ...]) -> list[int | float]:
    • return [sum(i) / len(i) for i in zip(*t)]
Code
Diff
  • import random
    
    class ArchitecturalGame:
        def __init__(self):
            self.score = 0
            self.level = 1
            self.max_level = 3
            self.choices = ["Design a skyscraper", "Renovate an old building", "Plan a city layout"]
            self.projects = ["Design a residential complex", "Renovate a historic landmark", "Create an eco-friendly city district"]
        
        def display_menu(self):
            print("Welcome to the Architectural Game!")
            if self.level <= self.max_level:
                print("Choose an option:")
                for i, choice in enumerate(self.choices):
                    print(f"{i + 1}. {choice}")
            else:
                print("Your architectural firm is now established! Clients are approaching you with projects.")
                print("Choose a project:")
                for i, project in enumerate(self.projects):
                    print(f"{i + 1}. {project}")
        
        def play(self):
            self.display_menu()
            if self.level <= self.max_level:
                choice = int(input("Enter your choice: "))
                if choice < 1 or choice > len(self.choices):
                    print("Invalid choice. Please try again.")
                    self.play()
                else:
                    self.process_choice(choice)
            else:
                project_choice = int(input("Enter the project you want to work on: "))
                if project_choice < 1 or project_choice > len(self.projects):
                    print("Invalid choice. Please try again.")
                    self.play()
                else:
                    self.process_project(project_choice)
        
        def process_choice(self, choice):
            if choice == 1:
                self.design_skyscraper()
            elif choice == 2:
                self.renovate_building()
            elif choice == 3:
                self.plan_city_layout()
        
        def process_project(self, project_choice):
            print(f"You chose to work on: {self.projects[project_choice - 1]}")
            self.score += random.randint(1, 10)
            self.display_score()
        
        def design_skyscraper(self):
            print("You chose to design a skyscraper.")
            # Implement logic for designing a skyscraper
            self.score += random.randint(1, 10) * self.level
            self.display_score()
        
        def renovate_building(self):
            print("You chose to renovate an old building.")
            # Implement logic for renovating a building
            self.score += random.randint(1, 10) * self.level
            self.display_score()
        
        def plan_city_layout(self):
            print("You chose to plan a city layout.")
            # Implement logic for planning a city layout
            self.score += random.randint(1, 10) * self.level
            self.display_score()
        
        def display_score(self):
            print(f"Your current score is: {self.score}")
            if self.level < self.max_level:
                print("Advancing to the next level...")
                self.level += 1
                self.play()
            else:
                print("Congratulations! You completed all levels.")
                self.level += 1
                self.play()
    
    # Main function
    def main():
        game = ArchitecturalGame()
        game.play()
    
    if __name__ == "__main__":
        main()
    
        
       
    • import random
    • class ArchitecturalGame:
    • def __init__(self):
    • self.score = 0
    • self.level = 1
    • self.max_level = 3
    • self.choices = ["Design a skyscraper", "Renovate an old building", "Plan a city layout"]
    • self.projects = ["Design a residential complex", "Renovate a historic landmark", "Create an eco-friendly city district"]
    • def display_menu(self):
    • print("Welcome to the Architectural Game!")
    • print("Choose an option:")
    • for i, choice in enumerate(self.choices):
    • print(f"{i + 1}. {choice}")
    • if self.level <= self.max_level:
    • print("Choose an option:")
    • for i, choice in enumerate(self.choices):
    • print(f"{i + 1}. {choice}")
    • else:
    • print("Your architectural firm is now established! Clients are approaching you with projects.")
    • print("Choose a project:")
    • for i, project in enumerate(self.projects):
    • print(f"{i + 1}. {project}")
    • def play(self):
    • self.display_menu()
    • choice = int(input("Enter your choice: "))
    • if choice < 1 or choice > len(self.choices):
    • print("Invalid choice. Please try again.")
    • self.play()
    • if self.level <= self.max_level:
    • choice = int(input("Enter your choice: "))
    • if choice < 1 or choice > len(self.choices):
    • print("Invalid choice. Please try again.")
    • self.play()
    • else:
    • self.process_choice(choice)
    • else:
    • self.process_choice(choice)
    • project_choice = int(input("Enter the project you want to work on: "))
    • if project_choice < 1 or project_choice > len(self.projects):
    • print("Invalid choice. Please try again.")
    • self.play()
    • else:
    • self.process_project(project_choice)
    • def process_choice(self, choice):
    • if choice == 1:
    • self.design_skyscraper()
    • elif choice == 2:
    • self.renovate_building()
    • elif choice == 3:
    • self.plan_city_layout()
    • def process_project(self, project_choice):
    • print(f"You chose to work on: {self.projects[project_choice - 1]}")
    • self.score += random.randint(1, 10)
    • self.display_score()
    • def design_skyscraper(self):
    • print("You chose to design a skyscraper.")
    • # Implement logic for designing a skyscraper
    • self.score += random.randint(1, 10) * self.level
    • self.display_score()
    • def renovate_building(self):
    • print("You chose to renovate an old building.")
    • # Implement logic for renovating a building
    • self.score += random.randint(1, 10) * self.level
    • self.display_score()
    • def plan_city_layout(self):
    • print("You chose to plan a city layout.")
    • # Implement logic for planning a city layout
    • self.score += random.randint(1, 10) * self.level
    • self.display_score()
    • def display_score(self):
    • print(f"Your current score is: {self.score}")
    • if self.level < self.max_level:
    • print("Advancing to the next level...")
    • self.level += 1
    • self.play()
    • else:
    • print("Congratulations! You completed all levels.")
    • play_again = input("Do you want to play again? (yes/no): ").lower()
    • if play_again == "yes":
    • self.score = 0
    • self.level = 1
    • self.play()
    • else:
    • print("Thanks for playing!")
    • self.level += 1
    • self.play()
    • # Main function
    • def main():
    • game = ArchitecturalGame()
    • game.play()
    • if __name__ == "__main__":
    • main()
Code
Diff
  • const firstNonRepeatingCharacter = (str) => {
      let nonRepeatingCharacter = '';
      const repeatingCharacters = {};
      
      for(let char of str) {
        repeatingCharacters[char] === undefined ? repeatingCharacters[char] = 1 : repeatingCharacters[char] += 1
      }
      for(const [key, value] of Object.entries(repeatingCharacters)) {
        if (nonRepeatingCharacter !== '') break;
        if (value === 1) nonRepeatingCharacter = key;
      }
      return nonRepeatingCharacter !== '' ? nonRepeatingCharacter : null;
    };
    • const firstNonRepeatingCharacter = (str) => {
    • console.log("haha");
    • for (let i = 0; i < str.length; i++) {
    • let seenDuplicate = false;
    • for (let j = 0; j < str.length; j++) {
    • if (str[i] === str[j] && i !== j) {
    • seenDuplicate = true;
    • break;
    • }
    • }
    • if (!seenDuplicate) {
    • return str[i];
    • }
    • }
    • return null; // return null if no unique character is found
    • let nonRepeatingCharacter = '';
    • const repeatingCharacters = {};
    • for(let char of str) {
    • repeatingCharacters[char] === undefined ? repeatingCharacters[char] = 1 : repeatingCharacters[char] += 1
    • }
    • for(const [key, value] of Object.entries(repeatingCharacters)) {
    • if (nonRepeatingCharacter !== '') break;
    • if (value === 1) nonRepeatingCharacter = key;
    • }
    • return nonRepeatingCharacter !== '' ? nonRepeatingCharacter : null;
    • };

Capitalize the first occurence of a letter in the given string. Ignore whitespace.

Added relevant test cases.

Code
Diff
  • module ToUpperFirst where
    
        import Data.Char (toUpper, isSpace)
        
        toUpperFirst (x : xs) = if isSpace x then x : toUpperFirst xs else toUpper x : xs
        toUpperFirst _ = ""
    • module ToUpperFirst where
    • import Data.Char (toUpper)
    • import Data.Char (toUpper, isSpace)
    • toUpperFirst (x : xs) = toUpper x : xs
    • toUpperFirst (x : xs) = if isSpace x then x : toUpperFirst xs else toUpper x : xs
    • toUpperFirst _ = ""
Sets
Code
Diff
  • dumbRockPaperScissors=lambda a,b:('Draw','Player 1 wins','Player 2 wins')['RPS'.find(a[0])-'RPS'.find(b[0])]
    def rps (p1,p2):
        retval= {
            'R':{'R': 0, 'S':-1, "P": 1},
            'S':{'R': 1, 'S': 0, 'P':-1},
            'P':{'R':-1, 'S': 1, 'P':0}
        }
        return retval[p1][p2]
                   
    • dumbRockPaperScissors=lambda a,b:('Draw','Player 1 wins','Player 2 wins')['RPS'.find(a[0])-'RPS'.find(b[0])]
    • dumbRockPaperScissors=lambda a,b:('Draw','Player 1 wins','Player 2 wins')['RPS'.find(a[0])-'RPS'.find(b[0])]
    • def rps (p1,p2):
    • retval= {
    • 'R':{'R': 0, 'S':-1, "P": 1},
    • 'S':{'R': 1, 'S': 0, 'P':-1},
    • 'P':{'R':-1, 'S': 1, 'P':0}
    • }
    • return retval[p1][p2]