Ad

(Authors note: Introducing: FixDatTrash. This is a new kumite concept that I have begun where over time I create both simple and complex noob scenarios where YOU have to find a way to fix the code. You could also suggest a faster, more easier version of the scenarios code too by just changing it to that in your fork. Get wack, translate, checklist each problem, complicate it, use you creativity! Each scenario has a little fictional character and in the next FixDatTrash as a bonus along with a new scenario you also get a response and some feedback from the character on the previous scenario.)

= = = = = = =

Scenario

= = = = = = =

= = No. 2 = =

  • Persons Name: Tracy

  • Gender: Female

  • Programming Language: Python 3.10

  • Subject: Need help with a solution problem!

Description

Hello! My name is Tracy and I have been working on a program for college where we create our own math functions for Python from scratch without any modules. However, I'm a bit confused with the syntax. I need your help filling in the gaps here! Maybe you could make it a bit more impressive? I really need a high score, help me code warriors!

Joe's Response (Previous Scenario)

You can find the previous scenario here (https://www.codewars.com/kumite/62d5fa79d32b8cd04217e44f?sel=62d5fa79d32b8cd04217e44f)

Oh, hey Code Warriors! I want to first of all congratulate you on your contribution and second of all, thank you for the code you have shared. Shoutout to the almighty code warrior 'seraph776' for being the first code warrior to fix my code. Not only did this code warrior fix it, but turned it into a even faster and completely different statement! 'rowcased' and 'Dawnt' simplified it even further and turned it into some kind of array instead of a function... My god, there is so much to learn out there! Another good one to mention is 'Thirdkoopa' they helped me gain a better understanding and simplified the if statements. Not only am I learning, but so is my good ol friend Fred! If you need a bit of a refresh, Fred lost his memory and couldnt remember which fruit was which. I recently began using your contributions in helping him learn the names of fruit again and it's working!

Thank you so much Code Warriors!

- Joe

def power(num, amount):
    result = num
    i = 0
    while i < amount:
        i += 1
        result *= num
    return result
    
def square_root(num):
    return power(num, 0.5)
    
def cube_root(num):
    return power(num, 1/3)

def get_pi():
    return 22/7

def get_circumference(diameter):
    return get_pi * diameter

#Your Checklist:
#(Optional: put a list of problems you solved or features you added here in lines of comments, along with the line number)
#[Example] 1: Fixed function syntax (Line 9)

(Authors note: Introducing: FixDatTrash. This is a new kumite concept that I have begun where over time I create both simple and complex noob scenarios where YOU have to find a way to fix the code. You could also suggest a faster, more easier version of the scenarios code too by just changing it to that in your fork. Get wack, translate, checklist each problem, complicate it, use you creativity! Each scenario has a little fictional character and in the next FixDatTrash as a bonus along with a new scenario you also get a response and some feedback from the character on the previous scenario.)

= = = = = = =

Scenario

= = = = = = =

= = No. 1 = =

  • Persons Name: Joe
  • Gender: Male
  • Programming Language: Python 3.1
  • Subject: Help! My Python Fruit Colour Detector is broken!

Description

Joe: Hey code warriors! I'm going on a shopping spree with my friend Fred. However, there is a problem, recnetly Fred has lost his memory! Sadly, he has no memory of most names of fruit, but can remember colours.

So, I am building a tool just made for him to use! One problem, I am absolutely TRASH at programming, trust me. I can't even see what's wrong! I would be so glad if some nice code warrior at codewars.com could take some of their time to make this code better. Please, I would do anything to help my friend Fred.
def colouroffruit(fruit):
    if fruit == "Apple":
        return "Red"
    elseif fruit == "Orange":
        return "Orange"
    elif fruit = "Blueberry":
        return "Blue"
    elif frut == "Pear":
        return "Green"
    elif fruit == "banana"
        return "Yellow"
    elif fruit = "Strawberry":
        return "Red"
    elif fruit == "Lemon":
        return "Yellow"
    elif fruit == "Lime":
        print("Green")
    elif fruit == "Raspberry"
        return "Red":
        elif fruit == "Pineapple":
            return "Yellow"
    elif fruit == "Melon":
        return "Green"
    if fruit == "Plum":
        return "Purple"
    elif fruit == "Strawberry":
        return "Red"
    elif fruit == "Cabbage"
        return "Greem"

#Your Checklist:
#(Optional: put a list of problems you solved here in lines of comments, along with the line number)
#[Example] 1: Fixed if statement syntax (Line 2)
Strings
Mathematics
Logic

Lua has INFINITE IQ

input:

print(Lua > Python)

output:

true
Code
Diff
  • local solution = {}
    
    function solution.initperson(name, iq)
      local Person = {}
      Person.name = name
      Person.iq = iq
      return Person
    end
            
    local you = solution.initperson("you",0)
    
    print(you.name.." has "..1/you.iq.." IQ!")
    
    return solution
    -- hahaha rekt python nerd, lua = INFINITE IQ
    • class Person:
    • def __init__(self,name,iq=1):
    • self.name=name
    • self.iq= 1 if iq == 0 else iq
    • local solution = {}
    • function solution.initperson(name, iq)
    • local Person = {}
    • Person.name = name
    • Person.iq = iq
    • return Person
    • end
    • you = Person("you",0)
    • local you = solution.initperson("you",0)
    • print(you.name.." has "..1/you.iq.." IQ!")
    • print(1/you.iq)
    • # hahaha un-rekt!
    • return solution
    • -- hahaha rekt python nerd, lua = INFINITE IQ
Strings

Inspired by PyCalc! https://www.codewars.com/kumite/62347c29a786a2004a613da9?sel=62b1afd8ff12495f950a56d8

A interactive terminal program for making your own directory, at a specific path or the current directory the user is in. Feel free to do what you want with the code.

Code
Diff
  • # importing os
    import os
    import sys
    
    class CreateDirectory:
        
        OPTIONS = {1: "Current Path",
               2: "Other Path",
               3: "Cancel"}
        
        def __init__(self, name=None, path_=None):
            self.name = name
            self.path_ = path_
        
        # Function for creating new directory.
        def create_folder(self, folder_name, dirpath):
            # Resets color
            print("\033[0m")
            
            if dirpath != 0:
                print("Checking if path exists...", end="\r")
                if os.path.exists(dirpath):
                    print("\033[32;1mPath found!\033[0m                ")
                    path_ = os.path.join(dirpath, folder_name)
                else:
                    print("\033[31;1mError:\033[0m Invalid path!             ")
                    return False
            else:    
                # creating a variable path to the new folder.
                path_ = os.path.join(os.getcwd(), folder_name)
            
            # check to see if the folder already exists.
            print("Checking if directory already exists...", end="\r")
            if not os.path.exists(path_):
                # if not, make directory
                print(f"\033[32;1mDirectory created successfully at {path_}\033[0m            ")
                os.mkdir(path_)
                return True
            print("\033[31;1mError:\033[0m Directory already exists!             ")
            return False
        
    def display_option_menu(menu_options: dict) -> str:
        # Some code is taken from PyCalc!
        for k, v in menu_options.items():
            print(f'\t({k})-{v.title()}')
    
        while True:
            user_input = input(f'Select option: (1-{len(menu_options)}):\n{chr(129094)} ')
            # Validate input: If not a digit or in menu option, continue to ask user for input.
            if not user_input.isdigit() or int(user_input) not in menu_options:
                print("\033[31;1mError:\033[0m Invalid input!")
                continue
            else:
                # If input is valid; break.
                break
        # Returns user's choice.
        return menu_options.get(int(user_input))
        
    def main():
        # Initializaton of directory creator
        create = CreateDirectory()
        create_options = create.OPTIONS
        while True:
            print("\033[34;4;1m/ / / TELEVISIONIA's Directory Creator / / /\033[0m")
            userinput = display_option_menu(create_options)
            
            match userinput:
                case "Current Path":
                    create.create_folder(input("New Directory name: \033[35m"), 0)
                case "Other Path":
                    create.create_folder(input("New Directory name: \033[35m"), input("\033[0mNew Directory path: \033[35m"))
                case "Cancel":
                    sys.exit()
                case _:
                    return main()
    if __name__ == '__main__':
        main()
    
    • # importing os
    • import os
    • import sys
    • class CreateDirectory:
    • OPTIONS = {1: "Current Path",
    • 2: "Other Path",
    • 3: "Cancel"}
    • def __init__(self, name=None, path_=None):
    • self.name = name
    • self.path_ = path_
    • # Function for creating new directory.
    • def create_folder(self, folder_name, dirpath):
    • # Resets color
    • print("\033[0m")
    • if dirpath != 0:
    • print("Checking if path exists...", end="\r")
    • if os.path.exists(dirpath):
    • print("\033[32;1mPath found!\033[0m ")
    • path_ = os.path.join(dirpath, folder_name)
    • else:
    • print("\033[31;1mError:\033[0m Invalid path! ")
    • return False
    • else:
    • # creating a variable path to the new folder.
    • path_ = os.path.join(os.getcwd(), folder_name)
    • # check to see if the folder already exists.
    • print("Checking if directory already exists...", end="\r")
    • if not os.path.exists(path_):
    • # if not, make directory
    • print(f"\033[32;1mDirectory created successfully at {path_}\033[0m ")
    • os.mkdir(path_)
    • return True
    • print("\033[31;1mError:\033[0m Directory already exists! ")
    • return False
    • def display_option_menu(menu_options: dict) -> str:
    • # Some code is taken from PyCalc!
    • for k, v in menu_options.items():
    • print(f'\t({k})-{v.title()}')
    • def create_folder(folder_name='MyFolder'):
    • # creating a variable path to the new folder.
    • path_ = os.path.join(os.getcwd(), folder_name)
    • # check to see if the folder already exists.
    • if not os.path.exists(folder_name):
    • # if not, make directory
    • os.mkdir(folder_name)
    • return True
    • return False
    • while True:
    • user_input = input(f'Select option: (1-{len(menu_options)}):\n{chr(129094)} ')
    • # Validate input: If not a digit or in menu option, continue to ask user for input.
    • if not user_input.isdigit() or int(user_input) not in menu_options:
    • print("\033[31;1mError:\033[0m Invalid input!")
    • continue
    • else:
    • # If input is valid; break.
    • break
    • # Returns user's choice.
    • return menu_options.get(int(user_input))
    • def main():
    • # Initializaton of directory creator
    • create = CreateDirectory()
    • create_options = create.OPTIONS
    • while True:
    • print("\033[34;4;1m/ / / TELEVISIONIA's Directory Creator / / /\033[0m")
    • userinput = display_option_menu(create_options)
    • match userinput:
    • case "Current Path":
    • create.create_folder(input("New Directory name: \033[35m"), 0)
    • case "Other Path":
    • create.create_folder(input("New Directory name: \033[35m"), input("\033[0mNew Directory path: \033[35m"))
    • case "Cancel":
    • sys.exit()
    • case _:
    • return main()
    • if __name__ == '__main__':
    • main()
Fundamentals
Strings

I suck at C++ and i need some help. I'm having this stdder error and I cannot fix it.

Code
Diff
  • #include <string.h>
    std::string digest(std::string param) {
        std::string result;
        for (int i = 0; sizeof(param); i++) {
          result += param[i];
          result += ' ';
        }
        return result;
    } //Please fix!
    • class DigestWord:
    • def __init__(self, param):
    • self.param = param
    • def digest(self):
    • return ' '.join([str(item) for item in str(self.param)])
    • #include <string.h>
    • std::string digest(std::string param) {
    • std::string result;
    • for (int i = 0; sizeof(param); i++) {
    • result += param[i];
    • result += ' ';
    • }
    • return result;
    • } //Please fix!
Strings

If you were to run this function through a terminal (not all terminals support ANSI escape code colors, try downloading the new windows terminal or a different terminal of your preference if it does not work) the text would be a different color.

ColorAdder.AddColor(color in string, colored text)

Info:
https://en.wikipedia.org/wiki/ANSI_escape_code
List of escape codes: https://gist.github.com/Prakasaka/219fe5695beeb4d6311583e79933a009

I don't know C# that well so if you could fix the warnings for me that would be awesome.

Feel free to translate and develop on the concept.

public class ColorAdder
{
    public static string AddColor(string color, string text)
    {
      string Reset = "\033[0m";
      string Red = "\033[31m";
      string Green = "\033[32m";
      string Yellow = "\033[33m";
      string Blue = "\033[34m";
      string Magenta = "\033[35m";
      string Cyan = "\033[36m";
      string White = "\033[37m";

      switch(color) {
        case "Red":
          return string.Concat(string.Concat(Red, text), Reset);
          break;
        case "Green":
          return string.Concat(string.Concat(Green, text), Reset);
          break;
        case "Yellow":
          return string.Concat(string.Concat(Yellow, text), Reset);
          break;
        case "Blue":
          return string.Concat(string.Concat(Blue, text), Reset);
          break;
        case "Magenta":
          return string.Concat(string.Concat(Magenta, text), Reset);
          break;
        case "Cyan":
          return string.Concat(string.Concat(Cyan, text), Reset);
          break;
        case "White":
          return string.Concat(string.Concat(White, text), Reset);
          break;
        default:
          return "Invalid Color";
          break;
      }
    }
}

(Lua translation)

Return the area of a triangle using its width and height.

Code
Diff
  • local solution = {}
    
    function solution.AreaOfTriangle(w, h)
        local A = (w * h) / 2;
        return A
    end
    
    return solution --Lua runs better than python ;)
    • float AreaOfTriangle(float w, float h) {
    • float A = (w * h) / 2;
    • return A;
    • }
    • local solution = {}
    • function solution.AreaOfTriangle(w, h)
    • local A = (w * h) / 2;
    • return A
    • end
    • return solution --Lua runs better than python ;)

Find the area of a triangle from its width and height.

Code
Diff
  • float AreaOfTriangle(float w, float h) {return (w * h) / 2;} //Get one-lined
    • float AreaOfTriangle(float w, float h) {
    • float A = (w * h) / 2;
    • return A;
    • }
    • float AreaOfTriangle(float w, float h) {return (w * h) / 2;} //Get one-lined
Fundamentals
Strings

We need to program our creature to be able to digest food! Make it so the digest() function returns the given string with a space between every single letter.

Example:

digest("Burger")

should return:

"B u r g e r"
def digest(food):
    return " ".join(food)
Strings
Fundamentals

Convert and return all letters in a given string to upper case letters.

Example 1:

uppercase("codewars")

expected result:

"CODEWARS"

Example 2:

uppercase("coDEwArS")

expected result:

"CODEWARS"
Code
Diff
  • def upper_case(s): return s.upper()
    • upper_case = lambda s: s.upper()
    • def upper_case(s): return s.upper()
Strings
Fundamentals

Convert a number in a range of 0 to 9 to a worded version of that number in a string. If number is not a one digit number, return the same number given back.

Example:

converter(2)

should return:

"two"
Code
Diff
  • def converter(number):
        list = ['zero','one','two','three','four','five','six','seven','eight','nine']
        if number < 10:
            return list[number]
        else:
            return number
    
    • def converter(number):
    • match number:
    • case 0:
    • return 'zero'
    • case 1:
    • return 'one'
    • case 2:
    • return 'two'
    • case 3:
    • return 'three'
    • case 4:
    • return 'four'
    • case 5:
    • return 'five'
    • case 6:
    • return 'six'
    • case 7:
    • return 'seven'
    • case 8:
    • return 'eight'
    • case 9:
    • return 'nine'
    • case _:
    • return number
    • list = ['zero','one','two','three','four','five','six','seven','eight','nine']
    • if number < 10:
    • return list[number]
    • else:
    • return number