content
stringlengths
7
1.05M
"""Static variables used in the module""" # Using integers because it shouldn't be matchable to anything in the config ANY = 0 NAME_TO_UPPER = 1 NAME_AS_IS = 2
def request_resolver(func): def _wrapped_view(request, *args, **kwargs): if 'dev' in request.path: kwargs['report_type'] = 'dummy' return func(request, *args, **kwargs) else: kwargs['report_type'] = 'status' return func(request, *args, **kwargs) return _wrapped_view
""" Unmerged conflicts in status, which are one of: DD unmerged, both deleted AU unmerged, added by us UD unmerged, deleted by them UA unmerged, added by them DU unmerged, deleted by us AA unmerged, both added UU unmerged, both modified """ MERGE_CONFLICT_PORCELAIN_STAT...
def return_value(status, message, data=None, status_code=200): return_object = dict() return_object['status'] = status return_object['message'] = message if data: return_object['data'] = data return return_object, status_code
class TxtFile: def read_file(self,PATH_FILE): fd = open(PATH_FILE, mode='r') data = fd.read() fd.close() return data
a=8 b=28 i=0 while(b>=0): b=b-a i=i+1 b=b+a print(b,i)
""" Напишете функция, която намира най-голямото по стойност число, измежду три дадени числа. >>> min3(3, 1, 2) 1 >>> min3(-1, 2, 0) -1 """ def min3(a, b, c): raise Exception('Not implemented')
words = input().split(", ") input_string = input() list_new = [i for i in words if i in input_string] print(list_new)
with open('input', 'r') as raw: i = sorted(raw.read().strip().split('\n')) guard = None sleeping = False start = None change = False guards = {} for line in i: minute = int(line[15:17]) if line[19] == 'f': sleeping = True start = minute elif line[19] == 'w': sleeping = False ...
bind = "0.0.0.0:8000" workers = 10 pythonpath = "/home/box/web/ask" errorlog = "/home/box/web/etc/ask-error.log" loglevel = "debug"
def get_numero(prompt): while True: try: return int(input(prompt)) except ValueError: print("Debes escribir un número") cantidadpar, cantidadimpar, sumatoriapar, sumatoriaimpar = 0, 0, 0, 0 print("Ingrese los valores que desee (presione 0 para terminar)") print("Al me...
# Link to the problem: https://www.hackerrank.com/challenges/common-child/problem def commonChild(s1, s2, n): prev_lcs = [0]*(n+1) curr_lcs = [0]*(n+1) for c1 in s1: curr_lcs, prev_lcs = prev_lcs, curr_lcs for i, c2 in enumerate(s2, 1): curr_lcs[i] = ( 1 + prev_l...
""" Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Example 1: Input: s = "()" Output: true Example 2:...
class database: def __init__(self, conn): self.conn = conn @staticmethod def db_schema(db_conn): db_conn.execute('''CREATE TABLE "computers" ( "id" integer PRIMARY KEY, "ip" text, "hostname" text, "domain" text, "os" text, ...
class Entry: def __init__(self): self.image_path = "" self.image_small = "" self.image_full = "" self.source = "" self.tags = [] self.score = -1 self.headers = {} self.title = None def as_dict(self): return {'path': self.image_path, ...
def mergeIntervals(arr): new = list() arr.sort(key=lambda x:x[0]) for i in range(0, len(arr)): if not new or new[-1][1] < arr[i][0]: new.append(arr[i]) else: new[-1][1] = max(new[-1][1], arr[i][1]) return new arr = [[2,3],[4,5],[6,7],[8,9],[1,10]] new = m...
class Solution: def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: assert isinstance(candidates, list) and isinstance(target, int) if not candidates: return def dfs(l,r,target,rst): if r+1<l or target < 0: retur...
''' Convert English miles to Roman paces Status: Accepted ''' ############################################################################### def main(): """Read input and print output""" paces = 5280000 * float(input()) / 4854 result = int(paces) if paces - result >= 0.5: result += 1 pr...
class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: ans = [] for i in range(2**len(nums)): bitmask = bin(i)[2:] bitmask = '0'*(len(nums)-len(bitmask)) + bitmask ans.append([nums[j] for j in range(len(nums)) if bitmask[j] == '1']) ...
"""Metadata for the FastAPI instance""" # Main TITLE = "Hive Global Notification System (API)" DESCRIPTION = """ Global notification system for dApps on the Hive Blockchain. """ VERSION = "1.0" CONTACT = { "name": "imwatsi", "url": "https://hive.blog/@imwatsi", "email": "imwatsi@outlook.com", } LI...
ACTIVATED_TEXT = 'ACTIVATED' ACTIVATION_DAYS = 7 REMEMBER_ME_DAYS = 30 LOGIN_REDIRECT_URL = 'home' DEFAULT_AVATAR_URL = 'files/no_image/avatar.jpg'
list = ['gilbert', 'cuerbo', 'defante', 'exam'] # for loop for name in list: print(f' - { name }') for i in range(0, 5): print(f' * { i }') # while loop index = 0 while index < len(list): print(f' # {list[index]}') index = index + 1
class BlastLine(object): __slots__ = ('query', 'subject', 'pctid', 'hitlen', 'nmismatch', 'ngaps', \ 'qstart', 'qstop', 'sstart', 'sstop', 'eval', 'score') def __init__(self, sline): args = sline.split("\t") self.query =args[0] self.subject = args[1] self.pcti...
class hosp_features(): def __init__(self): self.P_GOLD = '#FFD700' self.P_ORANGE = "#F08000" self.P_BLU = "#0000FF" self.P_DARK_BLU = "#000080" self.P_GREEN = "#66ff99" self.P_DARK_GREEN = "#026b2c" self.P_FUCHSIA = "#FF00FF" self.P_PURPLE = "#cf0...
''' This problem was asked by Apple. Implement a queue using two stacks. Recall that a queue is a FIFO (first-in, first-out) data structure with the following methods: enqueue, which inserts an element into the queue, and dequeue, which removes it. ''' class FIFOQueue: def __init__(self): self.in_stack = ...
class FileType(object): """The MIME type of the content you are attaching to an Attachment.""" def __init__(self, file_type=None): """Create a FileType object :param file_type: The MIME type of the content you are attaching :type file_type: string, optional """ self._fi...
class Fee(object): def __init__(self): self.default_fee = 10 self.fee_cushion = 1.2 def calculate_fee(self): return int(self.default_fee * self.fee_scale * self.load_scale) def set_fee_scale(self, tx): fee_base = float(tx['fee_base']) fee_ref = float(tx['fee_ref']) fee_scale = fee_base / fee_ref ...
# O(n) solution, check all elements class Solution: def isPeak(self, arr, n): if n==0: if arr[n] > arr[n+1]: return True else: return False if n == len(arr)-1: if arr[n] > arr[n-1]: return True ...
def cls(): while(i<=15): print('\n') i=i+1
class DurationTrackingListener(object): ROBOT_LISTENER_API_VERSION = 3 # The following will measure the duration of each test. This listener will fail each test if they run beyond the maximum run time (max_seconds). def __init__(self, max_seconds=10): self.max_milliseconds = float(max_seconds) * 1000 ...
class Solution: def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int: # pick each ele to be maximum ele # Then sliding windows res = 0 for ind,num in enumerate(nums): # num itself is in or not if left <= num <= right: ...
class Simulation: def __init__(self, blocks): self._blocks = blocks self._finished = False def run(self): while not self._finished: self._step() def _step(self): visited = set() queue = [b for b in self._blocks if not b.inputs] nothing_changed = ...
def plus(arr): p, n, z = 0, 0, 0 for i in arr: if i>0: p+=1 elif i<0: n+=1 else: z+=1 print(format(p/len(arr), '.6f')) print(format(n/len(arr), '.6f')) print(format(z/len(arr), '.6f')) arr = list(map(int, input().rstrip().split())) plus(a...
# Mary McHale, 14th April 2018 # Project based on Iris Data, Working out the mean # https://docs.python.org/3/tutorial/floatingpoint.html?highlight=significant%20digits for reducing the number of decimal places in the mean f = open('data/iris.csv' , 'r') # This opens the file called iris.csv print("Means are bel...
numbers = [4,2,7,1,8,3,6] f = 0 x = int(input("Enter the number to be found out: ")) for i in range(len(numbers)): if (x==numbers[i]): print(" Successful search, the element is found at position", i) f = 1 break if(f==0): print("Oops! Search unsuccessful")
"""Variant 3""" current_day = float(10) percent = 1.1 summa = 0 for i in range(7): summa += current_day current_day *= percent print("Ran in 7 days: %.3f" % summa)
a_binary_string = "110000 1100110 1011111" binary_values = a_binary_string.split() ascii_string = "" for binary_value in binary_values: an_integer = int(binary_value, 2) ascii_character = chr(an_integer) ascii_string += ascii_character print(ascii_string)
n= str(input('Qual seu nome completo?')).lower() print ('No seu nome tem Silva?','silva'in n) n1= str(input('Digite um numero:')) print ('Existe o numero 1?','1' in n1)
data = ( 'Qiao ', # 0x00 'Chou ', # 0x01 'Bei ', # 0x02 'Xuan ', # 0x03 'Wei ', # 0x04 'Ge ', # 0x05 'Qian ', # 0x06 'Wei ', # 0x07 'Yu ', # 0x08 'Yu ', # 0x09 'Bi ', # 0x0a 'Xuan ', # 0x0b 'Huan ', # 0x0c 'Min ', # 0x0d 'Bi ', # 0x0e 'Yi ', # 0x0f 'Mian ', # 0x10 'Yon...
[[0,3],[2,7],[3,4],[4,6]] [0,6] def find_min_intervals(intervals, target): intervals.sort() res = 0 cur_target = target[0] i = 0 max_step = 0 while i < len(intervals) and cur_target < target[1]: while i < len(intervals) and intervals[i][0] <= cur_target: max_step = max(max_...
class TaskHandler(): def __init__(self, tasks=[]): self.tasks = tasks def add(self): pass def delete(self): pass def clear_all(self): pass def show_info(self): pass class Task(): def __init__(self, task_name, sub_tasks, date): self.task_name ...
BOT_NAME = 'czech_political_parties' SPIDER_MODULES = ['czech_political_parties.spiders'] USER_AGENT = 'czech-political-parties (+https://github.com/honzajavorek/czech-political-parties)' FEED_EXPORTERS = { 'sorted_json': 'czech_political_parties.exporters.SortedJsonItemExporter', } FEEDS = { 'items.json': ...
class Document(object): """Output of pipeline""" def __init__(self): self.sentences = [] # List of sentence objects def __iter__(self): return iter(self.sentences) @property def stuples(self): """Semantic tuples from every sentences""" return [stuple for sent in s...
# # This file contains the Python code from Program 7.20 of # "Data Structures and Algorithms # with Object-Oriented Design Patterns in Python" # by Bruno R. Preiss. # # Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved. # # http://www.brpreiss.com/books/opus7/programs/pgm07_20.txt # class Polynomial(C...
"""https://github.com/stevecshanks/lift-kata/blob/master/tests/SmallControllerTest.php""" class Person: def __init__(self, name, current_floor, destination): pass class SmallLift: def __init__(self, floor): pass def getTotalNumberOfVisits(self): return 0 class SmallControlle...
class JWTExtendedException(Exception): """ Base except which all flask_graphql_auth errors extend """ pass class JWTDecodeError(JWTExtendedException): """ An error decoding a JWT """ pass class NoAuthorizationError(JWTExtendedException): """ An error raised when no authoriz...
#This is a freestlye by yah boy Chuka def displayItems(offSet): print('\n') for i in enumerate(items[offSet:]): print(i[0]+offSet+1,i[1]) def displaySingle(): userItem=int(input("Enter a number to select an item: "))-1 print(f'{descriptions[userItem]}\n{items[userItem]} costs ${prices[userItem...
#Given an int array length 2, return True if it contains a 2 or a 3. #has23([2, 5]) → True #has23([4, 3]) → True #has23([4, 5]) → False def has23(lis): return 2 in lis or 3 in lis
def minion_game(s): ls = 'AEIOU' a = 0 b = 0 n = len(s) for i in range(0,n): val = n - i if ls.find(s[i]) == -1: a += val else: b += val if a > b: print('Stuart',a) elif b > a: print('Kevin',b) else: print('Draw') s = input() minion_game(s)
"""***************************************************************************** * Copyright (C) 2019 Microchip Technology Inc. and its subsidiaries. * * Subject to your compliance with these terms, you may use Microchip software * and any derivatives exclusively with Microchip products. It is your * responsibility to ...
n = 500 # This is the final formula after lots of counting. # First notice how squares are on the upper right diagonal, # then work you way towards the total. print(int(1 + 2 / 3 * n * (8 * n ** 2 + 15 * n + 13)))
def solution(citations) : max_comp = max(citations) hindex = [] for comp in range(max_comp+1) : count = 0 for citation in citations : if comp <= citation : count += 1 if comp <= count : hindex.append(comp) br...
a = int(input('Digete um valor: ')) print(type(a)) b = bool(input('Digete um valor: ')) print(type(b)) c = float(input('Digete um valor: ')) print(type(c)) d = str(input('Digete um valor: ')) print(type(d))
# -*- coding: utf-8 -*- # Helper functions def return_sublist(main_list, indices ): sublist = [[item[i] for i in indices] for item in main_list] return sublist
total = 0 totmil = 0 menor = 0 cont = 0 barato = ' ' while True: produto = str(input('Produto: ')) preco = float(input('Preço R$')) cont += 1 total += preco if preco > 1000: totmil += 1 if cont == 1 or preco < menor: menor = preco barato = produto resp = ' ' whi...
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") def github_archive(org, repo, version, ext): return "https://github.com/{org}/{repo}/archive/{version}.{ext}".format( org=org, repo=repo, version=version, ext=ext) def github_prefix(repo, version): return "{repo}-{version}".format(...
# -*- coding: utf-8 -*- A = input() B = input() X = A + B print ("X = %i" %X)
""" 'a1m' is the boiler and everything around that. Example: { "SlaveId": 1, "BaudRate": 3, "Parity": 0, "FirmwareVersion": 30012, "DetectedSystemType": 1, "FaultCode": 8000, "SystemState": 1, "OperatingMode": 0, "OperatingModeDHW": 1, ...
# -*- coding: utf-8 -*- # ____________________________________________________________________ BaseModel class BaseEstimator(): """The base class that every model used for :class:`skassist` must inherit from. It defines the interface through which the module trains the model and makes predictions. It also ...
class UnwrapError(Exception): pass class RedisProtocolFormatError(Exception): pass class ExceptionWithReplyError(Exception): def __init__(self, reply="ERR", *args): super().__init__(*args) self.reply = reply class NoPasswordError(ExceptionWithReplyError): pass class WrongComman...
second_name = "Соколов" Name = 24 l = [5, 4, 3, 2, 1] a = b = c = 10
def set_isic_configs(args): args.batch_size = 128 args.fixmatch_k_img = 8192 args.simclr_batch_size = 512 args.stop_labeled = 9134 args.add_labeled = 1015 args.start_labeled = 203 args.merged = False args.pseudo_labeling_num = 20264 - args.stop_labeled if args.novel_class_detection:...
linha = '\033[1;96m=\033[m' * 50 print(linha) print('CALCULO SALARIAL COM DESCONTOS'.center(50)) print(linha) def salario(): ganho_hora = float(input('\nDigite o quanto você ganha por hora: ')) horas = int(input('\nDigite as horas que você trabalhou no mês: ')) print(f'\n{linha}') bruto = ganho_hora ...
############################################################################### # Define everything needed to build nightly Julia for gc debugging ############################################################################### julia_gc_debug_factory = util.BuildFactory() julia_gc_debug_factory.useProgress = True julia...
n,k=map(int,input().split()) l=[int(x) for x in input().split()] l.sort() s=set([]) ans=0 for i in l: if i%k==0: if i//k not in s: s.add(i) ans+=1 else: ans+=1 s.add(i) print(ans) # https://codeforces.com/problemset/problem/274/A
""" @author Huaze Shen @date 2019-08-01 """ def max_sub_array(nums): return helper(nums, 0, len(nums) - 1) def helper(nums, left, right): if left == right: return nums[left] p = (left + right) // 2 left_sum = helper(nums, left, p) right_sum = helper(nums, p + 1, right) cross_sum = cr...
num = int(input('digite um numero: ')) total = 0 for c in range(1, num + 1): if num % c == 0: print('\033[33m', end=' ') total = total + 1 else: print('\033[31m', end=' ') print('{}'.format(c), end=' ') print('\n\033[m0 o numero {} foi dividido {} veses '.format(num, total)) if total...
def fib(n): if n <= 1: return n tab = [i for i in range(n+1)] tab[0] = 0 tab[1] = 1 for i in range(2, n + 1): tab[i] = tab[i-1] + tab[i-2] return tab[n] if __name__ == '__main__': print(fib(4))
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode: def helper(arr): if not arr: retur...
class Settings(): """存储《外星人入侵》的所有设置的类""" def __init__(self): """初始化游戏的设置""" #屏幕设置 self.screen_width = 1200 self.screen_height = 800 self.bg_color = (230,230,230) self.ship_speed_factor = 20 #子弹设置 self.bullet_speed_factor = 20 self.bullet_width = 3 self.bullet_height = 15 self.bullet_color = 60...
# -*- coding: utf-8 -*- def test_config_profile(pepper_cli, session_minion_id): '''Test the using a profile''' ret = pepper_cli('*', 'test.ping', profile='pepper') assert ret[session_minion_id] is True
''' Candies and two Sisters ''' t = int(input()) for i in range(t): n = int(input()) half = n // 2 method = n - 1 - half print(method)
def infer_breach(value, lowerLimit, upperLimit): if value < lowerLimit: return 'TOO_LOW' if value > upperLimit: return 'TOO_HIGH' return 'NORMAL' def classify_temperature_breach(coolingType, temperatureInC): reference_for_upperLimit = { 'PASSIVE_COOLING' : [0,35], 'HI_ACTIVE_COOLING' ...
# -*- coding: utf-8 -*- # # "config" here is a python module that must have "parser" function. # That function should generate signature of the email and # pass that to "eeas" object (passed as arg) methods. # Not calling any of these would mean that email can't be classified. # # Already present in the namespace: it,...
{ 'variables': { 'firmware_path': '../src', 'lpc18xx_path': '../lpc18xx', 'usb_path': '../deps/usb', 'runtime_path': "../deps/runtime", 'builtin_path': '../builtin', 'tools_path': '../tools', 'otp_path': '../otp', 'erase_path': '../erase', 'boot_path': '../boot', 'cc3k_path': '...
def find_low_index(arr, key): low = 0 high = len(arr) - 1 mid = int(high / 2) # Binary Search while low <= high: mid_elem = arr[mid] if mid_elem < key: low = mid + 1 else: high = mid - 1 mid = low + int((high - low) / 2) if low < len(arr...
#!/usr/bin/env python3 # # Utility functions # # Author: Joe Block <jblock@zscaler.com> # License: Apache 2.0 # Copyright 2022, ZScaler Inc. def dumpObject(obj): """ Dump an object for debugging """ for attr in dir(obj): print("obj.%s = %r" % (attr, getattr(obj, attr)))
# https://leetcode.com/problems/sqrtx/ class Solution: def mySqrt(self, x): i = 0 while x > i * i: i += 1 return i - 1
def sort(a: list) -> list: for i in range(len(a) - 1): for j in range(len(a) - i - 1): if a[j] > a[j + 1]: a[j], a[j + 1] = a[j + 1], a[j] return a a = [5, 6, 7, 8, 1, 2, 0, 3, 4, 5, 9] print(sort(a))
# ------------------------------------ # CODE BOOLA 2015 PYTHON WORKSHOP # Mike Wu, Jonathan Chang, Kevin Tan # Puzzle Challenges Number 5 # ------------------------------------ # Last one of the group! # You a deserve a break after this one. # ------------------------------------ # INSTRUCTIONS: # Let's keep w...
BASE_PHRASES = """ **** ahead Be wary of **** Try **** Need **** Imminent ****... Weakness:**** **** ****? Good Luck I did it! Here! I can't take this... Praise the Sun! """.strip().split("\n") FILL_PHRASES = """ Enemy Tough enemy Hollow Soldier Knight Sniper Caster Giant Skeleton Ghost Bug Poison bug Lizard Drake Fli...
def verbose_on(*args, **kwargs): """ dumb wrapper for print, see verbose_off and verbose """ print(*args, **kwargs) def verbose_off(*args, **kwargs): """ dummy function provides alternative to verbose_off """ _ = args, kwargs # dumb way of doing optional verbose output, see verbose...
def jumps(lines, part2): a = 0 steps = 0 while a < len(lines): val = lines[a] if part2 and val > 2: lines[a] = lines[a] - 1 else: lines[a] += 1 a += val steps += 1 return steps lines = [] with open("inputs/5.txt") as f: for line in f:...
def digit_stack(commands): value, stack = 0, [] for cmd in commands: if ' ' in cmd: stack.append(int(cmd[-1])) elif stack: value += stack[-1] if cmd == 'PEEK' else stack.pop() return value
print("Format is fghjstei:t:____n") print("Letters to ignore : Letters to include (yellow) : Letters correctly placed (green)") clue = input("What's the clue? ").split(':') #clue = "arosearose::_____".split(':') ignore = clue[0] use = clue[1] placed = clue[2] print(ignore, use, placed, " criteria letters.") with open...
class Product: def __init__(self, name, price, recipe): self.name = name self.price = price self.recipe = recipe def get_price(self): return self.price def make(self): print(self.recipe) class CashBox: def __init__(self): self.credit = 0 #why do i ...
#TESTS is a dict with all you tests. #Keys for this will be categories' names. #Each test is dict with # "input" -- input data for user function # "answer" -- your right answer # "explanation" -- not necessary key, it's using for additional info in animation. TESTS = { "1. Small By Hand 1 (Example)": [ { ...
# -*- coding: utf-8 -*- """ Created on Fri Feb 2 12:37:51 2018 @author: User """ def graph(src, dest): paths = {} paths['A'] = ['A', 'B', 'C','D', 'E', 'F', 'G'] paths['B'] = ['B', 'D', 'F', 'G'] for key, value in paths.items(): if src in key: if dest in value: ...
# -*- encoding:utf-8 -*- u""" ================================== Input and output (:mod:`scipy.io`) ================================== .. currentmodule:: scipy.io SciPy has many modules, classes, and functions available to read data from and write data to a variety of file formats. .. seealso:: :ref:`numpy-reference...
class Solution: def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool: """ 0 1 2 3 [1,3,2,1] t = 2, k = 2 ^ num 8 t = 2 left = 8 - 2 = 6 right = 8 + 2 = 10 0 1 2 3 4 5 [5,10,10] ...
soma = 0 cont = 0 for c in range(1,7): n = int(input('Digite o {}º valor: '.format(c))) if n % 2 == 0: soma += n cont += 1 print('Você informou {} números PARES e a soma foi {}.'.format(cont, soma))
height=4.5 h_inch=height*12 h_meter=(height*2.54)/100 print('Height is ',h_inch,'inch') print('Height is ',h_meter,'meter')
with open("advent5.txt", "r") as file: input_ = file.read().split('\n') row_ids = [] for seat in input_: rows = seat[:7] cols = seat[7:] row_range = range(128) for letter in rows: middle_index = len(row_range)//2 if letter == "F": row_range = row_range[:middle_index] ...
# -*- coding: utf-8 -*- FILE_NAME = '.gitignore' def read_file(): """Read gitignore file and return its data. :return: gitignore data """ with open(FILE_NAME) as f: data = f.read() return data def write_file(data): """Write in gitignore file :param data: the data to be insert in...
shepherd = "Mary" age = 32 stuff_in_string = "Shepherd {} is {} years old.".format(shepherd, age) print(stuff_in_string) shepherd = "Martha" age = 34 # Note f before first quote of string stuff_in_string = "Shepherd %s is %d years old." % (shepherd, age) print(stuff_in_string)
def dict_contains(child_dict, parent_dict): for key, value in child_dict.items(): if key not in parent_dict: return False if parent_dict[key] != value: return False return True
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: words = s.split(' ') patternMap, wordMap = {}, {} if len(pattern) != len(words): return False for index, char in enumerate(pattern): if char in patternMap: if patternMap[char]...
#!/usr/bin/env python # # Copyright (c) 2015 Pavel Lazar pavel.lazar (at) gmail.com # # The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. ##################################################################### class ClickConfiguration(object): REQUIREMENTS_PATTERN = 'require(package "{package}");' ...
scale = 1000000 prime_checker = [i for i in range(scale + 1)] prime_checker[1] = 0 for i in range(2, int(scale ** 0.5) + 1): if prime_checker[i] != 0: for j in range(2, (scale // i) + 1): prime_checker[i * j] = 0 for _ in range(int(input())): count = 0 k = int(input()) for a in ran...
def findDecision(obj): #obj[0]: Passanger, obj[1]: Time, obj[2]: Coupon, obj[3]: Gender, obj[4]: Age, obj[5]: Children, obj[6]: Education, obj[7]: Occupation, obj[8]: Income, obj[9]: Bar, obj[10]: Coffeehouse, obj[11]: Restaurant20to50, obj[12]: Direction_same, obj[13]: Distance # {"feature": "Distance", "instances": ...