content
stringlengths
7
1.05M
# -*- coding: utf-8 -*- # # Authors: Toni Ruottu, Finland 2014 # Tomi Jylhä-Ollila, Finland 2016-2019 # # This file is part of Kunquat. # # CC0 1.0 Universal, http://creativecommons.org/publicdomain/zero/1.0/ # # To the extent possible under law, Kunquat Affirmers have waived all # copyright and related or ne...
#num1=int(raw_input("Enter num #1:")) #num2=int(raw_input("Enter num #2:")) #total= num1 + num2 #print("The sum is: "+ str(total)) # need to be a string so computer can read it # all strings can be integers but not all integers can be strings # num = int(raw_input("Enter a number:")) # if num>0: # print("That's a p...
# -*- encoding: utf-8 -*- # This is a package that contains a number of modules that are used to # test import from the source files that have different encodings. # This file (the __init__ module of the package), is encoded in utf-8 # and contains a list of strings from various unicode planes that are # encoded...
class SinavroObject: pass def init(self, val): self.value = val gencls = lambda n: type(f'Sinavro{n.title()}', (SinavroObject,), {'__init__': init, 'type': n}) SinavroInt = gencls('int') SinavroFloat = gencls('float') SinavroString = gencls('string') SinavroBool = gencls('bool') SinavroArray = gencls('array'...
''' 191. Number of 1 Bits Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight). For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3. ''' class Solution(object): de...
def lambda_handler(event): try: first_num = event["queryStringParameters"]["firstNum"] except KeyError: first_num = 0 try: second_num = event["queryStringParameters"]["secondNum"] except KeyError: second_num = 0 try: operation_type = event["queryStringParame...
input1 = int(input("Enter the first number: ")) input2 = int(input("Enter the second number: ")) input3 = int(input("Enter the third number: ")) input4 = int(input("Enter the fourth number: ")) input5 = int(input("Enter the fifth number: ")) tuple_num = [] tuple_num.append(input1) tuple_num.append(input2) tuple_nu...
# Time: O(n!) # Space: O(n) class Solution(object): def constructDistancedSequence(self, n): """ :type n: int :rtype: List[int] """ def backtracking(n, i, result, lookup): if i == len(result): return True if result[i]: ...
#Longest Common Prefix in python #Implementation of python program to find the longest common prefix amongst the given list of strings. #If there is no common prefix then returning 0. #define the function to evaluate the longest common prefix def longestCommonPrefix(s): p = '' #declare an empty s...
#!/usr/bin/env python P = int(input()) for _ in range(P): N, n, m = [int(i) for i in input().split()] print(f"{N} {(n - m) * m + 1}")
def handler(event, context): return { "statusCode": 302, "headers": { "Location": "https://www.nhsx.nhs.uk/covid-19-response/data-and-covid-19/national-covid-19-chest-imaging-database-nccid/" }, }
# Utwórz klasy do reprezentacji Produktu, Zamówienia, Jabłek i Ziemniaków. # Stwórz po kilka obiektów typu jabłko i ziemniak i wypisz ich typ za pomocą funkcji wbudowanej type. # Stwórz listę zawierającą 5 zamówień oraz słownik, w którym kluczami będą nazwy produktów # a wartościami instancje klasy produkt. class Pr...
def bin2dec(binNumber): decNumber = 0 index = 1 binNumber = binNumber[::-1] for i in binNumber: number = int(i) * index decNumber = decNumber + number index = index * 2 return decNumber print('ВВЕДИТЕ ДВОИЧНОЕ 8-БИТНОЕ ЧИСЛО') binNumber = input('>') if len(binNumber) != 8: print('ВВЕДИТЕ ПРАВИЛЬНОЕ 8-БИТН...
__name__ = 'factory_djoy' __version__ = '2.2.0' __author__ = 'James Cooke' __copyright__ = '2021, {}'.format(__author__) __description__ = 'Factories for Django, creating valid model instances every time.' __email__ = 'github@jamescooke.info'
def get_lorawan_maximum_payload_size(dr): mac_payload_size_dic = {'0':59, '1':59, '2':59, '3':123, '4':230, '5':230, '6':230} fhdr_size = 7 #in bytes. Assuming that FOpts length is zero fport_size = 1 #in bytes frm_payload_size = mac_payload_size_dic.get(str(dr)) - fhdr_size - fport_size ret...
class CyclesMeshSettings: pass
l = ["+", "-"] def backRec(x): for j in l: x.append(j) if consistent(x): if solution(x): solutionFound(x) backRec(x) x.pop() def consistent(s): return len(s) < n def solution(s): summ = list2[0] if not len(s) == n -...
""" Triangle Challenge Given the perimeter and the area of a triangle, devise a function that returns the length of the sides of all triangles that fit those specifications. The length of the sides must be integers. Sort results in ascending order. triangle(perimeter, area) ➞ [[s1, s2, s3]] Examples triangle(12, 6) ➞ ...
# block between mission & 6th and howard & 5th in SF. # appears to have lots of buses. # https://www.openstreetmap.org/way/88572932 -- Mission St # https://www.openstreetmap.org/relation/3406710 -- 14X to Daly City # https://www.openstreetmap.org/relation/3406709 -- 14X to Downtown # https://www.openstreetmap.org/relat...
class Zoo: def __init__(self, name, locations): self.name = name self.stillActive = True self.locations = locations self.currentLocation = self.locations[1] def changeLocation(self, direction): neighborID = self.currentLocation.neighbors[direction] self.currentLo...
UNKNOWN = u'' def describe_track(track): """ Prepare a short human-readable Track description. track (mopidy.models.Track): Track to source song data from. """ title = track.name or UNKNOWN # Simple/regular case: normal song (e.g. from Spotify). if track.artists: artist = next(it...
# -*- coding: utf-8 -*- class Tile(int): TILES = ''' 1s 2s 3s 4s 5s 6s 7s 8s 9s 1p 2p 3p 4p 5p 6p 7p 8p 9p 1m 2m 3m 4m 5m 6m 7m 8m 9m ew sw ww nw wd gd rd '''.split() def as_data(self): return self.TILES[self // 4] class TilesConverter(object): @stat...
def test_get_news(sa_session, sa_backend, sa_child_news): assert(sa_child_news == sa_backend.get_news(sa_child_news.id)) assert(sa_backend.get_news(None) is None) def test_get_news_list(sa_session, sa_backend, sa_child_news): assert(sa_child_news in sa_backend.get_news_list()) assert(sa_child_news in ...
# Implemented from: https://stackoverflow.com/questions/9501337/binary-search-algorithm-in-python def binary_search(sequence, value): lo, hi = 0, len(sequence) - 1 while lo <= hi: mid = (lo + hi) // 2 if sequence[mid] < value: lo = mid + 1 elif value < sequence[mid]: ...
''' Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. Example: Given array nums = [-1, 2, 1, -4], and target = 1. The sum that is closest to...
"""An extension for workspace rules.""" load("@bazel_skylib//lib:paths.bzl", "paths") load("//:dependencies.bzl", "dependencies") def _workspace_dependencies_impl(ctx): platform = ctx.os.name if ctx.os.name != "mac os x" else "darwin" for dependency in dependencies: ctx.download( executabl...
# -*- coding:UTF-8 -*- ''' MIT License Copyright (c) 2018 Robin Chen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, co...
def print_lol(arr): for row in arr: if (isinstance(row, list)): print_lol(row) else: print row
class Source: """Source class to define News Source Objects""" def __init__(self,id,name,description,url,category,country): self.id = id self.name = name self.description = description self.url = url self.category = category self.country = country class Article:...
def cwinstart(callobj, *args, **kwargs): print('cwinstart') print(' args', repr(args)) for arg in args: print(' ', arg) print(' kwargs', len(kwargs)) for k, v in kwargs.items(): print(' ', k, v) w = callobj(*args, **kwargs) print(' callobj()->', w) return w def cwincall(req1, req2, ...
#!/usr/bin/env python3 # Copyright (C) 2020-2021 The btclib developers # # This file is part of btclib. It is subject to the license terms in the # LICENSE file found in the top-level directory of this distribution. # # No part of btclib including this file, may be copied, modified, propagated, # or distributed except...
for num in range(1,6): #code inside for loop if num == 4: continue #code inside for loop print(num) #code outside for loop print("continue statement executed on num = 4")
def get_remain(cpf: str, start: int, upto: int) -> int: total = 0 for count, num in enumerate(cpf[:upto]): try: total += int(num) * (start - count) except ValueError: return None remain = (total * 10) % 11 remain = remain if remain != 10 else 0 ...
class Student: def __init__(self, name, hours, qpoints): self.name = name self.hours = float(hours) self.qpoints = float(qpoints) def get_name(self): return self.name def get_hours(self): return self.hours def get_qpoints(self): return self.qpoints ...
class Solution: def firstUniqChar(self, s): table = {} for ele in s: table[ele] = table.get(ele, 0) + 1 # for i in range(len(s)): # if table[s[i]] == 1: # return i for ele in s: if table[ele] == 1: return s.index(ele...
#program to compute and print sum of two given integers (more than or equal to zero). # If given integers or the sum have more than 80 digits, print "overflow". print("Input first integer:") x = int(input()) print("Input second integer:") y = int(input()) if x >= 10 ** 80 or y >= 10 ** 80 or x + y >= 10 ** 80: pri...
# Crie um programa que leia nome, sexo e idade de várias pessoas, guardando os dados # de cada pessoa em um dicionário e todos os dicionários em uma lista. No final, mostre: # A) Quantas pessoas foram cadastradas B) A média de idade C) Uma lista com as mulheres # D) Uma lista de pessoas com idade acima da média dados ...
{ "targets": [ { "target_name": "allofw", "include_dirs": [ "<!@(pkg-config liballofw --cflags-only-I | sed s/-I//g)", "<!(node -e \"require('nan')\")" ], "libraries": [ "<!@(pkg-config liballofw --libs)", "<!@(pkg-config glew --libs)", ], "cflag...
TOKEN_PREALTA_CLIENTE = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6InJhdWx0ckBnbWFpbC5jb20iLCJleHAiOjQ3MzM1MTA0MDAsIm93bmVyX25hbWUiOiJSYXVsIEVucmlxdWUgVG9ycmVzIFJleWVzIiwidHlwZSI6ImVtYWlsX2NvbmZpcm1hdGlvbl9uZXdfY2xpZW50In0.R-nXh1nXvlBABfEdV1g81mdIzJqMFLvFV7FAP7PQRCM' TOKEN_PREALTA_CLIENTE_CADUCO = 'eyJ0eXAiOiJ...
""" It converts Strings in the format # to deactivate commands just comment them out by putting a # to the beginning of the line # optional commands can be deactivated by putting a # to the lines' beginning and activated by removing # from the beginning # replace 'example.com' with the hostname or ip address of the se...
SRM_TO_HEX = { "0": "#FFFFFF", "1": "#F3F993", "2": "#F5F75C", "3": "#F6F513", "4": "#EAE615", "5": "#E0D01B", "6": "#D5BC26", "7": "#CDAA37", "8": "#C1963C", "9": "#BE8C3A", "10": "#BE823A", "11": "#C17A37", "12": "#BF7138", "13": "#BC6733", "14": "#B26033", ...
# ------ [ API ] ------ API = '/api' # ---------- [ BLOCKCHAIN ] ---------- API_BLOCKCHAIN = f'{API}/blockchain' API_BLOCKCHAIN_LENGTH = f'{API_BLOCKCHAIN}/length' API_BLOCKCHAIN_BLOCKS = f'{API_BLOCKCHAIN}/blocks' # ---------- [ BROADCASTS ] ---------- API_BROADCASTS = f'{API}/broadcasts' API_BROADCASTS_NEW_BLOCK =...
#tables or h5py libname="h5py" #tables" #libname="tables" def setlib(name): global libname libname = name
if __name__ == "__main__": pages = [5, 4, 3, 2, 1, 4, 3, 5, 4, 3, 2, 1, 5] faults = {3: 0, 4: 0} for frames in faults: memory = [] for page in pages: out = None if page not in memory: if len(memory) == frames: out =...
a={'a':'hello','b':'1','c':'jayalatha','d':[1,2]} d={} val=list(a.values()) val.sort(key=len) print(val) for i in val: for j in a: if(i==a[j]): d.update({j:a[j]}) print(d)
# -*- coding: utf-8 -*- """ Created on Wed Nov 04 17:37:37 2015 @author: Kevin """
load("@io_bazel_rules_dotnet//dotnet:defs.bzl", "core_library", "core_resx", "core_xunit_test") core_resx( name = "core_resource", src = ":src/Moq/Properties/Resources.resx", identifier = "Moq.Properties.Resources.resources", ) core_library( name = "Moq.dll", srcs = glob(["src/Moq/**/*.cs"]), ...
# Time: O(n^2) # Space: O(n) # Given an array of unique integers, each integer is strictly greater than 1. # We make a binary tree using these integers and each number may be used for # any number of times. # Each non-leaf node's value should be equal to the product of the values of # it's children. # How many binary...
def run(): animal = str(input('¿Cuál es tu animal favorito? ')) if animal.lower() == 'tortuga' or animal.lower() == 'tortugas': print('También me gustan las tortugas.') else: print('Ese animal es genial, pero prefiero las tortugas.') if __name__ == '__main__': run()
class reversor: def __init__(self, value): self.value = value def __eq__(self, other): return self.value == other.value def __lt__(self, other): """ Inverted it to be able to sort in descending order. """ return self.value >= other.value if __name__ == '__...
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Yue-Wen FANG' __maintainer__ = "Yue-Wen FANG" __email__ = 'fyuewen@gmail.com' __license__ = 'Apache License 2.0' __creation_date__= 'Dec. 25, 2018' """ This example shows the functionality of positional arguments and keyword ONLY arguments. The positional a...
""" A unival tree (which stands for "universal value") is a tree where all nodes under it have the same value. Given the root to a binary tree, count the number of unival subtrees. For example, the following tree has 5 unival subtrees: 0 / \ 1 0 / \ 1 0 / \ 1 1 """ class Node...
# Iterations: Definite Loops ''' Use the 'for' word there is a iteration variable like 'i' or 'friend' ''' # for i in [5, 4, 3, 2, 1] : # print(i) # print('Blastoff!') # friends = ['matheus', 'wataru', 'mogli'] # for friend in friends : # print('happy new year:', friend) # print('Done!')
class formstruct(): name = str() while True: name = input("\n.bot >> enter your first name:") if not name.isalpha(): print(".bot >> your first name must have alphabets only!") continue else: name = name.upper() break city = str() while True: c...
# # @lc app=leetcode id=719 lang=python3 # # [719] Find K-th Smallest Pair Distance # # https://leetcode.com/problems/find-k-th-smallest-pair-distance/description/ # # algorithms # Hard (30.99%) # Likes: 827 # Dislikes: 30 # Total Accepted: 29.9K # Total Submissions: 96.4K # Testcase Example: '[1,3,1]\n1' # # Gi...
def chess_knight(start, moves): def knight_can_move(from_pos, to_pos): return set(map(lambda x: abs(ord(x[0]) - ord(x[1])), zip(from_pos, to_pos))) == {1, 2} def knight_moves(pos): return {f + r for f in 'abcdefgh' for r in '12345678' if knight_can_move(pos, f + r)} # till ...
# -*- coding: utf-8 -*- """ Created on Thu Sep 20 20:17:52 2018 @author: Administrator 最优分割 时间限制:C/C++语言 1000MS;其他语言 3000MS 内存限制:C/C++语言 65536KB;其他语言 589824KB 题目描述: 依次给出n个正整数A1,A2,… ,An,将这n个数分割成m段,每一段内的所有数的和记为这一段的权重, m段权重的最大值记为本次分割的权重。问所有分割方案中分割权重的最小值是多少? 输入 第一行依次给出正整数n,m,单空格切分;(n <= 10000, m <= 10000, ...
n = str(input()) if("0000000" in n): print("YES") elif("1111111" in n): print("YES") else: print("NO")
list = ['a','b','c'] print(list)
# # Copyright 2017 ABSA Group Limited # # 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 ...
''' Переменные настройки для parser. ''' link_MireaSchedule = "https://www.mirea.ru/schedule/" links_file = "links.txt" first_september = [2021, 9, 1] first_january = [2022, 1, 1] semestr_start = [2021, 8, 30] # День отсчета начала семестра block_tags = { # Список тегов, которые не будут обрабатыватся "Коллед...
############################################################################## # Parte do livro Introdução à Programação com Python # Autor: Nilo Ney Coutinho Menezes # Editora Novatec (c) 2010-2017 # Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8 # Primeira reimpressão - Outubro/2011 # Segunda reimpressão - ...
""" Darshan Error classes and functions. """ class DarshanBaseError(Exception): """ Base exception class for Darshan errors in Python. """ pass class DarshanVersionError(NotImplementedError): """ Raised when using a feature which is not provided by libdarshanutil. """ min_version = ...
try: width=float(input("Ieraksti savas istabas platumu (metros): ")) height=float(input("Ieraksti savas istabas augstumu (metros): ")) length=float(input("Ieraksti savas istabas garumu (metros): ")) capacity=round(width*height*length, 2) print(f"Tavas istabas tilpums ir {capacity} m\u00b3.") except ...
file = open("input.txt", "r") num_valid = 0 for line in file: # policy = part before colon policy = line.strip().split(":")[0] # get min/max number allowed for given letter min_max = policy.split(" ")[0] letter = policy.split(" ")[1] min = int(min_max.split("-")[0]) max = int(min_max.split("-")[1]) ...
class Empleado(object): "Clase para definir a un empleado" def __init__(self, nombre, email): self.nombre = nombre self.email = email def getNombre(self): return self.nombre jorge = Empleado("Jorge", "jorge@mail.com") jorge.guapo = "Por supuesto" # Probando hasattr, getattr, seta...
# Problem code def search(nums, target): return search_helper(nums, target, 0, len(nums) - 1) def search_helper(nums, target, left, right): if left > right: return -1 mid = (left + right) // 2 # right part is good if nums[mid] <= nums[right]: # we fall for it if target >= ...
# # PySNMP MIB module CISCO-EMBEDDED-EVENT-MGR-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-EMBEDDED-EVENT-MGR-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:39:13 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python vers...
"""AyudaEnPython: https://www.facebook.com/groups/ayudapython # ------------------------ REDACCION ORIGINAL ------------------------ 1. Crear un programa que pida un número entero e imprimirlo, si no se ingresa deberá preguntar otra vez por el número entero hasta que ingrese un número positivo. 2. Crear una lista que...
screen_resX=1920 screen_resY=1080 img_id=['1.JPG_HIGH_', '2.JPG_HIGH_', '7.JPG_HIGH_', '12.JPG_HIGH_', '13.JPG_HIGH_', '15.JPG_HIGH_', '19.JPG_HIGH_', '25.JPG_HIGH_', '27.JPG_HIGH_', '29.JPG_HIGH_', '41.JPG_HIGH_', '42.JPG_HIGH_',...
def create_matrix(rows_count): matrix = [] for _ in range(rows_count): matrix.append([int(x) for x in input().split(', ')]) return matrix def get_square_sum(row, col, matrix): square_sum = 0 for r in range(row, row + 2): for c in range(col, col + 2): square_sum += matri...
#!/usr/bin/env python3 # Diodes "1N4148" "1N5817G" "BAT43" # Zener "1N457" # bc junction of many transistors can also be used as dioded, i.e. 2SC1815, 2SA9012, etc. with very small leakage current (~1pA at -4V).
clientId = 'CLIENT_ID' clientSecret = 'CLIENT_SECRET' geniusToken = 'GENIUS_TOKEN' bitrate = '320'
''' Created on Jun 15, 2016 @author: eze ''' class NotFoundException(Exception): ''' classdocs ''' def __init__(self, element): ''' Constructor ''' self.elementNotFound = element def __str__(self, *args, **kwargs): return "NotFoundException(%s)" %...
# Solution to the practise problem # https://automatetheboringstuff.com/chapter6/ # Table Printer def printTable(tableList): """Prints the list of list of strings with each column right justified""" colWidth = 0 for row in tableList: colWidth = max(colWidth, max([len(x) for x in row])) col...
class Contact: def __init__(self, first_name = None, last_name = None, mobile_phone = None): self.first_name = first_name self.last_name = last_name self.mobile_phone = mobile_phone
class Solution(object): def shortestToChar(self, S, C): """ :type S: str :type C: str :rtype: List[int] """ pl = [] ret = [0] * len(S) for i in range(0, len(S)): if S[i] == C: pl.append(i) for i in range(...
# Optional solution with tidy data representation (providing x and y) monthly_victim_counts_melt = monthly_victim_counts.reset_index().melt( id_vars="datetime", var_name="victim_type", value_name="count" ) sns.relplot( data=monthly_victim_counts_melt, x="datetime", y="count", hue="victim_type", ...
def findSmallest(arr): smallest = arr[0] smallest_index = 0 for i in range(1, len(arr)): if arr[i] < smallest: smallest = arr[i] smallest_index = i return smallest_index def selection_sort(arr): newarr = [] for i in range(len(arr)): smallest...
{ 'Hello World':'Salve Mondo', 'Welcome to web2py':'Ciao da wek2py', }
domain='https://monbot.hopto.org' apm_id='admin' apm_pw='New1234!' apm_url='https://monbot.hopto.org:3000' db_host='monbot.hopto.org' db_user='izyrtm' db_pw='new1234!' db_datadbase='monbot'
def norm(x, ord=None, axis=None): # TODO(beam2d): Implement it raise NotImplementedError def cond(x, p=None): # TODO(beam2d): Implement it raise NotImplementedError def det(a): # TODO(beam2d): Implement it raise NotImplementedError def matrix_rank(M, tol=None): # TODO(beam2d): Implemen...
def load(): with open("input") as f: yield next(f).strip() next(f) for x in f: yield x.strip().split(" -> ") def pair_insertion(): data = list(load()) polymer, rules = list(data[0]), dict(data[1:]) for _ in range(10): new_polymer = [polymer[0]] for...
def compChooseWord(hand, wordList, n): """ Given a hand and a wordList, find the word that gives the maximum value score, and return it. This word should be calculated by considering all the words in the wordList. If no words in the wordList can be made from the hand, return None. hand: ...
class Colors: END = '\033[0m' ERROR = '\033[91m[ERROR] ' INFO = '\033[94m[INFO] ' WARN = '\033[93m[WARN] ' def get_color(msg_type): if msg_type == 'ERROR': return Colors.ERROR elif msg_type == 'INFO': return Colors.INFO elif msg_type == 'WARN': return Colors.WARN else: return Colors.END...
def naive_string_matching(t, w, n, m): for i in range(n - m + 1): j = 0 while j < m and t[i + j + 1] == w[j + 1]: j = j + 1 if j == m: return True return False
# Leo colorizer control file for kivy mode. # This file is in the public domain. # Properties for kivy mode. properties = { "ignoreWhitespace": "false", "lineComment": "#", } # Attributes dict for kivy_main ruleset. kivy_main_attributes_dict = { "default": "null", "digit_re": "", "esc...
""" Information on the Rozier Cipher can be found at: https://www.dcode.fr/rozier-cipher ROZIER.py Written by: MrLukeKR Updated: 16/10/2020 """ # The Rozier cipher needs a string based key, which can be constant for ease # or changed for each message, for better security constant_key = "DCODE" def encrypt(plaintext:...
#!/usr/bin/env python3 # xml 资源 xml_w3_book = """ <?xml version="1.0" encoding="ISO-8859-1"?> <bookstore> <book> <title lang="eng">Harry Potter</title> <price>29.99</price> </book> <book> <title lang="eng">Learning XML</title> <price>39.95</price> </book> </bookstore> """
""" Title: 0035 - Search Insert Position Tags: Binary Search Time: O(logn) Space: O(1) Source: https://leetcode.com/problems/search-insert-position/ Difficulty: Easy """ class Solution(object): def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype:...
"""Class static method test""" class TestClass(): """Test class""" def __init__(self, a=1, b=2): self.a = a self.b = b def add(self): return self.a + self.b @staticmethod def static_add(a, b): return 2 * a + 2 * b def add2(self): return self.static_a...
# Quotes from: https://www.notion.so/Quotes-by-Naval-Ravikant-3edaf88cfc914b06a98b58b62b6dc222 dic = [\ "Read what you love until you love to read.",\ "True Wisdom Comes From Understanding, Not Memorization.",\ "Meditation is the art of doing nothing. You cannot do meditation. By definition, if you’re doing some...
# -*- coding: utf-8 -*- def case_insensitive_string(string, available, default=None): if string is None: return default _available = [each.lower() for each in available] try: index = _available.index(f"{string}".lower()) except ValueError: raise ValueError(f"unrecognised in...
begin_unit comment|'# Copyright (c) 2014 The Johns Hopkins University/Applied Physics Laboratory' nl|'\n' comment|'# All Rights Reserved' nl|'\n' comment|'#' nl|'\n' comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may' nl|'\n' comment|'# not use this file except in compliance with t...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2019/5/5 12:39 AM @Author : sweetcs @Site : @File : config.py @Software: PyCharm """ DEBUG=True HOST="0.0.0.0" PORT=9292
# What should be printing the next snippet of code? intNum = 10 negativeNum = -5 testString = "Hello " testList = [1, 2, 3] print(intNum * 5) print(intNum - negativeNum) print(testString + 'World') print(testString * 2) print(testString[-1]) print(testString[1:]) print(testList + testList) # The sum of each three fir...
# THIS FILE IS GENERATED FROM NUMPY SETUP.PY short_version = '1.9.0' version = '1.9.0' full_version = '1.9.0' git_revision = '07601a64cdfeb1c0247bde1294ad6380413cab66' release = True if not release: version = full_version
"""Given a string and a pattern, find all anagrams of the pattern in the given string. Write a function to return a list of starting indices of the anagrams of the pattern in the given string.""" """Example: String="ppqp", Pattern="pq", Output = [1, 2] """ def find_string_anagrams(str1, pattern): result...
def table_pkey(table): query = f"""SELECT KU.table_name as TABLENAME,column_name as PRIMARYKEYCOLUMN FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU ON TC.CONSTRAINT_TYPE = 'PRIMARY KEY' AND TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME AND KU.table_n...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ File: __init__.py.py Author: Scott Yang(Scott) Email: yangyingfa@skybility.com Copyright: Copyright (c) 2021, Skybility Software Co.,Ltd. All rights reserved. Description: """