codewars test

Code
Diff
• ``const removeSymbols = s => s.match(/\w| /g).join````
• function removeSymbols(str) {
• return str.match(/\w| /g).join``
• }
• const removeSymbols = s => s.match(/\w| /g).join``

Reverse the word

Code
Diff
• ``g=w=>[...w].sort(x=>-1).join````
• g=w=>w.split('').reverse().join('')
• g=w=>[...w].sort(x=>-1).join``

kashiKASHI's Kumite #2

Use of \n

Code
Diff
• ``print("hello\n7")``
• print("hello")
• print(7)
• print("hello\n7")

Find if atleast 2 out of 3 booleans are ture.

Use of count in order to be more specific
golf with variable names

Code
Diff
• ``def solution(l):return 2 <= ([1 for p in l if p is True]).count(1)``
• def solution(param: list) -> bool:
• if 2 <= sum([1 for p in param if p is True]):
• return True
• else:
• return False
• def solution(l):return 2 <= ([1 for p in l if p is True]).count(1)

Format fixed decimal places in value if it is a number

A little cup of javascript golf

• Use of javascript interpolation string
• Convert to number with +
• Use of letter for variables
Code
Diff
• ``````const formatIfNumber = (v, n) => v / 2
? + (Math.round(`\${v}e\${n}`) + `e-\${n}` ) : v``````
• const formatIfNumber = (value, numberOfPlaces) =>
• value / 2
• ? Number(Math.round(value + 'e' + numberOfPlaces) + 'e-' + numberOfPlaces)
• : value
• const formatIfNumber = (v, n) => v / 2
• ? + (Math.round(`\${v}e\${n}`) + `e-\${n}` ) : v

\_(OcO)_/ aaaaaaahhh

It looks like it it trying to walk-through the directories of a .venv virtual enviornment folder.

I prefer to use the os.walk method.
In order to filter and flatten the array I'm using of the list comprehensions.
I ignore error in the reading

Code
Diff
• ``````import os
DIR = os.path.join(os.getcwd(), 'venv')

def list_venv():
tree_of_files = ([([ os.path.join(root, some_f)  for some_f in  files] ) for root, _, files in os.walk(DIR) if(len(files)>0)])
flatten_tree_of_files= [ a_file for subtree in tree_of_files for a_file in subtree ]
for some_file in flatten_tree_of_files:
with open(some_file,  mode='r', errors='ignore') as file:
return True

list_venv()``````
• import os
• DIR = os.path.join(os.getcwd(), 'venv')
• def list_venv():
• """ List venv dirs and files """
• try:
• print((ve := os.listdir(DIR)))
• for x in ve:
• list_subs(x)
• except:
• def list_subs(x):
• """ For files in venv, which will be (Libs, and Scripts) """
• try:
• # subdirs
• print(x, os.listdir(os.path.join(DIR, x)))
• for y in x:
• list_sub_sub(x, y)
• except:
• print_config(x)
• def list_sub_sub(x, y):
• """ List subdirs and files in subdirs
• Warning: the next code was full of
• `This does not get executed` messages """
• try:
• print(x, os.listdir(os.path.join(DIR, x, y)))
• for z in y:
• try:
• print_file(x, y) # not y, z?
• except:
• print("...goes on...")
• except:
• try:
• print_file_fallback(x)
• except:
• print("") # This gets executed (the only one!)
• def print_file(x, y):
• with open(os.path.join(DIR, x, y), 'r') as file:
• tree_of_files = ([([ os.path.join(root, some_f) for some_f in files] ) for root, _, files in os.walk(DIR) if(len(files)>0)])
• flatten_tree_of_files= [ a_file for subtree in tree_of_files for a_file in subtree ]
• for some_file in flatten_tree_of_files:
• with open(some_file, mode='r', errors='ignore') as file:
• return True
• def print_file_fallback(x):
• with open(os.path.join(DIR, x), 'r') as file:
• def print_config(x):
• """ This will get executed twice, opening
• the .gitignore, and pyvenv.cfg file """
• with open(os.path.join(DIR, x), 'r') as file:
• list_venv()
• list_venv()

Return a non-empty string which is equal to the source code of the function

Trying to make one line

Code
Diff
• ``def quine(): from inspect import getsource ; return getsource(quine)``
• from inspect import getsource
• def quine():
• return getsource(quine)
• def quine(): from inspect import getsource ; return getsource(quine)

FixDatTrash #2: Need help with a solution problem!

Code
Diff
• ``````from math import pi
from math import sqrt

class Calculator:

def __init__(self, num):
self.num = num

def calculate_power(self, exp):
return self.num**exp

def calculate_square_root(self):
return sqrt(self.num)

def calculate_cube_root(self):
return self.num ** (1. / 3)

def calculate_circumference(self):
return pi * self.num
``````
• #!/usr/bin/env python3
• """
• Debugging: FixDatTrash # 2
• """
• # constant:
• PI = 3.1415926535897
• from math import pi
• from math import sqrt
• class Calculator:
• """A calculator class."""
• def __init__(self, num):
• """Initialize attributes."""
• self.num = num
• def calculate_power(self, exp):
• """
• Calculates power of self.num.
• parameter `exp` is the exponent.
• """
• result = 1
• for exp in range(exp, 0, -1):
• result *= self.num
• return result
• return self.num**exp
• def calculate_square_root(self):
• """Calculates square root of self.num."""
• return self.num ** 0.5
• return sqrt(self.num)
• def calculate_cube_root(self):
• """Calculates cube root of self.num."""
• return self.num ** (1 / 3)
• return self.num ** (1. / 3)
• def calculate_circumference(self):
• """
• Calculates circumference of circle.
• self.num is the diameter of the circle.
• """
• return PI * self.num
• return pi * self.num

Round 2: Uly vs Jose - Prime Checker

My modifications:

• Use of a range vs use of a for loop
• use of a ternary
• use of the some method for array
Code
Diff
• ``````function prime_checker(n){
return n <= 1 ? false : !Array.from({ length: Math.round(Math.sqrt(n)) - 2 }).some((v, i) => n % (i + 2)===0)
}``````
• function prime_checker(n) {
• if (n <= 1) return false
• for (let i = 2; i <= Math.sqrt(n); i++) {
• if (n % i == 0) return false
• }
• return true
• function prime_checker(n){
• return n <= 1 ? false : !Array.from({ length: Math.round(Math.sqrt(n)) - 2 }).some((v, i) => n % (i + 2)===0)
• }

• Empty argument _
• No use of variable
• Arrow notation for function
Code
Diff
• ``const greetings = _ => "My name is: seraph776"``
• function greetings(){
• let name = "seraph776";
• return `My name is: \${name}`;
• }
• const greetings = _ => "My name is: seraph776"

power function definition

Complex code so I simplified it. We can use the ** in javascript to express power.

Code
Diff
• ``const power = (base,exp) => exp === 0 || base === 1 ? 1 : base**exp``
• function power (base, exp) {
• if (exp === [].length || base === [undefined].length) return [{...{}}].length;
• let thisVariableWillBeTheFinalProduct = ["_"].length;
• for (let loopingIndex = exp; loopingIndex >= [new Map([{}])].length; loopingIndex -= [()=>{}].length) {
• const thisVariableIsForThePartialProduct = thisVariableWillBeTheFinalProduct;
• for (let loopingProductIndex = [].length; loopingProductIndex < thisVariableIsForThePartialProduct; loopingProductIndex++) {
• thisVariableWillBeTheFinalProduct = thisVariableWillBeTheFinalProduct + (base - [()=>()=>{}].length);
• }
• }
• return thisVariableWillBeTheFinalProduct;
• }
• const power = (base,exp) => exp === 0 || base === 1 ? 1 : base**exp

Dan's Kumite

Use of a ternary condition.
Suppress of the try catch block. The len function is the only exception in the tests.
Concatenation of three arrays.

Code
Diff
• ``````def spawn_to_range(a, x, n):
return [] if(len(a)==0) else a[0:a.index(x)] + [x]*n + a[a.index(x)+1:] ``````
• def spawn_to_range(a, x, n):
• try:
• i = a.index(x)
• for _ in range(n - 1):
• a.insert(i, x)
• except ValueError:
• pass
• return a
• return [] if(len(a)==0) else a[0:a.index(x)] + [x]*n + a[a.index(x)+1:]

Katie Camel Case

Code
Diff
• ``````import re
def to_camel_case(text: str):
splitword =  re.split('\_|\-', text)
return splitword[0]+ "".join([word.capitalize() for word in splitword[1:]])``````
• import re
• def to_camel_case(text: str):
• split_chars = "-_"
• # loop over each character above
• for split_char in split_chars:
• split_parts = text.split(split_char)
• # skip if there was nothing to split on
• if len(split_parts) == 1:
• continue
• parts = []
• # break up the string in to it's parts
• for i, item in enumerate(split_parts):
• # save the first part but don't change the case of the first letter
• if i == 0:
• parts.append(item)
• continue
• parts.append(f"{item[0].upper()}{item[1:]}")
• # join the parts and overwrite the text variable for the next loop
• text = "".join(parts)
• return text
• splitword = re.split('\_|\-', text)
• return splitword[0]+ "".join([word.capitalize() for word in splitword[1:]])

"Remove All The Marked Elements of a List" Python Translation

Code
Diff
• ``````def remove(integers, values):
return [x for x in integers if x not in set(values)]``````
• def remove(integers, values):
• value_set = set(values)
• res = []
• for x in integers:
• if x not in value_set:
• res += [x]
• return res
• return [x for x in integers if x not in set(values)]