content
stringlengths
7
1.05M
""" Problem Statement If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. ? Find the sum of all the multiples of 3 or 5 below 1000 ? Solution - Loop through to the number below the given digit - Find all multiples of 3 then of 5 and app...
# Lecture 9.1, slide 10 def sqrtBi(x, eps): low = 0.0 high = max(1, x) ans = (high + low) / 2.0 while abs(ans ** 2 - x) >= eps: if ans ** 2 < x: low = ans else: high = ans ans = (high + low) / 2.0 return ans
def dir2tree(dirs): result = None for dir in dirs: if dir['parent_id']== None: result = Node(dir['id'], dir['name']) else: result.add_parent(dir['parent_id'], Node(dir['id'], dir['name'])) return result class Node: def __init__(self, id, name): self.id = ...
print('Tabela verdade - AND') print(30 * '-') print(True, "e", True, "=", (True and True)) print(True, "e", False, "=", (True and False)) print(False, "e", True, "=", (False and True)) print(False, "e", False, "=", (False and False)) print(30 * '-') print('Tabela verdade - or') print(30 * '-') print(True, "ou", True, ...
# http://codingbat.com/prob/p149391 def xyz_there(str): for i in range(len(str)-2): if (str[i:i+3] == "xyz"): if ( i == 0 or (i != 0 and str[i-1] != '.') ): return True return False
def extractTigertranslationsOrg(item): ''' Parser for 'tigertranslations.org' ''' ttmp = item['title'].replace("10 Years", "<snip> years").replace("10 Years Later", "<snip> years") vol, chp, frag, postfix = extractVolChapterFragmentPostfix(ttmp) if not (chp or vol) or "preview" in item['title'].lower(): retu...
expected_output = { "instance": { "isp": { "level": { 1: { "lspid": { "router-5.00-00": { "lsp": { "seq_num": "0x00000003", "checksum": "0x807...
a = [1, 2, 3, 4, 5,] print(*a) for i in a: print(i, end=' ')
# # This file contains the Python code from Program 16.21 of # "Data Structures and Algorithms # with Object-Oriented Design Patterns in Python" # by Bruno R. Preiss. # # Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved. # # http://www.brpreiss.com/books/opus7/programs/pgm16_21.txt # class Algorithms(...
# coding=UTF-8 svar = input("Vilken är Elis älsklingfärg?") if svar=="röd": print("Rätt") else: print(" %s är Fel" % svar) svar = input("Vilken är Elis favoriträtt?") if svar=="kyckling": print("Rätt") else: print(" %s är Fel" % svar) svar = input("hur gammal är elis ?") if svar=="9": print("Rätt") els...
# Some basic tests DataManager = tools.dynamicImportDev('dataManager').Manager # traininigDataFun, trainingData = tools.importData('training') # trainingDataProvider = DataProvider( # data = traininigDataFun, # bz = env.training.bz, # stochasticSampling = False, # indexingShape = [trainingData.shape[0...
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: data = {} output = [] for i in range(len(nums)): v = target - nums[i] if v in data.values(): output.append(nums.index(v)) output.append(i) ...
def to_ini(settings = {}): """ Custom Ansible filter to print out a YAML dictionary in the INI file format. Similar to the built-in to_yaml/to_json filters. """ s = '' # loop through each section for section in settings: # print the section header s += '[%s]\n' % section ...
DATA = """ :|'Autauga County, AL' 01001 'Autauga County, AL' 01001 'Chilton County, AL' 01021 'Dallas County, AL' 01047 'Elmore County, AL' 01051 'Lowndes County, AL' 01085 'Montgomery County, AL' 01101 :|'Baldwin County, AL' 01003 'Baldwin County, AL' 01003 'Clarke County, AL' 01025 'Escambia County, AL' 01053 ...
EXAMPLE = True MYSQL_HOST = "development.com" VERSION = 1 AGE = 15 NAME = "MIKE" IMAGE_1 = "aaa" IMAGE_2 = "bbb" IMAGE_4 = "a" IMAGE_5 = "b"
class Pessoa: def __init__(self, *filhos, nome = None, idade = 48): self.nome = nome self.idade = idade self.filhos = list(filhos) def cumprimentar(self): return f'Olá!!!{id(self)}' if __name__ == '__main__': amanda = Pessoa(nome='Amanda') fernanda = Pessoa(nome='Fernan...
total_secs = int(input("How many seconds, in total?")) hours = total_secs // 3600 secs_still_remaining = total_secs / 60 minutes = secs_still_remaining // 60 secs_finally_remaining = secs_still_remaining / 60 print("Hrs=", hours, " mines=", minutes, "secs=", secs_finally_remaining) n...
""" 86. Binary Search Tree Iterator https://www.lintcode.com/problem/binary-search-tree-iterator/description """ """ Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None Example of iterate a tree: iterator = BSTIterator(root) while itera...
class Solution: def minSwap(self, A: [int], B: [int]) -> int: swap, keep = 1, 0 for i in range(1, len(A)): if A[i] <= A[i - 1] or B[i] <= B[i - 1]: # swap nswap = keep + 1 nkeep = swap elif A[i] > B[i - 1] and B[i] > A[i - 1]: ...
# encoding: utf-8 HTTP = 'http://' '''配置文件名称''' CONFIG_FILENAME = 'config.ini' '''视频编码值''' H264_PAYLOAD = '96' H265_PAYLOAD = '98' '''接口ID''' TASK_ID_GET_IPCINFO = 1 TASK_ID_GET_STREAMQUERY = 2 TASK_ID_GET_MTSPULLINFO = 3 TASK_ID_GET_STREAMSTART = 4 TASK_ID_GET_OPENVIDEO = 5 TASK_ID_GET_STREAMSTATU...
# -*- coding: utf-8 -*- """ utils.py Various utilities """ __author__ = 'Jared M Smith' __license__ = 'MIT' __version__ = '0.1.0' __maintainer__ = 'Jared M Smith' __email__ = 'jared@jaredsmith.io' def format_keywords(keywords): fmt_keywords = [] for term_breakdown in keywords: kwd = "".join(term_b...
price_vegetables = float(input()) price_fruits = float(input()) kg_vegetables = int(input()) kg_fruits = int(input()) print(str((price_fruits*kg_fruits + price_vegetables*kg_vegetables)/1.94))
with open('abc.txt', 'w+') as file: file.write('linha 1\n') file.write('linha 2\n') file.write('linha 3\n') file.seek(0) print(file.read())
# # PySNMP MIB module CISCO-TN3270SERVER-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-TN3270SERVER-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:57:52 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (d...
"""This module implements mock Flask-User v0.6 classes to warn the developer that they are using v0.6 API calls against an incompatible v1.0+ Flask-User install. """ # Author: Ling Thio <ling.thio@gmail.com> # Copyright (c) 2013 Ling Thio LEGACY_ERROR =\ """ Flask-User Legacy ERROR: ----------------------------------...
class Car: """ This class represents an Car """ def __init__(self, brand, model, reg_no): """ Initalizing the Car with arguments brand model reg_no """ # instance attribute self.brand = brand self.model = model self.reg_no =...
MAGIC = [20210318223204031831, 1145141919810] BASE58 = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ' def encode(msg: str) -> str: temp = 0 for m in msg: temp = temp * 256 + ord(m) temp = (temp ^ MAGIC[0]) + MAGIC[1] msg = '' while temp: msg = BASE58[temp % 58] + msg ...
""" Stores settings related to Unreal importing process """ PNG_CACHE_FILE_SUFFIX = ".CACHE.PNG" bUsePNGCache = True
msg = 'Olá , Mundo' # msg é uma variável print(msg) #outra forma de fazer é a seguinte, sem variável print('Olá, Mundo!')
def binary_search(arr, item): low = 0 high = len(arr)-1 result = -1 while (low <= high): mid = (low + high)//2 if item == arr[mid]: result = mid high = mid - 1 elif (item < arr[mid]): high = mid - 1 else: low = mid + 1 return result
n = int(input()) if n == 1: print('x') elif n % 2 == 0: for x in range(n//2): print(" " * x + "\\" + " " * 2*(n//2-(x+1)) + "/") for x in range(n//2): print(" " * (n//2-(x+1)) + "/" + " " * 2*x + "\\") elif (n % 2) == 1: for i in range(n//2): print(" " * i + "\\" + " " * (2*(n//...
#!/usr/bin/python line = "Przykladoy tekst do zadania z przedmiotu Python" allWords = line.split() result = sum(len(x) for x in allWords) print(result)
''' 实现 pow(x, n) ,即计算 x 的 n 次幂函数。 示例 1: 输入: 2.00000, 10 输出: 1024.00000 ''' class Solution: """ 快速幂算法(递归) n是偶数,x^2就等于x^(n/2)次方再平方,如果是奇数,那么就还需要乘以x """ # def fastPow(self, x, n): # if n == 0: # return 1 # temp = self.fastPow(x, n / 2) # if n % 2 == 0: # ...
""" Crie um programa onde o usuário possa digitar vários valores numéricos e cadastre-os em uma lista. Caso o número já exista lá dentro, ele não será adicionado. No final, serão exibidos todos os valores únicos digitados em ordem crescente.""" numeros = [] while True: n = int(input('Digite um valor: ')) if n n...
params={ 'enc_type': 'lstm', 'dec_type': 'lstm', 'nz': 32, 'ni': 128, 'enc_nh': 512, 'dec_nh': 512, 'log_niter': 50, 'dec_dropout_in': 0.5, 'dec_dropout_out': 0.5, 'batch_size': 32, 'epochs': 100, 'test_nepoch': 5, 'train_data': 'datasets/snli_data/snli.train.txt', ...
def greet_user(first_name, last_name): print(f'Hi there, {first_name} {last_name}!') print('Welcome aboard') print("Start") greet_user(last_name="Smith", first_name="John") greet_user("Mary", "Bridges") # Keyword args should always come after positional args print("Finish") # can use return instea...
while True: s = input("[>] Enter string (for exit enter empty string): ") if s: print(f"[+] Lenght of string: {len(s)}") else: break
for i in range(int(input())): fact=1 a=int(input()) for j in range(1,a+1,1): fact=fact*j print(fact)
class ReloadProError(Exception): """Raised when the Re:load Pro returns an err status.""" class ReloadPro(object): def __init__(self, f): self.f = f # Handler functions for overtemp and undervolt conditions self.on_overtemp = lambda: None self.on_undervolt = lambda: None d...
createElement = React.createElement createContext = React.createContext forwardRef = React.forwardRef Component = ReactComponent = React.Component useState = React.useState useEffect = React.useEffect useContext = React.useContext useReducer = React.useReducer useCallback = React.useCallback useMemo = Re...
class dotLoadCommonAttributes_t(object): # no doc aPartFilter=None AutomaticPrimaryAxisWeight=None BoundingBoxDx=None BoundingBoxDy=None BoundingBoxDz=None CreateFixedSupportConditionsAutomatically=None FatherId=None LoadAttachment=None LoadDispersionAngle=None LoadGroupId=None ModelObject=None PartNames=N...
class Graph: def __init__(self, vertices): self.__nodes = vertices self.__edges = {} def add_edges(self, node1,node2): if (min(node1,node2),max(node1,node2)) in self.__edges: self.__edges[(min(node1,node2),max(node1,node2))] += 1 else: self.__edges[(min(...
lista = [] listaPar = [] listaImpar = [] continuar ='s' while continuar in 'Ss': valor = int(input('Insira o seu numero : ')) lista.append(valor) if valor % 2 == 0 : listaPar.append(valor) if valor % 2 == 1 : listaImpar.append(valor) continuar = str(input('Continuar [S/N] ?')) print(...
# -*- coding: utf-8 -*- """ Created on Thu Jun 3 17:25:24 2021 @author: Mahmu """
''' Recursion * "Design an algorithm to compute the nth" * "Write code to list the first n..." * "Implement a method to compute all..." How To Approach * recursive solutions built off of solutions to subproblems 1. to compute f(n), add/remove/changing the solution to f(n-1) 2. solve problem for first hal...
""" This module provides the different constants pertaining to the ``accounts`` app. """ OTP_CODE_LENGTH = 6 # Documentation string for OTP_CODE_LENGTH defined above. """ The length of the ``code`` field of :class:`apps.accounts.models.OTP`. """ CSRF_TOKEN_LENGTH = 32 # Documentation string for CSRF_TOKEN_LENGTH ...
name = "S - Interfering Lines" description = "Oscilloscope lines overlap" knob1 = "Number of Lines" knob2 = "Outer Spread" knob3 = "Center Spread" knob4 = "Color" released = "March 21 2017"
"""General-purpose routines. It seemed a shame for the ``api`` module to have to import large legacy modules to offer simple date handling, so this small module holds the routines instead. """ def jday(year, mon, day, hr, minute, sec): """Return two floats that, when added, produce the specified Julian date. ...
""" space : O(n) time : O(n) """ class Solution: def findPairs(self, nums: List[int], k: int) -> int: if k < 0: return 0 ans = 0 hashmap = {} for i in nums: if i not in hashmap: hashmap[i] = 1 else: hashmap[...
def precision_S(y_test, y_pred): corr_negative, corr_issue, corr_solution = 0, 0, 0 count_negative, count_issue, count_solution = 0, 0, 0 for i, prediction in enumerate(y_pred): if prediction[0] == 1: count_negative += 1 if y_test[i][0] == 1: corr_negative += ...
def cmn_denom(num, denom): while num % denom != 0: old_num = num old_denon = denom num = old_denon denom = old_num % old_denon return denom class Fraction: def __init__(self, num, denom): self.num = num self.denom = denom def __str__(self)...
""" Functions related to the (m,n) vsh mode indices """ def rmax_to_lmax(rmax): """obtain lmax from rmax""" lmax = int(-1 + (1+rmax)**0.5) return lmax def lmax_to_rmax(lmax): """obtain rmax from lmax""" rmax = lmax*(lmax + 2) return rmax def reduced_index(n, m): r = n*(n+2) - n + m - 1; ...
jill = 10 iack = 10 print(str(iack)+" "+str(jill)) for i in range(iack): print(i) for j in range(jill): print(jill + j*2) print("0 0")
""" Author: Shreck Ye Date: June 15, 2019 Time complexity: O(N) """ class Solution: def fib(self, N: int) -> int: fn, fnp1 = 0, 1 for _ in range(N): fn, fnp1 = fnp1, fn + fnp1 return fn
#for defining n inputs from the user print('enter 0 to stop.\n') def enter(x): while x: x=input() x=input() enter(x) #------------------ done ---------------------------
""" LeetCode Problem 111. Container With Most Water Link: https://leetcode.com/problems/container-with-most-water/ Language: Python Written by: Mostofa Adib Shakib """ """ Time Complexity: O(n) Space Complexity: O(1) we need to take the minimum of the two heights Traverse two pointers one from the left hand side and ...
""" proc.py -> Class definition for a Process """ class Process(object): """ Class that represents a simple process conforming just of: 1. Letter id. 2. Number of memory units. """ #Constants representing the number of minimum and maximum units #each process could request. MIN_UNITS = 2 MAX_UNITS = 15 ...
""" The "hardware" module contains the sub modules — one sub module per layer — that form together the hardware part of the 16-bit computer. - chips.py contains the logic gates used as the primitive building blocks for everything else. """
def f(): x = 8 def g(): nonlocal x x = 9 return x
""" Short Python function that counts the number of vowels in a given character string. """ def count_vowels(sequence_str: str) -> int: letters = list(sequence_str.lower()) # convert string to list in wich all elements are lowercase letter vowels = set('aeiou') # set of vowels to comparate count_vowel = s...
''' Leser filer gitt filnavn '''
# area_of_n-sided_polygon.py # https://www.codewars.com/kata/5727500a20c7f837fc001869/train/python # We use the "shoelace formula" to calculate the area. # https://www.101computing.net/the-shoelace-algorithm/ def area_polygon(vertex): if len(vertex) < 3: return -1 a = vertex[len(vertex) - 1][0]*vertex...
add_library('opencv_processing') img = None opencv = None def setup(): img = loadImage("test.jpg") size(img.width, img.height, P2D) opencv = OpenCV(this, img) def draw(): opencv.loadImage(img) opencv.brightness(int(map(mouseX, 0, width, -255, 255))) image(opencv.getOutput(), 0, 0)
def controllo_input(n): if len(n) < 4: raise TypeError("Errore: il numero deve avere minimo 4 cifre") def ordina_crescente(n): return "".join(sorted(n)) def ordina_decrescente(n): return "".join(reversed(sorted(n))) def costante_kaprekar(n): iterazioni_max_kaprekar = 7 for i in range(i...
def dato(diametro): if diametro == 1: # varilla de 8mm return 0.40 if diametro == 0: # varilla de 12mm return 0.60 if diametro == 2: # varilla de 14mm return 0.70 if diametro == 3: # varilla de 16mm return 0.80 if diametro == 4: ...
match x: case Class(1, foo=2, bar=3): pass
class Matrice: def __init__(self, n_init): self.n = n_init self.C = [] self.I = [] self.L = [int(0)] * (n_init+1) def __str__(self): return "Matrice({})\nC: {}\nI: {}\nL: {}\n".format(self.n, self.C, self.I, self.L) def set(self, i, j, value): """ In...
# https://leetcode.com/problems/minimize-maximum-pair-sum-in-array class Solution: def minPairSum(self, nums: List[int]) -> int: nums = sorted(nums) ans = 0 for i in range(len(nums) // 2): val = nums[i] + nums[-1 - i] ans = max(ans, val) return ans
class ClassDef(object): def __init__(self): # public self.name = "class_def" # private self.__age = 29 # protected self._sex = "man" def fun1(self): print("call public function") def __fun2(self): print("call private function") def _fun3(s...
# Non-OOP # Bank Version 1 # Single account accountName = 'Joe' accountBalance = 100 accountPassword = 'soup' while True: print() print('Press b to get the balance') print('Press d to make a deposit') print('Press w to make a withdrawal') print('Press s to show the account') print('Press q to ...
class VariablesDict: """ A VariablesDict is a sort of dictionary with special features, created to manage the variables of a monomial. In this case, we'll call keys variables and values exponents. Its main features are: - A VariablesDict is immutable - The default exponent is 0; there...
def getball(): rest() i01.setHandSpeed("right", 0.85, 0.75, 0.75, 0.75, 0.85, 0.75) i01.setArmSpeed("right", 1.0, 1.0, 1.0, 0.85) i01.setHeadSpeed(0.9, 0.9) i01.setTorsoSpeed(0.75, 0.55, 1.0) i01.moveHead(45,65) i01.moveArm("left",5,90,16,15) i01.moveArm("right",6,85,110,22) i01.moveHand("left",50,50,...
""" from: http://adventofcode.com/2017/day/2 --- Day 2: Corruption Checksum --- As you walk through the door, a glowing humanoid shape yells in your direction. "You there! Your state appears to be idle. Come help us repair the corruption in this spreadsheet - if we take another millisecond, we'll have to display an ho...
""" Scripts using nmap """ # TODO: Check if nmap is accessible. def Usable(entity_type, entity_ids_arr): """Nmap must be accessible""" return True
# config.py cfg = { 'name': 'Retinaface', 'min_sizes': [[16, 32], [64, 128], [256, 512]], 'steps': [8, 16, 32], 'variance': [0.1, 0.2], 'clip': False, 'loc_weight': 2.0, 'gpu_train': True }
class Publisher: def __init__(self): self.observers = [] def add(self, observer): if observer not in self.observers: self.observers.append(observer) else: print(f'Failed to add: {observer}') def remove(self, observer): ...
# https://www.acmicpc.net/problem/1110 class PlusCycle(object): def get_new_number(self, num): sum_of_each = int(num[0]) + int(num[1]) return str(num[1]) + str(sum_of_each%10) def get_cycle(self, n): n = '{:02d}'.format(int(n)) target = n count = 1 ne...
# # PySNMP MIB module NASUNI-FILER-MIB (http://snmplabs.com/pysmi) # ASN.1 source file://text/NASUNI-FILER-MIB # Produced by pysmi-0.3.4 at Mon Sep 20 10:57:46 2021 # On host C02YJ1DPJHD2 platform Darwin version 20.4.0 by user mpipaliya # Using Python version 3.7.4 (default, Oct 12 2019, 18:55:28) # Integer, OctetStri...
cpf = input('Digite um CPF: ') cpf = cpf.strip() numeroCPF = cpf.replace('.', '') numeroCPF = numeroCPF.replace('-', '') numeroCPF = numeroCPF.replace(' ', '') numeroCPF = numeroCPF.strip() if len(numeroCPF) < 11: print('CPF inválido !!!') else: digitoValidos = numeroCPF[-2::1] soma = 0 regressivo = ...
"""GCP saving package This package contains the modules for managing your services timelife and costs. The package works if you have added some tags on your objects: see the documentation on https://gcp-saving.readthedocs.io/en/latest/ It is part of the educational repositories (https://github.com/pandle/materials) t...
n = int(input('Digite um número:')) d = n * 2 t = n * 3 r = n ** (1/2) print('O dobro de {} é igual a {}'.format(n,d)) print('O triplo de {} é igual a {}'.format(n,t)) print('A raiz quadrada de {} é igual a {:.3f}'.format(n,r))
class VersionMixin(object): def _get_versioned_class(self, attribute): attribute = getattr(self, attribute) version = self.request.version # Return default if version is not specified if not version: return attribute["default"] try: # Return version ...
def area(): return larg * comp larg = float(input('informe a largura ')) comp = float(input('informe o comprimento ')) print(area())
def csvReader(file): ''' Reads a csv file creates a dictionary with the first three comma seperated values of each line key and the fourth as value. ''' fileObject = open(file) data = fileObject.readlines() dic = {} for i in range(0,len(data)): try: dic[data[i].strip...
for c in range (0,6): print('oi') for c in range (0,6): print(c) for c in range (6,0,-1): print(c) for c in range (0,20,2): print(c) n = int(input('Digite um número')) for c in range (0,n+1): print(c) i = int(input('Digite um número inicial')) f = int(input('Digite um número final')) p = int(input('...
""" LeetCode Problem 219. Contains Duplicate II Link: https://leetcode.com/problems/contains-duplicate-ii/ Written by: Mostofa Adib Shakib Language: Python Time Complexity: O(n) Space Complexity: O(n) """ class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: # Initializing a ...
class Room: def __init__(self): self.room_number = 0 self.room_things = { "room": { "look": "A room.", "pickup": "Don't be ridiculous.", "approach": "You're already in the room, man. No need.", "hit": "You kick and hit aroun...
""" :copyright: (c) 2020 Yotam Rechnitz :license: MIT, see LICENSE for more details """ class MatchAwards: def __init__(self, js: dict): try: self._cards = js["cards"] except KeyError: self._cards = 0 self._medals = js["medals"] self._medalsBronze = js["medals...
# solution 1 a = [1,2,1,3,4,5,5] a = list(set(a)) print(a) # solution 2 a = [1,2,1,3,4,5,5] res = [] for i in a: if i not in res: res.append(i) print(res)
class Udp(object): output_fields = ( 'saddr', 'saddr-raw', 'daddr', 'daddr-raw', 'ipid', 'ttl', 'classification', 'success', 'sport', 'dport', 'icmp_responder', 'icmp_type', 'icmp_code', 'icmp_unreach_str', 'udp_pkt_size', 'data', 'repeat', 'cooldown', 'timestamp-str', 'timestamp-ts', 'time...
#Creacion de la clase class Persona: def __init__(self, nombre, edad): self.__nombre = nombre self.__edad = edad def __str__(self): return "Nombre: "+self.__nombre+" y edad : "+str(self.__edad)
class Allergies: def __init__(self, score): self.score = score def allergic_to(self, item): return item in self.lst @property def lst(self): allergieList = ['eggs', 'peanuts', 'shellfish', 'strawberries', 'tomatoes', 'chocolate', 'pollen', 'cats'] allergicTo = list() ...
'''API END_POINT''' CENTER_CODE = 'PUT YOUR CENTER CODE HERE!!!!' API_ENDPOINT = "PUT YOUR URL HERE!!!!" URL_TIMEOUT = 3 '''QR Scanners config''' IN_SCANNER = '/dev/ttyUSB0' OUT_SCANNER = '/dev/ttyUSB1' WAIT_SECONDS_BLOCK_DOOR = 2.5 NUM_SCANNERS = 2 '''I2C Bus Options''' DEVICE_BUS = 1 PHY_DOORS_NUMBERS = 1 DEVICE_AD...
def bubble_sort(nums): for i in range(len(nums) - 1): for j in range(len(nums) - i - 1): if nums[j] > nums[j + 1]: nums[j + 1], nums[j] = nums[j], nums[j + 1] return nums def quick_sort(nums): if len(nums) < 1: return nums p = nums[0] l = [] r = [] ...
XK_ISO_Lock = 0xFE01 XK_ISO_Level2_Latch = 0xFE02 XK_ISO_Level3_Shift = 0xFE03 XK_ISO_Level3_Latch = 0xFE04 XK_ISO_Level3_Lock = 0xFE05 XK_ISO_Group_Shift = 0xFF7E XK_ISO_Group_Latch = 0xFE06 XK_ISO_Group_Lock = 0xFE07 XK_ISO_Next_Group = 0xFE08 XK_ISO_Next_Group_Lock = 0xFE09 XK_ISO_Prev_Group = 0xFE0A XK_ISO_Prev_Gro...
names = {'anonymous','tazri','focasa','troy','farha'}; # can use for loop for access names sets for name in names : print("Hello, "+name.title()+"!"); # can check value is exist in sets ? print("\n'tazri' in names : ",'tazri' in names); print("'solus' not in names : ",'solus' not in names); print("'xenon' in name...
def GenerateConfig(context): resources = [] project = context.env["project"] zone = context.properties["zone"] instance_name = "gcp-vm-" + context.env["project"] machine_type = context.properties["machineType"] resources.append({ "name": instance_name, "type": "compute.v1.i...
my_vals = [623, '43', 324.523, '23', '23.23', 234, '342'] def add(values): '''take a list of values and adds them up We assume that the contents of the list is either int, float or str where strings are numbers that can be converted to an int/float Parameters ---------- values : list (any) ...
# -*- coding: utf-8 -*- # @Time : 2021/11/24 10:31 # @Author : Meng Jianing # @FileName: ShowType.py # @Software: PyCharm # @Versions: v0.1 # @Github :https://github.com/NekoSilverFox # -------------------------------------------- class ShowType: """ 显示方式: - 0(默认值) - 1(高亮,即加粗) - 4(...
class Solution: """ @param nums: the sorted matrix @return: the number of Negative Number """ def countNumber(self, nums): if not nums or not nums[0]: return 0 n = len(nums) m = len(nums[0]) i = 0 j = m - 1 count = 0 while i < n an...