content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CON...
class Sensor: def __init__(self, black_level, saturation, ccm, camera_name): self.black_level = black_level self.saturation = saturation self.ccm = ccm self.camera_name = camera_name def to_dict(self): return {'camera_name': self.camera_name, 'black_level': self.black_l...
#def init(): #Global Variables #global sim_start_time sim_start_time = '2014-02-01 00:00:00' #global DatumLong #original coloseum DatumLong = 12.492373 #Eastwards DatumLong = 12.4420 #global DatumLat #original coloseum DatumLat = 41.890251 #Northwards DatumLat = 41.9280 #map bounds in paper #(41.856, 12.442),(41.928...
sim_start_time = '2014-02-01 00:00:00' datum_long = 12.442 datum_lat = 41.928
class Color(DefaultColor): HOSTNAME_FG = 231 HOSTNAME_BG = 23 HOME_SPECIAL_DISPLAY = False JOBS_FG = 15 JOBS_BG = 31
class Color(DefaultColor): hostname_fg = 231 hostname_bg = 23 home_special_display = False jobs_fg = 15 jobs_bg = 31
#!/usr/bin/env python """ AWS signature verification exceptions. """ class InvalidSignatureError(Exception): """ An exception indicating that the signature on the request was invalid. """ pass # Local variables: # mode: Python # tab-width: 8 # indent-tabs-mode: nil # End: # vi: set expandtab tabstop=8...
""" AWS signature verification exceptions. """ class Invalidsignatureerror(Exception): """ An exception indicating that the signature on the request was invalid. """ pass
def tabcompare(source, target): s_last_deal = 0 n = 0 with open('result.txt', 'w') as f: for s in source: for t in target: print('compare {} and {}'.format(s, t)) s_last_deal = s if s < t: f.write(str(s)) ...
def tabcompare(source, target): s_last_deal = 0 n = 0 with open('result.txt', 'w') as f: for s in source: for t in target: print('compare {} and {}'.format(s, t)) s_last_deal = s if s < t: f.write(str(s)) ...
# Time: O(n) # Space: O(1) def findThreeLargestNumbers(array): threeLargestNumbers = [None, None, None] for num in array: updateLargest(threeLargestNumbers, num) return threeLargestNumbers def updateLargest(threeLargest, num): if threeLargest[2] is None or num > threeLargest[2]: shift...
def find_three_largest_numbers(array): three_largest_numbers = [None, None, None] for num in array: update_largest(threeLargestNumbers, num) return threeLargestNumbers def update_largest(threeLargest, num): if threeLargest[2] is None or num > threeLargest[2]: shift_and_update(threeLarge...
INF = 999999 def print_distances(graph, from_vertex=0): num_vertices = len(graph) dists = [ INF ] * num_vertices visited = [ False ] * num_vertices dists[from_vertex] = 0 for k in range(num_vertices - 1): min_dist, vertex = INF, -1 for v in range(num_vertices): if...
inf = 999999 def print_distances(graph, from_vertex=0): num_vertices = len(graph) dists = [INF] * num_vertices visited = [False] * num_vertices dists[from_vertex] = 0 for k in range(num_vertices - 1): (min_dist, vertex) = (INF, -1) for v in range(num_vertices): if not vi...
# Created by MechAviv # Sheep Damage Skin | (2436721) if sm.addDamageSkin(2436721): sm.chat("'Sheep Damage Skin' Damage Skin has been added to your account's damage skin collection.") sm.consumeItem()
if sm.addDamageSkin(2436721): sm.chat("'Sheep Damage Skin' Damage Skin has been added to your account's damage skin collection.") sm.consumeItem()
class Solution: def checkPerfectNumber(self, num): """ :type num: int :rtype: bool """ if num <= 1: return False return sum(self.getFactors(num)) == num def getFactors(self, num): sqrt_num = int(math.sqrt(num)) # 1 is always a facto...
class Solution: def check_perfect_number(self, num): """ :type num: int :rtype: bool """ if num <= 1: return False return sum(self.getFactors(num)) == num def get_factors(self, num): sqrt_num = int(math.sqrt(num)) factors = set([1]) ...
# Space: O(1) # Time: O(n) class NumMatrix: def __init__(self, matrix): self.board = matrix def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int: res = 0 for y in range(row1, row2 + 1): for x in range(col1, col2 + 1): res += self.board[y]...
class Nummatrix: def __init__(self, matrix): self.board = matrix def sum_region(self, row1: int, col1: int, row2: int, col2: int) -> int: res = 0 for y in range(row1, row2 + 1): for x in range(col1, col2 + 1): res += self.board[y][x] return res
name = "Sophie" number = 24811 print (number) number -= 20 name += "!!!" print (name) print (number) age = 20016 age -= 20005 print ("Sophie is %s" % name)
name = 'Sophie' number = 24811 print(number) number -= 20 name += '!!!' print(name) print(number) age = 20016 age -= 20005 print('Sophie is %s' % name)
class CrudSerializer: get_list_response_model = None get_item_response_model = None update_item_request_model = None update_item_response_model = None create_item_request_model = None create_item_response_model = None remove_item_response_model = None
class Crudserializer: get_list_response_model = None get_item_response_model = None update_item_request_model = None update_item_response_model = None create_item_request_model = None create_item_response_model = None remove_item_response_model = None
name = "Jan Maximilan Schaffranek" result = name.find("an") if result == -1: print("Not found") else: print("Found at index: ", result) name2 = name.replace("Jan", "Yann") print(name) print(name2) name3 = name.upper() print(name3) name4 = name.lower() print(name4) name5 = name.split(" ") print(name5)...
name = 'Jan Maximilan Schaffranek' result = name.find('an') if result == -1: print('Not found') else: print('Found at index: ', result) name2 = name.replace('Jan', 'Yann') print(name) print(name2) name3 = name.upper() print(name3) name4 = name.lower() print(name4) name5 = name.split(' ') print(name5) count = na...
class CommandSyntaxException(Exception): CONTEXT_AMOUNT = 50 def __init__(self, exc_type, message, str_input=None, cursor=-1): super().__init__(message) self.type = exc_type self.message = message self.input = str_input self.cursor = cursor def get_message(self)...
class Commandsyntaxexception(Exception): context_amount = 50 def __init__(self, exc_type, message, str_input=None, cursor=-1): super().__init__(message) self.type = exc_type self.message = message self.input = str_input self.cursor = cursor def get_message(self): ...
x = True y = False print(x and y) # False print(x or y) # True print(not x) # False print(bool(10)) # True print(bool(0)) # False print(bool('')) # False print(bool('0')) # True print(bool('False')) # True print(bool([])) # False print(bool([False])) # True x = 10 # True y = 0 # False print(x and y) # 0 ...
x = True y = False print(x and y) print(x or y) print(not x) print(bool(10)) print(bool(0)) print(bool('')) print(bool('0')) print(bool('False')) print(bool([])) print(bool([False])) x = 10 y = 0 print(x and y) print(x or y) print(not x) x = 10 y = 100 print(x and y) print(y and x) print(x or y) print(y or x) x = 0 y =...
"Mirror of release info" TOOL_VERSIONS = { "v1.2.185": { "android-arm-eabi": "sha384-a9NRmV90j+tXV7xT3+LK+UBcUgKMVRp9k4yz29hKi7VRqwIQxuL3aKAcyP1mXCly", "android-arm64": "sha384-rdQq6yIfkTZtuhYiIz2eo0/Y1MuPDAGqf4See2ZPYRnzF6owWSAkU1MzUnKlwvas", "darwin-arm64": "sha384-hMId2tsrNKrkOUH5MLGmNfR...
"""Mirror of release info""" tool_versions = {'v1.2.185': {'android-arm-eabi': 'sha384-a9NRmV90j+tXV7xT3+LK+UBcUgKMVRp9k4yz29hKi7VRqwIQxuL3aKAcyP1mXCly', 'android-arm64': 'sha384-rdQq6yIfkTZtuhYiIz2eo0/Y1MuPDAGqf4See2ZPYRnzF6owWSAkU1MzUnKlwvas', 'darwin-arm64': 'sha384-hMId2tsrNKrkOUH5MLGmNfRo/MplSwiRGjdTYg2OuFJEHa3fy4...
a, b = input().split() a = int(a) b = int(b) if a < b: c = b % a if(c == 0): print('Sao Multiplos') else: print('Nao sao Multiplos') else: c = a % b if (c == 0): print('Sao Multiplos') else: print('Nao sao Multiplos')
(a, b) = input().split() a = int(a) b = int(b) if a < b: c = b % a if c == 0: print('Sao Multiplos') else: print('Nao sao Multiplos') else: c = a % b if c == 0: print('Sao Multiplos') else: print('Nao sao Multiplos')
def MFnComponent_elementCount(*args, **kwargs): pass def MFloatMatrix_isEquivalent(*args, **kwargs): pass def MTrimBoundaryArray_insert(*args, **kwargs): pass def boolPtr_value(*args, **kwargs): pass def MQuaternion_setToZAxis(*args, **kwargs): pass def MDataBlock_inputArrayValue(*args, **...
def m_fn_component_element_count(*args, **kwargs): pass def m_float_matrix_is_equivalent(*args, **kwargs): pass def m_trim_boundary_array_insert(*args, **kwargs): pass def bool_ptr_value(*args, **kwargs): pass def m_quaternion_set_to_z_axis(*args, **kwargs): pass def m_data_block_input_array_va...
expected_output = { 'prefixes':{ '/misc/config':{ 'size':'48648003584', 'free':'42960707584', 'type':'flash', 'flags':'rw' }, 'tftp:':{ 'size':'0', 'free':'0', 'type':'network', 'flags':'rw' }, 'disk2:':{ ...
expected_output = {'prefixes': {'/misc/config': {'size': '48648003584', 'free': '42960707584', 'type': 'flash', 'flags': 'rw'}, 'tftp:': {'size': '0', 'free': '0', 'type': 'network', 'flags': 'rw'}, 'disk2:': {'size': '4008443904', 'free': '3018457088', 'type': 'flash-disk', 'flags': 'rw'}, 'ftp:': {'size': '0', 'free'...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ############################################################################## # Thesis code # A model that emulates players' actions in the Settlers of Catan (SOC) game # based on linguistic references and previous actions. # # Data: jSettlers game logs (.soclog) # Autho...
class Devcard: """ A class used to present a development card In the Settlers of Catan there are 25 development cards: 14 knight cards 2 Road Building cards 2 Monopoly cards 2 Discovery cards 5 Victory Point cards Attributes ---------- cardType : i...
class QuickUnion: def __init__(self, N): self._id = list(range(N)) self._count = N self._rank = [0] * N def find(self, p): id = self._id while p != id[p]: p = id[p] = id[id[p]] # Path compression using halving. return p def union(self, p, q): ...
class Quickunion: def __init__(self, N): self._id = list(range(N)) self._count = N self._rank = [0] * N def find(self, p): id = self._id while p != id[p]: p = id[p] = id[id[p]] return p def union(self, p, q): id = self._id rank =...
class Solution: def intToRoman(self, num: int) -> str: roman_dict = { "I": 1, "IV": 4, "V": 5, "IX": 9, "X": 10, "XL": 40, "L": 50, "XC":90, "C": 100, "CD": 400, "D": 500, ...
class Solution: def int_to_roman(self, num: int) -> str: roman_dict = {'I': 1, 'IV': 4, 'V': 5, 'IX': 9, 'X': 10, 'XL': 40, 'L': 50, 'XC': 90, 'C': 100, 'CD': 400, 'D': 500, 'MD': 900, 'M': 1000} roman_list = [] for (k, v) in reversed(roman_dict.items()): while num > 0: ...
class Node: def __init__(self, val, children): self.val = val self.children = children class Solution: def levelOrder(self, root: 'Node') -> list: q, ans = [root], [] while any(q): ans.append([item.val for item in q]) q = [child for item in q for child i...
class Node: def __init__(self, val, children): self.val = val self.children = children class Solution: def level_order(self, root: 'Node') -> list: (q, ans) = ([root], []) while any(q): ans.append([item.val for item in q]) q = [child for item in q for c...
avancer() droite() avancer() gauche() avancer() droite() for _ in range(16): avancer() ouvrir()
avancer() droite() avancer() gauche() avancer() droite() for _ in range(16): avancer() ouvrir()
def apply(df, remove_common=False, include_activity_timest_in_key=False): """ Dataframe to grouped stream Parameters ------------- df Dataframe Returns ------------- grouped_stream Grouped stream of events """ stream = df.to_dict('r') grouped_stream = {} ...
def apply(df, remove_common=False, include_activity_timest_in_key=False): """ Dataframe to grouped stream Parameters ------------- df Dataframe Returns ------------- grouped_stream Grouped stream of events """ stream = df.to_dict('r') grouped_stream = {} ...
class Solution: def intToRoman(self, num): s = "M" * (num // 1000) s += "CM" if num % 1000 >= 900 else "D" *((num % 1000) // 500) s += "CD" if num % 500 >= 400 and s[-2:] != "CM" else "C" * ((num % 500) // 100) if num % 500 < 400 else "" s += "XC" if num % 100 >= 90 else "L" * ((num...
class Solution: def int_to_roman(self, num): s = 'M' * (num // 1000) s += 'CM' if num % 1000 >= 900 else 'D' * (num % 1000 // 500) s += 'CD' if num % 500 >= 400 and s[-2:] != 'CM' else 'C' * (num % 500 // 100) if num % 500 < 400 else '' s += 'XC' if num % 100 >= 90 else 'L' * (num %...
class Solution: def minScoreTriangulation(self, A: List[int]) -> int: memo = {} def dp(i, j): if (i, j) not in memo: memo[i, j] = min([dp(i, k) + dp(k, j) + A[i] * A[j] * A[k] for k in range(i + 1, j)] or [0]) return memo[i, j] return dp(0, len(A) - 1)
class Solution: def min_score_triangulation(self, A: List[int]) -> int: memo = {} def dp(i, j): if (i, j) not in memo: memo[i, j] = min([dp(i, k) + dp(k, j) + A[i] * A[j] * A[k] for k in range(i + 1, j)] or [0]) return memo[i, j] return dp(0, len(A) ...
"""Kata for tuples""" print("Hello Tuples!") mytuple = ('abcd', 786, 2.23, 'john', 70.2) tinytuple = (123, 'john') print(mytuple) # Prints complete tuple print(mytuple[0]) # Prints first element of the tuple print(mytuple[1:3]) # Prints elements starting from 2nd till 3rd print(mytuple[2:]...
"""Kata for tuples""" print('Hello Tuples!') mytuple = ('abcd', 786, 2.23, 'john', 70.2) tinytuple = (123, 'john') print(mytuple) print(mytuple[0]) print(mytuple[1:3]) print(mytuple[2:]) print(tinytuple * 2) print(mytuple + tinytuple)
S = input() check = [-1] * 26 for i in range(len(S)): if check[ord(S[i]) - 97] != -1: continue else: check[ord(S[i]) - 97] = i for i in range(26): print(check[i], end=' ')
s = input() check = [-1] * 26 for i in range(len(S)): if check[ord(S[i]) - 97] != -1: continue else: check[ord(S[i]) - 97] = i for i in range(26): print(check[i], end=' ')
l=range(1,50) #l=[1,2,6,99,455,21111111,5] print(type(l)) max=0 for i in l: if i>max : max=i print(f"max is {max}")
l = range(1, 50) print(type(l)) max = 0 for i in l: if i > max: max = i print(f'max is {max}')
class StorageInteractions: def __init__(self, **repositories): self._storage_repository = repositories["storage_repository"] def load(self, name): return self._storage_repository.load_file(name) def store(self, file): name = self._storage_repository.store_file(file) return...
class Storageinteractions: def __init__(self, **repositories): self._storage_repository = repositories['storage_repository'] def load(self, name): return self._storage_repository.load_file(name) def store(self, file): name = self._storage_repository.store_file(file) return...
"""The core module of ``soulsgym`` provides all necessary interfaces to the Dark Souls III process. At the lowest level we directly manipulate the game memory with the :mod:`.memory_manipulator`. The :mod:`.game_interface` acts as an abstraction layer and allows us to interact with the game as if we had access to the ...
"""The core module of ``soulsgym`` provides all necessary interfaces to the Dark Souls III process. At the lowest level we directly manipulate the game memory with the :mod:`.memory_manipulator`. The :mod:`.game_interface` acts as an abstraction layer and allows us to interact with the game as if we had access to the ...
########################################################## # Author: Raghav Sikaria # LinkedIn: https://www.linkedin.com/in/raghavsikaria/ # Github: https://github.com/raghavsikaria # Last Update: 16-5-2020 # Project: LeetCode May 31 Day 2020 Challenge - Day 16 ##########################################################...
class Solution: def odd_even_list(self, head: ListNode) -> ListNode: if head == None: return None odd_node = head even_node = head.next even_head = even_node while even_node is not None: if odd_node is None or even_node.next is None: b...
n=int(input("Tabuada de: ")) x=1 while x<=10: print(n*x) x=x+1
n = int(input('Tabuada de: ')) x = 1 while x <= 10: print(n * x) x = x + 1
# -*- coding: utf-8 -*- # # Copyright (C) 2021 CERN. # Copyright (C) 2021 Data Futures. # # OCFL Core is free software; you can redistribute it and/or modify it under the # terms of the MIT License; see LICENSE file for more details. """Storage implementations for OCFL.""" class Storage: """Base class for the st...
"""Storage implementations for OCFL.""" class Storage: """Base class for the storage APIs.""" def write(self, file_path, stream): """Write stream to the given file path. File path is relative to the OCFL storage root. """ raise NotImplementedError def move(self, other_sto...
class BasePOI: def __init__(self, lat, lng,value): self.lat = lat self.lng = lng self.value = value def __repr__(self): return ','.join(list(map(str, (self.lat, self.lng, self.value)))) # models realted to the db tables class Anemity(BasePOI): def __i...
class Basepoi: def __init__(self, lat, lng, value): self.lat = lat self.lng = lng self.value = value def __repr__(self): return ','.join(list(map(str, (self.lat, self.lng, self.value)))) class Anemity(BasePOI): def __init__(self, lat, lng, anemity_type, name): Bas...
# exception classes class Error(Exception): pass class ParameterError(Error): pass
class Error(Exception): pass class Parametererror(Error): pass
class ListViewItemSelectionChangedEventArgs(EventArgs): """ Provides data for the System.Windows.Forms.ListView.ItemSelectionChanged event. ListViewItemSelectionChangedEventArgs(item: ListViewItem,itemIndex: int,isSelected: bool) """ def __getitem__(self,*args): """ x.__getitem__(y) <==> x[y] """ p...
class Listviewitemselectionchangedeventargs(EventArgs): """ Provides data for the System.Windows.Forms.ListView.ItemSelectionChanged event. ListViewItemSelectionChangedEventArgs(item: ListViewItem,itemIndex: int,isSelected: bool) """ def __getitem__(self, *args): """ x.__getitem__(y) <==> x[y] "...
#!/usr/bin/env python3 """example settings """ # list of ports to listen react upon ports = [ 8888 ] # broadcast address that triggers the forwarding olddest = "10.0.2.255" # list of new destination ranges for the modified packet newdestranges = [ "10.0.2.0/24" ] # show the original and modified packet? # Only enab...
"""example settings """ ports = [8888] olddest = '10.0.2.255' newdestranges = ['10.0.2.0/24'] showpacks = False iface = 'em0'
input_file = "/Users/jrawling/Documents/Physics/DeadConeAnalysis/ATLASWork/samples/ttj/output.root" input_file = "/Users/jrawling/Documents/Physics/DeadConeAnalysis/ATLASWork/samples/ttj/410501_minisample.root" input_file = "/Users/jrawling/Documents/Physics/DeadConeAnalysis/ATLASWork/samples/ttj/410501.root" ...
input_file = '/Users/jrawling/Documents/Physics/DeadConeAnalysis/ATLASWork/samples/ttj/output.root' input_file = '/Users/jrawling/Documents/Physics/DeadConeAnalysis/ATLASWork/samples/ttj/410501_minisample.root' input_file = '/Users/jrawling/Documents/Physics/DeadConeAnalysis/ATLASWork/samples/ttj/410501.root' detector_...
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def middleNode(self, head): currNode = head count = 0 while currNode: currNode = currNode.next count += 1 middle = count // 2 + 1 ...
class Listnode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def middle_node(self, head): curr_node = head count = 0 while currNode: curr_node = currNode.next count += 1 middle = count // 2 + 1 ...
def pressureInFluid(f_perpendicular, A): """ variables: f_perpendicular = normal force A = area""" p=f_perpendicular/A return p def bulkStress(dp, dV, V0): """variables: dp=change in fluid pressure dV=change in subject volume V0=original s...
def pressure_in_fluid(f_perpendicular, A): """ variables: f_perpendicular = normal force A = area""" p = f_perpendicular / A return p def bulk_stress(dp, dV, V0): """variables: dp=change in fluid pressure dV=change in subject volume V0=ori...
async def test_make_coro(make_coro): coro = make_coro(1) assert 1 == await coro()
async def test_make_coro(make_coro): coro = make_coro(1) assert 1 == await coro()
# https://i.gyazo.com/38682c2adf56d01422a7266f62c4794f.png instruments = [ 'Acoustic Grand Piano', 'Bright Acoustic Piano', 'Electric Grand Piano', 'Honky tonk Piano', 'Electric Piano 1', 'Electric Piano 2', 'Harpsichord', 'Clavi', 'Celesta', 'Glockenspiel', 'Music Box', ...
instruments = ['Acoustic Grand Piano', 'Bright Acoustic Piano', 'Electric Grand Piano', 'Honky tonk Piano', 'Electric Piano 1', 'Electric Piano 2', 'Harpsichord', 'Clavi', 'Celesta', 'Glockenspiel', 'Music Box', 'Vibraphone', 'Marimba', 'Xylophone', 'Tubular Bells', 'Dulcimer', 'Drawbar Organ', 'Percussive Organ', 'Roc...
trick.real_time_enable() trick.exec_set_software_frame(0.1) # Instantiate the keyboard. Make sure you change the arguments to match your keyboard's # vendor and product IDs keyboard = trick.UsbKeyboard(0x413C, 0x2101) example.add(keyboard) # SingleFlightController's construtor takes the six Inputs we want to use for ...
trick.real_time_enable() trick.exec_set_software_frame(0.1) keyboard = trick.UsbKeyboard(16700, 8449) example.add(keyboard) roll = trick.CompositeInput() roll.addInput(keyboard.keypad9) roll.addInput(keyboard.keypad7, -1) pitch = trick.CompositeInput() pitch.addInput(keyboard.keypad8) pitch.addInput(keyboard.keypad2, -...
#pragma error #pragma repy global foo foo = 2
global foo foo = 2
def input_natural(): num = int(input("Digite o valor de n: ")) return num num = input_natural() fatorial = 1 if num < 0: input_natural() else: for i in range(1, num+1): fatorial += fatorial * (num - i) print(fatorial)
def input_natural(): num = int(input('Digite o valor de n: ')) return num num = input_natural() fatorial = 1 if num < 0: input_natural() else: for i in range(1, num + 1): fatorial += fatorial * (num - i) print(fatorial)
"import rules" load("@io_bazel_rules_dotnet//dotnet/private:context.bzl", "dotnet_context") load("@io_bazel_rules_dotnet//dotnet/private:common.bzl", "as_iterable") load("@io_bazel_rules_dotnet//dotnet/private:providers.bzl", "DotnetLibraryInfo") load("@io_bazel_rules_dotnet//dotnet/private:rules/common.bzl", "collect...
"""import rules""" load('@io_bazel_rules_dotnet//dotnet/private:context.bzl', 'dotnet_context') load('@io_bazel_rules_dotnet//dotnet/private:common.bzl', 'as_iterable') load('@io_bazel_rules_dotnet//dotnet/private:providers.bzl', 'DotnetLibraryInfo') load('@io_bazel_rules_dotnet//dotnet/private:rules/common.bzl', 'coll...
def authenticate_as(client, username, password): token = client.post( "/auth/authenticate/", {"username": username, "password": password} ).data["token"] client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")
def authenticate_as(client, username, password): token = client.post('/auth/authenticate/', {'username': username, 'password': password}).data['token'] client.credentials(HTTP_AUTHORIZATION=f'Bearer {token}')
class BinaryIndexedTree: """ A toy Binary Indexed Tree data structure that caches element sums (only numbers are considerred), for efficiently qurying/modifying subarray sums O(log(n)) modify and O(log(n)) query """ def __init__(self, A): """ :type A: list """ ...
class Binaryindexedtree: """ A toy Binary Indexed Tree data structure that caches element sums (only numbers are considerred), for efficiently qurying/modifying subarray sums O(log(n)) modify and O(log(n)) query """ def __init__(self, A): """ :type A: list """ ...
class BaseDatabaseValidation: """Encapsulate backend-specific validation.""" def __init__(self, connection): self.connection = connection def check(self, **kwargs): return [] def check_field(self, field, **kwargs): errors = [] # Backends may implement a check_field_typ...
class Basedatabasevalidation: """Encapsulate backend-specific validation.""" def __init__(self, connection): self.connection = connection def check(self, **kwargs): return [] def check_field(self, field, **kwargs): errors = [] if hasattr(self, 'check_field_type') and (...
# Huu Hung Nguyen # 10/07/2021 # Nguyen_HuuHung_donuts.py # Constants for price dozen and single of plain donuts, # and price dozen and single of fancy donuts. # The program prompts the user for the number of plain and fancy donuts. # It then calculates and displays the number of dozens and single donuts # for e...
price_dozen_plain = 7.0 price_single_plain = 0.6 price_dozen_fancy = 9.0 price_single_fancy = 0.8 dozen = 12 plain = int(input('Enter number of plain donuts you want to buy: ')) fancy = int(input('Enter number of fancy donuts you want to buy: ')) dozen_plain = plain // DOZEN single_plain = plain % DOZEN dozen_fancy = f...
""" Tuple Length To determine how many items a tuple has, use the len() method: """ thistuple = ("apple", "banana", "cherry") print(len(thistuple))
""" Tuple Length To determine how many items a tuple has, use the len() method: """ thistuple = ('apple', 'banana', 'cherry') print(len(thistuple))
file = open("input.txt", 'r') out_string = '' for segment in file.read().split('.'): out_string += segment.split(':')[0] + '@@' out = open('hello.html', 'w') out.write('<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<link rel=\"stylesheet\" href=\"https://www...
file = open('input.txt', 'r') out_string = '' for segment in file.read().split('.'): out_string += segment.split(':')[0] + '@@' out = open('hello.html', 'w') out.write('<meta charset="UTF-8">\n<meta name="viewport" content="width=device-width, initial-scale=1">\n<link rel="stylesheet" href="https://www.w3schools.co...
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ if s is None: return False if len(s) == 0: return True stack = [] for i in range(len(s)): c = s[i] if self._isLeftParenthese...
class Solution(object): def is_valid(self, s): """ :type s: str :rtype: bool """ if s is None: return False if len(s) == 0: return True stack = [] for i in range(len(s)): c = s[i] if self._isLeftParenthe...
""" API 5L Add dictionary of API pipe sizes """ sizes = {406.4: [4.8, 5.2, 5.6, 6.4, 7.1, 7.9, 8.7, 9.5, 10.3, 11.1, 11.9, 12.7, 14.3, 15.9, 17.5, 19.1, 20.6, 22.2, 23.8, 25.4, 27, 28.6, 30.2, 31.8], 457: [4.8, 5.6, 6.4, 7.1, 7.9, 8.7, 9.5, 10.3, 11.1, 11.9, 12.7, ...
""" API 5L Add dictionary of API pipe sizes """ sizes = {406.4: [4.8, 5.2, 5.6, 6.4, 7.1, 7.9, 8.7, 9.5, 10.3, 11.1, 11.9, 12.7, 14.3, 15.9, 17.5, 19.1, 20.6, 22.2, 23.8, 25.4, 27, 28.6, 30.2, 31.8], 457: [4.8, 5.6, 6.4, 7.1, 7.9, 8.7, 9.5, 10.3, 11.1, 11.9, 12.7, 14.3, 15.9, 17.5, 19.1, 20.6, 22.2, 23.8, 25.4, 27, 28...
class SingletonMeta(type): _instance = None def __call__(self): if self._instance is None: self._instance = super().__call__() return self._instance
class Singletonmeta(type): _instance = None def __call__(self): if self._instance is None: self._instance = super().__call__() return self._instance
def func1(): pass def func2(arg): print(arg)
def func1(): pass def func2(arg): print(arg)
def prefix_suffix(w, m): B, t = [-1] + [0] * m, -1 for i in range(1, m + 1): while t >= 0 and w[t + 1] != w[i]: t = B[t] # prefikso-sufiks to relacja przechodnia t = t + 1 B[i] = t return B
def prefix_suffix(w, m): (b, t) = ([-1] + [0] * m, -1) for i in range(1, m + 1): while t >= 0 and w[t + 1] != w[i]: t = B[t] t = t + 1 B[i] = t return B
# data_list = [(x, y), ...] b = np.matrix(map(lambda pair: [pair[1]], data_list)) a = np.matrix(map(lambda pair: [e**(d * pair[0]), e**(-d * pair[0]), 1], data_list))
b = np.matrix(map(lambda pair: [pair[1]], data_list)) a = np.matrix(map(lambda pair: [e ** (d * pair[0]), e ** (-d * pair[0]), 1], data_list))
#!/usr/bin/env python3 # _*_ coding:utf-8 _* # Parent class has to inherit from "object" class class Parent(object): def __init__(self): print("parent constructor called!")
class Parent(object): def __init__(self): print('parent constructor called!')
def sieve(number): prime = [True for i in range(number+1)] p = 2 while (p * p <= number): if (prime[p] == True): for i in range(p * p, number+1, p): prime[i] = False p += 1 primes = [] for p in range(2, number+1): if prime[p]: primes.ap...
def sieve(number): prime = [True for i in range(number + 1)] p = 2 while p * p <= number: if prime[p] == True: for i in range(p * p, number + 1, p): prime[i] = False p += 1 primes = [] for p in range(2, number + 1): if prime[p]: primes....
def main(): with open('input.txt', 'r') as f: lines = f.readlines() d = dict() for li in lines: s1, s2 = li.strip().split(')') d[s2] = s1 total_links = 0 for s2,s1 in d.items(): while s1: total_links += 1 s1 = d.get(s1, None) print(tota...
def main(): with open('input.txt', 'r') as f: lines = f.readlines() d = dict() for li in lines: (s1, s2) = li.strip().split(')') d[s2] = s1 total_links = 0 for (s2, s1) in d.items(): while s1: total_links += 1 s1 = d.get(s1, None) print(tot...
def reversible_count(d): if d % 4 == 1: return 0 # 2 digits: no carry over, and sum of two digits is odd # 2 digits => 20 # 4 digits: outer pair is the same as 2 digits # inner pair has 30 possibilities because 0 is allowed if d % 4 == 0 or d % 4 == 2: return 20 * 30 **...
def reversible_count(d): if d % 4 == 1: return 0 if d % 4 == 0 or d % 4 == 2: return 20 * 30 ** (d // 2 - 1) if d % 4 == 3: return 100 * 500 ** ((d - 3) // 4) print(sum([reversible_count(d) for d in range(1, 10)]))
def get_user_quota(user): """ Tiny helper for getting quota dict for user (left mostly for backward compatibility) """ return user.userplan.plan.get_quota_dict()
def get_user_quota(user): """ Tiny helper for getting quota dict for user (left mostly for backward compatibility) """ return user.userplan.plan.get_quota_dict()
class Locators(): base_url = "https://www.amazon.com.tr/" search_box_locator_id = "twotabsearchtextbox" search_box_text = "samsung galaxy m12" search_summit_button_id = "nav-search-submit-button" close_cookie_name = "accept" product_title = "productTitle" product = "span[class='a-size-base-p...
class Locators: base_url = 'https://www.amazon.com.tr/' search_box_locator_id = 'twotabsearchtextbox' search_box_text = 'samsung galaxy m12' search_summit_button_id = 'nav-search-submit-button' close_cookie_name = 'accept' product_title = 'productTitle' product = "span[class='a-size-base-plu...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]: lenA = 0 lenB = 0 tempA = h...
class Solution: def get_intersection_node(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]: len_a = 0 len_b = 0 temp_a = headA temp_b = headB while tempA: len_a += 1 temp_a = tempA.next while tempB: len_b += 1 ...
SEARCH_WORD_LIST = ['woman', 'wear', 'skirt']#['cat', 'and', 'dog'] SECRET_FILE = "./engine/data/refer/azure_secret_sample.json"# be careful not to expose! SAVE_DIR = "./engine/data/tmp" SAVE_PAR_DIR = "./engine/data/tmp/bingimgs" OBJINFO_PATH = "./engine/data/tmp/obj.json" AZURE_DICT = "./engine/data/tmp/azure_rel_di...
search_word_list = ['woman', 'wear', 'skirt'] secret_file = './engine/data/refer/azure_secret_sample.json' save_dir = './engine/data/tmp' save_par_dir = './engine/data/tmp/bingimgs' objinfo_path = './engine/data/tmp/obj.json' azure_dict = './engine/data/tmp/azure_rel_dict/search_word.pkl'
# Given a binary tree, find the length of the longest consecutive sequence path. # The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections. # The longest consecutive path need to be from parent to child (cannot be the reverse). # Example 1: # Input: ...
class Treenode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def longest_consecutive(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 stack ...
class DottedDict(dict): __slots__ = () def __getattr__(self, item): return self[item] def __setattr__(self, name, value): self[name] = value
class Dotteddict(dict): __slots__ = () def __getattr__(self, item): return self[item] def __setattr__(self, name, value): self[name] = value
class xsort(): # to find the max number in list we can # use max() function in python def findMax(_list): mout = _list[0] for i in _list: if i >= mout: mout = i return mout def run(_list): list_ = [] for i in range(len(_list...
class Xsort: def find_max(_list): mout = _list[0] for i in _list: if i >= mout: mout = i return mout def run(_list): list_ = [] for i in range(len(_list)): big = xsort.findMax(_list) list_.insert(0, big) _l...
class Currying(object): def __init__(self, fun): self.fun = fun self.argc = fun.__code__.co_argcount self.argl = () def __call__(self, *args): tmp = self.argl + args if len(tmp) >= self.argc: return self.fun(*tmp) curr = Currying(self.fun) cur...
class Currying(object): def __init__(self, fun): self.fun = fun self.argc = fun.__code__.co_argcount self.argl = () def __call__(self, *args): tmp = self.argl + args if len(tmp) >= self.argc: return self.fun(*tmp) curr = currying(self.fun) cu...
class Entity(object): def __init__(self, entity_input_config): if type(entity_input_config) is not dict: #self._ha_api.log("Config error, not a dict check your entity configs") self.entityId = "error" self.nameOverride = None self.iconOverride = None e...
class Entity(object): def __init__(self, entity_input_config): if type(entity_input_config) is not dict: self.entityId = 'error' self.nameOverride = None self.iconOverride = None else: self.entityId = entity_input_config.get('entity', 'unknown') ...
imgurr = { 1: "https://i.imgur.com/ZF6TzS4.jpg", 2: "https://i.imgur.com/eaSvBJR.jpg", 3: "https://i.imgur.com/bDoDm2W.jpg", 4: "https://i.imgur.com/5mCbYFU.jpg", 5: "https://i.imgur.com/zfnmieg.jpg", 6: "https://i.imgur.com/lLCL9qv.jpg", 7: "https://i.imgu...
imgurr = {1: 'https://i.imgur.com/ZF6TzS4.jpg', 2: 'https://i.imgur.com/eaSvBJR.jpg', 3: 'https://i.imgur.com/bDoDm2W.jpg', 4: 'https://i.imgur.com/5mCbYFU.jpg', 5: 'https://i.imgur.com/zfnmieg.jpg', 6: 'https://i.imgur.com/lLCL9qv.jpg', 7: 'https://i.imgur.com/F0i1BLU.jpg', 8: 'https://i.imgur.com/7OIXQLG.jpg', 9: 'ht...
""" ============ constants.py ============ Physical constants for astronomy & astrophysics Classes ======= Constant: Defines a physical constant for use in astronomical or physical computation. A Constant instance is defined by its value, description, and units attributes. """ class Constant(float): "...
""" ============ constants.py ============ Physical constants for astronomy & astrophysics Classes ======= Constant: Defines a physical constant for use in astronomical or physical computation. A Constant instance is defined by its value, description, and units attributes. """ class Constant(float): ""...
SEED_PORT = 12345 SEED_ADDR = ('192.168.1.100', 5000) UPDATE_INTERVAL = 20 BUFFER_SIZE = 102400 ALIVE_TIMEOUT = 20
seed_port = 12345 seed_addr = ('192.168.1.100', 5000) update_interval = 20 buffer_size = 102400 alive_timeout = 20
class Inside: """ check is value is in target or not value : any target : any """ def __init__(self, value): self.value = str(value) def is_in(self, target): """ check value in target :param target: any :return: bool """ validate = ...
class Inside: """ check is value is in target or not value : any target : any """ def __init__(self, value): self.value = str(value) def is_in(self, target): """ check value in target :param target: any :return: bool """ validate = t...
class Scanner(object): def __init__(self, regex, code): self.regex_list = regex self.code = code self.tokens = self.scan(code) def match_regex(self, i, line): start = line[i:] for regex, token in self.regex_list: tok = regex.match(start) if to...
class Scanner(object): def __init__(self, regex, code): self.regex_list = regex self.code = code self.tokens = self.scan(code) def match_regex(self, i, line): start = line[i:] for (regex, token) in self.regex_list: tok = regex.match(start) if tok...
CONFIGURATION_NAMESPACE = 'qmap' # It is here and not inside the manager module to avoid circular imports EXECUTION_ENV_FILE_NAME = 'execution' EXECUTION_METADATA_FILE_NAME = 'execution' class QMapError(Exception): """Base class for this package errors""" pass
configuration_namespace = 'qmap' execution_env_file_name = 'execution' execution_metadata_file_name = 'execution' class Qmaperror(Exception): """Base class for this package errors""" pass
def test_get_test(mocked_response, testrail_client, test_data, test): mocked_response(data_json=test_data) api_test = testrail_client.tests.get_test(test_id=1) assert api_test == test def test_get_tests(mocked_response, testrail_client, test_data, test): mocked_response(data_json=[test_data]) a...
def test_get_test(mocked_response, testrail_client, test_data, test): mocked_response(data_json=test_data) api_test = testrail_client.tests.get_test(test_id=1) assert api_test == test def test_get_tests(mocked_response, testrail_client, test_data, test): mocked_response(data_json=[test_data]) api_t...
""" 836. Rectangle Overlap Easy An axis-aligned rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) is the coordinate of its bottom-left corner, and (x2, y2) is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the...
""" 836. Rectangle Overlap Easy An axis-aligned rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) is the coordinate of its bottom-left corner, and (x2, y2) is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the...
# script that contains some path definitions path = '../' input_path = path + 'input_files/' output_path = path + 'output_files/' plot_path = path + 'plots/' rand_path = path + 'QBCHL_random_graphs/' rand_prefix = 'HQBCL_rand_network_'
path = '../' input_path = path + 'input_files/' output_path = path + 'output_files/' plot_path = path + 'plots/' rand_path = path + 'QBCHL_random_graphs/' rand_prefix = 'HQBCL_rand_network_'
#!/usr/bin/python # list_comprehension2.py lang = "Python" a = [] for e in lang: a.append(ord(e)) b = [ord(e) for e in lang] print (a) print (b)
lang = 'Python' a = [] for e in lang: a.append(ord(e)) b = [ord(e) for e in lang] print(a) print(b)
''' Created on Sep 2, 2010 @author: Wilder Rodrigues (wilder.rodrigues@ekholabs.nl) '''
""" Created on Sep 2, 2010 @author: Wilder Rodrigues (wilder.rodrigues@ekholabs.nl) """
COINS = [25, 21, 10, 5, 1] def min_coins_dp(coin_values, change, min_coins): for cents in range(change + 1): coin_count = cents potential_coins_to_use = [coin for coin in coin_values if coin <= cents] for potential_coin in potential_coins_to_use: balance = cents - potential_c...
coins = [25, 21, 10, 5, 1] def min_coins_dp(coin_values, change, min_coins): for cents in range(change + 1): coin_count = cents potential_coins_to_use = [coin for coin in coin_values if coin <= cents] for potential_coin in potential_coins_to_use: balance = cents - potential_coin...
miTupla = ("Pablo", 35, "Jole", 33) print(miTupla[:]) print("Cambio la tupla a lista") miLista = list(miTupla) print(miLista[:]) print("Lo vuelvo a pasar a tupla") miTupla2 = tuple(miLista) print(miTupla2[:]) print("Cuento los elementos en la tupla") print(miTupla2.count("Jole")) print("Pido el tota...
mi_tupla = ('Pablo', 35, 'Jole', 33) print(miTupla[:]) print('Cambio la tupla a lista') mi_lista = list(miTupla) print(miLista[:]) print('Lo vuelvo a pasar a tupla') mi_tupla2 = tuple(miLista) print(miTupla2[:]) print('Cuento los elementos en la tupla') print(miTupla2.count('Jole')) print('Pido el total de elementos en...
""" 656. Multiply Strings The length of both num1 and num2 is < 110. Both num1 and num2 contains only digits 0-9. Both num1 and num2 does not contain any leading zero. You must not use any built-in BigInteger library or convert the inputs to integer directly. """ class Solution: """ @param num1: a non-negativ...
""" 656. Multiply Strings The length of both num1 and num2 is < 110. Both num1 and num2 contains only digits 0-9. Both num1 and num2 does not contain any leading zero. You must not use any built-in BigInteger library or convert the inputs to integer directly. """ class Solution: """ @param num1: a non-negati...
def isPerfect( n ): # To store sum of divisors sum = 1 # Find all divisors and add them i = 2 while i * i <= n: if n % i == 0: sum = sum + i + n/i i += 1 # If sum of divisors is equal to # n, then n is a perfect number return (True if s...
def is_perfect(n): sum = 1 i = 2 while i * i <= n: if n % i == 0: sum = sum + i + n / i i += 1 return True if sum == n and n != 1 else False n = int(input()) for i in range(n): if is_perfect(i): print(i, end=' ')
class Solution: def maxProduct(self, nums: List[int]) -> int: ans=cmin=cmax=nums[0] for i in nums[1:]: cmin,cmax = min(i,cmin*i,cmax*i),max(i,cmin*i,cmax*i) if cmax>ans: ans = cmax return ans...
class Solution: def max_product(self, nums: List[int]) -> int: ans = cmin = cmax = nums[0] for i in nums[1:]: (cmin, cmax) = (min(i, cmin * i, cmax * i), max(i, cmin * i, cmax * i)) if cmax > ans: ans = cmax return ans
# # PySNMP MIB module TY1250I-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TY1250I-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:20:47 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 0...
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, single_value_constraint, value_range_constraint, constraints_intersection, constraints_union) ...
#!/usr/bin/env python """ Memory Loss github.com/irlrobot/memory_loss """ QUESTIONS = [ { "question": "Remember these words, Epic, Bird, Taco, Sphere. "\ "Was the second word, bird?", "answer": "yes" }, # { # "question": "Remember these words, Map, Computer, Fish, ...
""" Memory Loss github.com/irlrobot/memory_loss """ questions = [{'question': 'Remember these words, Epic, Bird, Taco, Sphere. Was the second word, bird?', 'answer': 'yes'}, {'question': 'Remember these numbers, 27, 22, 28, 25. Was the first number 26?', 'answer': 'no'}]
# list > list def op(x): return x * x # [1, 2, 3] > [1, 4, 9] # [1, 2, 3] > [op(1), op(2), op(3)] > [1, 4, 9] numbers = [1, 2, 3] squared = map(op, numbers) squared_lc = [op(x) for x in numbers] print(numbers) print(squared) """ a_list = [1,3,4,5,"aa"] def op(x): return "***{}***".format(x) adjust = m...
def op(x): return x * x numbers = [1, 2, 3] squared = map(op, numbers) squared_lc = [op(x) for x in numbers] print(numbers) print(squared) '\na_list = [1,3,4,5,"aa"]\n\ndef op(x):\n return "***{}***".format(x)\n\nadjust = map(op, a_list)\n\n\nfor x in adjust:\n print (x)\n\n\n'
""" LeetCode Problem: 7. Reverse Integer Link: https://leetcode.com/problems/reverse-integer/ Language: Python Written by: Mostofa Adib Shakib Time Complexity: O(N) Space Complexity: O(N) """ class Solution: def reverse(self, x: int) -> int: if -9 <= x <= 9: return x ans = 0 ...
""" LeetCode Problem: 7. Reverse Integer Link: https://leetcode.com/problems/reverse-integer/ Language: Python Written by: Mostofa Adib Shakib Time Complexity: O(N) Space Complexity: O(N) """ class Solution: def reverse(self, x: int) -> int: if -9 <= x <= 9: return x ans = 0 f...
""" Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 elements by 1. Example: Input: [1,2,3] Output: 3 Explanation: Only three moves are needed (remember each move increments two elements): [1,2,3] => [2,3,3]...
""" Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 elements by 1. Example: Input: [1,2,3] Output: 3 Explanation: Only three moves are needed (remember each move increments two elements): [1,2,3] => [2,3,3]...
# 1417. Reformat The String - LeetCode # https://leetcode.com/problems/reformat-the-string/ class Solution: def reformat(self, s: str) -> str: ret = "" alphabets = [] numbers = [] for c in s: if c.isdigit(): numbers.append(c) if c.isa...
class Solution: def reformat(self, s: str) -> str: ret = '' alphabets = [] numbers = [] for c in s: if c.isdigit(): numbers.append(c) if c.isalpha(): alphabets.append(c) if abs(len(alphabets) - len(numbers)) > 1: ...
print("INFORMACION: ","si es Ejecutivo:0","Jefe:1","Externo:2") cargo=int(input("ingrese el cargo del trabajador")) if cargo==0: sueldo=90 elif cargo==1: sueldo=100 else: sueldo=50 print("Su sueldo es: ",sueldo)
print('INFORMACION: ', 'si es Ejecutivo:0', 'Jefe:1', 'Externo:2') cargo = int(input('ingrese el cargo del trabajador')) if cargo == 0: sueldo = 90 elif cargo == 1: sueldo = 100 else: sueldo = 50 print('Su sueldo es: ', sueldo)
#String Ex1 #---------- ### Work in your pynet_test repository ### #a. Create a python script with three strings representing three names #b. Print these three names out in a column 30 wide, right aligned #c. Execute the script verify the output #d. Add a prompt for a fourth name, print this out as well #e. check yo...
name1 = 'Rudy' name2 = 'Tom' name3 = 'Greg' print('{:>30} {:>30} {:>30}'.format(name1, name2, name3))
''' You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. Example: [[1,2,3], ...
""" You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. Example: [[1,2,3], ...
class Solution: # One Pass (Accepted), O(n) time, O(1) space def maxScore(self, s: str) -> int: _max = cur = ones = 0 for i in range(1, len(s)-1): if s[i] == '0': cur += 1 _max = max(cur, _max) else: cur -= 1 ...
class Solution: def max_score(self, s: str) -> int: _max = cur = ones = 0 for i in range(1, len(s) - 1): if s[i] == '0': cur += 1 _max = max(cur, _max) else: cur -= 1 ones += 1 return int(s[0] == '0') + ...
class Solution1(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ for item in nums: if item ==target: return nums.index(target) return -1 class Solution2(object): def search(s...
class Solution1(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ for item in nums: if item == target: return nums.index(target) return -1 class Solution2(object): def search...