content
stringlengths
7
1.05M
''' Created on Jan 19, 2016 @author: elefebvre '''
a=int(input()) b=int(input()) if a>b:a,b=b,a for i in range(a+1,b): if i%5==2 or i%5==3:print(i)
class Solution: def permute(self, nums: List[int]) -> List[List[int]]: res = [] def backtrack(nums, temp): if not nums: res.append(temp) return for i in range(len(nums)): backtrack(nums[:i]+nums[i+1:], temp+[nums[i]]) ba...
class LibTiffPackage (Package): def __init__(self): Package.__init__(self, 'tiff', '4.0.9', configure_flags=[ ], sources=[ 'http://download.osgeo.org/libtiff/tiff-%{version}.tar.gz', ...
''' Encapsulation : Part 1 Encapsulation is the process of restricting access to methods and variables in a class in order to prevent direct data modification so that it prevents accidental data modification. Encapsulation basically allows the internal representation of an object to be hidden from the v...
#!/usr/bin/env python """job.py: File containing Job class to be used as the executors for the pipeline.""" __author__ = "Zeyad Osama" class Job: """ Job class to be used as the executors for the pipeline. """ def __init__(self) -> None: super().__init__() def initialize(self): ...
class UndefinedMockBehaviorError(Exception): pass class MethodWasNotCalledError(Exception): pass
class Solution: def decodeString(self, s: str) -> str: St = [] num = 0 curr = '' for c in s: if c.isdigit(): num = num*10 + int(c) elif c == '[': St.append([num, curr]) num = 0 curr = '' ...
# Belajar default argument value #defaul name berfungsi memberikan pengisian default pada parameter #sehingga pengisian parameter bersifat opsional def say_hello(nama="aris"): #menggunakan sama dengan lalu ketik default value nya print(f"Hello {nama}!") say_hello("karachi") say_hello() #akan error jika ti...
# getattr(object, name[, default]) class C: def A(self): pass print(getattr(C, 'A'))
arr=input("Enter array elements").split(' ') arr=[int(x) for x in arr] for i in range(len(arr)): for j in range(len(arr)-1-i): if(arr[j]>arr[j+1]): arr[j],arr[j+1]=arr[j+1],arr[j] print("Sorted array is:",arr) """ Problem Statement: Sort array using bubble sort technique Sample Input/Output:...
# # Copyright (C) 2017 The Android Open Source Project # # 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 la...
class PseudoData(dict): def __init__(self, name_func_dict, sweep): super(PseudoData, self).__init__() self.name_func_dict = name_func_dict self.sweep = sweep def __getitem__(self, key): if key in self.keys(): return dict.__getitem__(self, key) elif key in sel...
# LAB EXERCISE 05 print('Lab Exercise 05 \n') # SETUP pop_tv_shows = [ {"Title": "WandaVision", "Creator": ["Jac Schaeffer"], "Rating": 8.2, "Genre": "Action"}, {"Title": "Attack on Titan", "Creator": ["Hajime Isayama"], "Rating": 8.9, "Genre": "Animation"}, {"Title": "Bridgerton", "Creator": ["Chris Van D...
__author__ = 'chira' # "return" used for mathematical function composition def f(x): # x is an INPUT y = 2*x + 3 return y # y is an OUTPUT def g(x): # x is an INPUT y = pow(x,2) return y # y is an OUTPUT def h(x,y): # x and y are INPUTS z = pow(x,2) + 3*y; return z # z i...
def balancedSums(arr): if n == 1: return 'YES' sumL = 0 sumR = 0 i =0 j = n-1 while i <= j: if i ==j and sumL == sumR: return 'YES' elif sumL > sumR: sumR+=arr[j] j =j-1 else: sumL+=arr[i] i =i +1 re...
# 4. Создать (не программно) текстовый файл со следующим содержимым: # One — 1 # Two — 2 # Three — 3 # Four — 4 # Необходимо написать программу, открывающую файл на чтение и считывающую построчно данные. # При этом английские числительные должны заменяться на русские. Новый блок строк должен записываться # в новый текс...
def perfect_square(x): if (x == 0 or x == 1): return x i = 1 result = 1 while (result <= x): i += 1 result = i * i return i - 1 x = int(input('Enter no.')) print(perfect_square(x))
# Default delimiters INPUT1 = ''' pid 2 uptime 675 version 1.2.5 END pid 1 uptime 2 version 3 END ''' OUTPUT1 = '''{"pid": "2", "uptime": "675", "version": "1.2.5"} {"pid": "1", "uptime": "2", "version": "3"} ''' # --field-delim '=', --record-delim '%\n' INPUT2 = ''' a=1 b=2 c=3 % d=4 e=5 f=6 % ''' OUTPUT2 = '''{"a"...
def capitalize(string): sttings_upper = string.title() for word in string.split(): words = word[:-1] + word[0-1].upper() + " " return sttings_upper[:-1] print(capitalize("GoLand is a new commercial IDE by JetBrains aimed at providing an ergonomic environment " "for Go developmen...
"""Meta information for csv2sql.""" __version__ = '0.4.1' __author__ = 'Yu Mochizuki' __author_email__ = 'ymoch.dev@gmail.com'
# Artificial Intelligence # Grado en Ingeniería Informática # 2017-18 # play_tennis.py (Unit 3, slide 8) attributes=[('Outlook',['Sunny','Overcast','Rainy']), ('Temperature',['High','Low','Mild']), ('Humidity',['High','Normal']), ('Wind',['Weak','Strong'])] class_name='Play Tennis...
print('Adição + ',10 + 10 ) print('Subtração - ', 10 - 10 ) print('Multiplicação * ', 10 * 10 ) print('Divisão / ', 10 / 10 ) print('Potencia ** ', 10 ** 10 ) print('Divisão Inteiro // ', 10 // 3 ) print('Resto Divisão % ', 10 % 3 )
class Solution: def compareVersion(self, version1: str, version2: str) -> int: l1 = [int(s) for s in version1.split(".")] l2 = [int(s) for s in version2.split(".")] len1, len2 = len(l1), len(l2) if len1 > len2: l2 += [0] * (len1 - len2) elif len1 < len2: ...
""" File: anagram.py Name: Jason Huang ---------------------------------- This program recursively finds all the anagram(s) for the word input by user and terminates when the input string matches the EXIT constant defined at line 19 If you correctly implement this program, you should see the number of anagrams for eac...
############# constants TITLE = "Cheese Maze" DEVELOPER = "Jack Gartner" HISTORY = "A mouse wants eat his cheese, Make it to the Hashtag to win, watch out for plus signs, $ is a teleport, P is a power up, Obtain the Key (K) in order to unlock the door (D)" INSTRUCTIONS = "left arrow key\t\t\tto move left\nright arrow k...
score = float(input("Enter Score: ")) if score < 1 and score > 0: if score >= 0.9: print('A') elif score >= 0.8: print('B') elif score >= 0.7: print('C') elif score >= 0.6: print('D') else: print('F') else: print('Value of score is out of range.') l...
class BaseRequestError(Exception): def __init__(self, *args, **kwargs): self.errors = [] self.code = 400 if 'code' in kwargs: self.code = kwargs['code'] def add_error(self, err): self.info.append(err) def set_errors(self, errors): self.errors = errors ...
''' Created on May 19, 2019 @author: ballance ''' # TODO: implement simulation-access methods # - yield # - get sim time # - ... # # The launcher will ultimately implement these methods #
"""Provide some variants of assert.""" def _custom_assert(condition: bool, on_error_msg: str = "") -> None: """Provide a custom assert which is kept even if the optimized python mode is used. See https://docs.python.org/3/reference/simple_stmts.html#assert for the documentation on the classical assert fu...
def find_even_index(arr): for index, int in enumerate(arr): left = sum_range(arr, 0, index) right = sum_range(arr, index, len(arr)) if left == right: return index return -1 def sum_range(arr, a, b): return sum(arr[a:b + 1])
prompt = """Translate to French (fr) From English (es) ========== Bramshott is a village with mediaeval origins in the East Hampshire district of Hampshire, England. It lies 0.9 miles (1.4 km) north of Liphook. The nearest railway station, Liphook, is 1.3 miles (2.1 km) south of the village. ---------- Bramshott est u...
# DO NOT EDIT: this file is auto-generated def _jvm_deps_impl(ctx): content = """ load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file") def load_jvm_deps(): http_file(name="com.google.code.findbugs_jsr305_1.3.9", urls=["https://repo1.maven.org/maven2/com/google/code/findbugs/jsr305/1.3.9/jsr305-1.3...
""" CHALLENGE PROBLEM!! NOT FOR THE FAINT OF HEART! The Fibonacci numbers, discovered by Leonardo di Fibonacci, is a sequence of numbers that often shows up in mathematics and, interestingly, nature. The sequence goes as such: 1,1,2,3,5,8,13,21,34,55,... where the sequence starts with 1 and 1, and then each number i...
INSTALLED_APPS = ( "testapp", ) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } SECRET_KEY = "django_tests_secret_key"
# Databricks notebook source # MAGIC %md # Run transform # MAGIC this will load the schema, the raw txt tables, then transform the dataframes to structured dataframes. # COMMAND ---------- # MAGIC %run ./transform # COMMAND ---------- # MAGIC %md # Store # MAGIC write the transformed dataframes to our base-path # ...
# python3 def build_heap(data): """Build a heap from ``data`` inplace. Returns a sequence of swaps performed by the algorithm. """ # The following naive implementation just sorts the given sequence # using selection sort algorithm and saves the resulting sequence # of swaps. This turns the gi...
# Ex4. # # Create a program that is going to take a whole number as an input, and will calculate the factorial of the number. # # Factorial example: 5! = 5 * 4 * 3 * 2 * 1 = 120 factorial = 1 number = int(input('Enter a number: ')) for i in range(1, number+1): factorial *= i print(f'Factorial of {number} is {facto...
""" 描述 市政府想在品罗路建一些基站,保证这条路上每个公司的员工都能享受到 Wi-Fi。 为了简化问题,我们将品罗路理解成一条直线,一个 Wi-Fi 基站为直线上的一个点。 基站的费用为 A + k*B,其中A为建立基站的固定费用,B 为覆盖每单位距离需要的费用,k 为覆盖半径。 如果在 a 点建立基站,覆盖半径为 k,那么位于 [a-k, a+k] 的公司都能享受到这个基站的服务。 现在给出每个公司的坐标,以及 A 和 B,求覆盖到所有公司需要的最小建设费用。 输入 前两个整数是 A 和 B,然后是一个分号,然后是每个公司的坐标。(0 <= A, B <= 1000,0 <= 公司坐标 <= 1,000,000...
""" Parameters and syntactic sugar. """ def dec(func): def wrapper(*args, **kwargs): print('Top decoration') rv = func(*args, **kwargs) print('Bottom decoration') return rv return wrapper @dec def sum_it(a, b): return(a + b) x = sum_it(10, 5) print(x)
def read_lines_of_file(filename): with open(filename) as f: content = f.readlines() return content,len(content) alltext,alltextlen = read_lines_of_file('read.txt') for line in alltext: print(line.rstrip()) print("Number of lines read from file --> %d" %(alltextlen))
class Authenticator(): def validate(self, username, password): raise NotImplementedError() # pragma: no cover def verify(self, username): raise NotImplementedError() # pragma: no cover def get_password(self, username): raise NotImplementedError() # pragma: no cover
""" some types and constants """ # pylint: disable=too-few-public-methods NS = "starters" class Status: """ pseudo-enum for managing statuses """ # the starter isn't done yet, and more data is required CONTINUING = "continuing" # the starter is done, and should not continue DONE = "done" ...
""" Given a string s, consisting of "X" and "Y"s, delete the minimum number of characters such that there's no consecutive "X" and no consecutive "Y". Constraints n ≤ 100,000 where n is the length of s https://binarysearch.com/problems/Consecutive-Duplicates """ class Solution: def solve(self, s): #...
#!/usr/local/bin/python3 class Generator(): def __init__(self, init, factor, modulo, multiple): self.value = init self.factor = factor self.modulo = modulo self.multiple = multiple def getNext(self): self.value = (self.value * self.factor) % self.modulo while (s...
price = 1000000 good_credit = True high_income = True if good_credit and high_income: down_payment = 1.0 * price print(f"eligible for loan") else: down_payment = 2.0 * price print(f"ineligible for loan") print(f"down payment is {down_payment}")
# Constants shared between C++ code and python # TODO: Share properly via a configuration file # ControllerWithSimpleHistory::EvaluationPeriod EVALUATION_PERIOD_SEQUENCES = 64 # kWorkWindowSize in SysConsts.hpp STATE_TRANSFER_WINDOW = 300
# Python program to print # ASCII Value of Character # In c we can assign different # characters of which we want ASCII value c = 'g' # print the ASCII value of assigned character in c print("The ASCII value of '" + c + "' is", ord(c))
#!/usr/bin/python3 """ Contains empty class BaseGeometry with public instance method area """ class BaseGeometry: """ Methods: area(self) """ def area(self): """not implemented""" raise Exception("area() is not implemented")
""" Enable `django-admin-tools`_ to enhance the administration interface. This enables three widgets to customize certain elements. `filebrowser`_ is used, so if your project has not enabled it, you need to remove the occurrences of these widgets. .. warning:: This mod cannot live with `admin_style`_, you have...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue May 19 21:42:34 2020 @author: lukepinkel """ LBFGSB_options = dict(disp=10, maxfun=5000, maxiter=5000, gtol=1e-8) SLSQP_options = dict(disp=True, maxiter=1000) TrustConstr_options = dict(verbose=3, gtol=1e-5) TrustNewton_options = dict(gtol=1e-5) Trust...
def calculator(): values = input('Insira os valores que deseja calcular por exemplo 5+5: ') if not values: return 'Você não inseriu os valores.' try: primary = int(values[0]) secondary = int(values[2]) value = values[1] obj = { '+': primary + secondary,...
def find(tree, key, value): items = tree.get("children", []) if isinstance(tree, dict) else tree for item in items: if item[key] == value: yield item else: yield from find(item, key, value) def find_path(tree, key, value, path=()): items = tree.get("children", []) i...
# compat2.py # Copyright (c) 2013-2019 Pablo Acosta-Serafini # See LICENSE for details # pylint: disable=C0111,R1717,W0122,W0613 ### # Functions ### def _readlines(fname): # pragma: no cover """Read all lines from file.""" with open(fname, "r") as fobj: return fobj.readlines() # Largely from From h...
# GRADED FUNCTION: gram_matrix def gram_matrix(A): """ Argument: A -- matrix of shape (n_C, n_H*n_W) Returns: GA -- Gram matrix of A, of shape (n_C, n_C) """ ### START CODE HERE ### (≈1 line) GA = tf.matmul(A, tf.transpose(A)) ### END CODE HERE ### return GA
''' Problem: 13 Reasons Why Given 3 integers A, B, C. Do the following steps- Swap A and B. Multiply A by C. Add C to B. Output new values of A and B. ''' # When ran, you will see a blank line, as that is needed for the submission. # If you are debugging and want it to be easier, change it too # input ...
class Solution: def maxIncreaseKeepingSkyline(self, grid): skyline = [] for v_line in grid: skyline.append([max(v_line)] * len(grid)) for x, h_line in enumerate(list(zip(*grid))): max_h = max(h_line) for y in range(len(skyline)): skyline[...
class Solution: def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: output = [[]] result = [] for num in sorted(nums): res = [lst + [num] for lst in output] output += res for subset in output: if subset not in result: ...
with open('/home/ai/hdd/tupm/projects/textGenOCR/trdg/dicts/general_form_ocr.txt') as f: text = f.readlines() f2 = open('/home/ai/hdd/tupm/projects/textGenOCR/trdg/dicts/dlo_address.txt', 'w+') # data = list(set(text)) # data.sort() # # count2 = 0 # count = {e: 0 for e in data} # count2 = 0 for e in text: ...
# -*- coding: utf-8 -*- """Top-level package for Hauberk Email Automations.""" __author__ = """Andrew Kail""" __email__ = 'andrew.a.kail@gmail.com' __version__ = '0.1.0'
"""Common testing word list.""" # word list Breakdown # 1: a (1) # 2: go. no, be, by (4) # 3: cry, fun, run, for (4) # 4: demo, foul, wait, sell (4) # 5: yeast, wrong, water, skill (4) # 6: accept, admire, bicorn, biceps, planks (5) # 7: bizonal, biofuel, bigfoot, scalene (4) # 8: mobility, notebook, superior, taxpaye...
def foo(): ''' >>> class bad(): ... pass ''' pass
# -*- coding: utf-8 -*- """ Useful exception classes that are used to return HTTP errors. """ class ApiException(Exception): """ The base exception class for all APIExceptions. Parameters ---------- code : str Error code. message : str Human readable string describing the exce...
class InstanceObjectManager: def __init__(self, parent): self.parent = parent # All Instance Id's of instanced objects on this server. self.localInstanceIds = set() # Dict of {Temp Id: Instance Object} self.tempId2iObject = {} # Dict of {Instance Id: Instance Object} self.instanceId2iObject = {} #...
""" File: complement.py Name: 張文銓 ---------------------------- This program uses string manipulation to tackle a real world problem - finding the complement strand of a DNA sequence. THe program asks uses for a DNA sequence as a python string that is case-insensitive. Your job is to output the complement of it. """ d...
def append(list1, list2): pass def concat(lists): pass def filter(function, list): pass def length(list): pass def map(function, list): pass def foldl(function, list, initial): pass def foldr(function, list, initial): pass def reverse(list): pass
class Solution: def rob(self, nums: List[int]) -> int: def dp(i: int) -> int: if i == 0: return nums[0] if i == 1: return max(nums[0], nums[1]) if i not in memo: memo[i] = max(dp(i-1), nums[i]+dp(i-2)) return mem...
#!/usr/bin/env python3 ############################################################################### # Copyright 2018 The Apollo Authors. All Rights Reserved. # # 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...
class Matrix: def transpose(self, matrix): return list(zip(*matrix)) def column(self, matrix, i): return [row[i] for row in matrix]
class Solution: def flipLights(self, n, m): """ :type n: int :type m: int :rtype: int """ if n == 1: return 1 if m == 0 else 2 if m == 0: return 1 elif m & 1: if m == 1: return 3 if n <= 2 else 4 ...
#!/usr/bin/env python3 """ PartBuilder exception for part builder errors """ class PartBuilderException(Exception): """ Raised by PartBuilder functions when things go wrong """ pass
def create_histo_table(dataname, dimPerfMap, lines, histoLambda, meanLambda, subsectitle, header): colPairs = len(dimPerfMap) colspecs = '|c|c|' * colPairs lines.append("\\begin{table}[H]") lines.append("\centering") lines.append("\caption{%s: %s}" % (subsectitle, header)) lines.append("\\begin{adjustbox}{wid...
#!/usr/bin/python FILENAME="arr1new.txt" def matrix2column(filename): """ @filename: a file contains data format looks like <string1: value01, value02, .....> <string2: value11, value12, .....> return: a list looks like [value01, value11, ......, value02, value12......] """ ...
print('-' * 30) print('BANCO DO BRASILEIRO') print('-' * 30) valor = int(input('Qual valor você quer sacar? R$ ')) valorRestante = valor valores = [50, 20, 10, 1] for i in valores: if valorRestante // i > 0: print(f'Total de {valorRestante // i} cédulas de R${str(i)}') valorRestante = valorRestante...
example_schema_array = {"type": "array", "items": {"type": "string"}} example_array = ["string"] example_schema_integer = {"type": "integer", "minimum": 3, "maximum": 5} example_integer = 3 example_schema_number = {"type": "number", "minimum": 3, "maximum": 5} example_number = 3.2 example_schema_object = {"type": "obje...
# -*- coding: utf-8 -*- # @Time : 2018/11/21 16:31 # @Author : Xiao # 基础需求: # 让用户输入用户名密码 # 认证成功后显示欢迎信息 # 输错三次后退出程序 users = {"alex":123456,'Miller':654321,"Xiaogang":"123654"} count = 3 while count > 0: user = input("Your name :\n").strip() pwd = input("Password :\n").strip() if user in users and pwd ==...
# region headers # escript-template v20190611 / stephane.bourdeaud@nutanix.com # * author: MITU Bogdan Nicolae (EEAS-EXT) <Bogdan-Nicolae.MITU@ext.eeas.europa.eu> # * stephane.bourdeaud@emeagso.lab # * version: 2019/09/18 # task_name: CalmSetProjectOwner # description: Given a Calm project UUID, ...
class TCPControlFlags(): def __init__(self): '''Control Bits govern the entire process of connection establishment, data transmissions and connection termination. The control bits are listed as follows, they are''' '''It indicates if we need to use Urgent pointer field or not. If it is set to 1 th...
def isPalindrome(string): if len(string) <= 1: return True else: return string[0] == string[-1] and isPalindrome(string[1:-1]) userInput = input("Please enter a sequence to check if it is an palindrome: ") answer = isPalindrome(userInput) print("Is '" + userInput + "' an palindrome? " + str(a...
dia=input ('Qual é o dia que você nasceu?') mês=input ('Qual é o mês que você nasceu?') ano=input ('Qual é o ano que você nasceu?')
def gen_binary(control, n1, n2, prefix): if n1 == 0 and n2 == 0: print(prefix) else: if n1 > 0: gen_binary(control + 1, n1 - 1, n2, prefix + "(") if control > 0 and n2 > 0: gen_binary(control - 1, n1, n2 - 1, prefix + ")") def read_input(): n = int(input()) ...
#! /usr/bin/env python3 # # === This file is part of Calamares - <https://calamares.io> === # # SPDX-FileCopyrightText: 2019 Adriaan de Groot <groot@kde.org> # SPDX-License-Identifier: BSD-2-Clause # """ Python3 script to scrape some data out of zoneinfo/zone.tab. To use this script, you must have a zone.tab in a...
N = int(input()) A = [int(n) for n in input().split()] Aset = set(A) m = (10**9+7) o = {} ans = [] for a in A: o.setdefault(a, 0) o[a] += 1 for i in range(len(Aset)-1): for j in range(i+1, len(Aset)): ans.append((A[i]^A[j])*o[A[i]]*o[A[j]]) print(sum(ans)/m)
# DOWNLOADER_MIDDLEWARES = {} # DOWNLOADER_MIDDLEWARES.update({ # 'scrapy.downloadermiddlewares.httpcache.HttpCacheMiddleware': None, # 'scrapy_httpcache.downloadermiddlewares.httpcache.AsyncHttpCacheMiddleware': 900, # }) HTTPCACHE_STORAGE = 'scrapy_httpcache.extensions.httpcache_storage.MongoDBCacheStorage' ...
def flatten(aList): myList = [] for el in aList: if isinstance(el, list) or isinstance(el, tuple): myList.extend(flatten(el)) else: myList.append(el) return myList
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") def zlib(): if "zlib" not in native.existing_rules(): http_archive( name = "zlib", build_file = "//third_party/zlib:zlib.BUILD", sha256 = "91844808532e5ce316b3c010929493c0244f3d37593afd6de04f71821d5136d...
class Sampler(object): def __init__(self): self._params = None self._dim = None self._iteration = 0 def setParameters(self, params): self._params = params self._dim = params.getStochasticDim() def nextSamples(self, *args, **kws): raise NotImplementedError()...
class Trie: def __init__(self): """ Initialize your data structure here. """ self.main_trie = dict() def insert(self, word: str) -> None: """ Inserts a word into the trie. """ nav = self.main_trie #print(f"Inserting {word}") f...
# def calcula_investimento(inv, mes, tipo): # seleciona tipo de investimento # CDB if tipo == 'CDB': for i in range(1, mes + 1): inv = inv * 1.013 if i % 6 == 0: inv = inv * 1.012 # LCI elif tipo == 'LCI': inv = inv*1.016**(...
#!/usr/bin/env python3 def collatz(x): if x <= 0: raise ValueError("Collatz has become 0") if (x % 2) == 0: return x/2 else: return 3*x+1 if __name__ == "__main__": number = 10 print("Ausgangszahl: ", number) iteration = 0 while True: number = collatz(numbe...
''' 256 definitions cause LOAD_NAME and LOAD_CONST to both require EXTENDED_ARGS. Generated with: `for i in range(0, 0xff, 0x10): print(*[f'x{j:02x}=0x{j:02x}' for j in range(i, i+0x10)], sep='; ')` ''' x00=0x00; x01=0x01; x02=0x02; x03=0x03; x04=0x04; x05=0x05; x06=0x06; x07=0x07; x08=0x08; x09=0x09; x0a=0x0a; x0b=0x...
# This function tells a user whether or not a number is prime def isPrime(number): # this will tell us if the number is prime, set to True automatically # We will set to False if the number is divisible by any number less than it number_is_prime = True # loop over all numbers less than the input numb...
class Solution: def longestCommonSubstring(self, a, b): matrix = [[0 for _ in range(len(b))] for _ in range((len(a)))] z = 0 ret = [] for i in range(len(a)): for j in range(len(b)): if a[i] == b[j]: if i == 0 or j == 0: ...
class Geladeira: def __init__(self, alimentos=None): """ Estrutura principal formada por um dicionário self.alimentos em que as chaves são os nomes dos alimentos e os valores são listas que contém o objeto Comida e a sua quantidade na geladeira. {'nome_alimento': [Comida, quantidad...
# Copyright (c) 2020 The Khronos Group 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 ...
sigla = input('Digite uma das siglas: SP / RJ / MG: ') if sigla == 'RJ' or sigla == 'rj': print('Carioca') elif sigla == 'SP' or sigla == 'sp': print('Paulista') elif sigla == 'MG' or sigla == 'mg': print('Mineiro') else: print('Outro estado')
"""Базовый класс Widget для всех виджетов.""" class Widget: def __init__(self, app=None): self.app = app if app is not None: self.init_app(app) def init_app(self, app): # Должен работать как синглтон ? if self.app is None: self.app = app
""" Module: 'flowlib.lib.emoji' on M5 FlowUI v1.4.0-beta """ # MCU: (sysname='esp32', nodename='esp32', release='1.11.0', version='v1.11-284-g5d8e1c867 on 2019-08-30', machine='ESP32 module with ESP32') # Stubber: 1.3.1 class Emoji: '' def clear(): pass def draw_square(): pass def sho...
# Copyright (c) 2019 Ezybaas by Bhavik Shah. # CTO @ Susthitsoft Technologies Private Limited. # All rights reserved. # Please see the LICENSE.txt included as part of this package. # EZYBAAS RELEASE CONFIG EZYBAAS_RELEASE_NAME = 'EzyBaaS' EZYBAAS_RELEASE_AUTHOR = 'Bhavik Shah CTO @ SusthitSoft Technologies' EZYBAAS_RE...
class Solution(object): def rob_o(self, nums): # 依照上面的思路,其实我们用到的数据永远都是dp的dp[i-1]和dp[i-2]两个变量 # 因此,我们可以使用两个变量来存放前两个状态值 # 空间使用由O(N) -> O(1) size = len(nums) if size == 0: return 0 dp1 = 0 dp2 = nums[0] for i in range(2, size+1): ...