content
stringlengths
7
1.05M
""" parition dp f[k][i]: minimum time it will take for the first k copier to copy first i books funciton: f[k][i] = min for j=0..i(max(f[k - 1][j], A[j] + ... + A[i - 1])) intial: f[0][0] = 0 f[0][x] = sys.maxsize f[k][0] = 0 answer:f[k][n - 1] """ # import sys # class Solution: # """ # @param pages: an array o...
oredict = [ "logWood", "plankWood", "slabWood", "stairWood", "stickWood", "treeSapling", "treeLeaves", "vine", "oreGold", "oreIron", "oreLapis", "oreDiamond", "oreRedstone", "oreEmerald", "oreQuartz", "oreCoal", "ingotIron", "ingotGold", "ingot...
class Embed: def __init__(self, title=None, description=None, color=None, spoiler=False): self.title = title self.description = description self.color = color self.spoiler = spoiler self.field_data = None self.footer = None def add_field(self, name, value, inline...
"""External tests associated with doctest_private_tests.py. >>> my_function(['A', 'B', 'C'], 2) ['A', 'B', 'C', 'A', 'B', 'C'] """
"""Crie um programa que leia a idade e o sexo de várias pessoas. A cada pessoa cadastrada, o programa deverá perguntar se o usuário quer ou não continuar. No final, mostre: A) quantas pessoas tem mais de 18 anos. B) Quantos homens foram cadastrados. C) Quantas mulheres tem menos de 20 anos.""" Cont18 = ContHomens = Co...
# -*- coding: utf-8 -*- """ *************************************************************************** qgsfeature.py --------------------- Date : May 2018 Copyright : (C) 2018 by Denis Rouzaud Email : denis@opengis.ch **************************************...
""" 问题描述: 你和你的朋友,两个人一起玩 Nim游戏:桌子上有一堆石头,每次你们轮流拿掉 1 - 3 块石头。 拿掉最后一块石头的人就是获胜者。你作为先手。 你们是聪明人,每一步都是最优解。 编写一个函数,来判断你是否可以在给定石头数量的情况下赢得游戏。 示例: 输入: 4 输出: false 解释: 如果堆中有 4 块石头,那么你永远不会赢得比赛; 因为无论你拿走 1 块、2 块 还是 3 块石头,最后一块石头总是会被你的朋友拿走。 方法: f(4) = False f(5) = True f(6) = True f(7) = True f(8) = False 可以先多推几个,然后进行猜想和验证。这里可...
# -*- coding: utf-8 -*- """ Created on Thu Dec 7 16:09:41 2017 @author: User """ def sameChrs(): commonS = [] s1 = str(input('Enter first string\n')) s2 = str(input('Enter second string?\n')) print('This is what you entered\n', s1,'\n', s2) if len(s2) > len(s1): raise Value...
"""Singleton metaclass""" # Copyright (C) 2019 F5 Networks, 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 applicabl...
#!/usr/bin/env python3 # create a list containing three items my_list = ["192.168.0.5", 5060, "UP"] # display first item print("The first item in the list (IP): " + my_list[0] ) # Below needs to be cast from an int to a str for printing print("The second item in the list (port): " + str(my_list[1]) ) # displaying the f...
load("@bazel_gazelle//:deps.bzl", "go_repository") def pprof_go_repositories(): go_repository( name = "com_github_chzyer_logex", importpath = "github.com/chzyer/logex", sum = "h1:Swpa1K6QvQznwJRcfTfQJmTE72DqScAa40E+fbHEXEE=", version = "v1.1.10", ) go_repository( nam...
#SIMPLE CLASS TO SHOW HOW TO WORK WITH PACKAGES (look "11_test_my_package.py") #Santiago Garcia Arango #One of the modules to show how to create a simple package in python. class hello: def __init__(self, name): self.name = name def say_hi_to_someone(self): sentence = "Hello, " + self.name...
def leiaInt(text): while True: try: numero = int(input(text)) except (ValueError, TypeError): print('\033[0;31mErro! Por favor, digite um número inteiro válido!\033[m') continue else: return numero def linha(tam=42): return '-' * tam de...
""" Python program to pass list to a function and double the odd values and half the even values of the list and display the list elements after changing """ def operator_fn(a): new=[] for i in a: if i%2==0: i=i/2 new.append(i) elif i%2!=0: i=i*2...
class TextCompressor: def longestRepeat(self, sourceText): l = len(sourceText) for i in xrange(l / 2, 0, -1): for j in xrange(0, l - i): if sourceText[j : i + j] in sourceText[i + j :]: return sourceText[j : i + j] return ""
class Solution: def canIwin(self, maxint: int, desiredtotal: int) -> bool: if maxint * (maxint + 1) < desiredtotal: return False cache = dict() def dp(running_total, used): if used in cache: return cache[used] for k in range(maxint, 0, -1):...
x = 'Fortaleza', 'Athletico Paranaense', 'Atlético GO', 'Bragantino', 'Bahia', 'Fluminense', 'Palmeiras', 'Flamengo', 'Atlético Mineiro', 'Corinthians', 'Ceará', 'Santos', 'Cuiabá', 'Sport Recife', 'São Paulo', 'Juventude', 'Internacional', 'Grêmio', 'América Mineiro', 'Chapecoense' print(f'A lista de times do brasile...
class TreasureHunt: def __init__(self, table, user_clues=None): try: # check user_clues user_clues = [int(clue) for clue in user_clues] except (TypeError, ValueError, IndexError): print('Clue has wrong type, expect - <int>. Start default:') user_clues = None ...
#!/usr/bin/env python # # (c) Copyright Rosetta Commons Member Institutions. # (c) This file is part of the Rosetta software suite and is made available under license. # (c) The Rosetta software is developed by the contributing members of the Rosetta Commons. # (c) For more information, see http://www.rosettacommons.or...
def func(a, b, n, m): min_elem = max(a) max_elem = min(b) ans = [] for i in range(min_elem, max_elem+1): j = 0 while j < n and i%a[j] == 0: j += 1 if j == n: if i%a[j-1] == 0: k = 0 while k < m and b[k]%i == 0: k += 1 if k == m: if b[k-1]%i == 0: ans.append(i) retu...
# -*- coding: utf-8 -*- """ exceptions.py Exception class for pytineye. Copyright (c) 2021 TinEye. All rights reserved worldwide. """ class TinEyeAPIError(Exception): """Base exception.""" def __init__(self, code, message): self.code = code self.message = message def __repr__(self): ...
f = open('input.txt') triangles = [map(int,l.split()) for l in f.readlines()] possible = 0 for t in triangles: t.sort() if t[0] + t[1] > t[2]: possible += 1 print(possible)
# -*- coding: utf-8 -*- def import_object(name): """ from tornado.utils.import_object """ if name.count('.') == 0: return __import__(name, None, None) parts = name.split('.') obj = __import__('.'.join(parts[:-1]), None, None, [parts[-1]], 0) try: return getattr(obj, parts[-1]) e...
""" One Away: There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. Given two strings, write a function to check if they are one edit (or zero edits) away. EXAMPLE pale, ple -> true pales. pale -> true pale. bale -> true pale. bake -> fal...
"""Majordomo Protocol definitions""" # This is the version of MDP/Client we implement C_CLIENT = "MDPC01" # This is the version of MDP/Worker we implement W_WORKER = "MDPW01" # MDP/Server commands, as strings W_READY = "\001" W_REQUEST = "\002" W_REPLY = "\003" W_HEARTBEAT = "\004...
# ------------------------------ # 337. House Robber III # # Description: # The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses...
# Золотая подкова + Выигрышные номера нескольких тиражей def test_goldhorseshoe_winning_numbers_for_several_draws(app): app.ResultAndPrizes.open_page_results_and_prizes() app.ResultAndPrizes.click_game_goldhorseshoe() app.ResultAndPrizes.click_the_winning_numbers_for_several_draws() app.ResultAndPriz...
#!/usr/bin/python dist = int(input()) v_r = int(input()) v_c = int(input()) time_r = dist / v_r time_c = 50 / v_c if time_c > time_r: print("Meep Meep") else: print("Yum")
# Problem: Remove x from string def removeX(string): if len(string)==0: return string if string[0]=="x": return removeX(string[1:]) else: return string[0]+removeX(string[1:]) # Main string = input() print(removeX(string))
def add(num1,num2): c=num1+num2 return c a=int(input("ENTER num1 : ")) b=int(input("ENTER num1 : ")) print(add(a,b))
num1 = int(input('Primeiro termo: ')) raz = int(input('Razão: ')) c = 10 while c > 0: print('{} -> '.format(num1), end=' ') num1 += raz c -= 1 if c == 0: c = int(input('\nAcrescentar mais números na sequência: ')) print('FIM!')
# set per your own configs prefixs = [ '011XXXXX.', ] prefixs_mid_process = [] prefixs_post_process = [] # process ASTERISK-like regex pattern for a prefix # we are not expanding 'X' or '.' # this is because we don't support length based prefix matching # instead we utilize dr_rules longest-to-shortest prefix matching...
""" Bicycle Object. """ #Class Header class Bicycle : """ Initializer that creates three fields """ def __init__(self, gear_in, speed_in, color_in) : self.gear = gear_in self.speed = speed_in self.color = color_in #ACCESSORS """ Accessor function for the gear field """ def getgear(self)...
#~ def product(x,y): #~ return x*y #~ op = product(2,3) #~ print(op) #~ def product(x,y): #~ print(x*y) #~ op = product(2,3) #~ print(op) def product(x,y): print("i am before return") return x*y print("i am after return") product(2,3)
str1 = input() # str1='www.stepik.com' if str1.endswith('.com') or str1.endswith('.ru') == True: print('YES') else: print('NO') ''' .com or .ru На вход программе подается строка текста. Напишите программу, которая проверяет, что строка заканчивается подстрокой .com или .ru. Формат входных данных На вход про...
def optf(x, y, z): print("x = {}".format(x)) print("y = {}".format(y)) print("z = {}".format(z)) # 执行参数时的参数 # 位置参数 positional argument # 关键字参数 key=value keyword argument # 执行函数时, 位置参数一定要放在关键字参数前面 # positional argument follows keyword argument optf(1, y=2, z=3)
class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: # Solution: 2 pointer solution -> O(n*n) nums.sort() res = [] for i in range(len(nums)-2): if i > 0 and nums[i] == nums[i-1]: continue left, right = i+1, len(nums)-1 ...
# Marcelo Campos de Medeiros # ADS UNIFIP # Lista_2_de_exercicios # 15/03/2020 ''' 2 - Faça um Programa que peça um valor e mostre na tela se o valor é positivo ou negativo ''' #variáveis valor = float(input('Informe o um valor: ')) #comparando se o valor informado é ou não positivo if valor > 0: print(f'O valor...
l = int(input()) h = int(input()) t = str(input()) alphabet = [str(input()) for i in range(h)] for i in range(h): for char in t.lower(): if char >= 'a' and char <= 'z': x = ord(char) - ord('a') else: x = ord('z') - ord('a') + 1 print(alphabet[i][x*l : x*l+l], end='...
def fahrenheit_converter(C): fahrenheit = C * 9 / 5 + 32 print(str(fahrenheit) + 'F') c2f = fahrenheit_converter(35) print(c2f)
#!/usr/bin python # -*- coding: utf-8 -*- """ Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring. https://oj.leetcode.com/problems/longest-palindromic-substring/ """ class Solution: # @return...
# Variables inversion_bitcoin= 1.2 bitcoin_a_euro= 40000 # Función para el cambio de bitcoin a euro def bitcoin_euro(inversion_bitcoin, bitcoin_a_euro): resultado_euros= inversion_bitcoin * bitcoin_a_euro return resultado_euros # Si el valor está por debajo hay que avisar if (bitcoin_a_euro<30000): print(...
n = int(input()) tr = [] for _ in range(n): tr.append(int(input())) front = rear = 1 front_max = tr[0] for i in range(1,len(tr)): if front_max < tr[i]: front += 1 front_max = tr[i] tr.reverse() rear_max = tr[0] for i in range(1,len(tr)): if rear_max < tr[i]: rear += 1 re...
f_name = '../results/result-1__rf_log.txt' f = open(f_name,"r") line_ext = list() for line in f: if 'Kappa : ' in line: kappa = 'KAPPA\t'+line.strip().split(' : ')[1] if 'Accuracy : ' in line and 'Balanced' not in line: accu = 'ACCURACY\t'+line.strip().split(' : ')[1] if 'Sensitivity : ' in...
""" Module pour le cours sur les modules Opérations arithmétiques """ def division(a, b): """ une division : a / b """ return a / b
#迭代工具 #并行迭代 #zip函数可以用来进行并行迭代 #zip函数将两个序列压缩到一起,返回一个元祖,可以处理不等长的序列,当最短序列用完的时候就会停止 name=['Challenger','CY'] age=[11,12] for name,age in zip(name,age): print(name,age) #索引迭代 #enumerate函数可以在提供索引的地方迭代索引-值对 strings="abcdecfg" for index,string in enumerate(strings): if 'c' in string: print(strings[index],index)...
### stuff I don't need to make the cards def drawSquareGrid(dwg, widthInMillimeters): hLineGroup = dwg.add(dwg.g(id='hlines', stroke='green')) y = 0 while y < 100: hLineGroup.add(dwg.add(dwg.line( start = (0*mm, y*mm), end = (150*mm, y*mm)))) y += widthInMillimeters...
T = int(input()) for _ in range(T): n, k = map(int, input().split()) print((n ** k - 1) % 9 + 1)
class maxheap: ''' implements max heap: ''' def __init__(self, maxsize): ''' initialize an empty max heap with a max size. ''' self.size = 0 self.maxsize = maxsize self.Heap = [0] * (self.maxsize + 1) self.root = 1 def parent(self, pos): ...
def closure(graph): n = len(graph) reachable = [[0 for _ in range(n)] for _ in range(n)] for i, v in enumerate(graph): for neighbor in v: reachable[i][neighbor] = 1 for k in range(n): for i in range(n): for j in range(n): reachable[i][...
quant = int(input()) for c in range(quant): frase = input().split() for x in range(len(frase) - 1, 0, -1): for i in range(x): if len(frase[i]) < len(frase[i+1]): temp = frase[i] frase[i] = frase[i+1] frase[i+1] = temp resultado = ' '.join(f...
# $Id: local_dummy_lang.py 8452 2020-01-09 10:50:44Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be ...
#!/usr/bin/env python3 """This module contain a list subcommand for the docker-image resource.""" def configure_parser(docker_image_subparser): """Adds the parser for the list command to an argparse ArgumentParser""" docker_image_subparser.add_parser( "list", help="List docker images present on instan...
class Solution: def twoSum(self, arr: List[int], target: int) -> List[int]: l = 0 r = len(arr) - 1 while l < r: total = arr[l] + arr[r] if total == target: return l + 1, r + 1 elif total < target: l += ...
''' Created on 7 Feb 2015 @author: robrant ''' MONGO_DBNAME = 'dfkm' MONGO_HOST = 'localhost' MONGO_PORT = 27017 TESTING = True """ lat = 50.722 lon = -1.866 50m """
# #Ler o primeiro termo e a razão de uma PA, mostrando os 10 primeiros termos da progressão usando a estrutura while. # perguntando para o usuário se ele quer mostrar mais alguns termos. O programa encerrará quando ele disser que quer mostrar 0 termos. print('GERADOR DE PA') print('-=' * 20) primeiro = int(input('Prim...
'''' | cancer | Total symptom |No | Yes | no |99989 | 0 | 99989 yes |10 | 1 | 11 total |99999 | 1 | 100000 ''' def cal_bayes(prior_H, prob_E_given_H, prob_E): return prior_H * prob_E_given_H / prob_E if __name__ == '__main__': prior_H = 1 / 100000 # probability ...
METRICS_AGGREGATE_KEYS = [ 'sum', 'max', 'min' ] BUCKETS_AGGREGATE_KEYS = [ 'terms', 'date_histogram' ] BUCKETS_AGGREGATE_OPTIONALS = [ 'format', 'order', 'size', 'interval' ]
def book_dto(book): try: if not book: return None return { 'id': str(book.pk), 'book_name': book.name, 'summary': book.summary if book.summary else "", 'author': book.author, 'book_genre': book.genre, 'barcode': book...
count_dict, count, Last_item = {}, 0, None binario = str(bin(int(input()))) binary_list = [n for n in binario] for item in binary_list: if Last_item != item: Last_item = item count = 1 else: count += 1 if count > count_dict.get(item, 0): count_dict[item] = count print(coun...
class Sample(object): def func_0(self): return '0' def func_1(self, arg1): return arg1 def func_2(self, arg1, arg2): return arg1 + arg2 s = Sample() result = s.func_0() print(result) result = s.func_1('test1') print(result) result = s.func_2('test1', 'test2') print(result) fu...
# 647. Palindromic Substrings # Runtime: 128 ms, faster than 79.15% of Python3 online submissions for Palindromic Substrings. # Memory Usage: 14.1 MB, less than 85.33% of Python3 online submissions for Palindromic Substrings. class Solution: # Expand Around Possible Centers def countSubstrings(self, s: str)...
print('Pintura de parede') print('='*25) l = float(input('Qual a largura da parede? ')) a = float(input('Qual a altura da parede? ')) print('A área da parede é {:.3f} m² e é necessário {:.3f} L de tinta para pintá-lo.'.format(l*a, (l*a)/2))
def test_submit_retrieve(client) -> None: headers = { 'Content-Type': 'text/plain' } urls = { 'https://www.wikipedia.org/': '48VIcsBN5UX', 'https://www.google.com/': '48VIcsBN5UY', 'https://www.stackoverflow.com/': '48VIcsBN5UZ', 'https://www.youtube.com/watch?v=dQw4...
list1 = [ 9, 2, 8, 4, 0, 1, 34 ] # insert 45 at 5th index list1.insert(4, 45) print(list1) list2 = ['q', 'b', 'u', 'h', 'p'] # insert z at the front of the list list2.insert(0, 'z') print(list2)
# Implement regular expression matching with the following special characters: # . (period) which matches any single character # * (asterisk) which matches zero or more of the preceding element # That is, implement a function that takes in a string and a valid regular # expression and returns whether or not the string...
# # PySNMP MIB module SCA-FREXT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SCA-FREXT-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:52:53 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...
print('====' * 30) print('ANALISADOR DE TRIANGULOS') print('====' * 30) s1 = float(input('Primeiro segmento:')) s2 = float(input('Segundo segmento: ')) s3 = float(input('terceiro segmento: ')) if s1 < s2 + s3 and s2 < s1 + s3 and s3 < s1 + s2: print('Os segmentos FORMAM TRIANGULO ') else: print('os se...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def allPossibleFBT(self, N: int) -> List[TreeNode]: if N % 2 == 0: return [] dp = [[] for i ...
# Crie um programa que simule o funcionamento de um caixa eletrônico. No início, pergunte ao usuário qual será o valor a ser sacado (número inteiro) e o programa vai informar quantas cédulas de cada valor serão entregues. # OBS: considere que o caixa possui cédulas de R$50, R$20, R$10 e R$1. valor = int(input('Digite ...
ALPHABET = 'abcdefghijklmnopqrstuvwxyz' t = int(input()) allResult = '' for k in range(t): input() string = input() result = 'a' while string.find(result) != -1: if result[len(result) - 1] != 'z': result = result[:-1] + ALPHABET[ord(result[-1]) - 96] else: if result[0] == ALPHABET[25]: temp = '' f...
WECOM_USER_MAPPING_ODOO_USER = { "UserID": "wecom_userid", # 成员UserID "Name": "name", # 成员名称 "Mobile": "mobile", # 手机号码 "Email": "email", # 邮箱 "Status": "active", # 激活状态:1=已激活 2=已禁用 4=未激活 已激活代表已激活企业微信或已关注微工作台(原企业号)5=成员退出 "Alias": "alias", # 成员别名 "Telephone": "phone", }
# Time: O(n), n is the number of the integers. # Space: O(h), h is the depth of the nested lists. # """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ #class NestedInteger(object): # def isInteger(self): # """ # ...
# n = int(input()) # res = [[10 ** 9 for j in range(n)] for _ in range(n)] # res[0][0] = 0 # scores = [] # for _ in range(n): # scores.append(list(map(int, input().split()))) # direcs = [(0, 1), (0, -1), (-1, 0), (1, 0)] # d4_scores = [[[] for _ in range(n)] for _ in range(n)] # for i in range(n): # for j in range(n)...
for v in graph.getVertices(): print(v.value.rank)
class Solution: def coinChange(self, coins: 'List[int]', amount: int) -> int: coins.sort(reverse=True) impossible = (amount + 1) * 2 dp = [impossible] * (amount + 1) dp[0] = 0 for current in range(amount + 1): for coin in coins: if curren...
EXAMPLES1 = ( ('04-exemple1.txt', 4512), ) EXAMPLES2 = ( ('04-exemple1.txt', 1924), ) INPUT = '04.txt' def read_data(fn): with open(fn) as f: numbers = [int(s) for s in f.readline().strip().split(',')] boards = list() board = None for line in f: ...
""" For this challenge, create the worlds simplest IM client. It should work like this: if Alice on computer A wants to talk to Bob on computer B, she should start the IM program as a server listening to some port. Bob should then start the program on his end, punch in computer A's IP address with the right port. The t...
#!/usr/bin/python # # AbstractPatching is the base patching class of all the linux distros # # Copyright 2014 Microsoft Corporation # # 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 # # htt...
# pylint: disable=missing-module-docstring # # Copyright (C) 2020 by UsergeTeam@Github, < https://github.com/UsergeTeam >. # # This file is part of < https://github.com/UsergeTeam/Userge > project, # and is released under the "GNU v3.0 License Agreement". # Please see < https://github.com/uaudith/Userge/blob/master/LIC...
nuke.root().knob('onScriptSave').setValue(''' import re for n in nuke.allNodes(): if n.Class() == 'Write': code = """ import re fileVersion = re.search( r'[vV]\d+', os.path.split(nuke.root().name())[1]).group() print fileVersion for node in nuke.allNodes(): if node.Class() == 'Write': node.knob('file').setValue(...
""" Because on the ReadTheDocs Server we cannot import the core extension, because a libpython*so which the core.so is linked against is not found, this module fakes the core.so such that imports works """ __version__ = (1, 2, 3, 4) __features__ = {} ALL_SITES = -1 class SQSResult: pass class IterationSetting...
#entrada horas = int(input()) kmH = int(input()) #processamento litros = (horas * kmH) / 12 #saída print("{:.3f}".format(litros))
class Email: def __init__(self, sender, receiver, content, is_sent=False): self.sender = sender self.receiver = receiver self.content = content self.is_sent = is_sent def send(self): self.is_sent = True def get_info(self): return f"{self.sender} says to {sel...
# # PySNMP MIB module RBN-SMS1000-ENVMON-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RBN-SMS1000-ENVMON-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:53:21 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (d...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- assert ascii('中文') == "'\\u4e2d\\u6587'" assert ascii([]) == '[]' assert ascii('\x33') == "'3'" # 自带repr的效果, assert ascii('asdf') == "'asdf'"
""" Author : Drew Heasman Date(last updated) : 05 June 2021 Description : Geochemical calculations """ elements = {} elements["O"] = 15.9994 elements["Al"] = 26.981539 elements["Si"] = 28.0855 elements["K"] = 39.0983 elements["Cr"] = 51.9961 elements["Fe"] = 55.845 elements["Nd...
''' Given a singly linked list, determine if it is a palindrome. Example 1: Input: 1->2 Output: false Example 2: Input: 1->2->2->1 Output: true ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def isPalindro...
with open("sample.txt", 'a') as jabber: for i in range(1,13): for j in range(1,13): print(f"{j:>2} times {i:2} is {i*j:<}", file=jabber) print("-"*20, file=jabber)
""" In Python, a string can be split on a delimiter. Example: >>> a = "this is a string" >>> a = a.split(" ") # a is converted to a list of strings. >>> print a ['this', 'is', 'a', 'string'] Joining a string is simple: >>> a = "-".join(a) >>> print a this-is-a-string """ def split_and_join(line): # write you...
class SocketManager(object): def __init__(self): self.ws = set() def add_socket(self, ws): self.ws.add(ws) def remove_sockets(self, disconnected_ws): if not isinstance(disconnected_ws, set): disconnected_ws = {disconnected_ws, } self.ws -= disconnected_ws
# This class handles exceptions. All exceptions raised will be passed through the API to the client class DebugException(Exception): exception_dict = { 101: "Don't be naughty, type something with meaning >.<", # "Invalid input, please check your sentence", 301: "Keyword not found in Database", ...
""" 面试题39:二叉树的深度 题目一:输入一棵二叉树的根结点,求该树的深度。从根结点到叶结点依次经过的 结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。 https://leetcode.com/problems/maximum-depth-of-binary-tree/ Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as: a binary tree in which the depth of the two s...
# Copyright (c) 2020-2021 Matematyka dla Ciekawych Świata (http://ciekawi.icm.edu.pl/) # Copyright (c) 2020-2021 Robert Ryszard Paciorek <rrp@opcode.eu.org> # # MIT License # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Soft...
class MockFeeEstOne(): @property def status_code(self): return 200 def json(self): return {"fastestFee": 200, "halfHourFee": 200, "hourFee": 100} class TestDataOne(): @property def path(self): return 'tests/test_files' @property def pub_key_file_name(self): ...
# <auto-generated> # This code was generated by the UnitCodeGenerator tool # # Changes to this file will be lost if the code is regenerated # </auto-generated> def to_milligrams(value): return value * 28349.5231 def to_grams(value): return value * 28.3495231 def to_kilograms(value): return value / 35.274 def to_...
"""This module implements exceptions for this package.""" __all__ = ["Error", "InvalidRecordError", "InvalidHeaderError", "InvalidFooterError", "LogicError"] class Error(Exception): """ Base class for exceptions in this module. @see https://docs.python.org/3/tutorial/errors.html#user-defined-exceptions ...
S1 = "Hello World" print("Length of the String is", len(S1)) # To find the length of a String List1 = ["Emon", "Bakkar", "Ehassan", "Anik", "Ahad", "Sibbir"] print("After join the list:", ", ".join(List1)) # To join the String S2 = "Hey this is Emon" List2 = S2.split() print("After Split the String:{}".format(List2...
list = ['iam vengeance'] list1 = [] for k in list: list1.append(k.title()) print(list1)
def func_kwargs(**kwargs): print('kwargs: ', kwargs) print('type: ', type(kwargs)) func_kwargs(key1=1, key2=2, key3=3) # kwargs: {'key1': 1, 'key2': 2, 'key3': 3} # type: <class 'dict'> def func_kwargs_positional(arg1, arg2, **kwargs): print('arg1: ', arg1) print('arg2: ', arg2) print('kwargs: '...