content
stringlengths
7
1.05M
""" Use the Eratoshenes Algorithm to generate first 1229 prime numbers. """ max = 10000 smax = 100 # sqrt(10000) lst = [] # number list, all True (is prime) at first for i in range(max + 1): # initialization lst.append(True) for i in range(2, smax + 1): # Eratoshenes Algorithm sieve = 2 * i while sieve...
#Votes Voter0 = int(input("Vote:")) Voter1 = int(input("Vote:")) Voter2 = int(input("Vote:")) #Count def count_votes(): #Accounts voter0_account = 0 voter1_account = 0 voter2_account = 0 #Total total = Voter0 + Voter1 + Voter2 #Return if total > 1: voter2_account =+ 1 ...
# EXERCÍCIO 22 # Crie um programa que leia o nome completo de uma pessoa e mostre: # O nome com todas as letras maiúsculas e minúsculas. # Quantas letras ao todo (sem considerar espaços). # Quantas letras tem o primeiro nome. #strip - remove espaços desnecessários nome = str(input('Digite o seu nome completo: ')).stri...
otra_coordenada=(0, 1) new=otra_coordenada.x print(new)
#!/usr/bin/env python # coding: utf-8 # Given two arrays, write a function to compute their intersection. # # Example 1: # # Input: nums1 = [1,2,2,1], nums2 = [2,2] # Output: [2] # Example 2: # # Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] # Output: [9,4] # In[1]: def intersection(nums1, nums2): return list(...
s = 0 for c in range(0, 6): n = int(input('Digite numero inteiro: ')) if n%2==0: s += n print(f'A soma dos valores par e {s}')
# Unique Binary Search Trees II # https://www.interviewbit.com/problems/unique-binary-search-trees-ii/ # # Given A, how many structurally unique BST’s (binary search trees) that store values 1...A? # # Example : # # Given A = 3, there are a total of 5 unique BST’s. # # # 1 3 3 2 1 # \ ...
C=float(input('Informe a temperatura em ºC:')) F=C*1.8+32 #print('A temperatura de {}ºC corresponde a {}ºF!'.format(C,C*1.8+32)) print('A temperatura de {}ºC corresponde a {}ºF!'.format(C,F))
#stringCaps.py msg = "john nash" print(msg) # ALL CAPS msg_upper = msg.upper() print(msg_upper) # First Letter Of Each Word Capitalized msg_title = msg.title() print(msg_title)
def create_500M_file(name): native.genrule( name = name + "_target", outs = [name], output_to_bindir = 1, cmd = "truncate -s 500M $@", )
hotels = pois[pois['fclass']=='hotel'] citylondon = boroughs.loc[boroughs['name'] == 'City of London', 'geometry'].squeeze() cityhotels = hotels[hotels.within(citylondon)] [fig,ax] = plt.subplots(1, figsize=(12, 8)) base = boroughs.plot(color='lightblue', edgecolor='black',ax=ax); cityhotels.plot(ax=ax, marker='o', co...
class Config: PROXY_WEBPAGE = "https://free-proxy-list.net/" TESTING_URL = "https://google.com" REDIS_CONFIG = { "host": "redis", "port": "6379", "db": 0 } REDIS_KEY = "proxies" MAX_WORKERS = 50 NUMBER_OF_PROXIES = 50 RSS_FEEDS = { "en": [ ...
# This file describes some constants which stay the same in every testing environment # Total number of fish N_FISH = 70 # Total number of fish species N_SPECIES = 7 # Total number of time steps per environment N_STEPS = 180 # Number of possible emissions, i.e. fish movements # (all emissions are represented with ...
somaidade = 0 maioridadehomen = 0 nomevelho = '' totmulher20 = 0 for c in range(0, 4): print('---- {}ª Pessoa -----'.format(c+1)) nome = str(input('Nome: ')).strip() idade = int(input('Idade: ')) sexo = str(input('Sexo [M/F]: ')).strip() somaidade += idade if c == 1 and sexo in 'Mm': mai...
class Pessoa: olhos = 2 def __init__(self,*filhos, nome = None, idade = 35): self.idade = idade self.nome = nome self.filhos = list(filhos) def cumprimentar(self): return 'Olá mundo!' if __name__ == '__main__': marcio = Pessoa(nome='Marcio') max = Pessoa(marcio, no...
def print_idp(file_name: str, vocabulary_strings: list, theory_strings: list, structure_strings: list) -> None: """Takes all contents of vocab and theory as list of strings and prints it as IDP code in file_name :param file_name: Name of output file :param vocabulary_strings: list of strings, with every str...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def insert_sort(inputlist): """ 直接插入排序,升序 :param inputlist: a list of number :return: the ascending list """ length = len(inputlist) for x in range(1, length): key = inputlist[x] # 要插入的数 i = x - 1 while i >= 0: ...
""" * Setup and Draw. * * The code inside the draw() function runs continuously * from top to bottom until the program is stopped. """ y = 100 def setup(): """ The statements in the setup() function execute once when the program begins """ size(640, 360) # Size must be the first statement ...
{ "name": "Custom Apps", "summary": """Simplify Apps Interface""", "images": [], "vesion": "12.0.1.0.0", "application": False, "author": "IT-Projects LLC, Dinar Gabbasov", "support": "apps@itpp.dev", "website": "https://twitter.com/gabbasov_dinar", "category": "Access", "license"...
class Solution: def getLucky(self, s: str, k: int) -> int: nums = '' for char in s: nums += str(ord(char) - ord('a') + 1) for i in range(k): nums = str(sum((int(c) for c in nums))) return nums
#from sec.core.models import Meeting """ import datetime class GeneralInfo(models.Model): id = models.IntegerField(primary_key=True) info_name = models.CharField(max_length=150, blank=True) info_text = models.TextField(blank=True) info_header = models.CharField(max_length=765, blank=True) class Met...
keys = ['red', 'green', 'blue'] values = ['#FF0000','#008000', '#0000FF'] color_dictionary = dict(zip(keys, values)) print(color_dictionary)
#!/bin/python # list lauguage = 'Python' lst = list(lauguage) print(type(lst)) print(lst) print("-------------------------------") # [i for i in iterable if expression] lst = [i for i in lauguage] print(type(lst)) print(lst) print("-------------------------------") add_two_nums = lambda a, b: a + b print(add_two_num...
class Local(object): __slots__ = ("__storage__", "__ident_func__") def __init__(self): object.__setattr__(self, "__storage__", {}) object.__setattr__(self, "__ident_func__", get_ident) def __iter__(self): return iter(self.__storage__.items()) def __call__(self, proxy): """Create a proxy for a...
""" Module: 'json' on esp32_LoBo MCU: (sysname='esp32_LoBo', nodename='esp32_LoBo', release='3.2.24', version='ESP32_LoBo_v3.2.24 on 2018-09-06', machine='ESP32 board with ESP32') Stubber: 1.0.0 """ def dump(): pass def dumps(): pass def load(): pass def loads(): pass
def time2sec(timestr): """ Conver time specs to seconds """ if timestr[-1] == "s": return int(timestr[0:-1]) elif timestr[-1] == "m": return int(timestr[0:-1]) * 60 elif timestr[-1] == "h": return int(timestr[0:-1]) * 60 * 60 else: return int(timestr)
nome = input('\nInsira seu nome: \n') if 'SILVA' in nome.upper(): print('O seu nome tem SILAVA\n') else: print('Você não faz parte da família SILVA\n')
SERIAL_DEVICE = '/dev/ttyAMA0' SERIAL_SPEED = 115200 CALIBRATION_FILE = '/home/pi/stephmeter/calibration.json' TIMEOUT = 300 # 5 minutes MQTT_SERVER = '192.168.1.2' MQTT_PORT = 1883 MQTT_TOPIC_PWM = 'traccar/eta' MQTT_TOPIC_LED = 'traccar/led'
def example(): print('basic function') z=3+9 print(z) #Function with parameter def add(a,b): c=a+b print('the result is',c) add(5,3) add(a=3,b=5) #Function with default parameters def add_new(a,b=6): print(a,b) add_new(2) def basic_window(width,height,font='TNR',bgc='w',scrollbar=True):...
class Test: """ Lorem ipsum dolor sit amet, consectetur adipiscing elit, deserunt mollit anim id est laborum. .. sourcecode:: pycon >>> # extract 100 LDA topics, using default parameters >>> lda = LdaModel(corpus=mm, id2word=id2word, num_topics=100, distributed=True) using distrib...
# This program will compute the factorial of any number given by user # until user enter some negative values. n = int(input("please input a number: ")) # the loop for getting user inputs while n >= 0: # initializing fact = 1 # calculating the factorial for i in range(1, n+1): fact *= i ...
class Lang_EN: LabelFrame = "Controls" runBt = "Show result" fileBtn = "Load image" dropLab = "Choose mask" maskSlider = "Size of the mask" # options = {"Low pass Round": self.LPround(), "High pass Round": self.LPround(), "Low pass square": self.LPround(), # "High pass square": se...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ KanjiVG stub """ class KanjiVG: pass
class GroupDirectoryError(Exception): pass class NoSuchRoleIdError(GroupDirectoryError): def __init__(self, *args, role_id, **kwargs): super().__init__(*args, **kwargs) self.role_id = role_id class NoSuchRoleNameError(GroupDirectoryError): def __init__(self, *args, role_name, **kwargs): ...
def test(): assert ( "patterns = list(nlp.pipe(people))" in __solution__ ), "Você está usando nlp.pipe envolvido em uma lista (list)?" __msg__.good( "Bom trabalho! Vamos seguir agora com um exemplo prático que " "usa nlp.pipe para processar documentos com metadados adicionais." ...
consultation_mention = [ "rendez-vous pris", r"consultation", r"consultation.{1,8}examen", "examen clinique", r"de compte rendu", r"date de l'examen", r"examen realise le", "date de la visite", ] town_mention = [ "paris", "kremlin.bicetre", "creteil", "boulogne.billancou...
class Solution: def myPow(self, x: float, n: int) -> float: memo = {} def power(x,n): if n in memo:return memo[n] if n==0: return 1 elif n==1:return x elif n < 0: memo[n] = power(1/x,-n) return memo[n]...
def sum_Natural(n): if n == 0: return 0 else: return sum_Natural(n - 1) + n n = int(input()) result = sum_Natural(n) print(f"Sum of first {n} natural numbers -> {result}")
class Ultrapassagem(object): """ Métodos para resolução de tópicos de física: Ultrapassagem Obs: Utilize parâmetros nomeados """ ERROR = "Argumentos invalidos, verifique a documentação do método." @classmethod def velocidade_relativa(cls, V1: float=None, V2: float=None, sentidos_opostos: ...
config = { 'cf_template_description': 'This template is generated with python' 'using troposphere framework to create' 'dynamic Cloudfront templates with' 'different vars according to the' 'PY...
outputdir = "/map" rendermode = "smooth_lighting" world_name = "MCServer" worlds[world_name] = "/data/world" renders["North"] = { 'world': world_name, 'title': 'North', 'dimension': "overworld", 'rendermode': rendermode, 'northdirection': 'upper-left' } renders["East"] = { 'world': world_name, 'title': 'East', ...
def load(filename): lines = [s.strip() for s in open(filename,'r').readlines()] time = int(lines[0]) busses = [int(value) for value in lines[1].split(",") if value != "x"] return time,busses t,busses = load("input") print(f"Tiempo buscado {t}"); print(busses) for i in range(t,t+1000): for bus ...
ALL = 'All servers' def caller_check(servers = ALL): def func_wrapper(func): # TODO: To be implemented. Could get current_app and check it. Useful for anything? return func return func_wrapper
def max_sub_array(nums): """ Returns the max subarray of the given list of numbers. Returns 0 if nums is None or an empty list. Time Complexity: O(n) Space Complexity: O(1) """ if nums == None: return 0 if len(nums) == 0: return 0 dp = [0 for i in range(len...
print('Conversor de números\n') while True: n = input('Digite um número inteiro: ') if n.isnumeric(): print('Escolha uma opção para conversão: \n[1] para binário \n[2] para octal \n[3] para hexadeximal') break else: print('Digite uma opção válida!') while True: o = input('Digite uma opção para conversão: ') ...
#Programming I ####################### # Mission 5.1 # # Vitality Points # ####################### #Background #========== #To encourage their customers to exercise more, insurance companies are giving #vouchers for the distances that customers had clocked in a week as follows: #########################...
def resumo(num, aument=0, descont=0): print('=' * 41) print(f'{"Resumo do valor":^41}') print('=' * 41) print(f'Preço Analisado: \t{moeda(num):>20}') print(f'Dobro do preço: \t{dobro(num, True):>20}') print(f'Metade do preço: \t{metade(num, True):>20}') print(f'{aument}% de aumento: \t{aumen...
#program to get all strobogrammatic numbers that are of length n. def gen_strobogrammatic(n): """ :type n: int :rtype: List[str] """ result = helper(n, n) return result def helper(n, length): if n == 0: return [""] if n == 1: return ["1", "0", "8"] middles = helper(...
# Sage version information for Python scripts # This file is auto-generated by the sage-update-version script, do not edit! version = '9.6.beta5' date = '2022-03-12' banner = 'SageMath version 9.6.beta5, Release Date: 2022-03-12'
ls = list(input().split()) count = 0 for l in ls: if l == 1: count += 1 print(count)
def solve(n): F = [1, 1] while len(str(F[-1])) < n: F.append(F[-1] + F[-2]) return len(F) # n = 3 n = 1000 answer = solve(n) print(answer)
def isunique(s): for i in range(len(s)): for j in range(len(s)): if i != j: if(s[i] == s[j]): return False return True if __name__ == "__main__": res = isunique("hsjdfhjdhjfk") print(res)
uctable = [ [ 48 ], [ 49 ], [ 50 ], [ 51 ], [ 52 ], [ 53 ], [ 54 ], [ 55 ], [ 56 ], [ 57 ], [ 194, 178 ], [ 194, 179 ], [ 194, 185 ], [ 194, 188 ], [ 194, 189 ], [ 194, 190 ], [ 217, 160 ], [ 217, 161 ], [ 217, 162 ], [ 217, 163 ], [ 217, 164 ], [ 217, 165 ], [ 217, 166 ], ...
"""Top-level package for zeroml.""" __author__ = """kuba cieslik""" __email__ = 'kubacieslik@gmail.com' __version__ = '0.3.3'
class LazyDict(dict): def __init__(self, load_func, *args, **kwargs): self._load_func = load_func self._args = args self._kwargs = kwargs self._loaded = False super().__init__() def load(self): if not self._loaded: self.update(self._load_func(*self._a...
def gcd(a, b): i = min(a, b) while i>0: if (a%i) == 0 and (b%i) == 0: return i else: i = i-1 def p(s): print(s) if __name__ == "__main__": p("input a:") a = int(input()) p("input b:") b = int(input()) p("gcd of "+str(a)+" and "+str(b)+" is:") ...
""" Tutor allocation algorithm for allocating tutors to the optimal sessions. """ __author__ = "Henry O'Brien, Brae Webb" __all__ = ['allocation', 'doodle', 'model', 'solver', 'csvalidator']
class Solution: def sortedSquares(self, A: List[int]) -> List[int]: if A[0] >= 0 and A[-1] >= 0: return [a ** 2 for a in A] if A[0] <= 0 and A[-1] <= 0: return [a ** 2 for a in A][::-1] i = 0 while i < len(A) - 1 and A[i] < 0 and A[i + 1] < 0: ...
# pylint: disable=missing-docstring,invalid-name,too-few-public-methods class A: myfield: int class B(A): pass class C: pass class D(C, B): pass a = A() print(a.myfield) b = B() print(b.myfield) d = D() print(d.myfield) c = C() print(c.myfield) # [no-member]
''' The goal of binary search is to search whether a given number is present in the string or not. ''' lst = [1,3,2,4,5,6,9,8,7,10] lst.sort() first=0 last=len(lst)-1 mid = (first+last)//2 item = int(input("enter the number to be search")) found = False while( first<=last and not found): mid = (first + l...
num = (int(input('Digite um numero: ')), int(input('Digite outro numero: ')), int(input('Digite mais um numero: ')), int(input('Digite o ultimo numero: '))) print(f'Os numero digitados foram: {num}') print(f'O numero 9 apareceu {num.count(9)} vezes') if 3 in num: print(f'\nO numero 3 foi dig...
# SAME BSTS # O(N^2) time and space def sameBsts(arrayOne, arrayTwo): # Write your code here. if len(arrayOne) != len(arrayTwo): return False if len(arrayOne) == 0: return True if arrayOne[0] != arrayTwo[0]: return False leftSubtreeFirst = [num for num in arrayOne[1:] if num < arrayOne[0]] rightS...
consent = """<center><table width="800px"><tr><td> <font size="16"><b>University of Costa Rica<br/> </font> INFORMED CONSENT FORM for RESEARCH<br/></b> <b>Title of Study:</b> Hanabi AI Agents<br/> <b>Principal Investigator:</b> Dr. Markus Eger <br/> <h2>What are some general things you should know about re...
def getNextGreaterElement(array: list) -> None: if len(array) <= 0: return print(bruteForce(array)) print(optimizationUsingSpace(array)) # bruteforce def bruteForce(array: list) -> list: ''' time complexicity: O(n^2) space complexicity: O(1) ''' greater_element_list = [-1] * len...
#remove duplicates from an unsorted linked list def foo(linkedlist): current_node = linkedlist.head while current_node is not None: checker_node = current_node while checker_node.next is not None: if checker_node.next.value == current_node.value: checker_node.next =...
description = 'Verify the user can add an element to a page and save it successfully' pages = ['common', 'index', 'project_pages', 'page_builder'] def setup(data): common.access_golem(data.env.url, data.env.admin) index.create_access_project('test') common.navigate_menu('Pages'...
""" Faça um algoritmo que leia o salário de um funcionário e mostre seu novo salário, com 15% de aumento. """ salario = float(input('Salário atual do funcionário: R$')) salario = salario * 1.15 print('Salário do funcionário com 15% de aumento: R${:.2f}'.format(salario))
## # A collection of functions to search in lists. # ## # Returns the minimum element in a list of integers def maximum_in_list(list): # Your task: # - Check if this function works for all possible integers. # - Throw a ValueError if the input list is empty (see code below) # if not list: # ...
def set_fill_color(red, green, blue): pass def draw_rectangle(corner, other_corner): pass set_fill_color(red=161, green=219, blue=114) draw_rectangle(corner=(105,20), other_corner=(60,60))
#!/usr/bin/env python3 #-*- encoding: UTF-8 -*- def main(): salario = float(input("Salário-hora: R$ ")) tempo = int(input("Quantidade de horas trabalhadas: ")) ir = (salario * tempo) * (11/100) inss = (salario * tempo)* (8/100) sindicato = (salario * tempo) * (5/100) print("+ Salário bruto: R$"...
load("@io_bazel_rules_go//go:deps.bzl", "go_register_toolchains", "go_rules_dependencies") def anchore_extra_deps(configure_go=True): if configure_go: go_rules_dependencies() go_register_toolchains(version = "1.17.1")
def checkprime(value: int): factor = 2 sqrt = value ** 0.5 while factor <= sqrt: if value % factor == 0: return False factor += 1 return True def sum_primes_under(n: int): num = 2 sum = 0 while num < n: if checkprime(num): sum += num ...
month = input() days = int(input()) cost_a = 0 cost_s = 0 if month == "May" or month == "October": cost_a = days * 65 cost_s = days * 50 if 7 < days <= 14: cost_s = cost_s * 0.95 if days > 14: cost_s = cost_s * 0.7 elif month == "June" or month == "September": cost_a = days * 68.70...
## creat fct def raise_to_power(base_num, pow_num): ## fct take 2 input num result = 1 ## def var call result is going to store result for index in range(pow_num): ## specify for loop that loop through range of num result = result * base_num ## math is going to be store in result return resu...
""" Dado un carácter, construya un programa en Python para determinar si el carácter es un dígito o no. """ def isDigit(char): if len(char) > 1: print('Debe ingresar un solo caracter') return code = ord(char) if code > 47 and code < 58: print('El carácter {} es un dígito'.format(ch...
CENSUS_YEAR = 2017 COMSCORE_YEAR = 2017 N_PANELS = 500 N_CORES = 8 # income mapping for aggregating ComScore data to fewer # categories so stratification creates larger panels INCOME_MAPPING = { # 1 is 0 to 25k # 2 is 25k to 50k # 3 is 50k to 100k # 4 is 100k + 1: 1, # less than 10k and 10k-15k ...
def maximo(a, b, c): if a > b and a > c: return a elif b > c and b > a: return b elif c > a and c > b: return c elif a == b == c: return a
#A loop statement allows us to execute a statement or group of statements multiple times. def main(): var = 0 # define a while loop while (var < 5): print (var) var = var + 1 # define a for loop for var in range(5,10): print (var) # use a for loop over a collection days = ["Mon...
valor = float(input('Quanto custa o produto? R$')) avista = valor - (valor *10/100) parcelado = valor + ( valor *12/100) #desc = valor - novo #print ( 'O valor com o desconto de 5% fica de R$ {}.' .format(desc)) print (' O poduto que custava R$ {}, com o desconto de 10% do pagamento avista sai a R$ {} e com o acresci...
KERNAL_FILENAME = "kernel" INITRD_FILENAME = "initrd" DISK_FILENAME = "disk.img" BOOT_DISK_FILENAME = "boot.img" CLOUDINIT_ISO_NAME = "cloudinit.img"
class DES(object): ## Init boxes that we're going to use def __init__(self): # Permutation tables and Sboxes self.IP = ( 58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, ...
""" Build the CUDA-STREAM benchmark for multiple CUDA compute capabilities. Make each build available as a SCI-F application. """ Stage0 += baseimage(image='nvcr.io/nvidia/cuda:9.1-devel-centos7', _as='devel') # Install the GNU compiler Stage0 += gnu(fortran=False) # Install SCI-F Stage0 += pip(packages=['scif'], up...
# import math # def longest_palindromic_contiguous(contiguous_substring): # start_ptr = 0 # end_ptr = 0 # for i in range(len(contiguous_substring)): # len_1 = expand_from_center(contiguous_substring, i, i) # len_2 = expand_from_center(contiguous_substring, i, i + 1) # max_len = max...
# unselectGlyphsWithExtension.py f = CurrentFont() for gname in f.selection: if '.' in gname: f[gname].selected = 0
# Problem: https://www.hackerrank.com/challenges/s10-weighted-mean/problem # Score: 30 n = int(input()) arr = list(map(int, input().split())) weights = list(map(int, input().split())) print(round(sum([arr[x]*weights[x] for x in range(len(arr))]) / sum(weights), 1))
a = float(raw_input("What is the coefficients a? ")) b = float(raw_input("What is the coefficients b? ")) c = float(raw_input("What is the coefficients c? ")) d = b*b - 4.*a*c if d >= 0.0: print("Solutions are real") elif b == 0.0: print("Solutions are imaginary") else: print("Solutions are complex") pri...
class Bank: def __init__(self, bankName, address): self.bankName = bankName self.address = address self.accounts = [] def toString(self): print(str(Sparnord.__dict__) + " " + str(self.accounts) + "\n" + str(self.accounts[1].customer.name)) class Account: def __init__(s...
def separador(mano): lista_valor = [] lista_suit = [] valor_carta = {'2':1, '3':2, '4':3, '5':4, '6':5, '7':6, '8':7, '9':8, 'T':9, 'J':10, 'Q':11, 'K':12, 'A':13} for i in mano.split(' '): lista_valor.append(valor_carta.get(i[0])) lista_suit.append(i[1]) return(sorted(lista_valor), lista_suit) def Royal_F...
substring=input() word=input() while substring in word: word=word.replace(substring,"") print(word)
class Solution(object): def findAllConcatenatedWordsInADict(self, words): """ :type words: List[str] :rtype: List[str] """ ans = [] self.wordSet = set(words) for word in words: self.wordSet.remove(word) if self.search(word): ...
# names tuple names = ('Anonymous','Tazri','Focasa','Troy','Farha','Xenon'); print("names : ",names); ## adding value of names updating = list(names); updating.append('solus'); names = tuple(updating); print("update names : "); print(names);
AUTHOR = 'Name Lastname' SITENAME = "The name of your website" SITEURL = 'http://example.com' TIMEZONE = "" DISQUS_SITENAME = '' DEFAULT_DATE_FORMAT = '%d/%m/%Y' REVERSE_ARCHIVE_ORDER = True TAG_CLOUD_STEPS = 8 PATH = '' THEME = '' OUTPUT_PATH = '' MARKUP = 'md' MD_EXTENSIONS = 'extra' FEED_RSS = 'feeds/all.rss.xm...
instructor = { "name":"Cosmic", "num_courses":'4', "favorite_language" :"Python", "is_hillarious": False, 44 : "is my favorite number" } # Way to check if a key exists in a dict and returns True or False as a response a = "name" in instructor print(a) b = "phone" in instructor print(b...
""" Write a recursive function that implements the run-length compression technique described in Run-Lenght Decoding Exercise. Your function will take a list or a string as its only argument. It should return the run-length compressed list as its only result. Include a main program that reads a string from the user, ...
# Time: O(m * n) # Space: O(1) # 419 # Given an 2D board, count how many different battleships are in it. # The battleships are represented with 'X's, empty slots are represented with # '.'s. # You may assume the following rules: # # You receive a valid board, made of only battleships or empty slots. # Battleships ca...
""" This module pre-defines colors as defined by the W3C CSS standard: https://www.w3.org/TR/2018/PR-css-color-3-20180315/ """ ALICE_BLUE = (240, 248, 255) ANTIQUE_WHITE = (250, 235, 215) AQUA = (0, 255, 255) AQUAMARINE = (127, 255, 212) AZURE = (240, 255, 255) BEIGE = (245, 245, 220) BISQUE = (255, 228, 19...
#!/usr/bin/python3 """ Transforms a list into a string. """ l = ["I", "am", "the", "law"] print(" ".join(l))
class Solution: def twoSum(self, numbers, target): res = None left = 0 right = len(numbers) - 1 while left < right: result = numbers[left] + numbers[right] if result == target: res = [left + 1, right + 1] break elif ...
class CaesarShiftCipher: def __init__(self, shift=1): self.shift = shift def encrypt(self, plaintext): return ''.join( [self.num_2_char((self.char_2_num(letter) + self.shift) % 26) for letter in plaintext.lower()] ).upper() def decrypt(self, ciphertext: str) -> str: ...
# sToken和sEncodingAESKey来自于企业微信创建的应用 # sCorpID为企业微信号 sToken = "" sEncodingAESKey = "" sCorpID = ""