#!/usr/bin/env python3 """ Debugging: FixDatTrash # 2 """ # constant: PI = 3.1415926535897 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 def calculate_square_root(self): """Calculates square root of self.num.""" return self.num ** 0.5 def calculate_cube_root(self): """Calculates cube root of self.num.""" 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
def power(num, amount):result = numi = 0while i < amount:i += 1result *= numreturn resultdef square_root(num):return power(num, 0.5)def cube_root(num):return power(num, 1/3)def get_pi():return 22/7def 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)- #!/usr/bin/env python3
- """
- Debugging: FixDatTrash # 2
- """
- # constant:
- PI = 3.1415926535897
- 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
- def calculate_square_root(self):
- """Calculates square root of self.num."""
- return self.num ** 0.5
- def calculate_cube_root(self):
- """Calculates cube root of self.num."""
- 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
from solution import Calculator, 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) if __name__ == '__main__': unittest.main()
import codewars_test as test# TODO Write testsfrom solution import powerfrom solution import square_rootfrom solution import cube_rootfrom solution import get_pi# test.assert_equals(actual, expected, [optional] message)@test.describe("Example")def test_group():@test.it("test case")def test_case():test.assert_equals(power(2, 2), 4)test.assert_equals(power(4, 3), 64)test.assert_equals(square_root(3), 9)test.assert_equals(square_root(4), 16)test.assert_equals(cube_root(27), 3)test.assert_equals(cube_root(216), 6)test.assert_equals(get_pi, 22/7)test.assert_equals(get_circumference(10), get_pi * diameter)- from solution import Calculator, 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)
- if __name__ == '__main__':
- unittest.main()
def solution(param: list) -> bool: """Returns True if atleast 2 out of 3 booleans are True.""" return sum([1 for p in param if p is True]) >= 2
public class Kumite {public static boolean boolCheck(boolean[] bools) {return bools[0] ? bools[1] || bools[2] : bools[1] && bools[2];}}- def solution(param: list) -> bool:
- """Returns True if atleast 2 out of 3 booleans are True."""
- return sum([1 for p in param if p is True]) >= 2
from solution import solution import unittest class TestSolution(unittest.TestCase): """Test Solution""" def setUp(self) -> None: self.sample_cases = [((True, True, True), True), ((True, False, True), True), (('True', True, 'True'), False), ((True, False, False, False, True), True), ((None, None, None, False, True), False), ((1, True, False), False), ((True, True), True), ((False, 'False', False), False), (('False', False, False, 'True', True), False), ((False, False, 2, 'True', True), False), ((False, '1', True, False, None, 1, True), True), ((1, 2, 3, 4, True), False), ((True, 1, True), True), ((True, False), False), ] def test_solution(self): for sample, expected in self.sample_cases: self.assertEqual(solution(sample), expected) if __name__ == '__main__': unittest.main()
import org.junit.jupiter.api.Test;import static org.junit.jupiter.api.Assertions.assertEquals;- from solution import solution
- import unittest
// TODO: Replace examples and use TDD by writing your own tests- class TestSolution(unittest.TestCase):
- """Test Solution"""
class SolutionTest {@Testvoid test0True() {boolean[] bools = new boolean[3];assertEquals(false, Kumite.boolCheck(bools));}@Testvoid test1True() {boolean[] bools = new boolean[3];for(int i = 0; i < 3; i++) {for(int j = 0; j < 3; j++) {bools[j] = false;}bools[i] = true;assertEquals(false, Kumite.boolCheck(bools));}}@Testvoid test2True() {boolean[] bools = new boolean[3];for(int i = 0; i < 3; i++) {for(int j = 0; j < 3; j++) {bools[j] = true;}bools[i] = false;assertEquals(true, Kumite.boolCheck(bools));}}@Testvoid test3True() {boolean[] bools = new boolean[]{true, true, true};assertEquals(true, Kumite.boolCheck(bools));}}- def setUp(self) -> None:
- self.sample_cases = [((True, True, True), True),
- ((True, False, True), True),
- (('True', True, 'True'), False),
- ((True, False, False, False, True), True),
- ((None, None, None, False, True), False),
- ((1, True, False), False),
- ((True, True), True),
- ((False, 'False', False), False),
- (('False', False, False, 'True', True), False),
- ((False, False, 2, 'True', True), False),
- ((False, '1', True, False, None, 1, True), True),
- ((1, 2, 3, 4, True), False),
- ((True, 1, True), True),
- ((True, False), False),
- ]
- def test_solution(self):
- for sample, expected in self.sample_cases:
- self.assertEqual(solution(sample), expected)
- if __name__ == '__main__':
- unittest.main()
Prints H
shape pattern using letter H
's and returns number of H
's passed as asn argument.
For example:
Input: 5
Output:
H H
H H
H H
HHHHH
H H
H H
H H
HHHHH
def theletterh(howmuchh=1): for row in range(7): for col in range(5): if col in [0, 4] or (row in [3] and col in [1, 2, 3]): print('H', end='') else: print(end=' ') print() print() return 'H' * howmuchh #H return and H print (H😀😃😁)
- def theletterh(howmuchh=1):
for i in range(howmuchh):print('H')- for row in range(7):
- for col in range(5):
- if col in [0, 4] or (row in [3] and col in [1, 2, 3]):
- print('H', end='')
- else:
- print(end=' ')
- print()
- print()
- return 'H' * howmuchh
- #H return and H print (H😀😃😁)
def colour_of_fruit(fruit: str) -> str: """Returns the color of given fruit.""" match fruit: case "Apple" | "Raspberry" | "Strawberry": return "Red" case "Orange": return "Orange" case "Banana" | "Lemon" | "Pineapple": return "Yellow" case "Avocado" | "Lime" | "Melon" | "Pear": return "Green" case "Blueberry" | "Huckleberry": return "Blue" case "Plum" | "Grape" | "Maquiberry": return "Purple" case _: return 'Not a fruit!'
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":- def colour_of_fruit(fruit: str) -> str:
- """Returns the color of given fruit."""
- match fruit:
- case "Apple" | "Raspberry" | "Strawberry":
- return "Red"
- case "Orange":
- return "Orange"
- case "Banana" | "Lemon" | "Pineapple":
- return "Yellow"
elif fruit == "Melon":return "Green"if fruit == "Plum":return "Purple"elif fruit == "Strawberry":return "Red"elif fruit == "Cabbage"return "Greem"- case "Avocado" | "Lime" | "Melon" | "Pear":
- return "Green"
- case "Blueberry" | "Huckleberry":
- return "Blue"
- case "Plum" | "Grape" | "Maquiberry":
- return "Purple"
- case _:
- return 'Not a fruit!'
#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)
import unittest from solution import colour_of_fruit class TestColorOfFruit(unittest.TestCase): def setUp(self) -> None: self.fruit_samples = (("Apple", "Red"), ("Raspberry", "Red"), ("Strawberry", "Red"), ("Orange", "Orange"), ("Banana", "Yellow"), ("Lemon", "Yellow"), ("Pineapple", "Yellow"), ("Avocado", "Green"), ("Lime", "Green"), ("Melon", "Green"), ("Pear", "Green"), ("Blueberry", "Blue"), ("Huckleberry", "Blue"), ("Plum", "Purple"), ("Grape", "Purple"), ("Maquiberry", "Purple"), ("Cabbage", "Not a fruit!"), ) def test_fruit_color(self): for sample, expected in self.fruit_samples: self.assertEqual(colour_of_fruit(sample), expected) if __name__ == "__main__": unittest.main()
import codewars_test as testfrom solution import example- import unittest
- from solution import colour_of_fruit
@test.describe("Example")def test_group():@test.it("test case")def test_case():test.assert_equals(colouroffruit("Apple"), "Red")test.assert_equals(colouroffruit("Orange"), "Orange")test.assert_equals(colouroffruit("Blueberry"), "Blue")test.assert_equals(colouroffruit("Pear"), "Green")test.assert_equals(colouroffruit("Banana"), "Yellow")test.assert_equals(colouroffruit("Strawberry"), "Red")test.assert_equals(colouroffruit("Lemon"), "Yellow")test.assert_equals(colouroffruit("Lime"), "Green")test.assert_equals(colouroffruit("Raspberry"), "Red")test.assert_equals(colouroffruit("Pineapple"), "Yellow")test.assert_equals(colouroffruit("Melon"), "Green")test.assert_equals(colouroffruit("Plum"), "Purple")test.assert_equals(colouroffruit("Peach"), "Red")test.assert_equals(colouroffruit("Avacado"), "Green")- class TestColorOfFruit(unittest.TestCase):
- def setUp(self) -> None:
- self.fruit_samples = (("Apple", "Red"),
- ("Raspberry", "Red"),
- ("Strawberry", "Red"),
- ("Orange", "Orange"),
- ("Banana", "Yellow"),
- ("Lemon", "Yellow"),
- ("Pineapple", "Yellow"),
- ("Avocado", "Green"),
- ("Lime", "Green"),
- ("Melon", "Green"),
- ("Pear", "Green"),
- ("Blueberry", "Blue"),
- ("Huckleberry", "Blue"),
- ("Plum", "Purple"),
- ("Grape", "Purple"),
- ("Maquiberry", "Purple"),
- ("Cabbage", "Not a fruit!"),
- )
- def test_fruit_color(self):
- for sample, expected in self.fruit_samples:
- self.assertEqual(colour_of_fruit(sample), expected)
- if __name__ == "__main__":
- unittest.main()
def spawn_to_range(arr, val, ran): output = [] for i in arr: output.append(i) if i == val: for j in range(ran-1): output.append(i) return output
- def spawn_to_range(arr, val, ran):
return- output = []
- for i in arr:
- output.append(i)
- if i == val:
- for j in range(ran-1):
- output.append(i)
- return output
from bs4 import BeautifulSoup import requests import shutil import os def get_codewars_stats(username): """Scraps, and retrieves Codewars stats of given username.""" output = f'{username}\'s Codewars stats:\n' source = requests.get(f'https://www.codewars.com/users/{username}', stream=True) # Verify request status. Using 404 would miss a wide ranges of other failed connections. if source.status_code == 200: soup = BeautifulSoup(source.text, 'html.parser') stat_info = soup.findAll('div', class_='stat') important_values = [info.text for info in stat_info[:5] + stat_info[6:]] # Get url to users avatar/profile pic img_url = ''.join([el for el in str(soup.findAll('figure')[0].findNext('img')).split(' ') if 'src' in el]).replace('src="', '') # Get image_url requests: img_source = requests.get(img_url, stream=True) # The filepath where data will be saved: filepath = os.path.join(os.getcwd(), 'CodeWars') # Make Codewars directory if it does mot exist: if not os.path.isdir(filepath): os.mkdir(filepath) with open(os.path.join(filepath, username + '.jpg'), 'wb') as img_obj: # Save user's avatar/profile pic: img_source.raw.decode_content = True shutil.copyfileobj(img_source.raw, img_obj) print('Profile pic has been downloaded') with open(os.path.join(filepath, 'codewars_stats.txt'), 'w', encoding='utf-8') as file_obj: # Save user's Codewars stats: for item in important_values: file_obj.write(item + '\n') print('CodewarsStats have been successfully downloaded') output += '\n\t'.join([i for i in important_values]) return output else: return 'Something went wrong, enter a valid Codewars username.'
- from bs4 import BeautifulSoup
- import requests
- import shutil
- import os
- def get_codewars_stats(username):
- """Scraps, and retrieves Codewars stats of given username."""
source = requests.get(f'https://www.codewars.com/users/{username}')# Verify request status:if source.status_code == 404:return 'Something went wrong, enter a valid Codewars username.'soup = BeautifulSoup(source.text, 'html.parser')stat_info = soup.findAll('div', class_='stat')# i'm not sure why we dont show all of stat_info in the version before this# Would like someone to implement showing Profiles, since that is an image (maybe represent as link to profile?)# slicing the profiles out is my workaround for nowimportant_values = [info.text for info in stat_info[:5] + stat_info[6:]]- output = f'{username}\'s Codewars stats:\n'
- source = requests.get(f'https://www.codewars.com/users/{username}', stream=True)
seperator = '\n\t' # sadly f-strings don't allow backslashes, so we need to define a separator here insteadreturn f'{username}\'s Codewars stats:\n\t{seperator.join(important_values)}'- # Verify request status. Using 404 would miss a wide ranges of other failed connections.
- if source.status_code == 200:
- soup = BeautifulSoup(source.text, 'html.parser')
- stat_info = soup.findAll('div', class_='stat')
- important_values = [info.text for info in stat_info[:5] + stat_info[6:]]
- # Get url to users avatar/profile pic
- img_url = ''.join([el for el in str(soup.findAll('figure')[0].findNext('img')).split(' ') if 'src' in el]).replace('src="', '')
- # Get image_url requests:
- img_source = requests.get(img_url, stream=True)
- # The filepath where data will be saved:
- filepath = os.path.join(os.getcwd(), 'CodeWars')
- # Make Codewars directory if it does mot exist:
- if not os.path.isdir(filepath):
- os.mkdir(filepath)
- with open(os.path.join(filepath, username + '.jpg'), 'wb') as img_obj:
- # Save user's avatar/profile pic:
- img_source.raw.decode_content = True
- shutil.copyfileobj(img_source.raw, img_obj)
- print('Profile pic has been downloaded')
- with open(os.path.join(filepath, 'codewars_stats.txt'), 'w', encoding='utf-8') as file_obj:
- # Save user's Codewars stats:
- for item in important_values:
- file_obj.write(item + '\n')
- print('CodewarsStats have been successfully downloaded')
- output += '\n\t'.join([i for i in important_values])
- return output
- else:
- return 'Something went wrong, enter a valid Codewars username.'
import unittest from solution import get_codewars_stats from bs4 import BeautifulSoup import requests class TestGetCodeWarsStats(unittest.TestCase): """Setup testing variables.""" def setUp(self) -> None: # Feel free to use your username as a test sample instead: self.username_sample = 'seraph776' self.expected = get_codewars_stats(self.username_sample) def test_get_codewars_stats(self): """Tests get_codewars stats function.""" self.assertEqual(get_codewars_stats(self.username_sample), self.expected) self.assertEqual(get_codewars_stats('invalid_username'), 'Something went wrong, enter a valid Codewars username.') if __name__ == '__main__': unittest.main()
- import unittest
- from solution import get_codewars_stats
- from bs4 import BeautifulSoup
- import requests
- class TestGetCodeWarsStats(unittest.TestCase):
- """Setup testing variables."""
- def setUp(self) -> None:
- # Feel free to use your username as a test sample instead:
self.username_sample = 'Luk-ESC'- self.username_sample = 'seraph776'
- self.expected = get_codewars_stats(self.username_sample)
- def test_get_codewars_stats(self):
- """Tests get_codewars stats function."""
- self.assertEqual(get_codewars_stats(self.username_sample), self.expected)
self.assertEqual(get_codewars_stats(''), 'Something went wrong, enter a valid Codewars username.')- self.assertEqual(get_codewars_stats('invalid_username'), 'Something went wrong, enter a valid Codewars username.')
- if __name__ == '__main__':
- unittest.main()
from dataclasses import dataclass, field @dataclass class Dinosaur: name: str meat_eater: bool = field(default=False) @staticmethod def find_trex(lst): for dinosaur in lst: if isinstance(dinosaur, Tyrannosaurus) and dinosaur.meat_eater and dinosaur.name == 'tyrannosaurus': return True return False @dataclass class Tyrannosaurus(Dinosaur): meat_eater: bool = field(default=True)
exec(bytes("楦摮瑟敲⁸‽慬扭慤愠㨠∠祔慲湮獯畡畲≳椠", 'u16')[2:])- from dataclasses import dataclass, field
- @dataclass
- class Dinosaur:
- name: str
- meat_eater: bool = field(default=False)
- @staticmethod
- def find_trex(lst):
- for dinosaur in lst:
- if isinstance(dinosaur, Tyrannosaurus) and dinosaur.meat_eater and dinosaur.name == 'tyrannosaurus':
- return True
- return False
- @dataclass
- class Tyrannosaurus(Dinosaur):
- meat_eater: bool = field(default=True)
import unittest from solution import Dinosaur, Tyrannosaurus class TestFindTRex(unittest.TestCase): """Test FindTRex class.""" def setUp(self) -> None: tyrannosaurus = Tyrannosaurus('godzilla') trex0 = Tyrannosaurus('tyrannosaurus') trex1 = Tyrannosaurus('tyrannosaurus', False) trex2 = Tyrannosaurus('trex') trex3 = Dinosaur('velociraptor', False) trex4 = Dinosaur('tyrannosaurus', True) trex5 = Dinosaur('dinosaur') trex6 = Dinosaur('tyrannosaurus') trex7 = Tyrannosaurus('allosaurus') trex8 = Dinosaur('triceratops') trex9 = Dinosaur('brachiosaurus') trex10 = Dinosaur('Dinosaur') self.test_samples = (((trex0, tyrannosaurus, trex4, 'Triceratops', trex5, trex6, tyrannosaurus), True), ((trex7, 'tyrannosaurus', trex10, trex4, tyrannosaurus, trex9, trex9), False), ((trex7, 'tyrannosaurus', trex8, trex4, tyrannosaurus, trex3, trex6), False), ((trex5, trex1, trex3, trex2, tyrannosaurus, trex4, trex0, trex1), True), ((1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16), False), ((trex9, trex9, trex6, trex5, tyrannosaurus, trex4, tyrannosaurus), False), (('tyrannosaurus', trex7, trex3, trex4, False, trex5, trex0, trex4, trex2), True), ((tyrannosaurus, trex7, tyrannosaurus, trex4, trex5, 'trex0', trex4, trex2), False), (('Brachiosaurus', 'Velociraptor', 'Triceratops', trex4, tyrannosaurus), False), ((trex9, trex9, trex6, trex5, tyrannosaurus, trex4, tyrannosaurus), False), ((trex1, trex10, 'trex4', trex5, trex0, trex8, tyrannosaurus, trex7, trex10), True),) def test_find_trex(self): for sample, expected in self.test_samples: self.assertEqual(Dinosaur.find_trex(sample), expected) if __name__ == '__main__': unittest.main()
import codewars_test as test- import unittest
- from solution import Dinosaur, Tyrannosaurus
@test.describe("Example")def test_group():@test.it("test case")def test_case():test.assert_equals(find_trex(["Brontosaurus", "Stegosaurus", "Velociraptor"]), False)test.assert_equals(find_trex(["Boba Fett", "Palm Tree", "Tyrannosaurus", "Croissant"]), True)test.assert_equals(find_trex([]), False)- class TestFindTRex(unittest.TestCase):
- """Test FindTRex class."""
- def setUp(self) -> None:
- tyrannosaurus = Tyrannosaurus('godzilla')
- trex0 = Tyrannosaurus('tyrannosaurus')
- trex1 = Tyrannosaurus('tyrannosaurus', False)
- trex2 = Tyrannosaurus('trex')
- trex3 = Dinosaur('velociraptor', False)
- trex4 = Dinosaur('tyrannosaurus', True)
- trex5 = Dinosaur('dinosaur')
- trex6 = Dinosaur('tyrannosaurus')
- trex7 = Tyrannosaurus('allosaurus')
- trex8 = Dinosaur('triceratops')
- trex9 = Dinosaur('brachiosaurus')
- trex10 = Dinosaur('Dinosaur')
- self.test_samples = (((trex0, tyrannosaurus, trex4, 'Triceratops', trex5, trex6, tyrannosaurus), True),
- ((trex7, 'tyrannosaurus', trex10, trex4, tyrannosaurus, trex9, trex9), False),
- ((trex7, 'tyrannosaurus', trex8, trex4, tyrannosaurus, trex3, trex6), False),
- ((trex5, trex1, trex3, trex2, tyrannosaurus, trex4, trex0, trex1), True),
- ((1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16), False),
- ((trex9, trex9, trex6, trex5, tyrannosaurus, trex4, tyrannosaurus), False),
- (('tyrannosaurus', trex7, trex3, trex4, False, trex5, trex0, trex4, trex2), True),
- ((tyrannosaurus, trex7, tyrannosaurus, trex4, trex5, 'trex0', trex4, trex2), False),
- (('Brachiosaurus', 'Velociraptor', 'Triceratops', trex4, tyrannosaurus), False),
- ((trex9, trex9, trex6, trex5, tyrannosaurus, trex4, tyrannosaurus), False),
- ((trex1, trex10, 'trex4', trex5, trex0, trex8, tyrannosaurus, trex7, trex10), True),)
- def test_find_trex(self):
- for sample, expected in self.test_samples:
- self.assertEqual(Dinosaur.find_trex(sample), expected)
- if __name__ == '__main__':
- unittest.main()
exec(bytes('潳畬楴湯㴠氠浡摢›㌢•湩猠牴渨 ', 'u16')[2:]) """ .................................................................................................... .........:;;:..........::::::::,......,:::::,,............,::,..........,::::,,.........::,....::,.. .......,%@@@@S:.......,@@@@@@@@+......:@@@@@@@%,..........+@@*..........%@@@@@#?,.......S@+...,@@;.. .......%@@%%@@#,......,@@#SSSSS;......:@@SSSS@@%..........S@@#,.........S@#SS#@@*.......#@*...,@@;.. ......,@@;..;@@;......,@@;............:@@:...*@@,........:@@@@;.........S@?..,%@#,......#@+...,@@;.. ......,@@*,..;;,......,@@:............:@@,...;@@:........?@%?@%.........S@?...+@#,......#@+...,@@;.. .......?@@@S*:........,@@S%%%%%,......:@@*++*#@S........,#@;;@@:........S@?,,:S@S.......#@#%%%S@@;.. .......,?#@@@@?,......,@@@@@@@#,......:@@@@@@@S:........+@#..#@*........S@@@@@@@;.......#@@@@@@@@;.. .........,;?S@@+......,@@+:::::.......:@@??@@%,.........S@%;;%@#,.......S@@###%;........#@?:::;@@;.. ......:?*....%@%......,@@:............:@@,.;@@?........:@@@@@@@@;.......S@?,,...........#@+...,@@;.. ......;@@;...%@%......,@@:............:@@:..*@@+.......?@#????#@%.......S@?.............#@+...,@@;.. ......,S@@%?S@@+......,@@S%%%%%+......:@@:..,S@#,.....,#@*....+@@:......S@?.............#@+...,@@;.. .......:S@@@@@*.......,@@@@@@@@?......:@@:...:@@?.....+@@,....,#@*......S@?.............#@*...,@@;.. .........;++;,........,;;;;;;;;:......,;;,....:;:.....:;:..,:..:;:......:;:.............:;,...,;;,.. ..........................................................;*%?...................................... .........................................................,;+S#;..................................... .........................................................;*S@S*,.................................... .........................................................:*S#S*,.................................... .........................................................,*#S@*,.................................... .........................................................,+@#@?:.................................... .........................................................,;%%?*,.................................... ..........................................................+***;,....,:.............................. ..........................................................:?S%+......:,............................. ..........................................................,*S%+......::............................. ..........................................................,*%?;......,;............................. ...........................................................*%%+......:;............................. ...........................................................*SS*......;;............................. ..........................................................,*SS*.....:*,............................. ..........................................................,?%S?,...:*;.............................. ..........................................................,*SSS+:;*?;............................... .......................................................,:;.+%?%??*;,................................ ......................................................:+*?.;%?*,,................................... ....................................................,++**;.;S%+,.................................... ...............................,,:::::,,...........,+*?+,,.+S%:..................................... ............................,:;+**++;;+++:........,+*%;..,,*S?,..................................... ..........................::+++%%%*+;;;;;**:......+*%;...,;?%*,..................................... ........................,+?**%S#@@#??*+;;;;**:...;*%+....;???+...................................... ........................?S*%##@@@@@S%%%%?+;;+%?:,???....+S?*?:...................................... .......................;#%SS@@@@S%*+::;*%S?+:+?%?%%:..,*S?+**,...................................... ......................,%##%S@@#?+;;:::::;*%S?;;*?%%+;+%%*;+*:....................................... ......................+##S*S@#?+:,,.,,:;;;;?S%+;+**?%%*+;;*+........................................ .....................,%##%;%#%+:........:*+;+****+***++;+*+,........................................ .....................:S##?:*SS;...........:+;:;++********;.......................................... .....................;S##*:*S%;.............::;;:;;++++:,........................................... .....................+###*:+SSS???*+:,.......,:;++;:,,,............................................. .....................+###?:+%#S?**?%%%*:.......:*?;:,,,::;:,........................................ .....................;S@@%;+%#S+::::;*?%?:.....;?*;.;*SS###%*:...................................... .....................?#@@#++*#S?+;;:,,:;?%+,...:?;*%##SS%%S@@#?:.................................... ....................?##@@@%;+%S%?**++;:,:+??:...??##S?+;;+%@@@@S;,.................................. ...................*S?##@@%*;+SS%??**++;:,:*%;.,%##%+:;?%%S#@@@@#+,................................. ..................:#%*S@@#+%;:*SSS%%??*++;:,+%+?#S?;;?SSS#%??%#@@S;................................. ..................?#?+%#@S++%;:*SSS#S%??*++:,;S##?;*SSS??+:.,:+S@@?,................................ .................,SS?;?#@S;;**;:%%:;%#S%?*++;;S#S?%###%+:,.,,..+#@S:................................ .................:#S?:+S##++*%+;+S*..:%#%?*++%##S#@@#?;:;+,;:,.,*#S;................................ .................;@S?;:*S#S;;?*;:?S:...*#S?**####@@#?:,,;*+:....:%S+,............................... .................:##%+:;?#S*+S%+;;S?....+#S?%S@@@@S*;.:?%%S?*;..,*S+,............................... .................,S#S?;:+S#%;+S*;:%S,....+#S??S#@#*;;:,S%%?***+,:+?;,............................... ..................?#S%*;;*S#S;%?;:?#+.....;S++#@@?;+SS::%S?***+*+;+;,............................... ..................;#S%%*;+?#@+?%;:*@?......,:+S@#+;%SS%,.;%%**+*%*%*,............................... ..................:%#SS%?+*S@?*%;;?@S,.....,:*#@S;;#%?S*..,?%*++?%*;,............................... ...................+##SS%%?%#?+%+*?%#,.....,:*@@%:*#%??S:..,%?+;+S*,................................ ...................,?####SSS#++%%@#*S:.....,:?@@?:?#%?*%*,::*?+:;S+,................................ ....................:?#@@###?:+%#@#+?:.....:;%@@*;%#%?*?#S##%?;,+S?,................................ .....................,+%??SS;:;%@@#;?+,....+*%@#*+##%%*?S@#S%*:,*#+................................. .......................:;::::::S@@S;%?*+;;;%?S@#+?##%%**%##%?+,:%#+................................. ............................,::+@@S+%**??%S#?#@S;*SSS%?*??%?+::*S#:................................. ............................,:;+S@#*%+;+++*%?@@%+@*+#%%????*;;?%#?,................................. .............................,:;%@@?S?*+++*?S@@*;+;:S#%%???*?%%SS:.................................. .............................,;:*@@%%#%%??%%@@S+::;.;##S%%%%SS#S:................................... ..............................::;#@S%##SSS%S@@?;::;,.:%#######*:.................................... ..............................,::?@#*S###S?#@#+::;:,..,;*%%%?:,..................................... ..............................,::+#%S%S#%*S#S*:::;,.......,......................................... ...............................,::?%??%%%S##*:::::.................................................. ................................,;;S*+++*?%*;:;::,.................................................. .................................:*S%?**?%%;::::,................................................... .................................,;?SS%%S%*;;::,.................................................... ..................................,;?###S?;::,...................................................... ....................................,;+*+:,,........................................................ .................................................................................................... .................................................................................................... .....+#;..........,?#S;..........,?#S;............;#+...........,S?...........+SS*...........+SS*,.. ....;@@+..........%@#@@:.........%@#@@:..........:#@+..........,%@%..........+@@@@*.........+@@#@*.. ..,?@@@;.........:@S,+@?........:@S,+@?.........*@@@+.........;#@@%..........S@:,@#,........S@;,@@,. ..,@%%@;.........+@?.:@S........+@?.:@S........,@S?@+.........%#*@%.........,@#..S@:.......,@#,.S@:. ..,;.?@;.........*@*.,@#........*@*.,@#,.......,;.*@+.........;,:@%.........:@#..%@;.......,@#..%@;. .....?@;.........*@*.,@#........*@*.,@#,..........*@+...........:@%.........:@#..%@;.......:@#..%@;. .....?@;.........*@*.:@S........+@?.:@#...........*@+...........:@%.........,@#..S@:.......,@#,.%@;. .....?@;.........;@%.;@%........;@%.;@%...........*@+...........:@%.........,#@,.#@,.......,#@,.#@,. .....?@+.........,#@?S@+........,#@?S@+...........*@+...........:@%..........?@%?@%.........?@%?@%.. .....*@;..........;#@@?..........;#@@?............*@+...........:@%..........,%@@S:.........,%@@S:.. .....,,,...........,::............,::.............,,,............,,............::,............::,... .................................................................................................... Process finished with exit code 0 """
- exec(bytes('潳畬楴湯㴠氠浡摢›㌢•湩猠牴渨 ', 'u16')[2:])
- """
^&&7 Y@G.!B#Y^ ^5#G^.7PBP7: .^?PBP!.~@@! .:~7Y5PPY!.^&&^ .^?5P555JJJ?7777!!!7777?JJY5555YJ7~:.Y@5 :!J5GPJ!: ....^^^^^^~^^^^^:...:&@#JPP5?~..BBY!:. ........................ .............................................................................^~7????7~~^::.........::^^~!!77???7!~^:.:!?YPBGGBBB###&&&##GPYYJJYYY5PGGGPP55YYY5PGGPYJ7.:JY5^::::::^~!!7YB&##BBBBGP?~^::........~5BP5P:~JG&!.......:^^^^:.^#&#B#BGGY..::::........^GP5J.7G&~......:^^::::.^&&BP5PBG5:::.:. .::::.:5PP~.^5#Y.......::::::.J@#Y~^~5BG7...:. .:::::~YPY~..:7B#^.........::.~&&G~^^~!PBP~... .::::::!PP7~...:JBG~:........:?&@B7^^^~~7GBG?^...::::^7YPP?~!..:.:!PBGPYJJJJ5B&@&5!^^^^^~~!JGBGP5YYYY5PGPY!~!~::..:^7YPGBBBGPJ!^^^^^^^^~~~~~7?JY5555YJ7!~~~!.:::....::!^:::::::^^^^^^~~~~~~~~!!^~~~~~!!!!::^::::::~^~77!~^^^^^~~~~~~!!7?J7:.^!!!!!!!::^^::::::::^7?J7....:~....~?~..:~!!!!!!!..^~^^^^^^^::::. . .:^!!!!!!!!:.^~~~^^~^~^^^:. .. .~!!!!!!!!~:.:^~!~~~~~~~~~~~!~~!!!!!!!!~^..:^~!!!!!!!!!!!!!!!~^:....:::::::...- ....................................................................................................
- .........:;;:..........::::::::,......,:::::,,............,::,..........,::::,,.........::,....::,..
- .......,%@@@@S:.......,@@@@@@@@+......:@@@@@@@%,..........+@@*..........%@@@@@#?,.......S@+...,@@;..
- .......%@@%%@@#,......,@@#SSSSS;......:@@SSSS@@%..........S@@#,.........S@#SS#@@*.......#@*...,@@;..
- ......,@@;..;@@;......,@@;............:@@:...*@@,........:@@@@;.........S@?..,%@#,......#@+...,@@;..
- ......,@@*,..;;,......,@@:............:@@,...;@@:........?@%?@%.........S@?...+@#,......#@+...,@@;..
- .......?@@@S*:........,@@S%%%%%,......:@@*++*#@S........,#@;;@@:........S@?,,:S@S.......#@#%%%S@@;..
- .......,?#@@@@?,......,@@@@@@@#,......:@@@@@@@S:........+@#..#@*........S@@@@@@@;.......#@@@@@@@@;..
- .........,;?S@@+......,@@+:::::.......:@@??@@%,.........S@%;;%@#,.......S@@###%;........#@?:::;@@;..
- ......:?*....%@%......,@@:............:@@,.;@@?........:@@@@@@@@;.......S@?,,...........#@+...,@@;..
- ......;@@;...%@%......,@@:............:@@:..*@@+.......?@#????#@%.......S@?.............#@+...,@@;..
- ......,S@@%?S@@+......,@@S%%%%%+......:@@:..,S@#,.....,#@*....+@@:......S@?.............#@+...,@@;..
- .......:S@@@@@*.......,@@@@@@@@?......:@@:...:@@?.....+@@,....,#@*......S@?.............#@*...,@@;..
- .........;++;,........,;;;;;;;;:......,;;,....:;:.....:;:..,:..:;:......:;:.............:;,...,;;,..
- ..........................................................;*%?......................................
- .........................................................,;+S#;.....................................
- .........................................................;*S@S*,....................................
- .........................................................:*S#S*,....................................
- .........................................................,*#S@*,....................................
- .........................................................,+@#@?:....................................
- .........................................................,;%%?*,....................................
- ..........................................................+***;,....,:..............................
- ..........................................................:?S%+......:,.............................
- ..........................................................,*S%+......::.............................
- ..........................................................,*%?;......,;.............................
- ...........................................................*%%+......:;.............................
- ...........................................................*SS*......;;.............................
- ..........................................................,*SS*.....:*,.............................
- ..........................................................,?%S?,...:*;..............................
- ..........................................................,*SSS+:;*?;...............................
- .......................................................,:;.+%?%??*;,................................
- ......................................................:+*?.;%?*,,...................................
- ....................................................,++**;.;S%+,....................................
- ...............................,,:::::,,...........,+*?+,,.+S%:.....................................
- ............................,:;+**++;;+++:........,+*%;..,,*S?,.....................................
- ..........................::+++%%%*+;;;;;**:......+*%;...,;?%*,.....................................
- ........................,+?**%S#@@#??*+;;;;**:...;*%+....;???+......................................
- ........................?S*%##@@@@@S%%%%?+;;+%?:,???....+S?*?:......................................
- .......................;#%SS@@@@S%*+::;*%S?+:+?%?%%:..,*S?+**,......................................
- ......................,%##%S@@#?+;;:::::;*%S?;;*?%%+;+%%*;+*:.......................................
- ......................+##S*S@#?+:,,.,,:;;;;?S%+;+**?%%*+;;*+........................................
- .....................,%##%;%#%+:........:*+;+****+***++;+*+,........................................
- .....................:S##?:*SS;...........:+;:;++********;..........................................
- .....................;S##*:*S%;.............::;;:;;++++:,...........................................
- .....................+###*:+SSS???*+:,.......,:;++;:,,,.............................................
- .....................+###?:+%#S?**?%%%*:.......:*?;:,,,::;:,........................................
- .....................;S@@%;+%#S+::::;*?%?:.....;?*;.;*SS###%*:......................................
- .....................?#@@#++*#S?+;;:,,:;?%+,...:?;*%##SS%%S@@#?:....................................
- ....................?##@@@%;+%S%?**++;:,:+??:...??##S?+;;+%@@@@S;,..................................
- ...................*S?##@@%*;+SS%??**++;:,:*%;.,%##%+:;?%%S#@@@@#+,.................................
- ..................:#%*S@@#+%;:*SSS%%??*++;:,+%+?#S?;;?SSS#%??%#@@S;.................................
- ..................?#?+%#@S++%;:*SSS#S%??*++:,;S##?;*SSS??+:.,:+S@@?,................................
- .................,SS?;?#@S;;**;:%%:;%#S%?*++;;S#S?%###%+:,.,,..+#@S:................................
- .................:#S?:+S##++*%+;+S*..:%#%?*++%##S#@@#?;:;+,;:,.,*#S;................................
- .................;@S?;:*S#S;;?*;:?S:...*#S?**####@@#?:,,;*+:....:%S+,...............................
- .................:##%+:;?#S*+S%+;;S?....+#S?%S@@@@S*;.:?%%S?*;..,*S+,...............................
- .................,S#S?;:+S#%;+S*;:%S,....+#S??S#@#*;;:,S%%?***+,:+?;,...............................
- ..................?#S%*;;*S#S;%?;:?#+.....;S++#@@?;+SS::%S?***+*+;+;,...............................
- ..................;#S%%*;+?#@+?%;:*@?......,:+S@#+;%SS%,.;%%**+*%*%*,...............................
- ..................:%#SS%?+*S@?*%;;?@S,.....,:*#@S;;#%?S*..,?%*++?%*;,...............................
- ...................+##SS%%?%#?+%+*?%#,.....,:*@@%:*#%??S:..,%?+;+S*,................................
- ...................,?####SSS#++%%@#*S:.....,:?@@?:?#%?*%*,::*?+:;S+,................................
- ....................:?#@@###?:+%#@#+?:.....:;%@@*;%#%?*?#S##%?;,+S?,................................
- .....................,+%??SS;:;%@@#;?+,....+*%@#*+##%%*?S@#S%*:,*#+.................................
- .......................:;::::::S@@S;%?*+;;;%?S@#+?##%%**%##%?+,:%#+.................................
- ............................,::+@@S+%**??%S#?#@S;*SSS%?*??%?+::*S#:.................................
- ............................,:;+S@#*%+;+++*%?@@%+@*+#%%????*;;?%#?,.................................
- .............................,:;%@@?S?*+++*?S@@*;+;:S#%%???*?%%SS:..................................
- .............................,;:*@@%%#%%??%%@@S+::;.;##S%%%%SS#S:...................................
- ..............................::;#@S%##SSS%S@@?;::;,.:%#######*:....................................
- ..............................,::?@#*S###S?#@#+::;:,..,;*%%%?:,.....................................
- ..............................,::+#%S%S#%*S#S*:::;,.......,.........................................
- ...............................,::?%??%%%S##*:::::..................................................
- ................................,;;S*+++*?%*;:;::,..................................................
- .................................:*S%?**?%%;::::,...................................................
- .................................,;?SS%%S%*;;::,....................................................
- ..................................,;?###S?;::,......................................................
- ....................................,;+*+:,,........................................................
- ....................................................................................................
- ....................................................................................................
- .....+#;..........,?#S;..........,?#S;............;#+...........,S?...........+SS*...........+SS*,..
- ....;@@+..........%@#@@:.........%@#@@:..........:#@+..........,%@%..........+@@@@*.........+@@#@*..
- ..,?@@@;.........:@S,+@?........:@S,+@?.........*@@@+.........;#@@%..........S@:,@#,........S@;,@@,.
- ..,@%%@;.........+@?.:@S........+@?.:@S........,@S?@+.........%#*@%.........,@#..S@:.......,@#,.S@:.
- ..,;.?@;.........*@*.,@#........*@*.,@#,.......,;.*@+.........;,:@%.........:@#..%@;.......,@#..%@;.
- .....?@;.........*@*.,@#........*@*.,@#,..........*@+...........:@%.........:@#..%@;.......:@#..%@;.
- .....?@;.........*@*.:@S........+@?.:@#...........*@+...........:@%.........,@#..S@:.......,@#,.%@;.
- .....?@;.........;@%.;@%........;@%.;@%...........*@+...........:@%.........,#@,.#@,.......,#@,.#@,.
- .....?@+.........,#@?S@+........,#@?S@+...........*@+...........:@%..........?@%?@%.........?@%?@%..
- .....*@;..........;#@@?..........;#@@?............*@+...........:@%..........,%@@S:.........,%@@S:..
- .....,,,...........,::............,::.............,,,............,,............::,............::,...
- ....................................................................................................
- Process finished with exit code 0
- """
When I created this piece of code I thought it would be cool to develope a Codewars challenge that incorporated webscraping. This function scraps and retrieves the stats of a valid codewars username using the requests
and BeautifulSoup
module. If a valid username is entered the output will look as such:
Output:
username's Codewars stats:
Member Since:Jan 2020
Rank:4 kyu
Honor:1500
Leaderboard Position:#10,040
Honor Percentile:Top 2.354%
Total Completed Kata:776
Feel free to modify, and improve the code.
from bs4 import BeautifulSoup
import requests
def get_codewars_stats(username):
"""Scraps, and retrieves Codewars stats of given username."""
source = requests.get(f'https://www.codewars.com/users/{username}')
# Verify request status:
if source.status_code == 404:
return 'Something went wrong, enter a valid Codewars username.'
else:
soup = BeautifulSoup(source.text, 'html.parser')
stat_info = soup.findAll('div', class_='stat')
name, member, rank, honor, position, percentage, katas = (stat_info[0],
stat_info[3],
stat_info[9],
stat_info[10],
stat_info[11],
stat_info[12],
stat_info[13])
return f"{username}'s Codewars stats:\n\t{member.text}\n\t{rank.text}\n\t{honor.text}\n\t{position.text}\n\t{percentage.text}\n\t{katas.text}"
import unittest
from solution import get_codewars_stats
from bs4 import BeautifulSoup
import requests
class TestGetCodeWarsStats(unittest.TestCase):
"""Setup testing variables."""
def setUp(self) -> None:
# Feel free to use your username as a test sample instead:
self.username_sample = 'seraph776'
self.expected = get_codewars_stats(self.username_sample)
def test_get_codewars_stats(self):
"""Tests get_codewars stats function."""
self.assertEqual(get_codewars_stats(self.username_sample), self.expected)
self.assertEqual(get_codewars_stats('invalid_username'), 'Something went wrong, enter a valid Codewars username.')
if __name__ == '__main__':
unittest.main()
longest_string = lambda x: max(x.split(), key=lambda y: len(y))
const longestString = str => str.split(' ').reduce((a, b) => b.length > a.length ? b : a);- longest_string = lambda x: max(x.split(), key=lambda y: len(y))
import unittest from solution import longest_string class TestLongestString(unittest.TestCase): def setUp(self) -> None: self.test_samples = (('codewars longest string code challenge', 'challenge'), ('Guido van Rossum created the Python programming language', 'programming'), ("Python was named after the TV comedy series 'Monty Python’s Flying Circus'", 'Python’s'), ('Python is an open-source object-oriented programming language.', 'object-oriented'), ('Python does not require a compiler', 'compiler'), ('Elvis Presley was born in Mississippi 1/8/1935', 'Mississippi'), ) def test_longest_string(self): for sample, expected in self.test_samples: self.assertEqual(longest_string(sample), expected) if __name__ == '__main__': unittest.main()
describe("Solution", function(){it("did you find the longest?", function(){Test.assertEquals(longestString('I went running around the park'), "running", "try again");Test.assertEquals(longestString('There were a lot of barking dogs everywhere'), "everywhere", "try again");Test.assertEquals(longestString('now for some reason my shoe smells funny'), "reason", "try again");});});- import unittest
- from solution import longest_string
- class TestLongestString(unittest.TestCase):
- def setUp(self) -> None:
- self.test_samples = (('codewars longest string code challenge', 'challenge'),
- ('Guido van Rossum created the Python programming language', 'programming'),
- ("Python was named after the TV comedy series 'Monty Python’s Flying Circus'", 'Python’s'),
- ('Python is an open-source object-oriented programming language.', 'object-oriented'),
- ('Python does not require a compiler', 'compiler'),
- ('Elvis Presley was born in Mississippi 1/8/1935', 'Mississippi'),
- )
- def test_longest_string(self):
- for sample, expected in self.test_samples:
- self.assertEqual(longest_string(sample), expected)
- if __name__ == '__main__':
- unittest.main()