content
stringlengths
7
1.05M
# Lopez Chaidez Luis Enrique DDSIV def hello_user(name): """Function that returns a string that says hello to the name that you introduce Args: name (String): Name that you want to add to the string Returns: String: It returns '¡Hola {name}!' """ return '¡Hola ' + name + '!' name...
# Import Data commands = [] with open('../input/day_2.txt') as f: lines = f.read().splitlines() for line in lines: splitline = line.split(" ") splitline[1] = int(splitline[1]) commands.append(splitline) # Process Data positionHorizontal = 0 positionVertical = 0 for command in commands: ...
# def display_message(): # print("本章学习了定义函数") # for i in range(10): # display_message() # def favourite_book(title): # print(f"One of my favorite books is {title}.") # favourite_book("Alice in Wonderlan") # def make_shirt(a = 'T', b = 'I love Python'): # return f"订购的shirt的尺码为{a}\n打印的内容为{b}" # print(ma...
def product(fracs): t = reduce(lambda x, y: x * y, fracs, 1) return t.numerator, t.denominator
#Copyright 2010 Google 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 to in writing, softw...
# Crie um programa que leia uma frase qualquer e diga se ela é um palíndromo, desconsiderando os espaços. frase = str(input('\nDigite uma frase: ')) min = ''.join(frase.lower().split()) rev = ''.join(frase.lower().split())[::-1] if(min == rev): print('A frase é um palíndromo') else: print('A frase não é um pa...
'this crashed pychecker from calendar.py in Python 2.2' class X: 'd' def test(self, item): return [e for e in item].__getslice__() # this crashed in 2.2, but not 2.3 def f(a): a.a = [x for x in range(2) if x > 1]
#!/usr/bin/env python3 def round_down_to_even(value): return value & ~1 for _ in range(int(input())): input() # don't need n a = list(map(int, input().split())) for i in range(0, round_down_to_even(len(a)), 2): if a[i] > a[i + 1]: a[i], a[i + 1] = a[i + 1], a[i] print(*a)
# coding: utf-8 # 作者:Pscly # 创建日期: # 用意: # a = [1,2,3,4,5] # a.pop(0) # a.append(4) # print(a) # for i, j in enumerate(a,1): # print(i, j) # print(a[:-1]) a = '123456' print(a.split('x'))
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim:fileencoding=utf_8 """Add doc string """ __author__ = 'M. Kocher' __copyright__ = "" __credits__ = ['M. Kocher'] __license__ = 'MIT License' __maintainer__ = 'M. Kocher' __email__ = 'Michael.Kocher@me.com' __version__ = '0.1'
num = [int(x) for x in input("Enter the Numbers : ").split()] index=[int(x) for x in input("Enter the Index : ").split()] target=[] for i in range(len(num)): target.insert(index[i], num[i]) print("The Target array is :",target)
def func(param1=True, param2="default val"): """Description of func with docstring groups style (Googledoc). Parameters ---------- param1 : descr of param1 that has True for default value param2 : descr of param2 (Default value = 'default val') Returns ------- type ...
# Python Program to find Power of a Number number = int(input(" Please Enter any Positive Integer : ")) exponent = int(input(" Please Enter Exponent Value : ")) power = 1 for i in range(1, exponent + 1): power = power * number print("The Result of {0} Power {1} = {2}".format(number, exponent, power)) # by a...
# anything above 0xa0 is printed as Unicode by CPython # the abobe is CPython implementation detail, stick to ASCII for c in range(0x80): print("0x%02x: %s" % (c, repr(chr(c)))) print("PASS")
# Title : Linked list :- delete element at front and back of a list # Author : Kiran raj R. # Date : 30:10:2020 class Node: """Create a node with value provided, the pointer to next is set to None""" def __init__(self, value): self.value = value self.next = None class Simply_linked_list: ...
def solution(A,B): """ * 문제 이해 및 추상화 - 길이가 같은 각 배열에서 숫자를 뽑고 곱한 뒤 그 합이 가장 작은 값을 리턴 - arr1 정방향 sort, arr2 역방향 sort - 곱하면서 summation """ A.sort() B.sort(reverse=True) return sum([i[0]*i[1] for i in zip(A,B)]) A = [1,4,2] B = [5,4,4] solution(A,B)
TEMPLATE = """ # Related Pages Here is a list of all related documentation pages: {% for page in nodes -%} * [*{{page.title}}*]({{page.url}}) {{page.brief}} {% endfor -%} """
''' URL: https://leetcode.com/problems/reverse-words-in-a-string-iii/ Difficulty: Easy Description: Reverse Words in a String III Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. Example 1: Input: "Let's take LeetCod...
""" link: https://leetcode-cn.com/problems/magical-string problem: 某字符串固定以 122 开头,且仅由 1,2 俩字符组成,且每组 1,2 出现的数量正好可以拼回该字符前序子串,求 该字符的前 n 位有多少个 1, n ∈ [0,10^5] solution: 模拟。 """ class Solution: def magicalString(self, n: int) -> int: if not n: return 0 f = [0] * (n + 5) f...
"""Top-level package for Copernicus Marine ToolBox.""" __author__ = """E.U. Copernicus Marine Service Information""" __email__ = 'servicedesk.cmems@mercator-ocean.eu' __version__ = '0.1.17'
# PROCURANDO UMA STRING DENTRO DA OUTRA nome = str(input('Digite seu nome: ').strip().lower()) print("silva" in nome.split()) # DESSA MANEIRA EVITA-SE QUE SILVA SEJA CONFUNDIDO DENTRO DE OUTRA STRING.
'''THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OT...
class Node: def __init__(self, ch): self.ch = ch self.children = {} self.isWordTerminal = False class Trie: def __init__(self): """ Initialize your data structure here. """ self.root = Node('\0') def insert(self, word: str) -> None: """ ...
# # PySNMP MIB module HP-ICF-CONNECTION-RATE-FILTER (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HP-ICF-CONNECTION-RATE-FILTER # Produced by pysmi-0.3.4 at Wed May 1 13:33:37 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python ve...
_base_ = [ '../_base_/datasets/togal.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_160k.py' ] # model settings norm_cfg = dict(type='BN', requires_grad=True) model = dict( type='EncoderDecoder', pretrained=None, backbone=dict( type='Unet', encoder_name="tu-tf_effici...
class DimFieldModel: def __init__( self, *kwargs, field_key: str, project_id: str, name: str, control_type: str, default_value: str = None, counted_character: bool, counted_character_date_from_key: int, counted_character_time_from_key: ...
nome = input('what is your name? ') idade = input('how old are you ' + nome + '?') peso = input('what is your weight {}?'.format(nome) + '?') print('dados: {}'.format(nome) + ' Weight:' + peso + 'Idade:' + idade)
""" All the custom exceptions types """ class PylasError(Exception): pass class UnknownExtraType(PylasError): pass class PointFormatNotSupported(PylasError): pass class FileVersionNotSupported(PylasError): pass class LazPerfNotFound(PylasError): pass class IncompatibleDataFormat(PylasErr...
# common classes_file = './data/classes/voc.names' num_classes = 1 input_image_h = 448 input_image_w = 448 down_ratio = 4 max_objs = 150 ot_nodes = ['detector/hm/Sigmoid', "detector/wh/Relu", "detector/reg/Relu"] moving_ave_decay = 0.9995 # train train_data_file = './data/dataset/voc_train.txt' batch_size =...
# _*_ coding=utf-8 _*_ class Config(): def __init__(self): self.device = '1' self.data_dir = '../data' self.logging_dir = 'log' self.samples_dir = 'samples' self.testing_dir = 'test_samples' self.checkpt_dir = 'checkpoints' self.max_srclen = 25 se...
t1 = ('OI', 2.0, [40, 50]) print(t1[2:]) t = 1, 4, "THiago" tupla1 = 1, 2, 3, 4, 5 tulpla2 = 6, 7, 8, 9, 10 print(tupla1 + tulpla2) # concatena
avtobots = {"Оптімус Прайм": "Грузовик Peterbilt 379", "Бамблбі": "Chevrolet Camaro", "Джаз": "Porsche 935 Turbo"} for key in avtobots: if key == "Оптімус Прайм": print("Оптімус Прайм прибув")
yformat = u"%(d1)i\xB0%(d2)02i'%(d3)02.2f''" xformat = u"%(hour)ih%(minute)02im%(second)02.2fs" def getFormatDict(tick): degree1 = int(tick) degree2 = int((tick * 100 - degree1 * 100)) degree3 = ((tick * 10000 - degree1 * 10000 - degree2 * 100)) tick = (tick + 360) % 360 totalhours = float(tick * 24.0 / 360) ho...
print(""" 090) Faça um programa que leia nome e média de um aluno, guardando também a situação em um dicionário. No final, mostre o conteúdo a estrutura na tela. """) nome = input('Informe o nome do(a) aluno(a): ').strip() media = float(input(f'Informe e a média de {nome}: ').strip()) erro = 0 if 7 <= media <= 10: ...
print('MyMy',end=' ') print('Popsicle') print('Balloon','Helium','Blimp',sep=' and ')
N,M=map(int,input().split()) A=[int(input()) for i in range(M)][::-1] ans=[] s=set() for a in A: if a not in s:ans.append(a) s.add(a) for i in range(1,N+1): if i not in s:ans.append(i) print(*ans,sep="\n")
""" link: https://leetcode.com/problems/power-of-four problem: 问num是否是4的幂,要求O(1) solution: 位运算 """ class Solution: def isPowerOfFour(self, num: int) -> bool: return num > 0 and num & (num - 1) == 0 and num & 0xaaaaaaaa == 0
#fix me.. but for now lets just pass the data back.. def compress(data): return data def decompress(data): return data
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 1 09:26:03 2022 @author: thejorabek """ '''son=10 print(son,type(son)) son=3.14 print(son,type(son)) son='Salom Foundationchilar' print(son,type(son)) son=True print(son,type(son)) son=int() print(son,type(son)) print("Assalom",123,3.14,True,sep='...
# -*- coding: utf-8 -*- def find_first_unique_char(s): """ 字符串中找到第一个出现的唯一字符 :param s: :return: """ char_dict = dict() unique_char = list() for char in s: if char_dict.get(char): unique_char.remove(char) else: print(unique_char) uniq...
print('Hello World!!!') if True: print('FROM if') num = 1 while num <= 10: print(num) num += 1 list_ = [1, 2, 3, 4, 5] for i in range(1, 7): print(i)
# -*- coding: utf-8 -*- """ Created on Fri Dec 29 10:35:53 2017 @author: User """ L = [[1,2], [35,4,78], [7,8,1,10],[2,3], [9,1,45]] #def testA(L): # aFactor = 2 # for m in L: # for ind, element in enumerate(m): # newElement = element*aFactor # m.pop(ind) # this works...
# -*- coding: utf-8 -*- # Authors: Y. Jia <ytjia.zju@gmail.com> def binary_search(arr, target, begin=None, end=None): """ :param arr: :param target: :param begin: :param end: :return: """ if begin is None: begin = 0 if end is None: end = len(arr) - 1 if end <...
# # PySNMP MIB module LOWPAN-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/LOWPAN-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:58:25 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:...
def split_targets(targets, target_sizes): results = [] offset = 0 for size in target_sizes: results.append(targets[offset:offset + size]) offset += size return results
class Aggrraidtype(basestring): """ raid_dp|raid4 Possible values: <ul> <li> "raid_dp" , <li> "raid4" , <li> "raid0" , <li> "mixed_raid_type" </ul> """ @staticmethod def get_api_name(): return "aggrraidtype"
""" interploation search # interploation and binary are both require a SORTED list let said you have the follow phone number prefix array, and you are looking for 1144 0011, 0022, 0033, 1144, 1166, 1188, 3322, 3344, 3399 instead of using binary search in the middle, or linear search from the left...
# This sample tests the case where a finally clause contains some conditional # logic that narrows the type of an expression. This narrowed type should # persist after the finally clause. def func1(): file = None try: file = open("test.txt") except Exception: return None finally: ...
def remove_passwords(instances): clean_instances = [] for instance in instances: clean_instance = {} for k in instance.keys(): if k != 'password': clean_instance[k] = instance[k] clean_instances.append(clean_instance) return clean_instances
class cURL: def __init__(self, url_='.'): self.url = url_ def replace(self, replaceURL_, start_, end_): ''' example: 'https://www.google.com/search' https:// -> -1 www.google.com -> 0 search -> 1 ''' if start_ == -1: ...
def get_primes(n): # Based on Eratosthenes Sieve # Initially all numbers are prime until proven otherwise # False = Prime number, True = Compose number nonprimes = n * [False] count = 0 nonprimes[0] = nonprimes[1] = True prime_numbers = [] for i in range(2, n): if not nonprimes[...
""" link: https://leetcode-cn.com/problems/the-maze-ii problem: 求二维迷宫矩阵中,小球从 A 点到 B 点的最短路径,小球只能沿一个方向滚动直至碰壁 solution: BFS。广搜反复松弛,检查目标点是否优于之前搜索结果。 """ class Solution: def shortestDistance(self, maze: List[List[int]], start: List[int], destination: List[int]) -> int: if not maze or not maze[0]: ...
'''DATALOADERS''' def LoadModel(name): # print(name) # classes = [] # D = 0 # H = 0 # W = 0 # Height = 0 # Width = 0 # Bands = 0 # samples = 0 if name == 'PaviaU': classes = [] #Size of 3D images D = 610 H = 340 ...
parallel = dict( data=1, pipeline=1, tensor=dict(size=4, mode='2d'), )
# -*- coding: utf-8 -*- """ #============================================================================= # ProjectName: leetcode # FileName: the_difference_between_two_sorted_arrays # Desc: 给定两个大小为 m 和 n 的有序数组 nums1 和 nums2 # 请找出这 存在nums1数组中,但是不存在nums2数组中的所有数字,要求算法的时间复杂度为 O(log (m+n)) # ...
# -*- coding: utf-8 -*- project = "thumbtack-client" copyright = "2019, The MITRE Corporation" author = "The MITRE Corporation" version = "0.3.0" release = "0.3.0" extensions = [ "sphinx.ext.autodoc", "sphinx.ext.napoleon", "sphinx.ext.viewcode", ] templates_path = ["_templates"] source_suffix = ".rst"...
def main(): result = 0 with open("input.txt") as input_file: for x in input_file: x = int(x) while True: x = x // 3 - 2 if x < 0: break result += x print(result) if __name__ == "__main__": main()
DATAMART_AUGMENT_PROCESS = 'DATAMART_AUGMENT_PROCESS' # ---------------------------------------------- # Related to the "Add User Dataset" process # ---------------------------------------------- ADD_USER_DATASET_PROCESS = 'ADD_USER_DATASET_PROCESS' ADD_USER_DATASET_PROCESS_NO_WORKSPACE = 'ADD_USER_DATASET_PROCESS_NO...
alpha_num_dict = { 'a':1, 'b':2, 'c':3 } alpha_num_dict['a'] = 10 print(alpha_num_dict['a'])
""" 面试题 13:机器人的运动范围 题目:地上有一个 m 行 n 列的方格。一个机器人从坐标 (0, 0) 的格子开始移动,它 每一次可以向左、右、上、下移动一格,但不能进入行坐标和列坐标的数位之和 大于 k 的格子。例如,当 k 为 18 时,机器人能够进入方格 (35, 37),因为 3+5+3+7=18。 但它不能进入方格 (35, 38),因为 3+5+3+8=19。请问该机器人能够到达多少个格子? """ def moving_count(rows: int, cols: int, threshold: int) -> int: """ Count moving steps under the g...
""" Time: Best: O(n) Average: O(n^2) Worst: O(n^2) Space: O(1) Stable: Yes Worst Case Scenario: Reverse Sorted Array Algorithm Overview: This algorithm works like how a person would normally sort a hand of cards from left to right. You take the second card and compare with all the ...
# https://leetcode.com/problems/minimum-size-subarray-sum/ class Solution: def minSubArrayLen(self, target: int, nums: list[int]) -> int: min_len = float('inf') curr_sum = 0 nums_added = 0 for idx in range(len(nums)): num = nums[idx] if num >= target: ...
#!/usr/bin/env python # encoding: utf-8 class Dynamic(str): """Wrapper for the strings that need to be dynamically interpreted by the generated Python files.""" pass
#!/usr/bin/env python # -*- coding: utf-8 -*- """View module for Find Convex Hull program Notes ----- Comments are omitted because code is self-explanatory. """ colors = [ 'aquamarine', 'azure', 'blue', 'brown', 'chartreuse', 'chocolate', 'coral', 'crimson', 'cyan', 'darkblue',...
class DataGridSelectionUnit(Enum,IComparable,IFormattable,IConvertible): """ Defines constants that specify whether cells,rows,or both,are used for selection in a System.Windows.Controls.DataGrid control. enum DataGridSelectionUnit,values: Cell (0),CellOrRowHeader (2),FullRow (1) """ def __eq__(self,*arg...
class Solution: def sortArrayByParity(self, A: List[int]) -> List[int]: l = 0 r = len(A) - 1 while l < r: if A[l] % 2 == 1 and A[r] % 2 == 0: A[l], A[r] = A[r], A[l] if A[l] % 2 == 0: l += 1 if A[r] % 2 == 1: r -= 1 return A
peso = float(input('Peso em Kilogramas: ')) altura = float(input('Altura em Centimetros: ')) imc = peso / ((altura / 100) ** 2) print('O IMC esta em {:.2f}'.format(imc)) if imc < 18.5: print('Abaixo do Peso!') elif imc <= 25: print('Peso Ideal') elif imc <= 30: print('Sobrepeso') elif imc <= 40: print('...
def test(): assert ( 'spacy.blank("en")' in __solution__ ), "Você inicializou um fluxo de processamento em Inglês vazio?" assert "DocBin(docs=docs)" in __solution__, "Você criou o DocBin corretamente?" assert "doc_bin.to_disk(" in __solution__, "Você utilizou o método to_disk?" assert "train...
""" Place class. Part of the StoryTechnologies project. August 17, 2019 Brett Alistair Kromkamp (brett.kromkamp@gmail.com) """ class TimeInterval: def __init__(self, from_time_point: str, to_time_point: str) -> None: self.from_time_point = from_time_point self.to_time_point = to_time_point
class Menu(object): def __init__(self): gameList = None; def _populateGameList(self): pass def chooseGame(self): pass def start(self): pass
class Solution: # @param {integer[]} candidates # @param {integer} target # @return {integer[][]} def combinationSum2(self, candidates, target): self.results = [] candidates.sort() self.combination(candidates, target, 0, []) return self.results def combination(self,...
cadastro = list() while True: pessoa = dict() pessoa['nome'] = str(input('Nome: ')) pessoa['sexo'] = str(input('Sexo: ')) pessoa['idade'] = int(input('Idade: ')) cadastro.append(pessoa.copy()) resp = str(input('Quer continuar? (S/N) ')) if resp in "Nn": break print("-="*30) total =...
# -*- coding: utf-8 -*- """ file_utils module to hold simple bioinformatics course text file parsing class """ INPUT_STRING = 'Input' OUTPUT_STRING = 'Output' class FileUtil(object): """ Holds I/O values parsed from course text files for example problems Initialized with a text file, parses 'Input' and '...
t = int(input()) def solve(): candy = 0 x = input() r, c = map(int, input().split()) a = [] for _ in range(r): a.append(input()) for i in range(r): for j in range(c - 2): if a[i][j] == '>' and a[i][j + 1] == 'o' and a[i][j + 2] == '<': candy += 1 ...
# Write_a_function # Created by JKChang # 14/08/2018, 10:58 # Tag: # Description: https://www.hackerrank.com/challenges/write-a-function/problem # In the Gregorian calendar three criteria must be taken into account to identify leap years: # The year can be evenly divided by 4, is a leap year, unless: # The year can be...
class NorthInDTO(object): def __init__(self): self.platformIp = None self.platformPort = None def getPlatformIp(self): return self.platformIp def setPlatformIp(self, platformIp): self.platformIp = platformIp def getPlatformPort(self): return self.platformPort ...
h, m = map(int, input().split()) if h - 1 < 0: h = 23 m += 15 print(h,m) elif m - 45 < 0: h -= 1 m += 15 print(h, m) else: m -= 45 print(h, m)
class Settings(): """ This is just variables stored as properties of a class. It still needs (allthough void) .inputs(), .output() and .build() and defines whatever else is handy. (It is nice, as in this case, to separate constants from methods.) """ def inputs(self): return None def output(self): return ...
anum1 = int(input('Digite 1° valor: ')) bnum2 = int(input('Digite 2° valor: ')) cnum3 = int(input('Digite 3° valor: ')) #verificando quem é menor menor = anum1 if bnum2 < anum1 and bnum2 < cnum3: menor = bnum2 if cnum3 < anum1 and cnum3 < bnum2: menor = cnum3 #verificando quem é maior maior = anum1 if bnum2...
# 009.py 리스트 = [i for i in range(10)] for i in 리스트 : print(i) ''' 1 2 3 4 5 6 7 8 9 ''' for i in 'kimminsu' : print(i) ''' k i m m i n s u '''
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Advent of Code 2020 Day 4, Part 2 """ class Passport: def __init__(self, byr=-1, iyr=-1, eyr=-1, hgt=-1, hfc=-1, ecl=-1, pid=-1, cid=-1): self.fields = { 'byr': byr, 'iyr': iyr, 'eyr': eyr, 'hgt': hgt, ...
class Pessoa: def __init__(self, nome, email, celular): self.nome = nome self.email = email self.celular = celular def get_nome(self): return f"Caro(a) {self.nome}" def get_email(self): return(self.email) def get_celular(self): return(self.celular) d...
class Solution: def trailingZeroes(self, n: int) -> int: l2 = [self.func(i, 2) for i in range(1, n+1) if i % 2 == 0] l5 = [self.func(i, 5) for i in range(1, n + 1) if i % 5 == 0] suml2 = sum(l2) suml5 = sum(l5) r = min(suml2, suml5) return r def func(self, n, i):...
css = """ body { font-family: Roboto, Helvetica, Arial, sans-serif; font-size:14px; color: #555555; background-color:#f5f5f5; margin-left: 5px; } .container{ padding-right:5px; padding-left:5px; ...
def solution(N): # write your code in Python 3.6 binary = to_binary(N) started = False max_gap = 0 current_gap = 0 for i in range(len(binary)): if not started: started = binary[i] == '1' else: if binary[i] == '1': max_gap = max(current_gap,...
def soma(num1, num2): print(f'A soma dos numeros eh igual é: {num1+num2}') def sub(num1, num2): print(f'A soma dos numeros eh igual é: {num1-num2}') def mult(num1, num2): print(f'A soma dos numeros eh igual é: {num1*num2}') def divi(num1, num2): print(f'A soma dos numeros eh igual é: {num1/num2}')
# Here follows example input: fs = 48000 # Sample rate (Hz) base_freq = 100. # Base frequency (Hz) bpm = 120 # Beats per minute
class Solution: def is_isomorphic(self, s: str, t: str) -> bool: """ 根据值在两个字符串中的索引是否相同 """ for i, v in enumerate(s): if s.find(v) != t.find(t[i]): return False return True def other_solution(self, s, t): """ 将s中的字符对应的t中的字符存入字典,如果不符合条件则为False """ ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def verticalTraversal(self, root: 'TreeNode') -> 'List[List[int]]': queue = collections.deque([(root, 0, 0)]) d = collect...
VALIGN_TOP = "top" VALIGN_CENTER = "center" VALIGN_BASELINE = "baseline" VALIGN_BOTTOM = "bottom" HALIGN_LEFT = "left" HALIGN_CENTER = "center" HALIGN_RIGHT = "right" PROPAGATE_UP = "up" PROPAGATE_DOWN = "down" NO_PROPAGATION = "local" NO_LOCAL_INVOKE = "nolocal" BOLD = "bold" NORMAL = "normal" SEMIBOLD = "semibold" LE...
def sum_numbers(first_int, second_int): """Returns the sum of the two integers""" result = first_int + second_int return result def subtract(third_int): """Returns the difference between the result of sum_numbers and the third integer""" diff = sum_numbers(first_int=number_1, second_int=numbe...
# -*- coding: utf-8 -*- """ Created on 2018-6-12 @author: cheng.li """ class PortfolioBuilderException(Exception): def __init__(self, msg): self.msg = msg def __str__(self): return str(self.msg)
# hackerrank problem of problem solving # problem statement : Picking Numbers def pickingNumbers(arr) : left = 0 max_sum = 0;max_left = 0;max_right=0 for i in range(1, len(arr)) : if abs(arr[i] - arr[i-1]) > 1 : number = i - left if number > max_sum : ...
st = input() sum = 0 for s in st: t = ord(s) if t >= ord('a'): sum += t - ord('a') + 1 else: sum += t - ord('A') + 27 ii = 2 for i in range(2, sum + 1): if sum % i == 0: ii = i break if ii == sum or sum == 1 : print('It is a prime word.') else : print('It is not a...
def is_before_after(img_path): """ check weather image is a before after :param img_path: :return: """
mainstr="the quick brown fox jumped over the lazy dog. the dog slept over the verandah" newstr=mainstr.split(" ") i=0 a=" " while i<len(newstr): if newstr[i]=="over": a=a+"on"+" " else: a=a+newstr[i]+" " i+=1 print(a)
def chemelements(): periodic_elements = ["Ac","Al","Ag","Am","Ar","As","At","Au","B","Ba","Bh","Bi","Be", "Bk","Br","C","Ca","Cd","Ce","Cf","Cl","Cm","Co","Cr","Cs","Cu", "Db","Dy","Er","Es","Eu","F","Fe","Fm","Fr","Ga","Gd","Ge","H", "He","Hf","Hg","Ho...
"""Top-level package for evq.""" __author__ = """Sylwester Czmil""" __email__ = 'sylwekczmil@gmail.com' __version__ = '0.0.2'
# -*- coding: utf-8 -*- """Top-level package for MagniPy.""" __author__ = """Daniel Gilman""" __email__ = 'gilmanda@ucla.edu' __version__ = '0.1.0'
class Foo(): def g(self): pass class Bar(): def f(self): pass