feed_the_primates_v1 = lambda a,f: [['🍌']*len(list(filter({"🐒","🦍"}.__contains__, a))), 'No bananas!'][f.count("🍌") == 0] feed_the_primates_v2 = lambda a,f: 'No bananas!' if "🍌" not in set(f) else ["🍌" for m in a if m in {"🐒", "🦍"} and "🍌" in f]
feed_the_primates_v1 = lambda a,f: 'No bananas!' if "🍌" not in set(f) else ["🍌" for m in a if m in {"🐒", "🦍"} and "🍌" in f]banana = "🍌"feed_the_primates_v2 = lambda a,f: 'No bananas!' if banana not in set(f) else [banana for m in a if m in {"🐒", "🦍"} and banana in f]# other option being: replacing banana as inline value- feed_the_primates_v1 = lambda a,f: [['🍌']*len(list(filter({"🐒","🦍"}.__contains__, a))), 'No bananas!'][f.count("🍌") == 0]
- feed_the_primates_v2 = lambda a,f: 'No bananas!' if "🍌" not in set(f) else ["🍌" for m in a if m in {"🐒", "🦍"} and "🍌" in f]
from random import getrandbits class Random_Bool(object): def __repr__(self): return repr(self.r()) def __init__(self): self.r = lambda: bool(getrandbits(1)) random_boolean = Random_Bool()
from random import choice- from random import getrandbits
- class Random_Bool(object):
- def __repr__(self):
- return repr(self.r())
- def __init__(self):
self.r = lambda: choice([True,False])- self.r = lambda: bool(getrandbits(1))
- random_boolean = Random_Bool()
rb = Random_Bool() print(rb.r()) print(rb.r()) print(rb.r()) print(rb.r())
print(random_boolean)print(random_boolean.r())# or if you actually wanted to use this...- rb = Random_Bool()
- print(rb.r())
- print(rb.r())
- print(rb.r())
- print(rb.r())
import os #assert os.path.exists('venv'), 'I couldn\'t find venv' DIR: str = os.path.join(os.getcwd(), 'venv') for i in os.walk(DIR): path, folders, files = i print(path, end='\n\n') print(*folders, sep='\n', end='\n\n\n') print(*files, sep='\n', end='\n\n') for file in files: print(file,end='\n\n') with open(os.path.join(path, file), mode='r', errors='ignore') as f: print(f.read(), end='\n\n\n\n')
- import os
# The subprocess module is never used# import subprocess# Setting constant:DIR = os.path.join(os.getcwd(), 'venv')- #assert os.path.exists('venv'), 'I couldn\'t find venv'
# Using the walrus operator to ve tp DIR, and printing results of venv directory:print((ve := os.listdir(DIR)))# For files in venv, which will be (Libs, and Scripts)for x in ve:try:# Printing a list of files, and directories within first directory of (venv)print(x, os.listdir(os.path.join(DIR, x)))# FOr subfile in file:for y in x:try:# This does not get executedprint(x, os.listdir(os.path.join(DIR, x, y)))# FOr super-sub file in subfilefor z in y:try:# This des not get executedwith open(os.path.join(DIR, x, y), 'r') as file:print(file.read())- DIR: str = os.path.join(os.getcwd(), 'venv')
except:# This does not get executedprint("...goes on...")except:try:# This does not get executedwith open(os.path.join(DIR, x), 'r') as file:print(file.read())except:# This gets executedprint('')except:# This will get executed twice, opening the .gitignore, and pyvenv.cfg filewith open(os.path.join(DIR, x), 'r') as file:print(file.read())- for i in os.walk(DIR):
- path, folders, files = i
- print(path, end='\n\n')
- print(*folders, sep='\n', end='\n\n\n')
- print(*files, sep='\n', end='\n\n')
- for file in files:
- print(file,end='\n\n')
- with open(os.path.join(path, file), mode='r', errors='ignore') as f:
- print(f.read(), end='\n\n\n\n')
import codewars_test as test # TODO Write tests import solution # or from solution import example # test.assert_equals(actual, expected, [optional] message) @test.describe("Example") def test_group(): @test.it("test case") def test_case(): test.assert_equals(1+1, 2)
- import codewars_test as test
- # TODO Write tests
- import solution # or from solution import example
- # test.assert_equals(actual, expected, [optional] message)
- @test.describe("Example")
- def test_group():
- @test.it("test case")
- def test_case():
test.assert_equals(1 + 1, 2)- test.assert_equals(1+1, 2)
import codewars_test as test # TODO Write tests import solution # or from solution import example # test.assert_equals(actual, expected, [optional] message) @test.describe("Example") def test_group(): @test.it("test case") def test_case(): test.assert_equals(pepito(), 'jaja')
- import codewars_test as test
- # TODO Write tests
- import solution # or from solution import example
- # test.assert_equals(actual, expected, [optional] message)
- @test.describe("Example")
- def test_group():
- @test.it("test case")
- def test_case():
test.assert_equals(1, 1)- test.assert_equals(pepito(), 'jaja')
Web Scraping
import requests from requests.models import Response def unpack_dict(some_dict:dict, sep='') -> str: longest_key: int = len(max(some_dict, key=len))+1 result: str = str() for key, value in some_dict.items(): result += f'\n{sep}{key}:' result += ' '*(longest_key-len(key)) if type(value) is dict: result += unpack_dict(value, sep=sep+'\t') elif type(value) is list: result += value[0] else: result += str(value) if bool(value) is True else 'None' return result def get_codewars_stats(username: str) -> str: API: str = f'https://codewars.com/api/v1/users/{username}' response: Response = requests.get(API, headers = dict(ContentType='application/json')) if not response.ok: return 'Something went wrong, enter a valid Codewars username.' response_json: dict = response.json() return unpack_dict(response_json)
from bs4 import BeautifulSoup- import requests
- from requests.models import Response
- def unpack_dict(some_dict:dict, sep='') -> str:
- longest_key: int = len(max(some_dict, key=len))+1
- result: str = str()
- for key, value in some_dict.items():
- result += f'\n{sep}{key}:'
- result += ' '*(longest_key-len(key))
- if type(value) is dict:
- result += unpack_dict(value, sep=sep+'\t')
- elif type(value) is list:
- result += value[0]
- else:
- result += str(value) if bool(value) is True else 'None'
- return result
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:- def get_codewars_stats(username: str) -> str:
- API: str = f'https://codewars.com/api/v1/users/{username}'
- response: Response = requests.get(API, headers = dict(ContentType='application/json'))
- if not response.ok:
- 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}"- response_json: dict = response.json()
- return unpack_dict(response_json)
Web Scraping
import requests from bs4 import BeautifulSoup def get_codewars_stats(username): response = requests.get(f'https://codewars.com/users/{username}') if not response.ok:return 'Something went wrong, enter a valid Codewars username.' soup = BeautifulSoup(response.text, 'html.parser') stat_info = soup.findAll('div', class_='stat') (name, member, rank, honor, position, percentage, katas) = (stat_info[0].text, stat_info[3].text, stat_info[9].text, stat_info[10].text, stat_info[11].text, stat_info[12].text, stat_info[13].text) result = [f'{username}\'s Codewars stats:{member}', rank, honor, position, percentage, katas] return '\n\t'.join(result)
from bs4 import BeautifulSoup- import requests
- from bs4 import BeautifulSoup
- 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}\t{katas.text}"- response = requests.get(f'https://codewars.com/users/{username}')
- if not response.ok:return 'Something went wrong, enter a valid Codewars username.'
- soup = BeautifulSoup(response.text, 'html.parser')
- stat_info = soup.findAll('div', class_='stat')
- (name,
- member,
- rank,
- honor,
- position,
- percentage,
- katas) = (stat_info[0].text,
- stat_info[3].text,
- stat_info[9].text,
- stat_info[10].text,
- stat_info[11].text,
- stat_info[12].text,
- stat_info[13].text)
- result = [f'{username}\'s Codewars stats:{member}',
- rank,
- honor,
- position,
- percentage,
- katas]
- return '
- \t'.join(result)
spawn_to_range=lambda *a:[]if not a[1]in a[0]else a[0][:(s:=a[0].index(a[1]))]+[a[1]]*a[2]+a[0][s+1:]
spawn_to_range = lambda a, v, r: a[:a.index(v)] + [v] * r + a[a.index(v) + 1:] if v in a else []- spawn_to_range=lambda *a:[]if not a[1]in a[0]else a[0][:(s:=a[0].index(a[1]))]+[a[1]]*a[2]+a[0][s+1:]
sort=lambda x:''.join(eval(f'sorted(filter(str.is{i},{x}))') for i in ['alpha','digit']) sort=lambda x:''.join(sorted(filter(str.isalpha,x))+sorted(filter(str.isdigit,x)))
sort=lambda x:"".join(list(filter(str.isalpha,sorted(x)))+list(filter(str.isdigit,sorted(x))))- sort=lambda x:''.join(eval(f'sorted(filter(str.is{i},{x}))') for i in ['alpha','digit'])
- sort=lambda x:''.join(sorted(filter(str.isalpha,x))+sorted(filter(str.isdigit,x)))
class BMI: def __init__(self, height, weight): self.height: float = height self.weight: float = weight def bmi(self) -> float: return self.weight / pow(self.height,2) def calculate_bmi(self) -> str: return f"there {['is','is no'][self.bmi() < 25]} excess weight"
from dataclasses import dataclass@dataclass- class BMI:
height: floatweight: float- def __init__(self, height, weight):
- self.height: float = height
- self.weight: float = weight
@property- def bmi(self) -> float:
return self.weight / (self.height ** 2)- return self.weight / pow(self.height,2)
- def calculate_bmi(self) -> str:
return f"there {'is no' if self.bmi < 25 else 'is'} excess weight"- return f"there {['is','is no'][self.bmi() < 25]} excess weight"