g=w=>[...w].sort(x=>-1).join``
g=w=>w.split('').reverse().join('')- g=w=>[...w].sort(x=>-1).join``
// Since Node 10, we're using Mocha. // You can use `chai` for assertions. const chai = require("chai"); const assert = chai.assert; // Uncomment the following line to disable truncating failure messages for deep equals, do: // chai.config.truncateThreshold = 0; // Since Node 12, we no longer include assertions from our deprecated custom test framework by default. // Uncomment the following to use the old assertions: // const Test = require("@codewars/test-compat"); describe("Solution", function() { it("should test for something", function() { assert.strictEqual(g("hello"), "olleh"); assert.strictEqual(g("Hello World"), "dlroW olleH"); }); });
- // Since Node 10, we're using Mocha.
- // You can use `chai` for assertions.
- const chai = require("chai");
- const assert = chai.assert;
- // Uncomment the following line to disable truncating failure messages for deep equals, do:
- // chai.config.truncateThreshold = 0;
- // Since Node 12, we no longer include assertions from our deprecated custom test framework by default.
- // Uncomment the following to use the old assertions:
- // const Test = require("@codewars/test-compat");
- describe("Solution", function() {
- it("should test for something", function() {
// Test.assertEquals(1 + 1, 2);// assert.strictEqual(1 + 1, 2);- assert.strictEqual(g("hello"), "olleh");
- assert.strictEqual(g("Hello World"), "dlroW olleH");
- });
- });
Use of count in order to be more specific
golf with variable names
A little cup of javascript golf
- Use of javascript interpolation string
- Convert to number with +
- Use of letter for variables
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
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
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: print(file.read()) 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:print("Error: venv dir not found in the path")def list_subs(x):""" For files in venv, which will be (Libs, and Scripts) """try:# subdirsprint(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 subdirsWarning: 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:print(file.read())- 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:
- print(file.read())
- return True
def print_file_fallback(x):with open(os.path.join(DIR, x), 'r') as file:print(file.read())def print_config(x):""" This will get executed twice, openingthe .gitignore, and pyvenv.cfg file """with open(os.path.join(DIR, x), 'r') as file:print(file.read())list_venv()- list_venv()
Trying to make one line
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 = 1for exp in range(exp, 0, -1):result *= self.numreturn 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
from solution import Calculator from math import pi import unittest class TestCalculator(unittest.TestCase): def test_calculate_power(self): self.assertEqual(Calculator(2).calculate_power(2), 4) self.assertEqual(Calculator(4).calculate_power(4), 256) def test_calculate_square_root(self): self.assertEqual(Calculator(3).calculate_square_root(), 1.7320508075688772) self.assertEqual(Calculator(16).calculate_square_root(), 4) def test_calculate_cube_root(self): self.assertEqual(Calculator(27).calculate_cube_root(), 3) self.assertEqual(Calculator(125).calculate_cube_root(), 4.999999999999999) def test_calculate_circumference(self): self.assertEqual(Calculator(3).calculate_circumference(), 9.42477796076938) self.assertEqual(Calculator(12).calculate_circumference(), 37.69911184307752) if __name__ == '__main__': unittest.main()
from solution import Calculator, PI- from solution import Calculator
- from math import pi
- import unittest
- class TestCalculator(unittest.TestCase):
- def test_calculate_power(self):
- self.assertEqual(Calculator(2).calculate_power(2), 4)
- self.assertEqual(Calculator(4).calculate_power(4), 256)
- def test_calculate_square_root(self):
- self.assertEqual(Calculator(3).calculate_square_root(), 1.7320508075688772)
- self.assertEqual(Calculator(16).calculate_square_root(), 4)
- def test_calculate_cube_root(self):
- self.assertEqual(Calculator(27).calculate_cube_root(), 3)
- self.assertEqual(Calculator(125).calculate_cube_root(), 4.999999999999999)
- def test_calculate_circumference(self):
self.assertEqual(Calculator(3).calculate_circumference(), 9.424777960769099)self.assertEqual(Calculator(12).calculate_circumference(), 37.699111843076395)- self.assertEqual(Calculator(3).calculate_circumference(), 9.42477796076938)
- self.assertEqual(Calculator(12).calculate_circumference(), 37.69911184307752)
- if __name__ == '__main__':
- unittest.main()
My modifications:
- Use of a range vs use of a for loop
- use of a ternary
- use of the some method for array
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 falsefor (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
Complex code so I simplified it. We can use the ** in javascript to express power.
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
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.
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:passreturn a- return [] if(len(a)==0) else a[0:a.index(x)] + [x]*n + a[a.index(x)+1:]
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 abovefor split_char in split_chars:split_parts = text.split(split_char)# skip if there was nothing to split onif len(split_parts) == 1:continueparts = []# break up the string in to it's partsfor i, item in enumerate(split_parts):# save the first part but don't change the case of the first letterif i == 0:parts.append(item)continueparts.append(f"{item[0].upper()}{item[1:]}")# join the parts and overwrite the text variable for the next looptext = "".join(parts)return text- splitword = re.split('\_|\-', text)
- return splitword[0]+ "".join([word.capitalize() for word in splitword[1:]])