content
stringlengths
7
1.05M
A = [[1, 2], [3, 4], [5, 6]] B = max(A) V = 1
class config_library: def __init__(self, default): self.path = default.path + "/system/library/" self.ignore = ['__pycache__', '__init__.py'] def get(self): return self
# Usando imágenes # Por lo pronto primero hay que agregarlas desde Processing > Sketch > Añadir archivo def setup(): frameRate(2); smooth(); global img global img2 size(400, 400); # Make a new instance of a PImage by loading an image file # Declaring a variable of type PImage img = load...
""" OptimalK module. This module is used to determine the best number of clusters in functional data. """
f = open("/home/vleite/Desktop/range.txt", "w") f.write("x range:\n") for x in range(0, 55296, 64): f.write(str(x) + "-" + str(x + 64) + "\n") f.write("y range:\n") for x in range(0, 46080, 64): f.write(str(x) + "-" + str(x + 64) + "\n") f.write("z range:\n") for x in range(0, 514, 64): f.write(str(x) +...
class Solution(object): def runningSum(self, nums): """ :type nums: List[int] :rtype: List[int] """ add_nums = 0 running_sum = [] for x in nums: add_nums = add_nums + x running_sum.append(add_nums) return runnin...
pkgname = "libmodplug" pkgver = "0.8.9.0" pkgrel = 0 build_style = "gnu_configure" configure_args = ["--enable-static"] hostmakedepends = ["pkgconf"] pkgdesc = "MOD playing library" maintainer = "q66 <q66@chimera-linux.org>" license = "custom:none" url = "http://modplug-xmms.sourceforge.net" source = f"$(SOURCEFORGE_SI...
class Solution: def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ res = 0 maxRes = 0 strs = '' for i in range(len(s)): pos = strs.find(s[i]) if pos != -1: if res > maxRes: ...
# Copyright (c) 2008, Michael Lunnay <mlunnay@gmail.com.au> # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND T...
# O(1) constant time! def print_one_item(items): print(items[0]) # liniar O(n) def print_every_item(items): for item in items: print(item) # n = number of steps # quadratic O(n^2) def print_pairs(items): for item_one in items: for item_two in items: print(item_one, item_two)...
class Aranet4Exception(BaseException): """ Base exception for pyaranet4 """ pass class Aranet4NotFoundException(Aranet4Exception): """ Exception that occurs when no suitable Aranet4 device is available """ pass class Aranet4BusyException(Aranet4Exception): """ Exception that ...
# Time: O(n) # Space: O(c), c is the max of nums # counting sort, inplace solution class Solution(object): def sortEvenOdd(self, nums): """ :type nums: List[int] :rtype: List[int] """ def partition(index, nums): for i in xrange(len(nums)): j = i ...
""" link: https://leetcode-cn.com/problems/paint-house-ii problem: 给 n*k 的数组,每项选一个数字,相邻选中的列数不能一致,求最小和,要求时间复杂O(nk) solution: DP。dp状态很清晰,dp[i][j] 表示选到第 i 行时,选中第 j 项的当前最小和,显然有 dp[i][j] = min(min(dp[i-1][:j]), min(dp[i-1][j+1:])),区别只是填表的方式。 O(nkk)的思路很容易想到,每次遍历 dp[i-1] 的每一项找到最小值,每项花时间是O(k)。在这里做个优化,左右各...
# https://leetcode.com/problems/shortest-common-supersequence/ # Reference # https://www.geeksforgeeks.org/print-shortest-common-supersequence/ # https://www.youtube.com/watch?v=823Grn4_dCQ&list=PL_z_8CaSLPWekqhdCPmFohncHwz8TY2Go&index=25&ab_channel=AdityaVerma class Solution(object): # Runtime: 368 ms, faste...
# content of test_example.py (adapted from https://docs.pytest.org) def inc(x): """Functionality that we want to test""" return x + 1 def test_inc(): # This will give an error # assert inc(3) == 5 # This will not # (to see this: comment assertion line above, # uncomment line below and re...
word = input() times = int(input()) def repeat(): text = "" for _ in range(times): text += word print(text) repeat()
total = list([[], []]) while True: for c in range(1, 8): valor = int(input(f'Digite o {c} valor: ')) if valor % 2 == 0: total[0].append(valor) if valor % 2 != 0: total[1].append(valor) total[0].sort() total[1].sort() print(f'Os valores pares em ordem cresc...
# Exercício Python 049 # Refaça o desafio 009, tabuada utilizando o FOR n = int(input('Digite um número: ')) for c in range(1,11): print('{:2} x {:2} = {:2}'.format(n,c,c*n))
class STLException(Exception): pass class STLParseException(Exception): pass class STLOfflineException(Exception): pass
class TypeDeclaration: def __init__(self, file_path): self.file_path = file_path self.types_declared = set() def add_type_declared(self, new_type): if type(new_type) == set: self.types_declared = self.types_declared.union(new_type) else: self.types_d...
''' - Leetcode problem: 797 - Difficulty: Medium - Brief problem description: Given a directed, acyclic graph of N nodes. Find all possible paths from node 0 to node N-1, and return them in any order. The graph is given as follows: the nodes are 0, 1, ..., graph.length - 1. graph[i] is a list of all nodes j for ...
class BnBTreeNode(object): """ BnBTreeNode 是 BnBTree 的节点 Fields ------ left : BnBTreeNode, 左子节点,分支定界法里的左枝 right : BnBTreeNode, 右子节点,分支定界法里的右枝 x_idx : int, 分支定界法里新增条件的变量索引 x_c : str, 分支定界法里新增条件的比较运算符 "<=" 或 ">=" x_b : float, 分支定界法里新增条件的右端常数 res_x : numpy ar...
#Dictionary adalah stuktur data yang bentuknya seperti kamus. #Ada kata kunci kemudian ada nilaninya. Kata kunci harus unik, #sedangkan nilai boleh diisi denga apa saja. # Membuat Dictionary ira_abri = { "nama": "ira abri", "umur": 19, "hobi": ["makan", "jalan", "ngemoll"], "menikah": False,...
class WorkBot: def __init__(self): self.driver = webdriver.Chrome() self.driver.get("https://app.daily.dev/") self.WebDriverWait(self.driver).until(document_initialised) el = self.driver.find_element_by_xpath("/html/body/div/main/div/article/a") # names = [name.text for name ...
# This code is written in Python # This code prints the line number next to each line in the file FileName = "file1.txt" f = open(FileName,"r") fileContent = f.read() number_of_lines = 0 line_by_line = fileContent.split("\n") number_of_lines = len(line_by_line) print("The number of lines in the file are : ") print...
class Event: def __init__(self): self._callee_list = set() def __iadd__(self, fct): return self._callee_list.add(fct) def __isub__(self, fct): return self._callee_list.remove(fct) def __call__(self, sender, *event_args): for callee in self._callee_list: ...
# https://www.geeksforgeeks.org/kmp-algorithm-for-pattern-searching/ def get_lps(pat): n = len(pat) lps = [0] * n # longest proper prefix which is also suffix i = 1 l = 0 while i < n: if pat[i] == pat[l]: l += 1 lps[i] = l i += 1 else: if 0 < l: l = lps[l-1] e...
class ParsingSuccess: def __init__(self, string, rule_type, start_pos, end_pos, children): self.string = string self.rule_type = rule_type self.start_pos = start_pos self.end_pos = end_pos self.children = children @property def match_string(self): r...
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) class Pinentry(AutotoolsPackage): """pinentry is a small collection of dialog programs that allow GnuPG to read p...
#Faça um programa que leia o dia, o Mês e o Ano de seu nascimento. Dia = input("Que dia você nasceu = ") Mes = input("De qual mês = ") Ano = input("De qual ano = ") print("Você nasceu no dia ",Dia, "de",Mes, "de", Ano, ". Correto?")
# encoding=utf-8 WECHATGROUP = [u'运维告警',] SDPURL = 'http://192.168.0.111:8050' SDPAPIKEY = '5C45F603-DF68-4CC1-BB66-E923670EC2BD' OPMURL = 'http://192.168.0.96:8060' OPMAPIKEY = '67b287274fb1be2b449f1653508b7669' LISTENERHOST = 'localhost' LISTENERPORT = 6601 TULINGKEY = '8edce3ce905a4c1dbb965e6b35c3834d'
def information(*args): for arg in args: print(arg) information(1, 3, 6, 7, "Abelardo") def users(**kwargs): for k in kwargs.values(): print(k) users(name="bob", age=19)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Дано предложение. Определить порядковые номера # первой пары одинаковых соседних символов. # Если таких символов нет, # то должно быть напечатано соответствующее сообщение. if __name__ == '__main__': line = input("Введите предложение ") for ind in ran...
def sqr(n): if (n**.5)%1==0: return True return False l=[] for d in range(2,1001): if sqr(d)==False: y=1 while True: x=1+d*y*y if sqr(x)==True: print(x**.5,"^2 -",d,"*",y,"^2 = 1") l.append(int(x**.5)) ...
def soma_numeros(primeiro, segundo): return primeiro + segundo print(soma_numeros(15, 15))
def dict_eq(d1, d2): return (all(k in d2 and d1[k] == d2[k] for k in d1) and all(k in d1 and d1[k] == d2[k] for k in d2)) assert dict_eq(dict(a=2, b=3), {'a': 2, 'b': 3}) assert dict_eq(dict({'a': 2, 'b': 3}, b=4), {'a': 2, 'b': 4}) assert dict_eq(dict([('a', 2), ('b', 3)]), {'a': 2, 'b': 3}) a = {'g...
DISCORD_WEBHOOK_URL = 'https://discord.com/api/webhooks/{webhook_id}/{webhook_token}' DISCORD_WEBHOOK_RELAY_PARAMS = [ 'webhook_id', 'webhook_token', 'content', ]
class Forbidden(Exception): pass class InternalServerError(Exception): pass
# -*- coding: utf-8 -*- """ test_nsct ---------------------------------- Tests for `nsct` module. """ class TestNsct(object): @classmethod def set_up(self): pass @classmethod def tear_down(self): pass
print('calculate area of a circle') def circle(): radius = input('enter radius') radius = float(radius) area = 3.14*radius*radius print ('area is ') print (area) circle()
h = list(map(int, input().rstrip().split())) word = input() h = [h[ord(l) - ord("a")] for l in set(word)] print(max(h) * len(word))
load("//:import_external.bzl", import_external = "safe_wix_scala_maven_import_external") def dependencies(): import_external( name = "com_fasterxml_jackson_module_jackson_module_paranamer", artifact = "com.fasterxml.jackson.module:jackson-module-paranamer:2.9.6", artifact_sha256 = "dfd66598c0094d9...
"""Version and details for pcraft""" __description__ = "Pcraft" __url__ = "https://www.github.com/devoinc/pcraft" __version__ = "0.1.4" __author__ = "Sebastien Tricaud" __author_email__ = "sebastien.tricaud@devo.com" __license__ = "MIT" __maintainer__ = __author__ __maintainer_email__ = __author_email__
#!/usr/bin/env python def plot(parser, args): """ To do. """ pass if __name__ == "__main__": plot()
# 前台信息编码表 FrontMessageCode = {} # 后台信息编码表 BackMessageCode = {} # 编码、语言 FrontMessageCode['1'] = {"Help": "Username_Empty", "Zh": "用户不能为空"} FrontMessageCode['2'] = {"Help": "Password_Empty", "Zh": "密码不能为空"} FrontMessageCode['3'] = {"Help": "Username_NotEqual_Password", "Zh": "用户名和密码不匹配"} FrontMessageCode['4'] = {"Help...
# A game is a sequence of scores (positive for the home team, # negative for the visiting team). # For example, in American football, the set of valid scores is # {2,3,6,7,8,-2,-3,-6,-7,-8}. # For rugby, the set of valid scores in {3,5,7,-3,-5,-7} # A tie-less game is one in which the teams are never in a tie # (except...
class Solution: def getRow(self, rowIndex: int) -> List[int]: if rowIndex == 0: return [1] s = [1] for i in range(1, rowIndex + 1): s = [sum(x) for x in zip([0] + s, s + [0])] return s
#!/usr/bin/env python class AsciiFileReader: def __init__(self, infile): self.infile = infile def readInt(self): assert False
coordinates_E0E1E1 = ((123, 109), (123, 111), (123, 112), (123, 114), (124, 109), (124, 110), (125, 108), (125, 109), (125, 114), (126, 108), (126, 109), (127, 69), (127, 79), (127, 99), (127, 101), (127, 108), (128, 72), (128, 73), (128, 74), (128, 75), (128, 76), (128, 77), (128, 79), (128, 93), (128, 98), (128, 10...
def countWords(s): count=1 for i in s: if i==" ": count+=1 return count print(countWords("Hello World This is Rituraj"))
def imprime(nota_fiscal): print(f"Imprimindo nota fiscal {nota_fiscal.cnpj}") def envia_por_email(nota_fiscal): print(f"Enviando nota fiscal {nota_fiscal.cnpj} por email") def salva_no_banco(nota_fiscal): print(f"Salvando nota fiscal {nota_fiscal.cnpj} no banco")
#Write a function that accepts a string and a character as input and returns the #number of times the character is repeated in the string. Note that #capitalization does not matter here i.e. a lower case character should be #treated the same as an upper case character. def count_character(line, character): count =...
#!/usr/bin/env python # 平均の求め方 def Average(numList): return sum(numList) / len(numList) def main(): numList = [1, 2, 3] print(Average(numList)) if __name__ == "__main__": main()
""" Fragments of user mutations """ AUTH_PAYLOAD_FRAGMENT = ''' id token user { id } ''' USER_FRAGMENT = ''' id '''
def partfast(n): # base case of the recursion: zero is the sum of the empty tuple if n == 0: yield [] return # modify the partitions of n-1 to form the partitions of n for p in partfast(n-1): p.append(1) yield p p.pop() if p and (len(p) < 2 or p[-2] > p[-1...
mass_list = list(open('d01.in').read().split()) base_fuel = 0 total_fuel = 0 def calculate_fuel(mass): return int(mass) // 3 - 2 for mass in mass_list: fuel = calculate_fuel(mass) base_fuel += fuel while (fuel >= 0): total_fuel += fuel fuel = calculate_fuel(fuel) print('P1:', base_fu...
f=open('t.txt','r') l=f.readlines() d={} for i in (l): k=i.strip() m = list(k) if(m[0]=='R'): d[k] = [] j=k else: d[j].append(k) p=[] for i in d.keys(): m=d[i] k=''.join(x for x in m) d[i]=list(k) l1 = k.count('G') l2 = k.count('C') l = len(d[i]) per =...
def sign(val): if val == 0: return 0 return 1 if val > 0 else -1 def linear_interpolation(val, x0, y0, x1, y1): return y0 + ((val - x0) * (y1 - y0))/(x1 - x0)
# coding=utf8 # Copyright 2018 JDCLOUD.COM # # 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 ...
def bbox_xywh2cxcywh(bbox): cx = bbox[0] + bbox[2] / 2 cy = bbox[1] + bbox[3] / 2 return (cx, cy, bbox[2], bbox[3])
"""Шаблон бинарного поиска""" def search(sequence, item): """Бинарный поиск""" raise NotImplementedError()
class Dog(): def __init__(self, name, age): self.name = name self.age = age def set(self): print(self.name.title() + '请坐') class car(): def __init__(self, name, model, year): self.name = name self.model = model self.year = year def read_name(self): ...
A = float(input("Inserire il valore A: ")) # 0.1 B = float(input("Inserire il valore B: ")) # 0.01 C = float(input("Inserire il valore C: ")) # 0.01 D = float(input("Inserire il valore D: ")) # 0.00002 prey_old = int(input("Inserire il valore di prede iniziali: ")) # 1000 pred_old = int(input("Inserire il numero di pr...
class Block(object): def __init__(self, name) -> None: super().__init__() self.__name__ = name
""" # All classes should extend Veggies and override the following methods def __str__(selt) """ class Veggies : def __str__(self): assert False, 'This method should be overrided.' class BlackOlives(Veggies) : def __str__(self): return 'Black Olives' class Garlic(Veggies) : ...
print("======================") print("RADAR ELETRÔNICO!") print("======================") limite = 80.0 multa = 7 velocidade = float(input("Qual a sua velocidade: ")) if velocidade <= limite: print("Boa Tarde, cuidado na estrada, siga viagem!") else: valor = (velocidade - limite) * 7 print(f"Você ultrap...
def subsets(l): if not l: return [[]] else: all_subsets = [] for i in range(len(l)): sub_subsets = subsets(l[:i] + l[i + 1:]) [all_subsets.append(subset) for subset in sub_subsets if subset not in all_subsets] if l not in all_subsets: a...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class SizeError( Exception ): pass
"""Package contains objects representing a wordsearch board.""" class Line: """Represents a directionless character line on a word search board.""" def __init__(self, index, characters=""): """Initialize instance with provided starting characters.""" self.index = index self.characters...
class Solution: def numberOfArithmeticSlices(self, nums: List[int]) -> int: ''' -5 -2 1 4 5 6 7 9 11 <3 = 0 3 -> 1 4 -> 2+1 5 -> 3+2+1 6 -> 4+3+2+1 n -> n(n+1)/2 -n - (n-1) -> (n^2 - 3n + 2)/2 ''' def getCount(n): ...
class HelperError(Exception): pass class BaseHelper(object): def get_current_path(self): raise HelperError('you have to customized YourHelper.get_current_path') def get_params(self): raise HelperError('you have to customized YourHelper.get_params') def get_body(self): raise...
class Solution: def maxSubArray(self, nums: List[int]) -> int: maxsofar = nums[0] maxendinghere = nums[0] for i in range(1, len(nums)): maxendinghere = max(nums[i], nums[i] + maxendinghere) maxsofar = max(maxsofar, maxendinghere) return m...
map = [200090710, 200090610] sm.sendSay("Where would you like to go? \r\n#L0#Victoria Island#l\r\n#L1#Orbis#l") sm.warp(map[answer], 0)
class DependenceNode: def __init__(self): self.parents = [] self.children = [] self.inter_parents = [] self.inter_children = [] self.fictitious_parents = [] self.fictitious_children = [] self.ast = None def add_parent(self, parent): self.parents....
def longest_consec(strarr, k): output,n = None ,len(strarr) if n == 0 or k > n or k<=0 : return "" for i in range(n-k+1): aux = '' for j in range(i,i+k): aux += strarr[j] if output == None or len(output) < len(aux): output = aux return output
#!/usr/bin/env python # encoding: utf-8 ''' @author: Jason Lee @license: (C) Copyright @ Jason Lee @contact: jiansenll@163.com @file: 56.py @time: 2019/6/9 21:29 @desc: ''' class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: if not intervals or len(intervals) == 1: ...
_CUDA_TOOLKIT_PATH = "CUDA_TOOLKIT_PATH" _VAI_CUDA_REPO_VERSION = "VAI_CUDA_REPO_VERSION" _VAI_NEED_CUDA = "VAI_NEED_CUDA" _DEFAULT_CUDA_TOOLKIT_PATH = "/usr/local/cuda" # Lookup paths for CUDA / cuDNN libraries, relative to the install directories. # # Paths will be tried out in the order listed below. The first s...
f = open("demo.txt", "r")#read file print(f.read()) c=open("demosfile.txt","r") print(c.read()) w= open("demo.txt", "a") #update file with additional data w.write("Now the file has one more line!") ow = open("demo.txt", "w") #delete entire content and add new content ow.write("Woops! I have deleted the content!"...
#!usr/bin/python # -*- coding:utf8 -*- class people: # 定义基本属性 job = "gopher" def __init__(self, name, age, weight): self.name = name self.age = age # 注意__xx是私有变量,self._weight外部是可以直接访问到的 self.__weight = weight # 私有变量,翻译成了self._A__name = "python" def speak(self): ...
""" Home of all the miscellaneous BrainPywer utilities that don't deserve their own files """ def thaw(snowflake): """ Tiny function to return the unix timestamp of a snowflake :param snowflake: a discord snowflake (It's unique, just like you! ha.) :type snowflake: int :return: unix timestamp of ...
""" Programa 054 Área de estudos. data 24.11.2020 (Indefinida) Hs @Autor: Abraão A. Silva """ # Gerando valores impares dos parêmetros de "range()". # Opção 1 for num in range(1, 151): if num % 2 != 0: print(num, end=' ') # Opção 2 for num in range(1, 151, 2): print(num, end=' ')
""" Problem Description: In india there is a puzzle"5 characters my name, reverse- forward is the same." You will be presented with a 5 character String, you have to tell whether it satisfy above puzzle, if yes output "Yes" else "No" Input: Input is String S of 5 characters. Output: Print "Yes" if the String S satisf...
# Banker's Algorithm n = 5 # no. of processes / rows m = 4 # no. of resources / columns # Maximum matrix - denotes maximum demand of each process maxi = [[0, 0, 1, 2], [1, 7, 5, 0], [2, 3, 5, 6], [0, 6, 5, 2], [0, 6, 5, 6]] # Allocation matrix - denotes no. of resources allocated to pr...
class dotGuideline_t(object): # no doc Curve = None Id = None Spacing = None
# draw some simple shapes # hint! The order in which you draw is important # change x and y to move him around x = width/2 y = 25 w = 23 # make him bigger or smaller h = w # distort by changing the h seperatly bmi = 1 # body mass index # a line takes 4 values the starting point and the end point line(x - w, y + h, x +w...
class ClientError(Exception): pass class ProtocolError(ClientError): """ Error communicating with the OpenVPN server """ pass class InvalidPacketError(ProtocolError): """ Packet that doesn't make any sense and cannot be read correctly. """ pass class InvalidHMACError(InvalidPacketError): ...
AdminApp.install('/tmp/installers/war_app/JspDemo.war', '[ -nopreCompileJSPs -distributeApp -nouseMetaDataFromBinary -nodeployejb -appname JspDemo -createMBeansForResources -noreloadEnabled -nodeployws -validateinstall warn -noprocessEmbeddedConfig -filepermission .*\.dll=755#.*\.so=755#.*\.a=755#.*\.sl=755 -noallowDis...
class Queue(object): def __init__(self,vals,n=10): self.queue = [None for x in range(n)] self.head = -1 self.tail = -1 for val in vals: self.add(val) def add(self,val): if (self.tail+1) % len(self.queue) == self.head: print("Queue full") ...
""" DAY 41 : Find first set bit. https://www.geeksforgeeks.org/position-of-rightmost-set-bit/ QUESTION : Given an integer an N. The task is to return the position of first set bit found from the right side in the binary representation of the number. Note: If there is no set bit in the integer N, then return 0...
# Split into train and test data for GAN def build_dataset(X, nx, ny, n_test = 0): m = X.shape[0] print("Number of images: " + str(m) ) X = X.T Y = np.zeros((m,)) # Random permutation of samples p = np.random.permutation(m) X = X[:,p] Y = Y[p] # Reshape X and crop to 96x96 pixels X_new ...
# # Solution to Project Euler Problem 1 # by Lucas Chen # # Answer: 233168 # NUM = 1000 # Compute sum of the naturals that are a multiple of 3 or 5 and less than [NUM] def compute(): return sum(i for i in range(1, NUM) if i % 3 == 0 or i % 5 == 0) if __name__ == "__main__": print(compute())
n=int(input("enter a number ")) backup=n num=0 while(n>0): x=n%10 n=n//10 x=x**3 num+=x if(num==backup): print(num,"is a armstrong number") else: print(backup,"is not a armstrong number")
# Copyright (c) 2019-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # def f_gold ( arr , n , k ) : for i in range ( 0 , k ) : x = arr [ 0 ] for j in range ( 0 , n - 1 ) : ...
# # PySNMP MIB module CISCO-DOT11-HT-PHY-CAPABILITY (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-DOT11-HT-PHY-CAPABILITY # Produced by pysmi-0.3.4 at Mon Apr 29 17:38:23 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python ve...
#!/usr/bin/env python class Solution: def wordBreak(self, s, wordDict): if len(s) == 0: return True ret = False for w in wordDict: if s.startswith(w): ret = ret or self.wordBreak(s[len(w):], wordDict) return ret s, wordDict = 'leetcode', ['leet', 'code']...
exp = [] e = str(input('Digite a expressão: ')) for s in e: if s == '(': exp.append('(') elif s == ')': if len(exp) > 0: exp.pop() else: exp.append(')') break print('Sua expressão é valida' if len(exp) == 0 else 'Sua expressão é inválida')
customer_basket_cost = 34 customer_basket_weight = 44 shipping_cost = customer_basket_weight * 1.2 #Write if statement here to calculate the total cost if customer_basket_weight >= 100: coste_cesta = customer_basket_cost print("Total: " + str(coste_cesta) + " euros") else: coste_cesta = customer_basket_co...
def test(): # Here we can either check objects created in the solution code, or the # string value of the solution, available as __solution__. A helper for # printing formatted messages is available as __msg__. See the testTemplate # in the meta.json for details. # If an assertion fails, the message...
n, q = map(int, input().split()) graph = [[] for _ in range(n)] for i in range(n - 1): a, b = map(int, input().split()) graph[a - 1].append(b - 1) graph[b - 1].append(a - 1) group = [[], []] town_color = [-1] * n tmp = [[0, -1, 0]] while tmp: v, past, color = tmp.pop() town_color[v] = color gr...
def main(): grid = open("data.txt").readlines() for i in range(0, len(grid)): grid[i] = grid[i][:-1] x_width = len(grid[i]) y_length = len(grid) ctr = 0 y_pos = 0 x_pos = 0 product = 1 for i in [[1,1], [3,1], [5,1], [7,1], [1,2]]: while y_pos < y_length: ...