content
stringlengths
7
1.05M
#!/usr/bin/env python3 class FuseModel: def fuse(self, first, second): raise NotImplementedError()
"""Protocol for server side messenger app.""" def validate_request(raw): """Checking for exists of 'action' and 'time' in request.""" return True if 'action' in raw and 'time' in raw else False def make_response(request, code, data=None): """Make response based on passed request, status code and data.""...
# code - ascii - def safe_pawns(pawns): safe = 0 #转化成数组便于排序 listP = list(pawns) #用第二个数字key排序 listP.sort(key=lambda x:x[1]) # 如果是最后一排,肯定不安全,记下最后一排的数字(ASCII码) minNum = ord(listP[0][1]) for p in listP[1::]: if ord(p[1]) > minNum : #左下方守卫 ...
table = {"I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000} roman = "MDCLXVI" number = 0 for ch in roman: number += table[ch] print(number)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/12/5 18:15 # @Author : Zhiwei Yang # @File : bucket_sort.py.py def bucketSort(nums): max_number = max(nums) #选择待排序的list里面的一个最大的数 #接着创建一个元素全是0的列表,当做桶 print (max_number) bucket = [0]*(max_number+1) print (bucket) #接着把所有元素放入桶中,即把对...
# STATIC FILES HOUSING_SECTOR_BILL_FILE = 'static_files/bill.pdf' PRODUCTS_CSV_FILE = 'static_files/list.csv' INDEX_CSV_FILE = 'static_files/index.csv' # URLs URL_TO_PARSE_FUEL = "https://auto.mail.ru/fuel/" URL_TO_PARSE_MCD_TICKETS = "https://troikarta.ru/tarify/mcd/" URL_TO_PARSE_ELECTRICITY_PRICE = "https://www.mo...
class Solution: def twoSum(self, numbers, target): i, j = 0, len(numbers) - 1 while i < j: ts = numbers[i] + numbers[j] if ts == target: break elif ts > target: j = j - 1 else: i = i + 1 return [i...
''' Задача 2. Найдите все пары натуральных чисел (и их количество) являющихся решением уравнения x^2+y^2+z^2 = 2020 ''' # предварительные вычисления: x,y,z <= 45 count = 0 for x in range(1, 45): for y in range(1, 45): for z in range(1, 45): if x ** 2 + y ** 2 + z ** 2 == 2020: pr...
class bedfeature(object): def __init__(self, chr,start,stop, name=None,value=None,strand=None, thickStart=None,thickStop=None,itemRGB=None, blockCount=None,blockSizes=None,blockStarts=None): self.chr=chr self.start=int(start) self.stop=int(s...
__author__ = 'Aaron Yang' __email__ = 'byang971@usc.edu' __date__ = '3/23/2020 4:35 PM' if __name__ == '__main__': list = ['1', '2', '3', '4', '5'] print(list[10:]) # 切片操作不会引起下标越界异常
''' Find first missing positive integer (>0) Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well. Note: you can modify the ...
BASKET_CREATED = 'basket_created' ADD_ITEM = 'add_item' ITEM_ADDED = 'item_added' CHECKOUT = 'checkout' CHECKOUT_STARTED = 'checkout_started' PAY_ORDER = 'pay_order'
def check_scope(func): def check(self, other): if not isinstance(other, self.__class__) and type(other) != str: raise TypeError(f"Cannot compare type Scope with type {type(other).__name__}") if isinstance(other, self.__class__): other = other.scope if other not in sel...
year = int(input("Which year do you want to check? ")) # A Leap Year must be divisible by four. But Leap Years don't happen every four years … there is an exception. #If the year is also divisible by 100, it is not a Leap Year unless it is also divisible by 400. if year % 4 == 0: if year % 100 == 0: if year % 4...
try: unicode except NameError: unicode = str messages = [u'Circle is 360\u00B0', u'Hyv\u00E4\u00E4 \u00FC\u00F6t\u00E4', u'\u0989\u09C4 \u09F0 \u09FA \u099F \u09EB \u09EA \u09B9'] class NonAsciiLibrary: def print_non_ascii_strings(self): """Prints message containing non-...
expected_output = { { "object_manager_statistics": { "batch_begin": { "pending_acknowledgement": 0, "pending_issue": 0 }, "batch_end": { "pending_acknowledgement": 0, "pending_issue": 0 }, "childless_delete_objects": "0", ...
# creating a Class of name Employee class Employee: # creating a Class Variable increament = 1.5 # Creating a Constructor of the Class Employee def __init__(self, fname, lname, salary): # setting Values to the variables self.fname = fname # setting Values to the variables ...
## 백준 2588번 ## 곱셈 ## 입출력, 사칙연산, 수학 A = int(input()) B = input() for i in range(2, -1, -1): print(A*int(B[i])) print(A*int(B))
''' Count sort. Outperforms the default sorting routine when the range of values is reasonably bounded. ''' def count_sort(a): mn, mx = float('inf'), -float('inf') for x in a: if x < mn: mn = x if x > mx: mx = x counter = [0 for _ in range(mx - mn + 1)] for x in a: counter[x - ...
name = "alita" version = "0.3.28" build_command = "python -m rezutil build {root}" private_build_requires = ["rezutil-1"] # Variables unrelated to Rez are typically prefixed with `_` _data = { "label": "Alita - Battle Angel", "icon": "{root}/resources/icon_{width}x{height}.png" } _requires = { "any": [ ...
class Coins: ''' Coins class for monetization ''' def __init__(self): self.quarter = True
#Manejo de Archivos #Autor: Javier Arturo Hernández Sosa #Fecha: 24/Sep/2017 #Descripcion: Curso Python FES Acatlán # C:\Hola.py -> "C:/Hola.py" Cambiar las barras #C:/Github/Curso Python/copia.png #Abrir ficheros # open(nombre_de_archivo, modo) fichero = open("texto.txt","r") #Propiedades del objeto fil...
firstname = input("Give me your firstname: ") familyname = input("Give me your lastname: ") age = int(input("Give me your age: ")) # print(type(age)) print(firstname + familyname + str(age) + "years old") if age >= 18: print("You are an adult") elif age < 16: print("F U FAGGOT!") else: print("Fokking bab...
class EmployeeModel: def __init__(self, eid=0, did=0, name="", money=0): self.eid = eid self.did = did self.name = name self.money = money
# cmd blacklist __blacklist__ = { "help": "crashes the app (requires unsupported external user input)", "license": "crashes the app (requires unsupported external user input)" }
class NeispyException(Exception): pass class ArgumentError(NeispyException): def __init__(self): super().__init__("인자값이 틀립니다.") class HTTPException(NeispyException): def __init__(self, code: int, message: str): super().__init__(f"{code} {message}") class MissingRequiredValues(HTTPExcep...
def function1(x, n): if n <= 0: return x else: return 1 + function1(x, n - 1) def function2(a, b): if a <= 0: return 1 + function1(a+1, b**a) else: return b def function3(a, b): if b <= 0: return a else: return a + b + function3(a, b -1) def fun...
#Passphrases #Advent of Code 2017 Day 4 #deal with the file file = open('input4.txt','r') input = file.read() file.close() lines = input.split("\n") validLines = 0 def isValid(line): words = line.split(" ") #print( str(len(words))) for x in range( 0, len(words) ): for y in range( x+1, len(words...
# Merge two sorted linked lists and return it as a new list. # The new list should be made by splicing together the nodes # of the first two lists. # # Input: 1->2->4, 1->3->4 # Output: 1->1->2->3->4->4 class ListNode: def __init__(self, val): self.val = val self.next = None class Solution: ...
def get_doughnut(df, label='My dataset'): labels = ['Greg', 'Cha'] data = [] for i in labels: data.append(len(df.query('who == "%s" & action == "did"' % i))) graph = {'labels': labels, 'datasets': [{'label': label, 'data': data, ...
class Empty: """ A constant that is Like None, but adding a little more. When compared with "==", it negates the bool(other) e.g. [] == Empty, {} == Empty, None == Empty When compared with "is", "Empty is Empty" only evaluates to True. This feature about "is" is convenient when checking default arg...
rows = [[1 if c == '#' else 0 for c in line[:-1]] for line in open('input.txt')] height, width, result = len(rows), len(rows[0]), 1 steps = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)] for right, down in steps: trees, row, col = 0, 0, 0 for row in range(0, height, down): trees += rows[row][col] ...
def alternatingSort(a): b = [] i = 0 ; j = len(a)-1 j_turn = True while (i <= j): if (j_turn): b.append(a[i]) i += 1 j_turn = False else: b.append(a[j]) j -= 1 j_turn = True print(b) alter...
def writeuser_tex(text_tex,env): if env == 1: text_file = open("latex/user_eq.tex", "w") text_file.write(r"\begin{align*}") text_file.write("\n") text_file.write(r"%s" % text_tex) text_file.write("\n") text_file.write(r"\end{align*}") text_file.close() e...
def subset_sum(numbers, target, partial=[]): s = sum(partial) # check if the partial sum is equals to target if s == target: return True elif s > target: return False # if we reach the number why bother to continue i=0 while i < len(numbers): n = numbers[i] rem...
LEN_TIME = 3 MAPPING_TEXT = { "Train a l'approche": "APR", "Train a quai": "QAI", "Train retarde": "RET", "A l'approche": "APR", "A l'arret": "ARR", "Train arrete": "TAR", "": "NAV", "NAV": "NAV", "UNC": "UNC" } def get_timings(returned_page_data): first_destination = returned...
#Add prod locations and copy to file_locations_prod.py LAST_ID = 'last_id.txt' LOCK_FILE = 'locked.txt' LOG_FILE = 'errors.txt'
class Car: # class properties: counter = 0 def __init__(self): Car.counter += 1 # object properties: self.color = 'Black' self.seats = 7 self.maximumSpeed = 200 self.isTheEngineOn = False self.currentGear = 0 self.gears = 7 self.speed = 0 # these are the methods: def turnOn(se...
'''28. Faça um programa que receba o salário base e o tempo de serviço de um funcionário. Calcule e mostre: O imposto, conforme a tabela a seguir. A gratificação, de acordo com a tabela a seguir. O salário líquido, ou seja, salário base menos imposto mais gratificação. A categoria, que está na tabela a seguir.''' sal...
book = {"apple": 0.67, "banana": 1.49, "milk": 2.3 } book["avocado"] = 1.5 print(book) print(book["banana"]) print(book["avocado"])
print ("program mayor menor") numero1= input ("INTRODUCE UN NUMERO:") numero1= int (numero1) numero2= input ("INTRODUCE UN NUMERO:") numero2= int (numero2) if numero1<numero2: print ("Usted Escribio los nmeros %d " %numero1, end="") print (" y %d" %numero2)
''' Problem statement: Create a function to find only the root value of x in any quadratic equation ax^2 + bx + c. The function will take three arguments: - a as the coefficient of x^2 - b as the coefficient of x - c as the constant term Problem Link: https://edabit.com/challenge/MDWFcHCTiJfHmwTFx ''' def quadratic_eq...
def make_cmd_params(command, nodes, env, sourcehash): inputs = {} outputs = [] files = [] #to be monitored refs = [] output_refs = [] params = { "lineno": command["cmd"]["lineno"], "source": command["cmd"]["source"], "sourcehash": sourcehash, "refs": refs, ...
def marge(arr, start, mid, end): num1 = mid - start + 1 num2 = end - mid left = [0] * (num1) right = [0] * (num2) for i in range(0, num1): left[i] = arr[start+i] for j in range(0, num2): right[j] = arr[mid+1+j] i = 0 j = 0 k = start while i < num1 and j < num2:...
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def pathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: int """ self.result =...
#gas_flow_class class Gas(): def __init__(self) -> None: self.Pt = 0 self.Tt = 0 self.P = 0 self.T = 0 self.H = 0 self.S = 0 self.Cp = 1.005 self.f = 0 #fraction of air and gas self.mass = 0 #massflow self.c = 0 #velocity of gas in m/s ...
# -*- coding: utf-8 -*- class B: print('B is imported')
""" This unit test checks that a thread does not get to log(before exitall is called.,'\n') If exitall works, the program will terminate immediately, and the log(will not happen.,'\n') """ #pragma repy def thread(): sleep(0.1) log('After exitall called','\n') createthread(thread) exitall()
class Solution: def deckRevealedIncreasing(self, deck: List[int]) -> List[int]: n = len(deck) order = collections.deque(list(range(n))) m = [-1] * n cnt = 0 while order: idx = order.popleft() m[cnt] = idx cnt += 1 if order: ...
def test_StrOp_concat(): s: str s = '3' + '4' s = "a " + "test" s = 'test' + 'test' + 'test'
"""P1_boxPrint.py This program prints out a box based on input sizes. """ def boxPrint(symbol: str, width: int, height: int) -> None: """Box print Prints a box of given width and height using the given symbol. Args: symbol: String to use to make sides of box. width: Integer width of bo...
''' Write a Min Max Stack class. The class should support pushing and popping values on and off the stack, peeking at values at the top of the stack, and getting both the minimum and maximum values in the stack. All class methods, when considered independently, should run in constant time and with constant space. Inpu...
class SchemaAlreadyRegistered(Exception): """Error raised while trying to register a Schema that has already been registered """ def __init__(self, name): """ Args: name (str): schema name """ super(SchemaAlreadyRegistered, self).__init__("Schema \"%s\" has al...
class Categoria: """ Representa uma Categoria """ def __init__(self): self.id = None self.nome = None self.quantidade_ofertas = None self.link = None def construir(self, categoria: dict): """ Popula a categoria de acordo com os dados da Lomadee Para...
# Desenvolva um programa que pergunte a distância de uma viagem em Km. Calcule o #preço da passagem, cobrando R$0,50 por Km para viagens de até 200Km e R$0,45 #para viagens mais longas. km = int(input("Digite a distância da viagem em km: ")) if(km <= 200): preço = km * 0.50 print("A viagem irá lhe custa...
def genres(items, excludedGenres): filteredGenres = [] for item in items: for genre in item["genres"]: if len(list(set(genre.split()).intersection(excludedGenres))) == 0: genre = genre.replace(' ', '-').lower() if not genre in filteredGenres: ...
# # PySNMP MIB module SAVEPOWER-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SAVEPOWER-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:00:47 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 201...
num = int(input('Me diga um número qualquer: ')) if num % 2 == 0: print(f'O número {num} é PAR.') else: print(f'O número {num} é ÍMPAR.')
# encoding: utf-8 # Author: Kyohei Atarashi # License: MIT def _cd_linear_epoch(w, X, y, y_pred, col_norm_sq, alpha, loss, indices_feature): sum_viol = 0 n_samples = len(y) for j in indices_feature: update = 0 # compute gradient with respect to w_j for i in ran...
symbol_1 = input() symbol_2 = input() string = input() total_sum = 0 for letter in string: if ord(symbol_1) < ord(letter) < ord(symbol_2): total_sum += ord(letter) print(total_sum)
# BS mark.1-55 # /* coding: utf-8 */ # BlackSmith plugin # most_plugin.py # Coded by: 40tman (40tman@qip.ru) # ReCoded: by WitcherGeralt (WitcherGeralt@jabber.ru) MOST_C1 = None MOST_C2 = None def most_message_handler(raw, type, source, body): if type == 'public' and source[1] in [MOST_C1, MOST_C2]: if source[...
def teardown_func(): assert 1 == 0 def test(): pass test.teardown = teardown_func
# coding=utf-8 # # @lc app=leetcode id=674 lang=python # # [674] Longest Continuous Increasing Subsequence # # https://leetcode.com/problems/longest-continuous-increasing-subsequence/description/ # # algorithms # Easy (44.67%) # Likes: 476 # Dislikes: 98 # Total Accepted: 73.9K # Total Submissions: 165.4K # Testc...
class Note: def __init__(self, content: str): self.content = content
# Exercício Python 109: # Modifique as funções que form criadas no desafio 107 para que elas aceitem um parâmetro a mais, # informando se o valor retornado por elas vai ser ou não formatado pela função moeda(), desenvolvida no desafio 108. def moeda(valor): return f"R${valor:.2f}" def metade(numero, real...
def large_population(population): if(found > 2000): return True else: return False
#!/usr/bin/python3 # -*- coding: utf-8 -*- default_date = '2021-03-10' default_rates = {'EUR': 1.0, 'USD': 1.1892, 'JPY': 129.12, 'BGN': 1.9558, 'CZK': 26.226, 'DKK': 7.4366, 'GBP': 0.85655, 'HUF': 367...
# If set, it will update the default panel of the PANEL_DASHBOARD. DEFAULT_PANEL = 'billing_config' PANEL_DASHBOARD = 'billing' PANEL_GROUP = 'default' PANEL = 'billing_config' ADD_PANEL = 'astutedashboard.dashboards.billing.config.panel.Config'
point_dict = { '001': (100, 88, 81), '002': (77, 94, 85), '003': (80, 52, 99), } for student_id in point_dict: points = point_dict[student_id] subject_number = len(points) japanese, english, mathmatics = points total = japanese + english + mathmatics excellent = subject_number * 100 * 0...
class Node: def __init__(self, data) -> None: self.data = data self.next = None class LinkedList: def __init__(self) -> None: self.head = None def insert(self, item): temp = Node(item) temp.next = self.head self.head = temp def display(node): ...
#!/usr/bin/env python3 x = "text" # these do the same thing. print("x is:", x) # simply prints two things. print("x is: " + x) # concatenates to string(no space)
'''https://leetcode.com/problems/n-queens-ii/''' class Solution: def totalNQueens(self, n: int) -> int: board = [[0]*n for _ in range(n)] def placeQ(row, col): board[row][col] = 1 def removeQ(row, col): board[row][col] = 0 d...
A = [int(x) for x in input().split()] B = [int(x) for x in input().split()] C = int(input()) ans = [] if C in A: ans.extend(B) if C in B: ans.extend(A) ans = set(ans) print(len(ans)) print(*sorted(ans), sep='\n')
def fact(n:int=0)->int: if n <= 0: return (1) if n == 1: return (1) return fact(n-1) + fact(n-2) #main for i in range(0,10): print(f"{fact(i)}", end =" ")
saque = int(input('Valor do saque: R$')) notas = saque while saque != 0: if saque % 50 >= 0: notas = saque if notas // 50 != 0: print(f'Total de {notas//50} notas de R$50,00') saque = saque % 50 if saque % 20 >= 0: notas = saque if notas // 20 != 0: print(f'Total de {nota...
lista_inteiros = [ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [9, 1, 8, 9, 9, 7, 2, 1, 6, 8], [1, 3, 2, 2, 8, 6, 5, 9,6, 7], [3, 8, 2, 8, 6, 7, 7, 3, 1, 9], [4, 8, 8, 8, 5, 1, 10, 3, 1, 7], [1, 3, 7, 2, 2, 1, 5, 1, 9, 9], [10, 2, 2, 1, 3, 5, 1, 9, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ] def encont...
# Maltego Entities - Maltego Chlorine 3.6.0 # Parser written by: # Justin Seitz - justin@hunch.ly class Unknown(object): def __init__(self, entity_value): self.entity_value = entity_value self.entity_type = "maltego.Unknown" self.entity_attributes = {} self.entity_attribute_names = ...
# python3 (this comment tells the grading system at Coursera to use python3 rather than python3) def sum_of_two_digits(first_digit, second_digit): assert 0 <= first_digit <= 9 and 0 <= second_digit <= 9 return first_digit + second_digit if __name__ == '__main__': a, b = map(int, input().split()) pri...
for a in range(1,100): for b in range(1,100): for c in range(1,100): if a*a == b*b + c*c: print(a , b , c) elif b*b == a*a + c*c: print(b , a , c) elif c*c == a*a + b*b: print(c , a , b)
grid = [[int(x) for x in line] for line in open('input.txt').read().splitlines()] def dijkstra(grid, start, stop): distances, temp = {}, {start: 0} while len(temp)>0: # set closest point as definite x,y = min(temp, key=temp.get) distance = temp.pop((x,y)) distances[(x,y)] = dist...
class Solution: def slidingPuzzle(self, board: List[List[int]]) -> int: # 0 1 2 # 3 4 5 target = '123450' start = ''.join(map(str, board[0])) + ''.join(map(str, board[1])) start_idx = start.index('0') moves = [(1, 3), (0, 2, 4), (1, 5), (0, 4), (1, 3, 5), (2, 4)] ...
# define a class class Dog(object): kind = "canine" # class variable def __init__(self, name): self.name = name #instance variable self.tricks = [] #instance variable def add_trick(self, trick): self.tricks.append(trick) # instance of a class e = Dog('Buddy') #first instance d = Dog...
""" Constant Module of device status """ STATUS_BROKEN=-1 STATUS_UNKNOWN=0 STATUS_WAIT=1 STATUS_RUNNING=2 STATUS_CHARGING=3 STATUS_AUTOPROTECT=4
def main(context): session = context.session session.execute("INSERT INTO test (id, name) values (1, 'jon')")
class ErrorTrapTransport(Exception): pass class ConfigNotFoundError(Exception): pass class ConfigNotParsedError(Exception): pass class MibCompileError(Exception): pass class MibCompileFailed(Exception): pass class FilterPathError(Exception): pass class FilterProcessError(Exception): pass c...
#!git python3 # -*- coding: utf-8 -*- def fact(n): return fact_iter(n, 1) def fact_iter(num, product): if num == 1: return product return fact_iter(num - 1, num * product) # 栈溢出 python没有针对尾递归进行优化 print(fact_iter(1000, 1))
#IMC - índice de massa corporal peso = float(input('Qual o seu peso em quilogramas(kg)? ')) altura = float(input('Qual sua altura em metros(m): ')) imc = peso/(altura*altura) print(f'O IMC desta pessoa é de {imc:.1f}') if imc >= 18.5 and imc <= 25: print('Peso Ideal') elif imc >= 25 and imc <= 30: print('So...
"""Adds repostories/archives.""" ######################################################################## # DO NOT EDIT THIS FILE unless you are inside the # https://github.com/3rdparty/stout-flags repository. If you # encounter it anywhere else it is because it has been copied there in # order to simplify adding tran...
H,W,*A = [x for x in open(0).read().split()] H=int(H) W=int(W) whites=[0]*W for a in A: for i,c in enumerate(a): if c=='.': whites[i]+=1 checks=[white != H for white in whites] wline='.'*W for a in A: if a == wline: continue print(''.join([c for i,c in enumerate(a) if checks[i]])...
# # PySNMP MIB module HARMONIC-INC-NSG9000-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HARMONIC-INC-NSG9000-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:11:45 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7....
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Settings for analysis setup The information set here """ raise NotImplementedError('work in progress...') #: Base directory for output storage OUT_BASE = './output/' # alternative ts_types in case one of the provided in setup is not in dataset TS_TYPE_READ_ALT = {'d...
# status: testado com exemplos da prova if __name__ == '__main__': N = input() values = [int(x) for x in input().split()] max_record = 0 last_record = 0 last_value = 0 for value in values: last_record += 1 if not value == last_value: last_record = 1 max_rec...
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: param root: The root of the binary search tree @param k1: An integer @param k2: An integer @return: return: Return all keys...
"""Fantasy Game Inventory.""" stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12, 'map fragments': 3} def display_inventory(inventory): """Print contents and total number of items in inventory.""" print('Inventory:') item_total = 0 for k, v in inventory.items(): ...
class Solution: def numIslands(self, grid): """ :type grid: List[List[str]] :rtype: int """ if not grid: return 0 if not len(grid[0]): return 0 visited = [[0 for i in range(len(grid[0]))] for j in range(len(grid))] result = 0...
P = 1000000007 # edit this Q = 2210070043 # edit this N = P * Q print(f"N={N} -- tell Bob this") Z = (P - 1) * (Q - 1) print(f"Z={Z}") print("Pick a different number between 1 and Z") E = 49979693 # edit this to be a different prime number between 1 and Z print(f"E={E} (public key)") D = pow(E, -1, Z) print(f"D=...
# -*- coding: utf-8 -*- """ Created on Wed Sep 21 11:52:34 2016 @author: WELG """ ##################################### # EXAMPLE: Towers of Hanoi ##################################### def printMove(fr, to): print('move from ' + str(fr) + ' to ' + str(to)) def Towers(n, fr, to, spare): if n == 1: p...
class FileHandler: """read input from file and provide states read state sequence and print out output file""" def __init__(self,filename): self.filename=filename self.testcases=0 self.train_num=[] #list or single value let it be list for now self.content=None #check1 def readFile(self): wi...
# TODO add linters, automated tests, etc def gos_py_library(name, **kwargs): native.py_library( name = name, **kwargs ) def gos_py_binary(name, **kwargs): native.py_binary( name = name, **kwargs ) def gos_py_test(name, **kwargs): native.py_test( name = name...
''' File: __init__.py Project: optimizer File Created: Monday, 17th August 2020 3:52:54 pm Author: Sparsh Dutta (sparsh.dtt@gmail.com) ----- Last Modified: Monday, 17th August 2020 3:52:54 pm Modified By: Sparsh Dutta (sparsh.dtt@gmail.com>) ----- Copyright 2020 Sparsh Dutta '''