content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
class Solution: def findReplaceString(self, S: str, indexes: List[int], sources: List[str], targets: List[str]) -> str: sl = list(S) for i, source, target in sorted(zip(indexes, sources, targets), reverse=True): if S[i: i + len(source)] == source: sl[i: i + len(source)] =...
class Solution: def find_replace_string(self, S: str, indexes: List[int], sources: List[str], targets: List[str]) -> str: sl = list(S) for (i, source, target) in sorted(zip(indexes, sources, targets), reverse=True): if S[i:i + len(source)] == source: sl[i:i + len(source)...
def sanitize_version(raw_version): if raw_version[0] == 'v': return raw_version[1:] elif raw_version.startswith('release/'): return raw_version[8:] return raw_version
def sanitize_version(raw_version): if raw_version[0] == 'v': return raw_version[1:] elif raw_version.startswith('release/'): return raw_version[8:] return raw_version
NORTH, EAST, SOUTH, WEST = 1, 2, 3, 4 _directional_advances = {NORTH: (0, 1), EAST: (1, 0), SOUTH: (0, -1), WEST: (-1, 0)} _possible_moves = {'L': 'turn_left', 'R': 'turn_right', 'A': 'advance'} def tuple_add(a, b): return tuple([item1 +...
(north, east, south, west) = (1, 2, 3, 4) _directional_advances = {NORTH: (0, 1), EAST: (1, 0), SOUTH: (0, -1), WEST: (-1, 0)} _possible_moves = {'L': 'turn_left', 'R': 'turn_right', 'A': 'advance'} def tuple_add(a, b): return tuple([item1 + item2 for (item1, item2) in zip(a, b)]) class Robot: def __init__(s...
p = int(input()) x = int(input()) y = int(input()) full_price = x + y / 100 full_price *= (1 + p / 100) full_price = round(full_price, 4) print(int(full_price), int(full_price * 100 % 100))
p = int(input()) x = int(input()) y = int(input()) full_price = x + y / 100 full_price *= 1 + p / 100 full_price = round(full_price, 4) print(int(full_price), int(full_price * 100 % 100))
def onPointcloud(name): polyData = pointcloudMap.take(name) if polyData: obj = vis.updatePolyData(polyData, name, colorByName='intensity', parent='ROS') if not obj.getChildFrame(): vis.addChildFrame(obj) pointcloudMap.connect('objectAssigned(const QString&)', onPointcloud)
def on_pointcloud(name): poly_data = pointcloudMap.take(name) if polyData: obj = vis.updatePolyData(polyData, name, colorByName='intensity', parent='ROS') if not obj.getChildFrame(): vis.addChildFrame(obj) pointcloudMap.connect('objectAssigned(const QString&)', onPointcloud)
#!/usr/bin/env python HMDSyntaxDefault = { # primitive 'STRING': r"[A-Za-z?'_]+", 'NUMBER': r'[\d]+', 'SPACE': r'[ ]+', # rule binding 'RULE_BEGIN': r'[(]', 'RULE_END': r'[)]', # match: positive 'MATCH_NEXT': r'[+]', 'MATCH_BEFORE': r'[-]', 'MATCH_ALWAYS': r'[@]', # ...
hmd_syntax_default = {'STRING': "[A-Za-z?'_]+", 'NUMBER': '[\\d]+', 'SPACE': '[ ]+', 'RULE_BEGIN': '[(]', 'RULE_END': '[)]', 'MATCH_NEXT': '[+]', 'MATCH_BEFORE': '[-]', 'MATCH_ALWAYS': '[@]', 'MATCH_NOT': '[!]', 'GRAMMAR_HAT': '[\\^]', 'GRAMMAR_WILD': '[%]', 'GRAMMAR_OR': '[|]', 'VARIABLE_IDENTIFIER': '[$]', 'VARIABLE_...
__version__ = "1.0.0" __name__ = "Test Mod" __modid__ = "Test_Mod" __main__ = "testmod.py"
__version__ = '1.0.0' __name__ = 'Test Mod' __modid__ = 'Test_Mod' __main__ = 'testmod.py'
API_URL = "https://www.metaweather.com/api/" API_METHODS = { "Location Search": "location/search/", "Location Day": "location/{woeid}/{date}/", } RAIN_STATES = [ "Heavy Rain", "Light Rain", "Showers", ]
api_url = 'https://www.metaweather.com/api/' api_methods = {'Location Search': 'location/search/', 'Location Day': 'location/{woeid}/{date}/'} rain_states = ['Heavy Rain', 'Light Rain', 'Showers']
# How to convert a list to a string in python? # https://youtu.be/24ZIhX30NPo def lst_to_str_with_loops(lst): output = '' for item in lst: output += str(item) # output += ' ' + str(item) return repr(output) def lst_to_str_with_join(lst): return repr(','.join(lst)) def lst_to_str_with_...
def lst_to_str_with_loops(lst): output = '' for item in lst: output += str(item) return repr(output) def lst_to_str_with_join(lst): return repr(','.join(lst)) def lst_to_str_with_lst_comprehension(lst): return repr(''.join([str(item) for item in lst])) def lst_to_str_with_map(lst): re...
class DataParserF8(object): def __init__(self, ch): self.ch = ch ###################################### @property def roomT(self): return self.ch.get_value()[1] ###################################### @property def waterT(self): return self.ch.get_value()[2] ################...
class Dataparserf8(object): def __init__(self, ch): self.ch = ch @property def room_t(self): return self.ch.get_value()[1] @property def water_t(self): return self.ch.get_value()[2] @property def electro_meter_t1(self): return self.ch.get_value()[4] @...
class FilterModule(object): def filters(self): return { 'normalize_sasl_protocol': self.normalize_sasl_protocol, 'kafka_protocol_normalized': self.kafka_protocol_normalized, 'kafka_protocol': self.kafka_protocol, 'kafka_protocol_defaults': self.kafka_protocol_...
class Filtermodule(object): def filters(self): return {'normalize_sasl_protocol': self.normalize_sasl_protocol, 'kafka_protocol_normalized': self.kafka_protocol_normalized, 'kafka_protocol': self.kafka_protocol, 'kafka_protocol_defaults': self.kafka_protocol_defaults, 'get_sasl_mechanisms': self.get_sasl_m...
# https://leetcode.com/problems/concatenation-of-array/submissions/ class Solution: def getConcatenation(self, nums: List[int]) -> List[int]: return 2*nums
class Solution: def get_concatenation(self, nums: List[int]) -> List[int]: return 2 * nums
# An implementation that uses a storage array as the backing # for the min heap. In order to emulate a binary tree structure, # we have the following rules: # 1. We can calculate a parent node's left child with the # formula `index * 2 + 1`. # 2. We can calculate a parent node's right child with the # formula `i...
class Heap: def __init__(self): self.storage = [] def insert(self, value): self.storage.append(value) self._bubbleUp(len(self.storage) - 1) def delete(self): if len(self.storage) == 0: return if len(self.storage) == 1: return self.storage.po...
# This is a sample quisk_conf.py configuration file for Microsoft Windows. # For Windows, your default config file name is "My Documents/quisk_conf.py", # but you can use a different config file by using -c or --config. Quisk creates # an initial default config file if there is none. To control Quisk, edit # "My Doc...
sample_rate = 48000 name_of_sound_capt = 'Primary' name_of_sound_play = 'Primary' latency_millisecs = 150 default_screen = 'Graph'
''' Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. If target is not found in the array, return [-1, -1]. You must write an algorithm with O(log n) runtime complexity. Example 1: Input: nums = [5,7,7,8,8,10], target = 8 Output: [3,4] Exampl...
""" Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. If target is not found in the array, return [-1, -1]. You must write an algorithm with O(log n) runtime complexity. Example 1: Input: nums = [5,7,7,8,8,10], target = 8 Output: [3,4] Exampl...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ============================================================================= # # ============================================================================= __author__ = 'Chet Coenen' __copyright__ = 'Copyright 2020' __credits__ = ['Chet Coenen'] __license__ = '/LICE...
__author__ = 'Chet Coenen' __copyright__ = 'Copyright 2020' __credits__ = ['Chet Coenen'] __license__ = '/LICENSE' __version__ = '1.0' __maintainer__ = 'Chet Coenen' __email__ = 'chet.m.coenen@icloud.com' __socials__ = '@Denimbeard' __status__ = 'Complete' __description__ = 'Insert Sort Algorithm' __date__ = '30 Novemb...
class Solution: def smallestCommonElement(self, mat: List[List[int]]) -> int: x={} for i in range(len(mat)): for j in range(len(mat[0])): if mat[i][j] not in x: x[mat[i][j]]=1 else: x[mat[i][j]]+=1 if...
class Solution: def smallest_common_element(self, mat: List[List[int]]) -> int: x = {} for i in range(len(mat)): for j in range(len(mat[0])): if mat[i][j] not in x: x[mat[i][j]] = 1 else: x[mat[i][j]] += 1 ...
def Writerecord(sroll,sname,sperc,sremark): with open ('StudentRecord.dat','ab') as Myfile: srecord={"SROLL":sroll,"SNAME":sname,"SPERC":sperc, "SREMARKS":sremark} pickle.dump(srecord,Myfile) def Readrecord(): with open ('StudentRecord.dat','rb') as Myfile: ...
def writerecord(sroll, sname, sperc, sremark): with open('StudentRecord.dat', 'ab') as myfile: srecord = {'SROLL': sroll, 'SNAME': sname, 'SPERC': sperc, 'SREMARKS': sremark} pickle.dump(srecord, Myfile) def readrecord(): with open('StudentRecord.dat', 'rb') as myfile: print('\n-------D...
if enable_http_handler: zaruba_module_name_http_controller(app, mb, rpc) if enable_event_handler: zaruba_module_name_event_controller(mb) if enable_rpc_handler: zaruba_module_name_rpc_controller(rpc)
if enable_http_handler: zaruba_module_name_http_controller(app, mb, rpc) if enable_event_handler: zaruba_module_name_event_controller(mb) if enable_rpc_handler: zaruba_module_name_rpc_controller(rpc)
''' Decorator function for appending class docstrings ''' def adddocs(original): def wrapper(target): target.__doc__ += '\n\n' + original.__doc__ return target return wrapper
""" Decorator function for appending class docstrings """ def adddocs(original): def wrapper(target): target.__doc__ += '\n\n' + original.__doc__ return target return wrapper
class Student: def __init__(self, name, year): self.name = name self.year = year self.grades = [] def add_grade(self, grade): if type(grade) is Grade: self.grades.append(grade) class Grade: minimum_passing = 65 def __init__(self, score): self.score = score roger = Stu...
class Student: def __init__(self, name, year): self.name = name self.year = year self.grades = [] def add_grade(self, grade): if type(grade) is Grade: self.grades.append(grade) class Grade: minimum_passing = 65 def __init__(self, score): self.score...
# Read: http://jinja.pocoo.org/docs/dev/api/#custom-filters def first_upper(s): if s: return s[0].upper() + s[1:] def first_lower(s): if s: return s[0].lower() + s[1:] filters = { 'first_upper': first_upper, 'first_lower': first_lower }
def first_upper(s): if s: return s[0].upper() + s[1:] def first_lower(s): if s: return s[0].lower() + s[1:] filters = {'first_upper': first_upper, 'first_lower': first_lower}
class RangeModule: def __init__(self): self.lefts = [] self.rights = [] def crossedRange(self, left: int, right: int) -> []: pos = [] for i in range(len(self.lefts)): if not (left >= self.rights[i] or right <= self.lefts[i]): pos.append(i) re...
class Rangemodule: def __init__(self): self.lefts = [] self.rights = [] def crossed_range(self, left: int, right: int) -> []: pos = [] for i in range(len(self.lefts)): if not (left >= self.rights[i] or right <= self.lefts[i]): pos.append(i) r...
PROJECTNAME = 'Perham example' TARGET = 0 NPATHS = 200 DURATION = 10*365.25 NREALIZATIONS = 200 BASE = 0.0 C_DIST = (12.0, 65.0, 120.0) P_DIST = (0.20, 0.25) T_DIST = (10, 20, 30) BUFFER = 100 SPACING = 4 UMBRA = 8 SMOOTH = 2 CONFINED = True TOL = 1 MAXSTEP = 10 WELLS = [ (302338, 5162551, 0.2, 1372), (302...
projectname = 'Perham example' target = 0 npaths = 200 duration = 10 * 365.25 nrealizations = 200 base = 0.0 c_dist = (12.0, 65.0, 120.0) p_dist = (0.2, 0.25) t_dist = (10, 20, 30) buffer = 100 spacing = 4 umbra = 8 smooth = 2 confined = True tol = 1 maxstep = 10 wells = [(302338, 5162551, 0.2, 1372), (302320, 5162497,...
''' Created on 2017/09/25 @author: lionheart '''
""" Created on 2017/09/25 @author: lionheart """
class Seat: def __init__(self, id, flight_id, team_member_id, seat_number): self.id = id self.startpoint = startpoint self.flight_id = flight_id self.team_member_id = team_member_id self.seat_number = seat_number def to_dict(self): retur...
class Seat: def __init__(self, id, flight_id, team_member_id, seat_number): self.id = id self.startpoint = startpoint self.flight_id = flight_id self.team_member_id = team_member_id self.seat_number = seat_number def to_dict(self): return {'id': self.id, 'flight...
# pylint: disable=unused-argument class Top: def __add__(self, other): return self def __and__(self, other): return self def __sub__(self, other): return self def __rsub__(self, other): return self def __radd__(self, other): return self def __ror__(...
class Top: def __add__(self, other): return self def __and__(self, other): return self def __sub__(self, other): return self def __rsub__(self, other): return self def __radd__(self, other): return self def __ror__(self, other): return self ...
def count_consonants(): list123=['a','e','i','o','u'] dstring=input(" enter the string ") index=0 for i in dstring: if i in list123: index+=0 else: index+=1 return index print(count_consonants())
def count_consonants(): list123 = ['a', 'e', 'i', 'o', 'u'] dstring = input(' enter the string ') index = 0 for i in dstring: if i in list123: index += 0 else: index += 1 return index print(count_consonants())
num_tests = int(raw_input()) for test_index in range(num_tests): (num_nodes, num_edges) = map(int, raw_input().split()) for edge_index in range(num_edges): (from_node, to_node, weight) = map(int, raw_input().split()) print(num_nodes + num_edges)
num_tests = int(raw_input()) for test_index in range(num_tests): (num_nodes, num_edges) = map(int, raw_input().split()) for edge_index in range(num_edges): (from_node, to_node, weight) = map(int, raw_input().split()) print(num_nodes + num_edges)
# 45. Jump Game II class Solution: def jump(self, nums) -> int: n = len(nums) if n == 1: return 0 ans = 1 r, next_r = nums[0], 0 for i, j in enumerate(nums[:-1]): next_r = max(next_r, i+j) if i == r: ans += 1 r ...
class Solution: def jump(self, nums) -> int: n = len(nums) if n == 1: return 0 ans = 1 (r, next_r) = (nums[0], 0) for (i, j) in enumerate(nums[:-1]): next_r = max(next_r, i + j) if i == r: ans += 1 r = next_...
CREATE_TABLE_SQL = "CREATE TABLE {name} ({fields});" CONDITIONAL_OPRATORS = { '=' : '=', '&' : 'AND', '!=': '!=', '|' : 'OR', 'in': 'IN', 'not in': 'NOT IN', 'like': 'LIKE' } class CelertixSql: ''' POSTGRESQL SCHEMA AND INFORMATION RELATED QURIES ''' @classmethod ...
create_table_sql = 'CREATE TABLE {name} ({fields});' conditional_oprators = {'=': '=', '&': 'AND', '!=': '!=', '|': 'OR', 'in': 'IN', 'not in': 'NOT IN', 'like': 'LIKE'} class Celertixsql: """ POSTGRESQL SCHEMA AND INFORMATION RELATED QURIES """ @classmethod def get_all_tables(cls): r...
class Leaf: def __init__(self, di): self.di = di self.lzt = [] self.hits = 0 def add(self, trail): self.hits += 1 if len(trail) < 1: return for x in self.lzt: if (x.di == trail[0]): x.add(trail[1:]) ...
class Leaf: def __init__(self, di): self.di = di self.lzt = [] self.hits = 0 def add(self, trail): self.hits += 1 if len(trail) < 1: return for x in self.lzt: if x.di == trail[0]: x.add(trail[1:]) return ...
{ 'variables': { 'target_arch%': '<!(node preinstall.js --print-arch)>' }, 'targets': [ { 'target_name': 'libsodium-prebuilt', 'include_dirs' : [ "<!(node -e \"require('nan')\")", 'libsodium.build/include' ], 'sources': [ 'binding.cc', ], 'xcode_...
{'variables': {'target_arch%': '<!(node preinstall.js --print-arch)>'}, 'targets': [{'target_name': 'libsodium-prebuilt', 'include_dirs': ['<!(node -e "require(\'nan\')")', 'libsodium.build/include'], 'sources': ['binding.cc'], 'xcode_settings': {'OTHER_CFLAGS': ['-g', '-O3']}, 'cflags': ['-g', '-O3'], 'libraries': ['<...
def shift_dummies(df, col, shift): shift_cols = [] shift_sign = "+" if shift < 0: shift_sign = "-" for t in range(shift): col_name = f"{col} t{shift_sign}{abs(t)}" df[col_name] = df[col].shift(t) shift_cols.append(col_name) if shift_sign == "+": prefix =...
def shift_dummies(df, col, shift): shift_cols = [] shift_sign = '+' if shift < 0: shift_sign = '-' for t in range(shift): col_name = f'{col} t{shift_sign}{abs(t)}' df[col_name] = df[col].shift(t) shift_cols.append(col_name) if shift_sign == '+': prefix = 'post...
## 1. The Spark DataFrame: An Introduction ## f = open('census_2010.json') for i in range(0,4): print(f.readline()) ## 3. Schema ## sqlCtx = SQLContext(sc) df = sqlCtx.read.json("census_2010.json") df.printSchema() ## 4. Pandas vs Spark DataFrames ## df.show(5) ## 5. Row Objects ## first_five = df.head(5) f...
f = open('census_2010.json') for i in range(0, 4): print(f.readline()) sql_ctx = sql_context(sc) df = sqlCtx.read.json('census_2010.json') df.printSchema() df.show(5) first_five = df.head(5) for r in first_five: print(r.age) df[['age']].show() df[['age', 'males', 'females']].show() five_plus = df[df['age'] > 5]...
# A list of dictionary... person1 = {'first_name':'alex','last_name':'brucle','age': 25,'city':'newyork'} person2 = {'first_name':'shreya','last_name':'rani','age': 25,'city':'puna'} person3 = {'first_name':'vidya','last_name':'vox','age': 28,'city':'kerla'} person = [person1,person2,person3] #storing dictionary i...
person1 = {'first_name': 'alex', 'last_name': 'brucle', 'age': 25, 'city': 'newyork'} person2 = {'first_name': 'shreya', 'last_name': 'rani', 'age': 25, 'city': 'puna'} person3 = {'first_name': 'vidya', 'last_name': 'vox', 'age': 28, 'city': 'kerla'} person = [person1, person2, person3] for info in person: print(in...
class Solution: def canMakeArithmeticProgression(self, arr: List[int]) -> bool: arr.sort() i = 0 while i < len(arr)-1: if i == 0: diff = arr[i] - arr[i+1] else: if arr[i] - arr[i+1] != diff: return False ...
class Solution: def can_make_arithmetic_progression(self, arr: List[int]) -> bool: arr.sort() i = 0 while i < len(arr) - 1: if i == 0: diff = arr[i] - arr[i + 1] elif arr[i] - arr[i + 1] != diff: return False else: ...
print("####################################################") print("#FILENAME:\t\ta2p1.py\t\t\t #") print("#ASSIGNMENT:\t\tHomework Assignment 2 Pt. 1#") print("#COURSE/SECTION:\tCIS 3389.251\t\t #") print("#DUE DATE:\t\tMonday, 30.March 2020\t #") print("####################################################\n") ...
print('####################################################') print('#FILENAME:\t\ta2p1.py\t\t\t #') print('#ASSIGNMENT:\t\tHomework Assignment 2 Pt. 1#') print('#COURSE/SECTION:\tCIS 3389.251\t\t #') print('#DUE DATE:\t\tMonday, 30.March 2020\t #') print('####################################################\n') ...
program_title = "Smelted: Rezz-a-tron 4000" HOST = "localhost" PORT = 5250 current_unit = "U0"
program_title = 'Smelted: Rezz-a-tron 4000' host = 'localhost' port = 5250 current_unit = 'U0'
a = int(input()) b = int(input()) c = int(input()) d = int(input()) e = int(input()) lista = [a, b, c, d, e] pares = [num for num in lista if num % 2 == 0] impares = [num for num in lista if num % 2 != 0] positivos = [num for num in lista if num > 0] negativos = [num for num in lista if num < 0] print(f"{len(pares)}...
a = int(input()) b = int(input()) c = int(input()) d = int(input()) e = int(input()) lista = [a, b, c, d, e] pares = [num for num in lista if num % 2 == 0] impares = [num for num in lista if num % 2 != 0] positivos = [num for num in lista if num > 0] negativos = [num for num in lista if num < 0] print(f'{len(pares)} va...
def fizzbuzz(): for i in range (1, 100): if (i % 3 == 0 and i % 5 == 0): print("fizzbuzz") elif i % 3 == 0: print("fizz") elif i % 5 == 0: print("buzz") else: print(i) def prime(): n = int(input("enter any number.")) for i in range(2, n + 1): counter = 0 for j in range(2, i): if i % j ==...
def fizzbuzz(): for i in range(1, 100): if i % 3 == 0 and i % 5 == 0: print('fizzbuzz') elif i % 3 == 0: print('fizz') elif i % 5 == 0: print('buzz') else: print(i) def prime(): n = int(input('enter any number.')) for i in rang...
#!/usr/bin/python # -*- coding: utf-8 -*- # Classes class app: version = " v1.00 " # released 2022/02/18 class emoji: bye = "\U0001F44B" clock = "\U000023F3" help = "\U0001F4A1" class colour: grey = "\033[2m" default = "\033[m" class dictionary: projects = {} tasks = {} class list: ...
class App: version = ' v1.00 ' class Emoji: bye = '👋' clock = '⏳' help = '💡' class Colour: grey = '\x1b[2m' default = '\x1b[m' class Dictionary: projects = {} tasks = {} class List: projects = []
def rule(event): # check that this is a password change event; # event id 11 is actor_user changed password for user # Normally, admin's may change a user's password (event id 211) return event.get('event_type_id') == 11 def title(event): return 'A user [{}] password changed by user [{}]'.format(...
def rule(event): return event.get('event_type_id') == 11 def title(event): return 'A user [{}] password changed by user [{}]'.format(event.get('user_name'), event.get('actor_user_name'))
class Solution: def isPalindrome(self, head): w = [] while head: w.append(head.val) head = head.next return w == w[::-1]
class Solution: def is_palindrome(self, head): w = [] while head: w.append(head.val) head = head.next return w == w[::-1]
#!/usr/bin/env python STAGES = { # anonymous step { "install": "/path/to/file", "install": "/path/to/file", "install": "/path/to/file", "send": "", }, } def pre_handler(scenario): pass def post_handler(scenario): pass
stages = {{'install': '/path/to/file', 'install': '/path/to/file', 'install': '/path/to/file', 'send': ''}} def pre_handler(scenario): pass def post_handler(scenario): pass
#!/usr/bin/env python # $Id: 20121004$ # $Date: 2012-10-04 16:35:23$ # $Author: Marek Lukaszuk$ # based on: # http://keccak.noekeon.org/specs_summary.html rc = [0x0000000000000001,0x000000008000808B, 0x0000000000008082,0x800000000000008B, 0x800000000000808A,0x8000000000008089, 0x8000000080008000,0x8000000000008003, ...
rc = [1, 2147516555, 32898, 9223372036854775947, 9223372036854808714, 9223372036854808713, 9223372039002292224, 9223372036854808579, 32907, 9223372036854808578, 2147483649, 9223372036854775936, 9223372039002292353, 32778, 9223372036854808585, 9223372039002259466, 138, 9223372039002292353, 136, 9223372036854808704, 2147...
while True : a = int (input()) if a == 0: break
while True: a = int(input()) if a == 0: break
n = 600851475143 i = 2 while i ** 2 < n: while n % i == 0: n //= i i += 1 print(n)
n = 600851475143 i = 2 while i ** 2 < n: while n % i == 0: n //= i i += 1 print(n)
# Description: "Hello World" Program in Python print("Hello World!") print('Hello Again! But in single quotes') print("You can't enter double quotes inside double quoted string but can use ' like this.") print('Similarly you can enter " inside single quoted string.') print('Or you can escape single quotes like t...
print('Hello World!') print('Hello Again! But in single quotes') print("You can't enter double quotes inside double quoted string but can use ' like this.") print('Similarly you can enter " inside single quoted string.') print("Or you can escape single quotes like this ' inside single quoted string.") print('Or you can...
cont_18 = cont_M = cont_F = 0 while True: print('-' * 25) print(' CADASTRE UMA PESSOA') print('-' * 25) idade = int(input('Idade: ')) sexo = ' ' while sexo not in 'MF': sexo = str(input('Sexo: [M/F] ')).upper().strip()[0] print('-' * 25) if idade >= 18: cont_18 += 1 ...
cont_18 = cont_m = cont_f = 0 while True: print('-' * 25) print(' CADASTRE UMA PESSOA') print('-' * 25) idade = int(input('Idade: ')) sexo = ' ' while sexo not in 'MF': sexo = str(input('Sexo: [M/F] ')).upper().strip()[0] print('-' * 25) if idade >= 18: cont_18 += 1 ...
with open('secrets.txt') as input: with open("src/secrets.h", "w") as output: for line_number, define in enumerate(input): output.write("#define {}".format(define))
with open('secrets.txt') as input: with open('src/secrets.h', 'w') as output: for (line_number, define) in enumerate(input): output.write('#define {}'.format(define))
n_plots_per_species = survey_data.groupby(["name"])["verbatimLocality"].nunique().sort_values() fig, ax = plt.subplots(figsize=(10, 8)) n_plots_per_species.plot(kind="barh", ax=ax) ax.set_xlabel("Number of plots"); ax.set_ylabel("");
n_plots_per_species = survey_data.groupby(['name'])['verbatimLocality'].nunique().sort_values() (fig, ax) = plt.subplots(figsize=(10, 8)) n_plots_per_species.plot(kind='barh', ax=ax) ax.set_xlabel('Number of plots') ax.set_ylabel('')
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHET...
url_scheme = 'https://' allowed_methods = frozenset(['GET', 'POST', 'PUT', 'DELETE', 'PATCH']) body_methods = frozenset(['POST', 'PUT', 'PATCH']) query_methods = frozenset(['GET', 'DELETE']) default_content_headers = {'content-type': 'application/json'} status_ok = 200 status_invalid_request = 400 status_unauthorized =...
# Start with the program you wrote for Exercise 6-1 (page 99). tesla = { 'first_name': 'elon', 'last_name': 'musk', 'age': 45, 'city': 'los angeles', } # Make two new dictionaries representing different people, and store all three # dictionaries in a list called people. Loop through your list of pe...
tesla = {'first_name': 'elon', 'last_name': 'musk', 'age': 45, 'city': 'los angeles'} microsoft = {'first_name': 'bill', 'last_name': 'gates', 'age': 70, 'city': 'seattle'} apple = {'first_name': 'steve', 'last_name': 'jobs', 'age': 63, 'city': 'cupertino'} ceo_list = [] ceo_list.append(tesla) ceo_list.append(microsoft...
CONTROL_NAMES = { 'anti_malware': 'Anti-Malware', 'web_reputation': 'Web Reputation', 'firewall': 'Firewall', 'intrusion_prevention': 'Intrusion Prevention', 'integrity_monitoring': 'Integrity Monitoring', 'log_inspection': 'Log Inspection', }
control_names = {'anti_malware': 'Anti-Malware', 'web_reputation': 'Web Reputation', 'firewall': 'Firewall', 'intrusion_prevention': 'Intrusion Prevention', 'integrity_monitoring': 'Integrity Monitoring', 'log_inspection': 'Log Inspection'}
#!/usr/local/bin/python3 ################################################################################################################################# class Merchant: def __init__(self, name, classtype, description, items): self.name = name self.description = description self.inventory = items self.clas...
class Merchant: def __init__(self, name, classtype, description, items): self.name = name self.description = description self.inventory = items self.classtype = classtype self.taken = False def is_taken(self): return False
def solve(arr): visited = set() max_length = 0 for elem in arr: if elem not in visited: length = 1 current = elem while current not in visited: visited.add(current) current = arr[current] length += 1 max...
def solve(arr): visited = set() max_length = 0 for elem in arr: if elem not in visited: length = 1 current = elem while current not in visited: visited.add(current) current = arr[current] length += 1 max_...
arr = [5,3,20,15,8,3] n = len(arr) max = -999999 for i in range(n-1,-1,-1): if arr[i] > max: print(arr[i], end = " ") # you can use stack and then print to get in the same order max = arr[i] # Leader of an array are the elements in which no element on the right side of teh element is greater than that...
arr = [5, 3, 20, 15, 8, 3] n = len(arr) max = -999999 for i in range(n - 1, -1, -1): if arr[i] > max: print(arr[i], end=' ') max = arr[i]
a = [1, 8, 5, 3, 11, 6, 15] def selection_sort(array): for i in range(len(array)): swap_from = i swap_to = -1 for j in range(i + 1, len(array)): if array[swap_from] > array[j] and ( swap_to == -1 or array[swap_to] > array[j] ): swap_...
a = [1, 8, 5, 3, 11, 6, 15] def selection_sort(array): for i in range(len(array)): swap_from = i swap_to = -1 for j in range(i + 1, len(array)): if array[swap_from] > array[j] and (swap_to == -1 or array[swap_to] > array[j]): swap_to = j if swap_to > 0: ...
# # PySNMP MIB module A3Com-products-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM-PRODUCTS-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:08:14 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, ...
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, value_size_constraint, constraints_union, value_range_constraint, constraints_intersection) ...
def find_similar_dogs(breed): temperment = dogs[breed] good_boys = set() most_common = 0 for dog in dogs: if dog == breed: continue common = 0 for x in temperment: if x in dogs[dog]: common += 1 if common ...
def find_similar_dogs(breed): temperment = dogs[breed] good_boys = set() most_common = 0 for dog in dogs: if dog == breed: continue common = 0 for x in temperment: if x in dogs[dog]: common += 1 if common > most_common: ...
def checksum(s1,s2): length=len(s1) check_sum="" carry=0 for i in range(length-1,-1,-1): if s1[i]=='0' and s2[i]=='0': if carry==0: check_sum="0"+check_sum else: check_sum="1"+check_sum carry=0 elif (s1[i]=='0' and s...
def checksum(s1, s2): length = len(s1) check_sum = '' carry = 0 for i in range(length - 1, -1, -1): if s1[i] == '0' and s2[i] == '0': if carry == 0: check_sum = '0' + check_sum else: check_sum = '1' + check_sum carry = 0 ...
GEM_NAME = 'CloudGemDynamicContent' TEST_FILENAMES = [ 'DynamicContentTest.manifest.pak', 'UserRequestedData.shared.pak', 'DynamicContentTestData.shared.pak' ] STAGING_STATUS_PUBLIC = 'PUBLIC' STAGING_STATUS_PRIVATE = 'PRIVATE' STAGING_STATUS_WINDOW = 'WINDOW'
gem_name = 'CloudGemDynamicContent' test_filenames = ['DynamicContentTest.manifest.pak', 'UserRequestedData.shared.pak', 'DynamicContentTestData.shared.pak'] staging_status_public = 'PUBLIC' staging_status_private = 'PRIVATE' staging_status_window = 'WINDOW'
# https://www.hackerrank.com/challenges/sherlock-and-the-beast/problem?isFullScreen=true def decentNumber(n): # Write your code here a, b = divmod(n,3) while b%5: b+=3 a-=1 if a>-1: print("5"*a*3+"3"*b) else: print("-1")
def decent_number(n): (a, b) = divmod(n, 3) while b % 5: b += 3 a -= 1 if a > -1: print('5' * a * 3 + '3' * b) else: print('-1')
w = [] for _ in range(10): w.append(int(input())) k = [] for _ in range(10): k.append(int(input())) w.sort(reverse=True) k.sort(reverse=True) print(sum(w[0:3]), sum(k[0:3]))
w = [] for _ in range(10): w.append(int(input())) k = [] for _ in range(10): k.append(int(input())) w.sort(reverse=True) k.sort(reverse=True) print(sum(w[0:3]), sum(k[0:3]))
def main(): a=[10,20,5,49,32,68] print(mergeSort(a)) def mergeSort(a): key=len(a)//2 left=a[0] right=a[-1] l=mergeSort(a[left:key]) r=mergesort(a[key+1:right]) return(merge(a,l,r)) def merge(a,l,r): if a[l]<a[r]: pass elif a[l]>a[r]: a[l],a[r]=a[r]...
def main(): a = [10, 20, 5, 49, 32, 68] print(merge_sort(a)) def merge_sort(a): key = len(a) // 2 left = a[0] right = a[-1] l = merge_sort(a[left:key]) r = mergesort(a[key + 1:right]) return merge(a, l, r) def merge(a, l, r): if a[l] < a[r]: pass elif a[l] > a[r]: ...
number=int(input()) cond1=(number%9==0) conv_to_str=str(number) digit1=int(conv_to_str[0]) digit2=int(conv_to_str[1]) cond2=(digit1 or digit2) if cond1 and cond2: print("Lucky Number") else: print("Unlucky Number")
number = int(input()) cond1 = number % 9 == 0 conv_to_str = str(number) digit1 = int(conv_to_str[0]) digit2 = int(conv_to_str[1]) cond2 = digit1 or digit2 if cond1 and cond2: print('Lucky Number') else: print('Unlucky Number')
# 0 1 1 2 3 5 8 13 21 34 nterms=int(input("Enter the number of terms:")) n1=0 n2=1 count=0 if nterms <=0: print("Please enter a positive number.") elif nterms==1: print("Fibonacci series upto", nterms,":") print(n1) else: print("Fibonacci series upto", nterms," is:") while coun...
nterms = int(input('Enter the number of terms:')) n1 = 0 n2 = 1 count = 0 if nterms <= 0: print('Please enter a positive number.') elif nterms == 1: print('Fibonacci series upto', nterms, ':') print(n1) else: print('Fibonacci series upto', nterms, ' is:') while count < nterms: print(n1, end=...
class User: GENDER = ['male', 'female'] MULTIPLIERS = {'female': 0.413, 'male': 0.415} AVERAGES = {'female': 70.0, 'male': 78.0} def __init__(self, gender=None, height=None, stride=None): try: self.gender = str(gender).lower() if gender else None except ValueError: ...
class User: gender = ['male', 'female'] multipliers = {'female': 0.413, 'male': 0.415} averages = {'female': 70.0, 'male': 78.0} def __init__(self, gender=None, height=None, stride=None): try: self.gender = str(gender).lower() if gender else None except ValueError: ...
f = open("input/day6input.txt", "r") gans = f.read().split('\n\n') pyes = 0 # passenger yes gyes = 0 # gyes pcl = [] grpans = [] for ans in gans: gcl = list(set()) pcl.clear() for a in ans.split('\n'): cset = set() for l in a: for c in l: pcl.append(c...
f = open('input/day6input.txt', 'r') gans = f.read().split('\n\n') pyes = 0 gyes = 0 pcl = [] grpans = [] for ans in gans: gcl = list(set()) pcl.clear() for a in ans.split('\n'): cset = set() for l in a: for c in l: pcl.append(c) cset.add(c) ...
class geotile(): class gps(): def __init__(self, latitude, longitude): self.latitude = latitude self.longitude = longitude if latitude < -90.0 or latitude > 90.0: raise ValueError("Latitude must be between -90 and 90") if longi...
class Geotile: class Gps: def __init__(self, latitude, longitude): self.latitude = latitude self.longitude = longitude if latitude < -90.0 or latitude > 90.0: raise value_error('Latitude must be between -90 and 90') if longitude < -180.0 or l...
class Category: def __init__(self, name, image): self.name = name self.image = image self.description = None
class Category: def __init__(self, name, image): self.name = name self.image = image self.description = None
#!/usr/bin/python class Token: KEYWORD = 1 SYMBOL = 2 IDENTIFIER = 3 INT_CONST = 4 STRING_CONST = 5 class JackTokenizer: def __init__(self, filename): self.initTransitionTable() f = open(filename, 'r') self.data = f.read() f.close() self.tokens = [] self.currentTokenId = -1 s...
class Token: keyword = 1 symbol = 2 identifier = 3 int_const = 4 string_const = 5 class Jacktokenizer: def __init__(self, filename): self.initTransitionTable() f = open(filename, 'r') self.data = f.read() f.close() self.tokens = [] self.currentTo...
# check old-Code-Analysis.py for feedback of your code # An SMS Simulation class SMSMessage(object) class SMSMessage: #class variables initialized with default value hasBeenRead = False messageText = "text" fromNumber = 12345 #for initializing object def __init__(self, hasBeenRead, messageText...
class Smsmessage: has_been_read = False message_text = 'text' from_number = 12345 def __init__(self, hasBeenRead, messageText, fromNumber): self.hasBeenRead = hasBeenRead self.messageText = messageText self.fromNumber = fromNumber def mark_as_read(self): self.hasBee...
# -*- coding=utf-8 -*- class _Missing(object): def __repr__(self): return "no value" def __reduce__(self): return "_missing" def __nonzero__(self): return False _missing = _Missing() class cached_property(object): def __init__(self, func, name=None, doc=None): sel...
class _Missing(object): def __repr__(self): return 'no value' def __reduce__(self): return '_missing' def __nonzero__(self): return False _missing = __missing() class Cached_Property(object): def __init__(self, func, name=None, doc=None): self.__name__ = name or func...
class LinkedListNode: def __init__(self, val): self.data = val self.next = None def add_to_linked_list(head, node): cur = head while cur.next != None: cur = cur.next cur.next = node def contains_cycle(head): slow = head.next fast = head.next.next maxi = 0 while ...
class Linkedlistnode: def __init__(self, val): self.data = val self.next = None def add_to_linked_list(head, node): cur = head while cur.next != None: cur = cur.next cur.next = node def contains_cycle(head): slow = head.next fast = head.next.next maxi = 0 while...
expected_output = { 'clock_state': {'system_status': {'associations_address': '10.4.1.1', 'clock_state': 'synchronized', 'clock_stratum': 8, 'root_delay': 0.01311}}, 'vrf': { 'default': { ...
expected_output = {'clock_state': {'system_status': {'associations_address': '10.4.1.1', 'clock_state': 'synchronized', 'clock_stratum': 8, 'root_delay': 0.01311}}, 'vrf': {'default': {'peer': {'10.4.1.1': {'delay': 0.01311, 'local': '0.0.0.0', 'mode': 'synchronized', 'poll': 16, 'reach': 377, 'remote': '10.4.1.1', 'st...
''' POW(X,N) Implement pow(x, n), which calculates x raised to the power n (xn). ''' def myPow(x: float, n: int) -> float: if n < 0: x, n = (1/x), -n if n == 0: return 1 if n % 2: return x * self.myPow(x*x, n//2) return self.myPow(x*x, n//2)
""" POW(X,N) Implement pow(x, n), which calculates x raised to the power n (xn). """ def my_pow(x: float, n: int) -> float: if n < 0: (x, n) = (1 / x, -n) if n == 0: return 1 if n % 2: return x * self.myPow(x * x, n // 2) return self.myPow(x * x, n // 2)
# # @lc app=leetcode id=81 lang=python3 # # [81] Search in Rotated Sorted Array II # # @lc code=start class Solution: def search(self, nums: List[int], target: int) -> bool: left = 0 right = len(nums) - 1 while left <= right: middle = (left + right) // 2 if nums[midd...
class Solution: def search(self, nums: List[int], target: int) -> bool: left = 0 right = len(nums) - 1 while left <= right: middle = (left + right) // 2 if nums[middle] == target: return True elif nums[middle] == nums[left]: ...
class NoConfigValueError(LookupError): def __init__(self, *args): super(NoConfigValueError, self).__init__(*args) self.message = ("No local configuration value for: '%s'." % args[0]) class Config(dict): def __getitem__(self, x): # Re-write for better error message try: ...
class Noconfigvalueerror(LookupError): def __init__(self, *args): super(NoConfigValueError, self).__init__(*args) self.message = "No local configuration value for: '%s'." % args[0] class Config(dict): def __getitem__(self, x): try: return super(Config, self).__getitem__(x)...
dataset_defaults = { 'fmow': { 'epochs': 12, 'batch_size': 64, 'optimiser': 'Adam', 'optimiser_args': { 'lr': 1e-4, 'weight_decay': 0, 'amsgrad': True, 'betas': (0.9, 0.999), }, 'pretrain_iters': 24000, 'meta_lr...
dataset_defaults = {'fmow': {'epochs': 12, 'batch_size': 64, 'optimiser': 'Adam', 'optimiser_args': {'lr': 0.0001, 'weight_decay': 0, 'amsgrad': True, 'betas': (0.9, 0.999)}, 'pretrain_iters': 24000, 'meta_lr': 0.01, 'meta_steps': 5, 'selection_metric': 'acc_worst_region', 'reload_inner_optim': True, 'print_iters': 500...
def palavras_sao_iguais(palavras): p1 = palavras.split("-") if len(p1) < 2: return False modelo = p1[0] iguais = True for p in p1: if p != modelo: iguais = False return iguais print(palavras_sao_iguais('abobrinha')) # 'pega-pega', 'cri-cri', 'zum-zum'
def palavras_sao_iguais(palavras): p1 = palavras.split('-') if len(p1) < 2: return False modelo = p1[0] iguais = True for p in p1: if p != modelo: iguais = False return iguais print(palavras_sao_iguais('abobrinha'))
READER_NAME = "self.reader" PROCESSOR_FUNCTION_FIELD = "__processor__" REPROCESS_AFTER_FIELD = "__reprocess_after__" REPROCESSOR_FUNCTION_FIELD = "__reprocessor__" REPROCESS_ASSIGN_TO_FIELD = "__reprocessor_name__" PREFUNCTION_FIELD = "__duckparse_first__" STREAM_TYPE_FIELD = "__duckparse_stream_type__" DATAKIND_GUA...
reader_name = 'self.reader' processor_function_field = '__processor__' reprocess_after_field = '__reprocess_after__' reprocessor_function_field = '__reprocessor__' reprocess_assign_to_field = '__reprocessor_name__' prefunction_field = '__duckparse_first__' stream_type_field = '__duckparse_stream_type__' datakind_guard_...
fruits = ["Nanas","Apel","Pepaya","Kentang"] x = 3 for x in range (4): print(fruits[x])
fruits = ['Nanas', 'Apel', 'Pepaya', 'Kentang'] x = 3 for x in range(4): print(fruits[x])
class PlannerSystem: def __init__(self): self.maps = {} self.dispensers = {} self.taskboards = {} self.goals = {} self.task_assigned = {} self.states = {} self.default_metas = { 'is_goal': False, 'is_task_board': False, 'a...
class Plannersystem: def __init__(self): self.maps = {} self.dispensers = {} self.taskboards = {} self.goals = {} self.task_assigned = {} self.states = {} self.default_metas = {'is_goal': False, 'is_task_board': False, 'are_dispensers': False} self.ta...
# SOURCE SYSTEMS ECE_REPORTER = 'ECE Reporter' HISTORICAL_ECIS = 'Historical ECIS Snapshot' # Pensieve PENSIEVE_SCHEMA = 'Pensieve' # Canonical Times FULL_TIME = 'FT' PART_TIME = 'PT' # ECIS times ECIS_FULL_TIME = 'F/T' ECIS_WRAP_AROUND = 'WA' ECIS_SCHOOL_AGE = 'School Age' # Age Groups INFANT_TODDLER = 'Infant/Tod...
ece_reporter = 'ECE Reporter' historical_ecis = 'Historical ECIS Snapshot' pensieve_schema = 'Pensieve' full_time = 'FT' part_time = 'PT' ecis_full_time = 'F/T' ecis_wrap_around = 'WA' ecis_school_age = 'School Age' infant_toddler = 'Infant/Toddler' preschool = 'Preschool' school_age = 'School-age'
peso = float(input('Insira o peso: ')) limite = 50 excesso = peso - limite multa = excesso * 4 print(f'Multa no valor de: R$ {multa}')
peso = float(input('Insira o peso: ')) limite = 50 excesso = peso - limite multa = excesso * 4 print(f'Multa no valor de: R$ {multa}')
expected_output = { 'app_id' : 'meraki', 'owner' : 'iox', 'state' : 'RUNNING', 'application':{ 'type' : 'docker', 'name' : 'cat9k-app', 'version' : 'T-202106031655-G5c6da678-L0b29c1a9M-clouisa-creditor', 'activated_profile_name' : 'custom' }, 'resource_reservation...
expected_output = {'app_id': 'meraki', 'owner': 'iox', 'state': 'RUNNING', 'application': {'type': 'docker', 'name': 'cat9k-app', 'version': 'T-202106031655-G5c6da678-L0b29c1a9M-clouisa-creditor', 'activated_profile_name': 'custom'}, 'resource_reservation': {'memory': '512 MB', 'disk': '2 MB', 'cpu': '500 units', 'cpu_...
def main(): name = input("What's your name? ") if name != "Richard": print("Hi,",name) else: print("I have a secret message for you.") print("You are AWESOME!!!") print("Goodbye!") main()
def main(): name = input("What's your name? ") if name != 'Richard': print('Hi,', name) else: print('I have a secret message for you.') print('You are AWESOME!!!') print('Goodbye!') main()
# coding: utf-8 class Solution: # @param {int} n the nth # @return {string} the nth sequence def countAndSay(self, n): # Write your code here return self._countAndSay(n) def _countAndSay(self, n): if n == 1: return '1' ret = '' prev_str = self._count...
class Solution: def count_and_say(self, n): return self._countAndSay(n) def _count_and_say(self, n): if n == 1: return '1' ret = '' prev_str = self._countAndSay(n - 1) i = 0 while i < len(prev_str): ch = prev_str[i] sum = 1 ...
class Solution: def romanToInt(self, s: str) -> int: value = {'M': 1000,'D': 500, 'C': 100,'L': 50,'X': 10,'V': 5,'I': 1} p = 0;ans = 0 n = len(s) for i in range(n-1, -1, -1): if value[s[i]] >= p: ans += value[s[i]] else: ans -...
class Solution: def roman_to_int(self, s: str) -> int: value = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1} p = 0 ans = 0 n = len(s) for i in range(n - 1, -1, -1): if value[s[i]] >= p: ans += value[s[i]] else: ...
duanweichang=(1298,438) refresh=(106, 65) biaoqing=(1735, 621) biaoqing0=(1398, 500) biaoqing1=(1398, 500) biaoqing2=(1531, 490) biaoqing3=(1684, 506) biaoqing4=(1421, 624) biaoqing5=(1550, 639) biaoqing6=(1681, 629) biaoqing7=(1402, 779) biaoqing8=(1549, 774) biaoqing9=(1682, 772) queding=(1648, 967) fanhui=(218, 192)...
duanweichang = (1298, 438) refresh = (106, 65) biaoqing = (1735, 621) biaoqing0 = (1398, 500) biaoqing1 = (1398, 500) biaoqing2 = (1531, 490) biaoqing3 = (1684, 506) biaoqing4 = (1421, 624) biaoqing5 = (1550, 639) biaoqing6 = (1681, 629) biaoqing7 = (1402, 779) biaoqing8 = (1549, 774) biaoqing9 = (1682, 772) queding = ...
class deer: def __init__(self, name, speed, dash, rest): self.name = name self.speed = speed self.dash = dash self.rest = rest self.points = 0 return def ret_val(self): return self.name, self.speed, self.dash, self.rest def race(time, speed, dash, rest): clock = dist = stam = 0 wh...
class Deer: def __init__(self, name, speed, dash, rest): self.name = name self.speed = speed self.dash = dash self.rest = rest self.points = 0 return def ret_val(self): return (self.name, self.speed, self.dash, self.rest) def race(time, speed, dash, res...
class Solution: def maxSum(self, nums1: List[int], nums2: List[int]) -> int: s1=[0]*(len(nums1)+1) s2=[0]*(len(nums2)+1) index1=len(nums1)-1 index2=len(nums2)-1 while index1>=0 and index2>=0: if nums1[index1]>nums2[index2]: s1[index1]=s1[in...
class Solution: def max_sum(self, nums1: List[int], nums2: List[int]) -> int: s1 = [0] * (len(nums1) + 1) s2 = [0] * (len(nums2) + 1) index1 = len(nums1) - 1 index2 = len(nums2) - 1 while index1 >= 0 and index2 >= 0: if nums1[index1] > nums2[index2]: ...
class Solution: def combinationSum4(self, nums, target): memo = {} def dfs(sm): if sm in memo: return memo[sm] else: if sm >= target: memo[sm] = sm == target return memo[sm] cnt = 0 ...
class Solution: def combination_sum4(self, nums, target): memo = {} def dfs(sm): if sm in memo: return memo[sm] else: if sm >= target: memo[sm] = sm == target return memo[sm] cnt = 0 ...
def capitalizeVowels(word): result = "" vowels = 'AaEeIiOoUu' for i in word: if (i in vowels): result += i.upper() else: result +=i return result print(capitalizeVowels('apple'))
def capitalize_vowels(word): result = '' vowels = 'AaEeIiOoUu' for i in word: if i in vowels: result += i.upper() else: result += i return result print(capitalize_vowels('apple'))
# Verifying an Alien Dictionary: https://leetcode.com/problems/verifying-an-alien-dictionary/ # In an alien language, surprisingly they also use english lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters. # Given a sequence of words written in the a...
class Solution: def is_alien_sorted(self, words, order: str) -> bool: alien_value = {} for (index, value) in enumerate(order): alienValue[value] = index for i in range(1, len(words)): word1 = words[i - 1] word2 = words[i] for j in range(len(wo...
class Solution: def partition(self, s: str) -> list[list[str]]: res = [] def is_palindrome(s): start, end = 0, len(s)-1 while start < end: if s[start] != s[end]: return False start += 1 end -= 1 ...
class Solution: def partition(self, s: str) -> list[list[str]]: res = [] def is_palindrome(s): (start, end) = (0, len(s) - 1) while start < end: if s[start] != s[end]: return False start += 1 end -= 1 ...
class BlockError: def __init__(self): self.errors = {} self.error_count = 0 @staticmethod def get() -> {str}: return BlockError().get_block_error() def add_error(self, block_id: str, error: str): if block_id not in self.errors: self.error_count += 1 ...
class Blockerror: def __init__(self): self.errors = {} self.error_count = 0 @staticmethod def get() -> {str}: return block_error().get_block_error() def add_error(self, block_id: str, error: str): if block_id not in self.errors: self.error_count += 1 ...
x = input().split() y = float(x[1]) x = float(x[0]) if(y == 0): if(x == 0): print("Origem") else: print("Eixo X") else: if(x == 0): if(y != 0): print("Eixo Y") else: if(x > 0): if(y > 0): print("Q1") else: print("Q4") else: if(y > 0): print("Q2") else: print("Q3")
x = input().split() y = float(x[1]) x = float(x[0]) if y == 0: if x == 0: print('Origem') else: print('Eixo X') elif x == 0: if y != 0: print('Eixo Y') elif x > 0: if y > 0: print('Q1') else: print('Q4') elif y > 0: print('Q2') else: print('Q3')