content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
def game_to_genre(game_name): genres_dict = {} with open('genres_dict.txt', 'r') as file: file.seek(0) for line in file: stripped_line = line.strip() key, *value = stripped_line.split(', ') genres_dict[key] = value game_genre = None lowered_ga...
def game_to_genre(game_name): genres_dict = {} with open('genres_dict.txt', 'r') as file: file.seek(0) for line in file: stripped_line = line.strip() (key, *value) = stripped_line.split(', ') genres_dict[key] = value game_genre = None lowered_game_name...
""" Given head, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is co...
""" Given head, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connec...
# -*-coding:utf-8 -*- """ Created on 2013-4-25 @author: Danny<manyunkai@hotmail.com> DannyWork Project """ def required(wrapping_functions,patterns_rslt): """ Used to require 1..n decorators in any view returned by a url tree Usage: urlpatterns = required(func,patterns(...)) urlpatterns = re...
""" Created on 2013-4-25 @author: Danny<manyunkai@hotmail.com> DannyWork Project """ def required(wrapping_functions, patterns_rslt): """ Used to require 1..n decorators in any view returned by a url tree Usage: urlpatterns = required(func,patterns(...)) urlpatterns = required((func,func,func...
""" List of Fanfou method names that require the use of POST. """ POST_ACTIONS = [ # Status Methods 'update', # Direct-messages Methods 'new', # Account Methods 'update_notify_num', 'update_profile', 'update_profile_image', # Blocks Methods, Friendships Methods, Favorites Methods, ...
""" List of Fanfou method names that require the use of POST. """ post_actions = ['update', 'new', 'update_notify_num', 'update_profile', 'update_profile_image', 'create', 'destroy', 'accept', 'deny', 'cancel_recommendation', 'upload', 'token', 'access_token', 'request_token', 'invalidate_token']
# Copyright (C) 2021 Clinton Garwood # MIT Open Source Initiative Approved License # hw_assignment_4_clinton.py # CIS-135 Python # Homework Assignment #4 - A Phone Sales Application # Code Summary: # A program that computes total charges for phones sold # and displays the initial charge, the tax and the total ...
def sales_data_report(total_phones_price, total_sales_tax_collected, total_sales): price_of_phone = 0.0 sales_tax = 0.0 tax_rate = 0.07 this_sale = 0.0 price_of_phone = float(input('\n\tPlease enter in the price of the phone: ')) sales_tax = price_of_phone * tax_rate this_sale = price_of_pho...
''' Positioning and styling legends Properties of the legend can be changed by using the legend member attribute of a Bokeh figure after the glyphs have been plotted. In this exercise, you'll adjust the background color and legend location of the female literacy vs fertility plot from the previous exercise. The figu...
""" Positioning and styling legends Properties of the legend can be changed by using the legend member attribute of a Bokeh figure after the glyphs have been plotted. In this exercise, you'll adjust the background color and legend location of the female literacy vs fertility plot from the previous exercise. The figu...
class AssignWorkers: def __init__(self, testcase, num_workers): """AssignWorkers helps to split the dataframe to a designated number of wokers""" self.testcase = testcase self.num_workers = self._validate_workers(num_workers) def _validate_workers(self, num_workers): """return t...
class Assignworkers: def __init__(self, testcase, num_workers): """AssignWorkers helps to split the dataframe to a designated number of wokers""" self.testcase = testcase self.num_workers = self._validate_workers(num_workers) def _validate_workers(self, num_workers): """return ...
alphabet = "".join([chr(65 + r) for r in range(26)] * 2) stringToEncrypt = input("please enter a message to encrypt") stringToEncrypt = stringToEncrypt.upper() shiftAmount = int(input("please enter a whole number from -25-25 to be your key")) encryptedString = "" for currentCharacter in stringToEncrypt: position =...
alphabet = ''.join([chr(65 + r) for r in range(26)] * 2) string_to_encrypt = input('please enter a message to encrypt') string_to_encrypt = stringToEncrypt.upper() shift_amount = int(input('please enter a whole number from -25-25 to be your key')) encrypted_string = '' for current_character in stringToEncrypt: posi...
fruit = input() size_set = input() ordered_sets = int(input()) price = 0.0 if size_set == "small": price = 2.0 if fruit == "Watermelon": price *= 56 elif fruit == "Mango": price *= 36.66 elif fruit == "Pineapple": price *= 42.10 elif fruit == "Raspberry": price *= 20 ...
fruit = input() size_set = input() ordered_sets = int(input()) price = 0.0 if size_set == 'small': price = 2.0 if fruit == 'Watermelon': price *= 56 elif fruit == 'Mango': price *= 36.66 elif fruit == 'Pineapple': price *= 42.1 elif fruit == 'Raspberry': price *= 20 i...
class Solution: def largeGroupPositions(self, s: str) -> List[List[int]]: indexes = []; start, end, n = 0, 0, len(s) while start < n: while end < n and s[start] == s[end]: end += 1 if end-start > 2: indexes.append([start,end-1]) start = end ...
class Solution: def large_group_positions(self, s: str) -> List[List[int]]: indexes = [] (start, end, n) = (0, 0, len(s)) while start < n: while end < n and s[start] == s[end]: end += 1 if end - start > 2: indexes.append([start, end - ...
class Class(object): def __enter__(self): print('__enter__') return self def __exit__(self, exc_type, exc_val, exc_tb): print('__exit__') with Class() as c: print(c) #raise Exception
class Class(object): def __enter__(self): print('__enter__') return self def __exit__(self, exc_type, exc_val, exc_tb): print('__exit__') with class() as c: print(c)
# coding=utf-8 """Sudoku Backtracking Algorithm solution Python implementation.""" N = 9 # Sudoku size def used_in_row(grid, row, num): return num in grid[row] def used_in_col(grid, col, num): for r in range(N): if grid[r][col] == num: return True return False def used_in_box(grid,...
"""Sudoku Backtracking Algorithm solution Python implementation.""" n = 9 def used_in_row(grid, row, num): return num in grid[row] def used_in_col(grid, col, num): for r in range(N): if grid[r][col] == num: return True return False def used_in_box(grid, bsr, bsc, num): for r in ra...
new_pod_repository( name = "FBSDKCoreKit", url = "https://github.com/facebook/facebook-ios-sdk/archive/v7.1.1.zip", podspec_url = "Vendor/Podspecs/FBSDKCoreKit.podspec.json", generate_header_map = 1 ) new_pod_repository( name = "FBSDKLoginKit", url = "https://github.com/facebook/facebook-ios-sdk/archive/v7....
new_pod_repository(name='FBSDKCoreKit', url='https://github.com/facebook/facebook-ios-sdk/archive/v7.1.1.zip', podspec_url='Vendor/Podspecs/FBSDKCoreKit.podspec.json', generate_header_map=1) new_pod_repository(name='FBSDKLoginKit', url='https://github.com/facebook/facebook-ios-sdk/archive/v7.1.1.zip', podspec_url='Vend...
class InvalidProgramException(SystemException, ISerializable, _Exception): """ The exception that is thrown when a program contains invalid Microsoft intermediate language (MSIL) or metadata. Generally this indicates a bug in the compiler that generated the program. InvalidProgramException() Invalid...
class Invalidprogramexception(SystemException, ISerializable, _Exception): """ The exception that is thrown when a program contains invalid Microsoft intermediate language (MSIL) or metadata. Generally this indicates a bug in the compiler that generated the program. InvalidProgramException() InvalidProgramE...
""" Gitter - Schaffst du es mit einem zweiten Loop ein Gittermuster herzustellen? """ newPage(300, 300) for i in range(0, width(), 10): stroke(0) line((i,0),(i, width())) for i in range(0, width(), 10): stroke(0) line((0,i),(width(),i))
""" Gitter - Schaffst du es mit einem zweiten Loop ein Gittermuster herzustellen? """ new_page(300, 300) for i in range(0, width(), 10): stroke(0) line((i, 0), (i, width())) for i in range(0, width(), 10): stroke(0) line((0, i), (width(), i))
class Simplest(): pass print(type(Simplest)) simp = Simplest() print(type(simp)) print(type(simp) == Simplest)
class Simplest: pass print(type(Simplest)) simp = simplest() print(type(simp)) print(type(simp) == Simplest)
print(''.join(['-' for x in range(70)])) # Functions are objects def my_func(x): print("Functions are objects:", x, my_func.foo) my_func.foo = 'foo' print(dir(my_func)) print(''.join(['-' for x in range(70)])) # Named and anonymous functions my_lambda = lambda x: print("Lambda:", x, my_lambda.bar) my_lambda.bar = 'b...
print(''.join(['-' for x in range(70)])) def my_func(x): print('Functions are objects:', x, my_func.foo) my_func.foo = 'foo' print(dir(my_func)) print(''.join(['-' for x in range(70)])) my_lambda = lambda x: print('Lambda:', x, my_lambda.bar) my_lambda.bar = 'bar' my_lambda(42) print(''.join(['-' for x in range(70...
END_MARKER = ("end", None) NEWLINE_1 = ("newline", 1) def number_of_lines(parsed_text): lines = 1 for (token, value) in parsed_text: if token == "newline": lines += value return lines def normalize_tokens(tokens): result = [] for token in tokens: key, value = token ...
end_marker = ('end', None) newline_1 = ('newline', 1) def number_of_lines(parsed_text): lines = 1 for (token, value) in parsed_text: if token == 'newline': lines += value return lines def normalize_tokens(tokens): result = [] for token in tokens: (key, value) = token ...
QUERY_ISSUE_RESPONSE = { "expand": "names,schema", "issues": [ { "expand": "operations,versionedRepresentations,editmeta,changelog,renderedFields", "fields": { "aggregateprogress": { "progress": 0, "total": 0 ...
query_issue_response = {'expand': 'names,schema', 'issues': [{'expand': 'operations,versionedRepresentations,editmeta,changelog,renderedFields', 'fields': {'aggregateprogress': {'progress': 0, 'total': 0}, 'aggregatetimeestimate': None, 'aggregatetimeoriginalestimate': None, 'aggregatetimespent': None, 'assignee': None...
# Author: Gaurav Pande # [520. Detect Capital](https://leetcode.com/problems/detect-capital/description/) class Solution: def detectCapitalUse(self, word): """ :type word: str :rtype: bool """ i = 0 list_res = [] while i < len(word): if word[i].i...
class Solution: def detect_capital_use(self, word): """ :type word: str :rtype: bool """ i = 0 list_res = [] while i < len(word): if word[i].islower(): list_res.append(False) else: list_res.append(True) ...
cod1, n1, v1 = input().split(' ') cod1 = int(cod1) n1 = int(n1) v1 = float(v1) cod2, n2, v2 = input().split(' ') cod2 = int(cod2) n2 = int(n2) v2 = float(v2) tot = n1 * v1 + n2 * v2 print(f'VALOR A PAGAR: R$ {tot:.2f}')
(cod1, n1, v1) = input().split(' ') cod1 = int(cod1) n1 = int(n1) v1 = float(v1) (cod2, n2, v2) = input().split(' ') cod2 = int(cod2) n2 = int(n2) v2 = float(v2) tot = n1 * v1 + n2 * v2 print(f'VALOR A PAGAR: R$ {tot:.2f}')
# Dictionary phonebook = {} print(phonebook) phonebook = { 'Andy': '9957558', 'John': '64746484', 'Jenny': '22282' } print(phonebook['Andy']) print(phonebook['John']) print(phonebook['Jenny']) print(dir(phonebook)) for phone in phonebook.values(): print(phone) for phone in phonebook.keys(): print(phone) ...
phonebook = {} print(phonebook) phonebook = {'Andy': '9957558', 'John': '64746484', 'Jenny': '22282'} print(phonebook['Andy']) print(phonebook['John']) print(phonebook['Jenny']) print(dir(phonebook)) for phone in phonebook.values(): print(phone) for phone in phonebook.keys(): print(phone) for (key, value) in ph...
def test_bearychat_badge_should_be_svg(test_client): resp = test_client.get('/badge/bearychat.svg') assert resp.status_code == 200 assert resp.content_type == 'image/svg+xml' def test_bearychat_badge_should_contain_bearychat(test_client): resp = test_client.get('/badge/bearychat.svg') assert 'Bear...
def test_bearychat_badge_should_be_svg(test_client): resp = test_client.get('/badge/bearychat.svg') assert resp.status_code == 200 assert resp.content_type == 'image/svg+xml' def test_bearychat_badge_should_contain_bearychat(test_client): resp = test_client.get('/badge/bearychat.svg') assert 'Beary...
def get_first_matching_attr(obj, *attrs, default=None): for attr in attrs: if hasattr(obj, attr): return getattr(obj, attr) return default
def get_first_matching_attr(obj, *attrs, default=None): for attr in attrs: if hasattr(obj, attr): return getattr(obj, attr) return default
# # PySNMP MIB module OG-SMI-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/OG-SMI-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:23:01 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, 09:...
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, constraints_union, constraints_intersection, value_size_constraint, value_range_constraint) ...
layer_adr_pt = QgsMapLayerRegistry.instance().mapLayersByName('adresse_pt_1')[0] layer_adr_line = QgsMapLayerRegistry.instance().mapLayersByName('troncon_fusion')[0] ids = [] for point in layer_adr_pt.getFeatures(): geom = point.geometry() for rue in layer_adr_line.getFeatures(): geom_rue = rue.geome...
layer_adr_pt = QgsMapLayerRegistry.instance().mapLayersByName('adresse_pt_1')[0] layer_adr_line = QgsMapLayerRegistry.instance().mapLayersByName('troncon_fusion')[0] ids = [] for point in layer_adr_pt.getFeatures(): geom = point.geometry() for rue in layer_adr_line.getFeatures(): geom_rue = rue.geometry...
# parsetab.py # This file is automatically generated. Do not edit. # pylint: disable=W,C,R _tabversion = '3.10' _lr_method = 'LALR' _lr_signature = 'leftPAR_ABREPAR_CIERRArightIGUALleftORleftANDleftNO_IGUALnonassocMAYORMENORMAYOR_IGUALMENOR_IGUALleftMASMENOSleftASTERISCODIVISIONMODULOleftPOTENCIArightNOTleftLLAVE_AB...
_tabversion = '3.10' _lr_method = 'LALR' _lr_signature = 'leftPAR_ABREPAR_CIERRArightIGUALleftORleftANDleftNO_IGUALnonassocMAYORMENORMAYOR_IGUALMENOR_IGUALleftMASMENOSleftASTERISCODIVISIONMODULOleftPOTENCIArightNOTleftLLAVE_ABRELLAVE_CIERRAADD ALL ALTER AND AS ASC ASTERISCO AVG BETWEEN BIGINT BOOLEAN BY CADENA CASE CAS...
#!/usr/bin/env python class Elf_parser: "Extracts parts from ELF files" def __init__(self, filename): self.elf_file = filename def get_text(self): "Returns the text section of the ELF file as array" pass def get_data(self): "Returns the data section of the ELF file as array" pass def hex_dump_text(s...
class Elf_Parser: """Extracts parts from ELF files""" def __init__(self, filename): self.elf_file = filename def get_text(self): """Returns the text section of the ELF file as array""" pass def get_data(self): """Returns the data section of the ELF file as array""" ...
""" @file @brief Shortcuts to *sklconv*. """
""" @file @brief Shortcuts to *sklconv*. """
def parse_binary(binary_string): if not all(char in ('0', '1') for char in binary_string): raise ValueError('invalid binary number') return sum(int(digit) * (2 ** power) for power, digit in enumerate(reversed(binary_string)))
def parse_binary(binary_string): if not all((char in ('0', '1') for char in binary_string)): raise value_error('invalid binary number') return sum((int(digit) * 2 ** power for (power, digit) in enumerate(reversed(binary_string))))
"""Main classes.""" class MainClass1: """Parent dummy class 1.""" pass class MainClass2: """Parent dummy class 2.""" pass class MainClass3: """Parent dummy class 3.""" pass class MainClass4: """Parent dummy class 4.""" pass class MainClass5: """Parent dummy class 5.""" ...
"""Main classes.""" class Mainclass1: """Parent dummy class 1.""" pass class Mainclass2: """Parent dummy class 2.""" pass class Mainclass3: """Parent dummy class 3.""" pass class Mainclass4: """Parent dummy class 4.""" pass class Mainclass5: """Parent dummy class 5.""" pass ...
class SystemFonts(object): """ Specifies the fonts used to display text in Windows display elements. """ @staticmethod def GetFontByName(systemFontName): """ GetFontByName(systemFontName: str) -> Font Returns a font object that corresponds to the specified system font name. systemFontNam...
class Systemfonts(object): """ Specifies the fonts used to display text in Windows display elements. """ @staticmethod def get_font_by_name(systemFontName): """ GetFontByName(systemFontName: str) -> Font Returns a font object that corresponds to the specified system font name. sys...
# -*- coding: utf-8 -*- # Copyright 2021 Cohesity Inc. class BackupSourceStats(object): """Implementation of the 'BackupSourceStats' model. Specifies statistics about a Backup task in a Protection Job Run. Specifies statistics for one backup task. One backup task is used to backup on Protection Sour...
class Backupsourcestats(object): """Implementation of the 'BackupSourceStats' model. Specifies statistics about a Backup task in a Protection Job Run. Specifies statistics for one backup task. One backup task is used to backup on Protection Source. This structure is also used to aggregate stats of ...
sample_rate = 16000 """number: Target sample rate during feature extraction.""" n_window = 1024 """int: Size of STFT window.""" hop_length = 664 """int: Number of samples between frames.""" n_mels = 64 """int: Number of Mel bins."""
sample_rate = 16000 'number: Target sample rate during feature extraction.' n_window = 1024 'int: Size of STFT window.' hop_length = 664 'int: Number of samples between frames.' n_mels = 64 'int: Number of Mel bins.'
# Copyright (c) 2021 Huawei Technologies Co.,Ltd. All rights reserved. # # StratoVirt is licensed under Mulan PSL v2. # You can use this software according to the terms and conditions of the Mulan # PSL v2. # You may obtain a copy of Mulan PSL v2 at: # http:#license.coscl.org.cn/MulanPSL2 # THIS SOFTWARE IS PRO...
"""Exceptions""" class Unknownfeatureexception(Exception): """Exception Class for invalid build feature.""" def __init__(self): """Just a constructor.""" Exception.__init__(self, 'Trying to get build binaries for unknown feature!') class Ssherror(Exception): """SSH error exception""" ...
def f(x): if(x>4): return f(x-1)+2*x elif(x>1 and x<=4): return f(x-2)*x + x else: return x print(f(6))
def f(x): if x > 4: return f(x - 1) + 2 * x elif x > 1 and x <= 4: return f(x - 2) * x + x else: return x print(f(6))
# encoding: utf-8 # module Grasshopper.GUI.Canvas.TagArtists calls itself TagArtists # from Grasshopper,Version=1.0.0.20,Culture=neutral,PublicKeyToken=dda4f5ec2cd80803 # by generator 1.145 """ NamespaceTracker represent a CLS namespace. """ # no imports # no functions # classes class GH_TagArtist(object,IG...
""" NamespaceTracker represent a CLS namespace. """ class Gh_Tagartist(object, IGH_TagArtist): def paint(self, canvas, channel): """ Paint(self: GH_TagArtist,canvas: GH_Canvas,channel: GH_CanvasChannel) """ pass def __init__(self, *args): """ x.__init__(...) initializes x; see x.__cla...
# Copyright 2016 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
"""Definition for Google Cloud Natural Language API entities. An entity is used to describe a proper name extracted from text. """ class Entitytype(object): """List of possible entity types.""" unknown = 'UNKNOWN' 'Unknown entity type.' person = 'PERSON' 'Person entity type.' location = 'LOCAT...
""" Code for identification of central nodes in a network. Let G_v be the network where f_v is a variable, then a node is "significant" if #ATTRACTORS(G_v) > #ATTRACTORS(G), and "central" if #ATTRACTORS(G_v) = max_u(#ATTRACTORS(G_u)) """
""" Code for identification of central nodes in a network. Let G_v be the network where f_v is a variable, then a node is "significant" if #ATTRACTORS(G_v) > #ATTRACTORS(G), and "central" if #ATTRACTORS(G_v) = max_u(#ATTRACTORS(G_u)) """
def stars_decorator(f): def wrapper(n): print("*" * 50) f(n) print("*" * 50) return wrapper # let's decorate greet: @stars_decorator def greet(name): print("Howdy {}!".format(name)) # and use it: greet("Pesho")
def stars_decorator(f): def wrapper(n): print('*' * 50) f(n) print('*' * 50) return wrapper @stars_decorator def greet(name): print('Howdy {}!'.format(name)) greet('Pesho')
tabby_cat="\tI'm tabbed in"; persian_cat="I'm split\non s line." backslash_cat="i'm \\ a \\ cat" fat_cat="I'll do a list:\t* Cat food \t* Fishies \t* Catnip\n\t* Grass" print(tabby_cat) print(persian_cat) print(backslash_cat) print(fat_cat)
tabby_cat = "\tI'm tabbed in" persian_cat = "I'm split\non s line." backslash_cat = "i'm \\ a \\ cat" fat_cat = "I'll do a list:\t* Cat food \t* Fishies \t* Catnip\n\t* Grass" print(tabby_cat) print(persian_cat) print(backslash_cat) print(fat_cat)
t= int(input("Enter the number of test cases\n")) n=[] stack=[] for i in range(t): n.append(input()) l=len(n[i]) stack.append([]) t=n[i][l-1] stack[i].append(n[i][l-1]) for j in range(l-2,-1,-1): if n[i][j]!=t: stack[i].append(n[i][j]) t=n[i][j] for i in stack: ...
t = int(input('Enter the number of test cases\n')) n = [] stack = [] for i in range(t): n.append(input()) l = len(n[i]) stack.append([]) t = n[i][l - 1] stack[i].append(n[i][l - 1]) for j in range(l - 2, -1, -1): if n[i][j] != t: stack[i].append(n[i][j]) t = n[i][...
def solution(a): sm_num = min(a) while not( all(x % sm_num == 0 for x in a)): a = sorted(a) lg_num = a[-1] sm_num = a[0] if lg_num % sm_num == 0: a[-1] = sm_num else: a[-1] = lg_num % sm_num return len(a) * sm_num
def solution(a): sm_num = min(a) while not all((x % sm_num == 0 for x in a)): a = sorted(a) lg_num = a[-1] sm_num = a[0] if lg_num % sm_num == 0: a[-1] = sm_num else: a[-1] = lg_num % sm_num return len(a) * sm_num
class AnimeDLError(Exception): pass class URLError(AnimeDLError): pass class NotFoundError(AnimeDLError): pass
class Animedlerror(Exception): pass class Urlerror(AnimeDLError): pass class Notfounderror(AnimeDLError): pass
''' Python program to format a specified string limiting the length of a string. ''' str_num = "1234567890" print("Original string:",str_num) print('%.6s' % str_num) print('%.9s' % str_num) print('%.10s' % str_num)
""" Python program to format a specified string limiting the length of a string. """ str_num = '1234567890' print('Original string:', str_num) print('%.6s' % str_num) print('%.9s' % str_num) print('%.10s' % str_num)
# Copyright Notice: # Copyright 2018 Dell, Inc. All rights reserved. # License: BSD License. For full license text see link: https://github.com/RedDrum-Redfish-Project/RedDrum-Frontend/LICENSE.txt class RdSystemsBackend(): # class for backend systems resource APIs def __init__(self,rdr): self....
class Rdsystemsbackend: def __init__(self, rdr): self.version = 1 self.rdr = rdr def update_resource_dbs(self, systemid, updateStaticProps=False, updateNonVols=True): return (0, False) def do_system_reset(self, systemid, resetType): self.rdr.logMsg('DEBUG', '--------SIM BA...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def swapPairs(self, head: ListNode) -> ListNode: if not head or not head.next: return head newhead = head.next pt...
class Solution: def swap_pairs(self, head: ListNode) -> ListNode: if not head or not head.next: return head newhead = head.next ptr = head prev = None while ptr: if ptr.next: tmp = ptr.next.next ptr.next.next = ptr ...
class Rectangle: # write your code here def __init__(self, x1, y1, x2, y2): self.x1 = x1 self.y1 = y1 self.x2 = x2 self.y2 = y2 print('Rectangle(',x1,', ',y1,', ',x2,', ',y2,') created') # Alternative Solutions class Rectangle2: def __init__(self, x1, y1, x2, y2): # class constructor if x...
class Rectangle: def __init__(self, x1, y1, x2, y2): self.x1 = x1 self.y1 = y1 self.x2 = x2 self.y2 = y2 print('Rectangle(', x1, ', ', y1, ', ', x2, ', ', y2, ') created') class Rectangle2: def __init__(self, x1, y1, x2, y2): if x1 < x2 and y1 > y2: ...
## Idiomatic dict comprehension # No.1 def i1(): emails = {user.name: user.email for user in users if user.email} # No.2 def i2(): dict_compr = {k: k**2 for k in range(10000)} # No.3 def i3(): new_dict_comp = {n:n**2 for n in numbers if n%2 == 0} # No.4 def i4(): dict1 = {'a': 1, 'b'...
def i1(): emails = {user.name: user.email for user in users if user.email} def i2(): dict_compr = {k: k ** 2 for k in range(10000)} def i3(): new_dict_comp = {n: n ** 2 for n in numbers if n % 2 == 0} def i4(): dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6} dict1_triple_cond = {k: v for...
""" 0526. Beautiful Arrangement Medium Suppose you have n integers labeled 1 through n. A permutation of those n integers perm (1-indexed) is considered a beautiful arrangement if for every i (1 <= i <= n), either of the following is true: perm[i] is divisible by i. i is divisible by perm[i]. Given an integer n, retu...
""" 0526. Beautiful Arrangement Medium Suppose you have n integers labeled 1 through n. A permutation of those n integers perm (1-indexed) is considered a beautiful arrangement if for every i (1 <= i <= n), either of the following is true: perm[i] is divisible by i. i is divisible by perm[i]. Given an integer n, retu...
print("Hello World1") a = 1 b = 2 c = a+b print("c:",c)
print('Hello World1') a = 1 b = 2 c = a + b print('c:', c)
class Solution: def largestTriangleArea(self, points): """ :type points: List[List[int]] :rtype: float """ maxArea = 0 n = len(points) def area(p1, p2, p3): return 0.5 * abs(p1[0] * p2[1] + p2[0] * p3[1] + p3[0] * p1[1] - p2[0] * p1[1] - p...
class Solution: def largest_triangle_area(self, points): """ :type points: List[List[int]] :rtype: float """ max_area = 0 n = len(points) def area(p1, p2, p3): return 0.5 * abs(p1[0] * p2[1] + p2[0] * p3[1] + p3[0] * p1[1] - p2[0] * p1[1] - p3[0]...
''' A simple documentation utility for python. It extracts the documentation from the `docstring` and generate `markdown` files from that. This documentation is also generated using `code2doc`. Module dependency graph: ![design](../img/design.png) Here are the list of all files and folders in this module:...
""" A simple documentation utility for python. It extracts the documentation from the `docstring` and generate `markdown` files from that. This documentation is also generated using `code2doc`. Module dependency graph: ![design](../img/design.png) Here are the list of all files and folders in this module: """
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: The root of the binary search tree. @param k1 and k2: range k1 to k2. @return: Return all keys that k1<=key<=k2 in ascending ord...
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: The root of the binary search tree. @param k1 and k2: range k1 to k2. @return: Return all keys that k1<=key<=k2 in ascending or...
#Author: OMKAR PATHAK #This program checks whether the entered number is prime or not def checkPrime(number): '''This function checks for prime number''' isPrime = False if number == 2: print(number, 'is a Prime Number') if number > 1: for i in range(2, number): if number % ...
def check_prime(number): """This function checks for prime number""" is_prime = False if number == 2: print(number, 'is a Prime Number') if number > 1: for i in range(2, number): if number % i == 0: print(number, 'is not a Prime Number') is_pri...
class AnalyticalLinkType(ElementType,IDisposable): """ An object that specifies the analysis properties for an AnalyticalLink element. """ def Dispose(self): """ Dispose(self: Element,A_0: bool) """ pass def getBoundingBox(self,*args): """ getBoundingBox(self: Element,view: View) -> BoundingBoxXYZ """ ...
class Analyticallinktype(ElementType, IDisposable): """ An object that specifies the analysis properties for an AnalyticalLink element. """ def dispose(self): """ Dispose(self: Element,A_0: bool) """ pass def get_bounding_box(self, *args): """ getBoundingBox(self: Element,view: Vie...
# # PySNMP MIB module APPIAN-TIMESLOTS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/APPIAN-TIMESLOTS-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:24:00 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (defau...
(ac_admin_status, ac_osap) = mibBuilder.importSymbols('APPIAN-SMI-MIB', 'AcAdminStatus', 'acOsap') (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constr...
# # PySNMP MIB module Unisphere-Data-ERX-Registry (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Unisphere-Data-ERX-Registry # Produced by pysmi-0.3.4 at Wed May 1 15:31:00 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python versio...
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, value_size_constraint, single_value_constraint, constraints_union, value_range_constraint) ...
# parsetab.py # This file is automatically generated. Do not edit. _tabversion = '3.2' _lr_method = 'LALR' _lr_signature = '\x11\x13C\xf3\x8a\xda\x0f\xf9op-\xf5B\xe1`\xb1' _lr_action_items = {'BOX':([0,8,9,12,14,15,16,23,24,25,28,29,30,31,32,35,37,40,48,54,56,59,63,64,70,74,75,80,84,87,91,92,95,99,101,104,111,1...
_tabversion = '3.2' _lr_method = 'LALR' _lr_signature = '\x11\x13Có\x8aÚ\x0fùop-õBá`±' _lr_action_items = {'BOX': ([0, 8, 9, 12, 14, 15, 16, 23, 24, 25, 28, 29, 30, 31, 32, 35, 37, 40, 48, 54, 56, 59, 63, 64, 70, 74, 75, 80, 84, 87, 91, 92, 95, 99, 101, 104, 111, 112, 113, 114], [1, -14, -3, -7, 1, -8, -10, -11, -39, -...
#!/usr/bin/env python3 END_MARK = None # any singleton could be used for this FALLBACK = '0' # text to print when there are no matches for _ in range(int(input())): input() # don't need n # Build the trie. trie = {} for word in input().split(): cur = trie for ch in word: ...
end_mark = None fallback = '0' for _ in range(int(input())): input() trie = {} for word in input().split(): cur = trie for ch in word: try: cur = cur[ch] except KeyError: nxt = {} cur[ch] = nxt cur = nxt ...
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: temp = [] result = 0 for i in s: if i not in temp: temp.append(i) else: result = max(result, len(temp)) temp = temp[temp.index(i)+1::] te...
class Solution: def length_of_longest_substring(self, s: str) -> int: temp = [] result = 0 for i in s: if i not in temp: temp.append(i) else: result = max(result, len(temp)) temp = temp[temp.index(i) + 1:] ...
followers_likes= {} followers_comments= {} while True: line = input() if line == 'Log out': break args = line.split(': ') command= args[0] username = args[1] if command == 'New follower': if username not in followers_likes and username not in followers_comments: ...
followers_likes = {} followers_comments = {} while True: line = input() if line == 'Log out': break args = line.split(': ') command = args[0] username = args[1] if command == 'New follower': if username not in followers_likes and username not in followers_comments: fo...
# Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. DEPS = [ 'core', 'recipe_engine/path', 'recipe_engine/properties', ] def RunSteps(api): api.core.setup() def GenTests(api): buildername = 'Bui...
deps = ['core', 'recipe_engine/path', 'recipe_engine/properties'] def run_steps(api): api.core.setup() def gen_tests(api): buildername = 'Build-Win-Clang-x86_64-Release-Vulkan' yield (api.test('test') + api.properties(buildername=buildername, repository='https://skia.googlesource.com/skia.git', revision='...
a=int(input("Enter a Number")) if (a%2==0): print(a,"Entered Number is Divisible by 2") if(a%5==0): print(a,"Entered Number is Divisible by 5") else: print(a,"Entered Number is Not Divisible by 5") else: print(a,"Entered Number is Not Divisible by 2")
a = int(input('Enter a Number')) if a % 2 == 0: print(a, 'Entered Number is Divisible by 2') if a % 5 == 0: print(a, 'Entered Number is Divisible by 5') else: print(a, 'Entered Number is Not Divisible by 5') else: print(a, 'Entered Number is Not Divisible by 2')
s = map(ord, input()) r = 0 c = 0 a = ord('a') z = ord('z') for x in s: if a <= x <= z: x -= a r += min(abs(x - c), 26 - abs(x - c)) c = x else: break print(r)
s = map(ord, input()) r = 0 c = 0 a = ord('a') z = ord('z') for x in s: if a <= x <= z: x -= a r += min(abs(x - c), 26 - abs(x - c)) c = x else: break print(r)
# generated by scripts/build_keyboard_adjacency_graphs.py ADJACENCY_GRAPHS = { "qwerty": {"!": ["`~", None, None, "2@", "qQ", None], "\"": [";:", "[{", "]}", None, None, "/?"], "#": ["2@", None, None, "4$", "eE", "wW"], "$": ["3#", None, None, "5%", "rR", "eE"], "%": ["4$", None, None, "6^", "tT", "rR"], "&": ["6^"...
adjacency_graphs = {'qwerty': {'!': ['`~', None, None, '2@', 'qQ', None], '"': [';:', '[{', ']}', None, None, '/?'], '#': ['2@', None, None, '4$', 'eE', 'wW'], '$': ['3#', None, None, '5%', 'rR', 'eE'], '%': ['4$', None, None, '6^', 'tT', 'rR'], '&': ['6^', None, None, '8*', 'uU', 'yY'], "'": [';:', '[{', ']}', None, N...
class Solution: def __init__(self, rects): self.rects, self.ranges, sm = rects, [], 0 for x1, y1, x2, y2 in rects: sm += (x2 - x1 + 1) * (y2 - y1 + 1) self.ranges.append(sm) def pick(self): x1, y1, x2, y2 = self.rects[bisect.bisect_left(self.ranges, random.randi...
class Solution: def __init__(self, rects): (self.rects, self.ranges, sm) = (rects, [], 0) for (x1, y1, x2, y2) in rects: sm += (x2 - x1 + 1) * (y2 - y1 + 1) self.ranges.append(sm) def pick(self): (x1, y1, x2, y2) = self.rects[bisect.bisect_left(self.ranges, rand...
class FoldrNode(object): def __init__(self, depth, code): ''' >>> node = FoldrNode(0,'aaa') >>> node.add(FoldrNode(1,'bbb')) >>> node.add(FoldrNode(2,'ccc')) >>> node.depth 0 >>> node.code 'aaa' >>> node.parent ''' self.dept...
class Foldrnode(object): def __init__(self, depth, code): """ >>> node = FoldrNode(0,'aaa') >>> node.add(FoldrNode(1,'bbb')) >>> node.add(FoldrNode(2,'ccc')) >>> node.depth 0 >>> node.code 'aaa' >>> node.parent """ self.dept...
class RebarShapeSegment(object,IDisposable): """ Part of a RebarShapeDefinitionBySegments,representing one segment of a shape definition. """ def Dispose(self): """ Dispose(self: RebarShapeSegment) """ pass def GetConstraints(self): """ GetConstraints(self: RebarShapeSegment) -> IList[RebarS...
class Rebarshapesegment(object, IDisposable): """ Part of a RebarShapeDefinitionBySegments,representing one segment of a shape definition. """ def dispose(self): """ Dispose(self: RebarShapeSegment) """ pass def get_constraints(self): """ GetConstraints(self: RebarShapeSeg...
class UnknownWrapper(object): """ Wraps objects the marshaler should marshal as a VT_UNKNOWN. UnknownWrapper(obj: object) """ @staticmethod def __new__(self,obj): """ __new__(cls: type,obj: object) """ pass WrappedObject=property(lambda self: object(),lambda self,v: None,lambda self: None) ...
class Unknownwrapper(object): """ Wraps objects the marshaler should marshal as a VT_UNKNOWN. UnknownWrapper(obj: object) """ @staticmethod def __new__(self, obj): """ __new__(cls: type,obj: object) """ pass wrapped_object = property(lambda self: object(), lambda self, v: None, l...
class Common(object): def __init__(self): pass def start(self, f, title): f.writelines("[TITLE]\n") f.writelines(title) f.writelines("\n") f.writelines("\n") def end(self, f): f.writelines("[END]") f.writelines("\n") def export_tags(self, f): ...
class Common(object): def __init__(self): pass def start(self, f, title): f.writelines('[TITLE]\n') f.writelines(title) f.writelines('\n') f.writelines('\n') def end(self, f): f.writelines('[END]') f.writelines('\n') def export_tags(self, f): ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Module with dummy functionality that isn't tested, to show a gap in the code coverage. """ class Baz(object): """ A class with many lines that don't get tested """ a: int = 123 b: int = 123 c: int = 123 d: int = 123 e: int = 123 ...
""" Module with dummy functionality that isn't tested, to show a gap in the code coverage. """ class Baz(object): """ A class with many lines that don't get tested """ a: int = 123 b: int = 123 c: int = 123 d: int = 123 e: int = 123 f: int = 123 g: int = 123 h: int = 123 ...
# -*- coding: utf-8 -*- source = """ AUDUSD NEW SIGNAL 2018.03.22 10:05:36AUDUSD #33557610BUY Above: 0.7754StopLoss: 0.7726TakeProfit: 0.7810 """ result = """AUDUSD NEW SIGNAL 2018.03.22 10:05:36 AUDUSD #33557610 BUY Above: 0.7754 StopLoss: 0.7726 TakeProfit: 0.7810""" source1 = """ EURGBP NEW PENDING ORDER 2018...
source = '\nAUDUSD NEW SIGNAL\n\n2018.03.22 10:05:36AUDUSD #33557610BUY Above: 0.7754StopLoss: 0.7726TakeProfit: 0.7810\n' result = 'AUDUSD NEW SIGNAL\n\n2018.03.22 10:05:36\nAUDUSD #33557610\nBUY Above: 0.7754\nStopLoss: 0.7726\nTakeProfit: 0.7810' source1 = '\nEURGBP NEW PENDING ORDER \n\n2018.03.22 14:00:04EURGBP #3...
# Flask settings DEBUG = False SQLALCHEMY_DATABASE_URI = "sqlite:///hortiradar.sqlite" CSRF_ENABLED = True # Flask-Babel BABEL_DEFAULT_LOCALE = "nl" # Flask-Mail settings MAIL_USERNAME = "noreply@acba.labs.vu.nl" MAIL_DEFAULT_SENDER = '"Hortiradar" <noreply@acba.labs.vu.nl>' MAIL_SERVER = "localhost" MAIL_PORT = 25 #...
debug = False sqlalchemy_database_uri = 'sqlite:///hortiradar.sqlite' csrf_enabled = True babel_default_locale = 'nl' mail_username = 'noreply@acba.labs.vu.nl' mail_default_sender = '"Hortiradar" <noreply@acba.labs.vu.nl>' mail_server = 'localhost' mail_port = 25 user_app_name = 'Hortiradar' user_enable_login_without_c...
""" Module containing errors that can be raised by key stores. """ class Error(Exception): """ Base class for key store errors. """ class UnsupportedOperation(Error): """ Raised when an unsupported operation is attempted. """ class KeyNotFound(Error): """ Raised when no SSH key can...
""" Module containing errors that can be raised by key stores. """ class Error(Exception): """ Base class for key store errors. """ class Unsupportedoperation(Error): """ Raised when an unsupported operation is attempted. """ class Keynotfound(Error): """ Raised when no SSH key can be...
def bubble_sort(arr): for i in range(len(arr)): for j in range(0, len(arr) - i - 1): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] array = [5, 3, 2, 4, 11, 9, 15, 7] bubble_sort(array) print(array)
def bubble_sort(arr): for i in range(len(arr)): for j in range(0, len(arr) - i - 1): if arr[j] > arr[j + 1]: (arr[j], arr[j + 1]) = (arr[j + 1], arr[j]) array = [5, 3, 2, 4, 11, 9, 15, 7] bubble_sort(array) print(array)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # How many rectangles can be formed from a set of points # jill-jenn vie et christoph durr - 2014-2015 # snip{ def rectangles_from_points(S): """How many rectangles can be formed from a set of points :param S: list of points, as coordinate pairs :returns: th...
def rectangles_from_points(S): """How many rectangles can be formed from a set of points :param S: list of points, as coordinate pairs :returns: the number of rectangles :complexity: :math:`O(n^2)` """ answ = 0 pairs = {} for j in range(len(S)): for i in range(j): (p...
# Epiphany (25512) | Luminous 4th Job if chr.getJob() == 2711: sm.flipDialoguePlayerAsSpeaker() sm.sendNext("(I feel the Light and Dark within me coming together, " "merging into a new kind of energy!)") sm.sendSay("(I've reached a new level of balance between the Light and Dark.)") sm.jobAdvance(...
if chr.getJob() == 2711: sm.flipDialoguePlayerAsSpeaker() sm.sendNext('(I feel the Light and Dark within me coming together, merging into a new kind of energy!)') sm.sendSay("(I've reached a new level of balance between the Light and Dark.)") sm.jobAdvance(2712) sm.startQuest(parentID) sm.comple...
#!/usr/bin/env python # -*- coding: utf-8 -*- class Writter(): """a class to normalize all output in console""" verbose = False def printed(method): """decorator to check if the self.verbose is true """ def wrapper(cls, *args): if cls.verbose: return method(cls, *args) return wrapper @classmeth...
class Writter: """a class to normalize all output in console""" verbose = False def printed(method): """decorator to check if the self.verbose is true """ def wrapper(cls, *args): if cls.verbose: return method(cls, *args) return wrapper @classmethod...
# encoding: utf-8 """ protocol.py Created by Thomas Mangin on 2010-01-15. Copyright (c) 2009-2013 Exa Networks. All rights reserved. """ # ===================================================================== Protocol # http://www.iana.org/assignments/protocol-numbers/ class Protocol (int): ICMP = 0x01 IGMP = ...
""" protocol.py Created by Thomas Mangin on 2010-01-15. Copyright (c) 2009-2013 Exa Networks. All rights reserved. """ class Protocol(int): icmp = 1 igmp = 2 tcp = 6 egp = 8 udp = 17 rsvp = 46 gre = 47 esp = 50 ah = 51 ospf = 89 ipip = 94 pim = 103 sctp = 132 ...
''' Graph as: - Vertex/node - contains name "key", data "payload" - Edge - connects 2 vertices, symbolizing relationship - Weight - cost to traverse vertex - G = (V,E) (V=vertex, E=edges) ex.) V = {V0..V5}, E = {(V0, V1, 5), (V1, V2, 2) ...} - Path - sequence of vertices connected by edges - Cycle - path that start...
""" Graph as: - Vertex/node - contains name "key", data "payload" - Edge - connects 2 vertices, symbolizing relationship - Weight - cost to traverse vertex - G = (V,E) (V=vertex, E=edges) ex.) V = {V0..V5}, E = {(V0, V1, 5), (V1, V2, 2) ...} - Path - sequence of vertices connected by edges - Cycle - path that start...
class Solution: def numSquares(self, n: int) -> int: if n==1: return n dp=[(n+1) for i in range(n+1)] sq=[i**2 for i in range(int(sqrt(n))+1)] for i in range(len(dp)): if i in sq: dp[i]=1 else: for j in sq: ...
class Solution: def num_squares(self, n: int) -> int: if n == 1: return n dp = [n + 1 for i in range(n + 1)] sq = [i ** 2 for i in range(int(sqrt(n)) + 1)] for i in range(len(dp)): if i in sq: dp[i] = 1 else: for j ...
load(":intellij_module.bzl", "IntellijModuleConfig") BazelPackageDep = provider( fields = { "bazel_package": "package name", "label_name": "label name", "attr_name": "the attribute name through which the dependency was established", "depends_on_bazel_package": "the bazel package dep...
load(':intellij_module.bzl', 'IntellijModuleConfig') bazel_package_dep = provider(fields={'bazel_package': 'package name', 'label_name': 'label name', 'attr_name': 'the attribute name through which the dependency was established', 'depends_on_bazel_package': 'the bazel package depends on this other package'}) bazel_pac...
# Your Nessus Scanner API Keys ACCESS_KEY = "Your_Nessus_Access_Key" SECRET_KEY = "Your_Nessus_SecretKey" # Your URL for the API API_URL = "https://nessus.yourInfo.com" # The Port Number API_PORT = "1234" # Warnings Greater than or equal to the number you want SEVERITY = '1' # Meaning we will see 1 and above # Bef...
access_key = 'Your_Nessus_Access_Key' secret_key = 'Your_Nessus_SecretKey' api_url = 'https://nessus.yourInfo.com' api_port = '1234' severity = '1' directory = False email = False email_address = 'Send_Emails_From_Here@site.com' password = '' delimiter = ':'
def create_python_script(filename): comments = "# Start of a new Python program" with open("program.py","w") as f: filesize = f.write(comments) return(filesize) print(create_python_script("program.py"))
def create_python_script(filename): comments = '# Start of a new Python program' with open('program.py', 'w') as f: filesize = f.write(comments) return filesize print(create_python_script('program.py'))
# The following RTTTL tunes were extracted from the following: # https://github.com/onebeartoe/media-players/blob/master/pi-ezo/src/main/java/org/onebeartoe/media/piezo/ports/rtttl/BuiltInSongs.java # most of which originated from here: # http://www.picaxe.com/RTTTL-Ringtones-for-Tune-Command/ # SONGS = [ 'Super M...
songs = ['Super Mario - Main Theme:d=4,o=5,b=125:a,8f.,16c,16d,16f,16p,f,16d,16c,16p,16f,16p,16f,16p,8c6,8a.,g,16c,a,8f.,16c,16d,16f,16p,f,16d,16c,16p,16f,16p,16a#,16a,16g,2f,16p,8a.,8f.,8c,8a.,f,16g#,16f,16c,16p,8g#.,2g,8a.,8f.,8c,8a.,f,16g#,16f,8c,2c6', 'Super Mario - Title Music:d=4,o=5,b=125:8d7,8d7,8d7,8d6,8d7,8d7...
class Solution(object): def minFlipsMonoIncr(self, s): """ :type s: str :rtype: int """ # we split the string into left part and right part, and count how many ones in left and zeros in right left_ones = 0 right_zeroes = s.count("0") ans = right_zeroe...
class Solution(object): def min_flips_mono_incr(self, s): """ :type s: str :rtype: int """ left_ones = 0 right_zeroes = s.count('0') ans = right_zeroes for c in s: if c == '1': left_ones += 1 if c == '0': ...
#https://leetcode.com/problems/count-binary-substrings/submissions/ # Referred : https://www.youtube.com/watch?v=MrVfk4HKAuU class Solution(object): def countBinarySubstrings(self, s): """ :type s: str :rtype: int """ groups = [1] for i in range(1, len(s)): ...
class Solution(object): def count_binary_substrings(self, s): """ :type s: str :rtype: int """ groups = [1] for i in range(1, len(s)): if s[i - 1] != s[i]: groups.append(1) else: groups[-1] += 1 ans = 0 ...
# config file name RIGOR_YML = "rigor.yml" # content-types TEXT_HTML = "text/html" TEXT_PLAIN = "text/plain" APPLICATION_JSON = "application/json" # headers CONTENT_TYPE = "Content-Type"
rigor_yml = 'rigor.yml' text_html = 'text/html' text_plain = 'text/plain' application_json = 'application/json' content_type = 'Content-Type'
"""General constants from python-openflow library.""" # Max values of each basic type UBINT8_MAX_VALUE = 255 UBINT16_MAX_VALUE = 65535 UBINT32_MAX_VALUE = 4294967295 UBINT64_MAX_VALUE = 18446744073709551615 OFP_ETH_ALEN = 6 OFP_MAX_PORT_NAME_LEN = 16 OFP_MAX_TABLE_NAME_LEN = 32 SERIAL_NUM_LEN = 32 DESC_STR_LEN = 256
"""General constants from python-openflow library.""" ubint8_max_value = 255 ubint16_max_value = 65535 ubint32_max_value = 4294967295 ubint64_max_value = 18446744073709551615 ofp_eth_alen = 6 ofp_max_port_name_len = 16 ofp_max_table_name_len = 32 serial_num_len = 32 desc_str_len = 256
__char_num = [('a',0),('b',1),('c',2),('d',3),('e',4),('f',5),('g',6),('h',7),('i',8),('j',9),('k',10),('l',11),('m',12),('n',13),('o',14),('p',15),('q',16),('r',17),('s',18),('t',19),('u',20),('v',21),('w',22),('x',23),('y',24),('z',25)] def char2num(char): return next(filter(lambda x: x[0] == char.lower(), __...
__char_num = [('a', 0), ('b', 1), ('c', 2), ('d', 3), ('e', 4), ('f', 5), ('g', 6), ('h', 7), ('i', 8), ('j', 9), ('k', 10), ('l', 11), ('m', 12), ('n', 13), ('o', 14), ('p', 15), ('q', 16), ('r', 17), ('s', 18), ('t', 19), ('u', 20), ('v', 21), ('w', 22), ('x', 23), ('y', 24), ('z', 25)] def char2num(char): retur...
class Solution: def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool: def intersect(p_left, p_right, q_left, q_right): return min(p_right, q_right) > max(p_left, q_left) return (intersect(rec1[0], rec1[2], rec2[0], rec2[2]) and intersect(rec1[1], rec1[3], rec2[1], rec2[3]))
class Solution: def is_rectangle_overlap(self, rec1: List[int], rec2: List[int]) -> bool: def intersect(p_left, p_right, q_left, q_right): return min(p_right, q_right) > max(p_left, q_left) return intersect(rec1[0], rec1[2], rec2[0], rec2[2]) and intersect(rec1[1], rec1[3], rec2[1], re...
__all__ = [ "messenger", "writer", "processor", "listener", ]
__all__ = ['messenger', 'writer', 'processor', 'listener']
class Solution: def hammingDistance(self, x: int, y: int) -> int: if x < 0 or y < 0: raise Exception("Negative Input(s)") h_dist = 0 while x > 0 or y > 0: if (x ^ y) & 1 == 1: h_dist += 1 x >>= 1 y >>= 1 return h_dist
class Solution: def hamming_distance(self, x: int, y: int) -> int: if x < 0 or y < 0: raise exception('Negative Input(s)') h_dist = 0 while x > 0 or y > 0: if (x ^ y) & 1 == 1: h_dist += 1 x >>= 1 y >>= 1 return h_dist
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def helper(self, l1, r1, l2, r2): if l1 > r1: return None mid = self.postorder[r2] ...
class Solution: def helper(self, l1, r1, l2, r2): if l1 > r1: return None mid = self.postorder[r2] mid_idx = self.inorder.index(mid) left_size = mid_idx - l1 return tree_node(mid, self.helper(l1, l1 + left_size - 1, l2, l2 + left_size - 1), self.helper(mid_idx + ...
def DIST_NAIF(x, y): return DIST_NAIF_REC(x, y, 0, 0, 0, float('inf')) def DIST_NAIF_REC(x, y, i, j, c, dist): """ x: Dna y: Dna i: indice dans [0..|x|] j: indice dans [0..|y|] dist: coup du meilleur alignement connu avant cet appel return dist meilleur coup connu apre cet appel ...
def dist_naif(x, y): return dist_naif_rec(x, y, 0, 0, 0, float('inf')) def dist_naif_rec(x, y, i, j, c, dist): """ x: Dna y: Dna i: indice dans [0..|x|] j: indice dans [0..|y|] dist: coup du meilleur alignement connu avant cet appel return dist meilleur coup connu apre cet appel ...
""" Safe Squares from Rooks On a generalized n-by-n chessboard, there are some number of rooks, each rook represented as a two-tuple (row, column) of the row and the column that it is in. (The rows and columns are numbered from 0 to n-1.) A chess rook covers all squares that are in the same row or in the same column a...
""" Safe Squares from Rooks On a generalized n-by-n chessboard, there are some number of rooks, each rook represented as a two-tuple (row, column) of the row and the column that it is in. (The rows and columns are numbered from 0 to n-1.) A chess rook covers all squares that are in the same row or in the same column a...
""" Link: https://www.hackerrank.com/challenges/python-print/problem?isFullScreen=true Problem: Print Function """ #Solution if __name__ == '__main__': n = int(input()) for i in range(1,n+1): print(i, end="")
""" Link: https://www.hackerrank.com/challenges/python-print/problem?isFullScreen=true Problem: Print Function """ if __name__ == '__main__': n = int(input()) for i in range(1, n + 1): print(i, end='')
def mergeSort(alist): if len(alist) > 1: mid = len(alist)//2 lefthalf = alist[:mid] righthalf = alist[mid:] mergeSort(lefthalf) mergeSort(righthalf) i = 0; j = 0; k = 0 while i < len(lefthalf) and j < len(righthalf): if lefthalf[i] < righthalf[j]...
def merge_sort(alist): if len(alist) > 1: mid = len(alist) // 2 lefthalf = alist[:mid] righthalf = alist[mid:] merge_sort(lefthalf) merge_sort(righthalf) i = 0 j = 0 k = 0 while i < len(lefthalf) and j < len(righthalf): if lefthalf[...
#AREA DO CIRCULO r= float(input()) resultado= 3.14* r**2/10000 print("Area={:.4f}".format(resultado) )
r = float(input()) resultado = 3.14 * r ** 2 / 10000 print('Area={:.4f}'.format(resultado))