content
stringlengths
7
1.05M
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/6/21 11:13 # @Author : CoderCharm # @File : custom_exc.py # @Software: PyCharm # @Desc : """ 自定义异常 """ class PostParamsError(Exception): def __init__(self, err_desc: str = "POST请求参数错误"): self.err_desc = err_desc class TokenAuthErro...
s = input() y = int(input()) n = int(input()) c = 0 for i in s: if int(i) <= y: c += 1 for i in range(n): for j in range(2, n-1): if int(s[i:j+i]) <= y: c += 1 print(c) ''' qx = [i for i in range(input1)] for i, j in input3: if i == 1: qx = qx[1:] i...
def to_braket(array): """ helper for pretty printing """ state = [] basis = ('|00>', '|10>', '|01>', '|11>') for im, base_state in zip(array, basis): if im: if abs(im.imag)>0.001: state.append(f'{im.real:.1f}{base_state}') else: state.appen...
def is_balanced(s): pairs = {"(": ")", "[": "]", "{": "}"} stack = [] for ch in s: if ch in pairs: stack.append(ch) else: if len(stack) == 0: return False if pairs[stack.pop()] != ch: return False return len(stack) == ...
def generate(label): ( bbox_xmin, bbox_ymin, bbox_xmax, bbox_ymax, img_width, img_height ) = ( label.get('xmin'), label.get('ymin'), label.get('xmax'), label.get('ymax'), label.get('img_width'), label.get('img_height...
""" A solution should include: 1. Benchmark scenario; 2. get_actions() method; 3. get_states() method. """ # Specify benchmark scenario below. BENCHMARK = "" # Benchmark name goes here... # Specify get_action() method below. def get_actions(state): # get_actions() code goes here... return # Sp...
print("hello") count=1 if count<1: print("yes") else: print("no")
""" Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. Example 1: Input: 121 Output: true Example 2: Input: -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. Examp...
# functions print("Demonstrating functions....") def fun(): print("Printing my function: fun") def fun1(): print("Printing my function: fun1") def multiply(x, y): z = x * y return z mulnum = multiply(150, 160) print(f"The return value is {mulnum}") # Demonstrating lambda functions # Lambda functi...
class MCP3008(): def __init__(self, channel): self.fake_val = 0 def value(self, pin=None): return self.fake_val
firt_tuple = (5,5,4,6,1,2,3) new_list = list(firt_tuple) new_tuple = tuple(new_list) print(len(firt_tuple)) print(max(new_list)) print(min(new_tuple))
# Please note that if you uncomment and press multiple times, the program will keep appending to the file. def cap_four(name): new_name = name[0].upper() + name[1:3] + name[3].upper() + name[4:] return new_name # Check answer = cap_four('macdonald') print(answer)
class Solution: def isPalindrome(self, s: str) -> bool: s=s.lower() s=[x for x in s if x.isalnum() ] return s==s[::-1]
#Создание двух таблиц Вижинера tablu = [[0 for i in range(0, 26)] for j in range(0, 26)] tabll = [[0 for i in range(0, 26)] for j in range(0, 26)] alphu = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" alphl = "abcdefghijklmnopqrstuvwxyz" s1 = "" s2 = "" for i in range(26): s1 = alphu[i:] s2 = alphu[:i] s = s1 + s2 for j...
#Faça um Programa que leia 20 números inteiros e #armazene-os num vetor. Armazene os números pares no #vetor PAR e os números IMPARES no vetor impar. Imprima #os três vetores. vetor=[] vetorP=[] vetorI=[] for c in range(0,7): vetor.append(int(input("Informe um numero: "))) if(vetor[c]%2==0): vetorP.app...
print('\033[31m-=-' * 9) print('\033[35mCalculador de Média') print('\033[31m-=-' * 9) n1 = float(input('\033[94mPrimeira nota do aluno: ')) n2 = float(input('Segunda nota do aluno: ')) print('\033[94mA média entre \033[1m{:.1f}\033[22m e \033[1m{:.1f}\033[22m é igual a \033[1m{:.1f}\033[22m.' .format(n1, n2, (n1...
if _: l = 2 else: l = []
class Solution(object): def partition(self, s): """ :type s: str :rtype: List[List[str]] """ substring = [] substrings = [] self.recursive(s, substring, substrings) return substrings def recursive(self, s, substring, substrings): if not s...
MONTHS = { 'january': 1, 'february': 2, 'march': 3, 'april': 4, 'may': 5, 'june': 6, 'july': 7, 'august': 8, 'september': 9, 'october': 10, 'november': 11, 'december': 12, } SHORT_MONTH = [ '', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep...
# Iterative approach - Time-Complexity = O(k), Space-Complexity = O(1) # k is the no of digits def replaceZeros(num): num += calculateAddedValue(num) return num def calculateAddedValue(num): decimal_place = 1 result = 0 if num == 0: result += decimal_place * 5 while num > 0: ...
# Copyright (c) 2009 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'targets': [ { 'target_name': 'subdir_file', 'type': 'none', 'msvs_cygwin_shell': 0, 'actions': [ { '...
"""Project Euler problem 3""" def sqrt(number): """Returns the square root of the specified number as an int, rounded down""" assert number >= 0 offset = 1 while offset ** 2 <= number: offset *= 2 count = 0 while offset > 0: if (count + offset) ** 2 <= number: count...
# nCk n, m = map(int, input().split(' ')) # numerator numerator = 1 for i in range(0, m): numerator *= n n -= 1 # denominator denominator = 1 for i in range(m, 0, -1): denominator *= i print(numerator // denominator)
# -*- coding: utf-8 -*- """ Created on Sun Jun 24 16:26:56 2018 @author: joshu """ letter_z = 'z' num_3 = '3' a_space = ' ' # Check if all characters are numbers print("Is z a letter or number: ", letter_z.isalnum()) # Checks if all characters are alphabetical print("Is z a letter: ", letter_z.isalpha()) # Check...
''' Problem Statement: ----------------- Given an array A of size N of integers. Your task is to find the minimum and maximum elements in the array. Example 1: --------- Input: N = 6 A[] = {3, 2, 1, 56, 10000, 167} Output: min = 1, max = 10000 Example 2: ---------- Input: N = 5 A[] = {1, 345, 234, 21, 56789} Output: ...
class Enum(object): def __init__(self, plugin, node): if node.tag != 'enum': raise ValueError('expected <enum>, got <%s>' % node.tag) self.plugin = plugin self.name = node.attrib['name'] self.item_prefix = node.attrib.get('item-prefix', '') self.base = int(node.at...
connChoices = ( {'name': 'automatic', 'rate': {'min': 0, 'max': 5000, 'def': 0}, 'conn': {'min': 0, 'max': 100, 'def': 0}, 'automatic': 1}, {'name': 'unlimited', 'rate': {'min': 0, 'max': 5000, 'def': 0, 'div': 50}, 'conn': {'min': 4, 'max': 100, 'def': 4}}, {'name': 'dialup/isdn'...
# # PySNMP MIB module HUAWEI-MA5200-DEVICE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-MA5200-DEVICE-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:46:33 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7....
# -*- coding: utf-8 -*- ''' File name: code\the_millionth_number_with_at_least_one_million_prime_factors\sol_615.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #615 :: The millionth number with at least one million prime factors # # For ...
BOT_NAME = 'podcast_scraper' SPIDER_MODULES = ['podcast_scraper.spiders'] NEWSPIDER_MODULE = 'podcast_scraper.spiders' SCHEDULER_DEBUG = 'True' LOG_LEVEL = 'DEBUG' # LOG_FILE = './logs/log.txt' # app.py will use OUTPUT_BUCKET to generate an OUTPUT_URI # using OUTPUT_BUCKET and spider_name. OUTPUT_BUCKET = 'output-rs...
"""3. Inference with Quantized Models ===================================== This is a tutorial which illustrates how to use quantized GluonCV models for inference on Intel Xeon Processors to gain higher performance. The following example requires ``GluonCV>=0.4`` and ``MXNet-mkl>=1.6.0b20190829``. Please follow `our ...
def fib(n_max): n, a, b = 0, 0, 1 while n < n_max: yield b a, b = b, a + b n = n + 1 list = fib(int(input("Input a number:"))) print(next(list)) for o in list: print(o)
""" Universidad del Valle de Guatemala CC---- thompson.py Proposito: AFN ya establecido """ class AFN: def __init__(self, start, end): self.start = start self.end = end # start and end states end.is_end = True self.text = "State Inicial: {}| State Final: {}".format(self.start,self....
"""Sparse Array""" def sparse_array(): r"""https://www.hackerrank.com/challenges/sparse-arrays? There are $N$ strings. Each string's length is no more than 20 characters. There are also $Q$ queries. For each query, you are given a string, and you need to find out how many times this string occurred pr...
def mostFrequentDigitSum(n): ''' A step(x) operation works like this: it changes a number x into x - s(x), where s(x) is the sum of x's digits. You like applying functions to numbers, so given the number n, you decide to build a decreasing sequence of numbers: n, step(n), step(step(n)), etc., with 0 as the last...
"""DTE Energy Bridge Exceptions.""" class DteEnergyBridgeError(Exception): """Base class for all DTE Energy Bridge exceptions""" class InvalidResponseError(DteEnergyBridgeError): """Response from DTE Energy Bridge was invalid""" class InvalidArgumentError(DteEnergyBridgeError): """Invalid argument"""
# x=int(input("enter the number")) # print("factors of ",x,"is:") # for i in range (1,x+1): # if X%i==0: # print(i) n=int(input("enter factors number=")) i=1 while i<=n: if n%i==0: print(i) i+=1
''' Created on Feb 20, 2013 @author: gorgolewski, steele ''' #import os #subjects = os.listdir("/scr/namibia1/baird/MPI_Project/Neuroimaging_Data/") working_dir = "/scr/alaska1/steele/BSL_IHI/processing/cmt" results_dir = "/scr/alaska1/steele/BSL_IHI/processing/cmt/results" freesurfer_dir = '/scr/alaska1/steele/BSL_I...
# (C) Datadog, Inc. 2020-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) def get_counter(check, metric_name, modifiers, global_options): """ https://prometheus.io/docs/concepts/metric_types/#counter https://github.com/OpenObservability/OpenMetrics/blob/master/spec...
class ShortCodeError(Exception): """Base exception raised when some unexpected event occurs in the shortcode OAuth flow.""" pass class UnknownShortCodeError(ShortCodeError): """Exception raised when an unknown error happens while running shortcode OAuth. """ pass class Short...
class Empty(Exception): """Use this class to raise exception if a container is empty.""" pass class CircularQueue: """Queue implemented using cicrcularly linked list for storage.""" class _Node: """Lightweight, nonpublic class for storing a singly linked node.""" __slots__ = ["_elemen...
def szyfr(ciag, k): nowy_ciag = "" for lit in ciag: nowy_ord = 65+(ord(lit)-65+k) % 26 nowy_ciag += chr(nowy_ord) return nowy_ciag def odszyfr(ciag, k): nowy_ciag = "" for lit in ciag: nowy_ord = 65+(ord(lit)-65-k) % 26 nowy_ciag += chr(nowy_ord) return nowy_cia...
#! python3 # __author__ = "YangJiaHao" # date: 2018/2/3 class Solution: def myAtoi(self, str): """ :type str: str :rtype: int """ str = str.strip() if str == "": return 0 num = '' symbol = 1 if str[0] == '-': symbol = -1...
__doc__ = '网上常用的python实现示例' # 图算法 -- 深度优先搜搜 -- DFS -- 栈(先进后出) # 1.利用栈实现 # 2.从源节点开始把节点按照深度放入栈,然后弹出 # 3.每弹出一个点,把该节点下一个没有进过栈的邻接点放入栈 # 4.直到栈变空 def DFS(graph, start): stack = [start] visited = set() step = 0 # 记录扩散的步数 while stack: vertex = stack.pop() if vertex not in visited: ...
#! coding:utf-8 # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None def addTwoNumbers(l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ # Definition for singly-linked list. # c...
#!/usr/bin/python patch_size = [11, 15, 21] detector = ["FeatureDetectorHarrisCV", "FeatureDetectorUniform"] filter_size = [1, 3] max_disparity = [140, 160, 180, 200] fp_runscript = open("/mnt/ssd/kivan/cv-stereo/scripts/eval_batch/run_batch_grid_search_stage2.sh", 'w') fp_runscript.write("#!/bin/bash\n\n") cnt = 0 ...
# 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 isMirror(self, r1: TreeNode, r2: TreeNode) -> bool: if r1 == None and r2 == None: re...
class Passenger: def __init__(self, name): self.name = name def selectTrip(self, tripOptions): ''' Given a list of trip options, a passenger may select a trip This trip is then added to the trip queue, which allows for later return pricing tripOptions: the queue of give...
# -*- coding: utf-8 -*- """ -------------------------------------- @File : stats.py @Author : maixiaochai @Email : maixiaochai@outlook.com @CreatedOn : 2020/6/8 23:29 -------------------------------------- 一些统计信息 1)任务数量, 总数、成功、失败、运行中、运行完 2)任务数量分布统计 3)历史成功率统计 4)硬件信息统计,磁盘、cpu、内存、文件数量 ...
# A file containing mappings of CC -> MC file names # Pack version 3 VER3 = { 'char.png': 'minecraft/textures/entity/steve.png', 'chicken.png': 'minecraft/textures/entity/chicken.png', 'creeper.png': 'minecraft/textures/entity/creeper/creeper.png', 'pig.png': 'minecraft/textures/entity/pig/pig.png', ...
# output: ok assert(max(1, 2, 3) == 3) assert(max(1, 3, 2) == 3) assert(max(3, 2, 1) == 3) assert(min([1]) == 1) assert(min([1, 2, 3]) == 1) assert(min([1, 3, 2]) == 1) assert(min([3, 2, 1]) == 1) exception = False try: min() except TypeError: exception = True assert(exception) exception = False try: max...
# Hack 1: InfoDB lists. Build your own/personalized InfoDb with a list length > 3, create list within a list as illustrated with Owns_Cars blue = "\033[34m" white = "\033[37m" InfoDb = [] # List with dictionary records placed in a list InfoDb.append({ "FirstName": "Michael", "Las...
x,y,z = map(int,input().split(' ')) a,b,c = map(int,input().split(' ')) if (x, y, z) == (a, b, c): print("0") elif (y, z) == (b, c): print(15 * (x - a)) elif z==c: if y<=b and x<=a: print("0") else: print(500 * (y - b)) elif z>c: print("10000") else: print("0")
def get_sum(arr,i,j): sum = 0 sum += arr[i-1][j-1] sum += arr[i-1][j] sum += arr[i - 1][j+1] sum += arr[i][j] sum += arr[i+1][j-1] sum += arr[i+1][j] sum += arr[i+1][j+1] return sum if __name__ == '__main__': arr = [] for _ in range(6): arr.append(list(map(int, inp...
""" The exceptions here tries to follow PEP249 (https://www.python.org/dev/peps/pep-0249/#exceptions) """ class Warning(Exception): """Exception raised for important warnings like data truncations while inserting, etc.""" pass class Error(Exception): """Exception that is the base class of all other error ...
BROKER_URL = "redis://localhost:6379/0" CELERY_RESULT_BACKEND = "redis://localhost:6379/0" CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_ACCEPT_CONTENT=['json'] CELERY_ENABLE_UTC = True CELERY_TRACK_STARTED=True
def substring (Str,n): for i in range(n): print(i) #0 #1 for j in range(i ,n): #0 to 3 #1 to 3 for k in range(i, (j + 1)): #0 to 1 => 0 #1 to 2 => 1 print(Str[k], end="") #print 0th element of the string. #print 0th and 1st element side by side. pr...
class MockPresenterFactory: def __init__(self): self.__presented_logs = [] def register_presenter(self, presenter): pass def present(self, obj): text = "" if isinstance(obj, str): text = obj elif isinstance(obj, list): if len(obj) > 0: ...
def is_growth(numbers): for i in range(1, len(numbers)): if numbers[i] <= numbers[i - 1]: return False return True def main(): numbers = list(map(int, input().split())) if is_growth(numbers): print('YES') else: print('NO') if __name__ == '__main__': main()...
""" https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/1/array/31/ 题目:旋转图像 给定一个 n × n 的二维矩阵表示一个图像。 将图像顺时针旋转 90 度。 说明: 你必须在原地旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要使用另一个矩阵来旋转图像。 示例 1: 给定 matrix = [ [1,2,3], [4,5,6], [7,8,9] ], 原地旋转输入矩阵,使其变为: [ [7,4,1], [8,5,2], [9,6,3] ] @author Niefy @date ...
# -*- coding: utf-8 -*- # this file is released under public domain and you can use without limitations ######################################################################### ## This is a sample controller ## - index is the default action of any application ## - user is required for authentication and authorization...
a="#" b="@" c=1 d=int(input("Enter Number:")) if d%2==0: f=d/2 else: f=d//2+1 h=f-3 e=1 g=2 while c<=d: if c<=2 or c==f: print (a*c) c+=1 elif c>2 and c<f: print (a+(b*e)+a) c+=1 e+=1 elif c>f and c<d-1: print (a+(b*h)+a) c+=1 h=h-1 ...
# substitution ciphers # or, how to transform data from one thing to another encode_table = { 'A': 'H', 'B': 'Z', 'C': 'Y', 'D': 'W', 'E': 'O', 'F': 'R', 'G': 'J', 'H': 'D', 'I': 'P', 'J': 'T', 'K': 'I', 'L': 'G', 'M': 'L', 'N': 'C', 'O': 'E', 'P': 'X', ...
class Color: pass class rgb(Color): "A representation of an RGBA color" def __init__(self, r, g, b, a=1.0): self.r = r self.g = g self.b = b self.a = a def __repr__(self): return "rgba({}, {}, {}, {})".format(self.r, self.g, self.b, self.a) @property ...
aggregate_genres = [{"rock": ["symphonic rock", "jazz-rock", "heartland rock", "rap rock", "garage rock", "folk-rock", "roots rock", "adult alternative pop rock", "rock roll", "punk rock", "arena rock", "pop-rock", "glam rock", "southern rock", "indie rock", "funk rock", "country rock", "piano rock", "art rock", "rocka...
""" Mock module for _luastack C++ extension. Behaves like true _luastack module, but operates an imaginary Lua stack represented by a list. """ class StackPad: """Stub for padding the stack to make indexing start at 1.""" def __repr__(self): return "<StackPad>" stack = [StackPad()] # Imaginary Lua...
# Number of images used for training (rest goes for validation) train_size = 55000 # Image width and height of mnist width = 28 height = 28 # The total number of labels num_labels = 10 # The number of batches to prefetch when training on GPU num_prefetch = 5 # Number of neurons the weight matrices as specified in t...
#recursive solution def fib(n): if (n<=2): return 1 return fib(n-1)+fib(n-2) #print(fib(6)) #should be 8 #dp solution def fib_dp(n): a = [0]*n a[0] = a[1] = 1 for i in range(2, n): a[i] = a[i-1] + a[i-2] #print(a) return a fib_dp(6)
preco = float(input('Digite o preço do produto: ')) pagamento = int(input('Digite a forma de pagamento (0 (avista), 1 (cartão avista) ou + número de prestações: ')) if pagamento == 0: preco = preco * 0.9 elif pagamento == 1: preco = preco * 0.95 elif pagamento == 2: preco = preco / 2 else: preco = preco...
## configuration settings c = get_config() ## Configure SSL ----------------------------------------------- c.JupyterHub.ssl_key = "/srv/jupyterhub/ssl/jhub.privkey.pem" c.JupyterHub.ssl_cert = "/srv/jupyterhub/ssl/jhub.fullchain.pem" c.JupyterHub.ip = '128.59.232.200' c.JupyterHub.port = 443 ## Configure OAuth ----...
class Config(object): DEBUG = True DEVELOPMENT = True class ProductionConfig(Config): DEBUG = False DEVELOPMENT = False
N, M = map(int, input().split()) G = [[] for _ in range(N)] for _ in range(M): A, B = map(int, input().split()) G[A].append(B) G[B].append(A) dist = [-1] * N nodes = [[] for _ in range(N)] dist[0] = 0 nodes[0] = [0] for k in range(1, N): for v in nodes[k-1]: for next_v in G[v]: ...
# -*- coding: UTF-8 -*- class Global: G_TEXT_LOGO = ''' ____ _ / __ )(_)___ ____ _____ / __ / / __ \/ __ `/ __ \\ / /_/ / / / / / /_/ / /_/ / /_____/_/_/ /_/\__, /\____/ /____/ ...
n = [1, 2, 3, 4, 5] new = [] k = int(input('Сдвиг: ')) for _ in range(5): new.append(n[-k]) k -= 1 print(n) print(new)
def store_value(redis_client,key_name,value): redis_client.setnx(key_name,value) return True def get_key_value(redis_client,key_name): return redis_client.get(key_name)
class HTTPException(Exception): def __init__(self, status: int, reason: str): self.status = status self.reason = reason def __str__(self): return "HTTPException: {}: {}".format(self.status, self.reason)
#!/usr/bin/env python3 def find_root(n, m): r = int(pow(m, 1 / n)) if r**n == m: return r if (r + 1)**n == m: return r + 1 return -1 for t in range(int(input())): print(find_root(*map(int, input().split())))
class QuantumProcessor: """A class for defining a quantum processor""" def __init__(self, qubit_num=1, execution_time=0.1): """Define a quantum processor Args: qubit_num (int, optional): The number of qubits. Defaults to 1. execution_time (float, optional): The executi...
hooked_function = None def set_hook(hook): global hooked_function hooked_function = hook hooked_function def do_it(): if hooked_function != None: hooked_function() else: print("Did not get hooked")
# assign first item to dictionary, give value of 1 # go through items # if item name isn't equal to any dictionary, set it to a new dictionary # if item name equals existing dictionary, set that dictionary's value to +=1 # after everything, print dictionaries people = {} with open('tweeters.txt') as file: for line...
#! /usr/bin/env python """ Some type definitions for metadata extraction """ class MetadataError(RuntimeError): pass
USER_INFORMATION ={ "object": "user", "url": "https://api.wanikani.com/v2/user", "data_updated_at": "2020-05-01T05:20:41.769053Z", "data": { "id": "7a18daeb-4067-4e77-b0ea-230c7c347ea8", "username": "Tadgh11", "level": 12, "profile_url": "https://www.wanikani.com/users/Tadgh11", "started_at"...
# -*- coding: utf-8 -*- """ KVSキャッシュモジュール get/set/deleteメソッドを実装すること """ class Cache(object): """ キャッシュモジュールのベースクラス """ def get(self, key, default = None): """ 値の取得 @param key: キー @param default: 取得できない場合のデフォルト値 @return: 取得した値 """ raise NotImplementedError("Cache::get") def set(self, key, value, lif...
class PyginationError(Exception): pass class PaginationError(Exception): pass
soma = 0 cont = 0 for imp in range(1, 501, 2): if imp % 3 == 0: cont = cont + 1 soma = soma + imp print('A soma de todos os {} valores solicitados é : {} '.format(cont, soma))
## CLASSES class NamedThing(object): """ a databased entity or concept/class """ def __init__(self, id=None, label=None): self.id=id self.label=label def __str__(self): return "id={} label={} ".format(self.id,self.label) def __repr__(...
#!/usr/bin/env python3 def part_one(file): return(min(main(file))) def part_two(file): return(max(main(file))) def main(file): distances = dict() cities = set([s.strip().split(" ")[0] for s in open(file)]) cities.update([s.strip().split(" ")[2] for s in open(file)]) for city in cities: ...
#Handling Exceptions try: age = int(input("Enter your age:")) except ValueError as ex: print(ex) print(type(ex)) print("Please enter valid age!") else: print("else part executed")
def uncycle(list): if len(list) <= 3: return max(list) m = int(len(list) / 2) if list[0] < list[m]: return uncycle(list[m:]) else: return uncycle(list[:m])
def _build_csv_path(target:str, directory:str, cell_line:str): return "{target}/{directory}/{cell_line}.csv".format( target=target, directory=directory, cell_line=cell_line ) def get_raw_epigenomic_data_path(target:str, cell_line:str): return _build_csv_path(target, "epigenomic_data...
# -*- coding: utf-8 -*- # Copyright: (c) 2017, Wayne Witzel III <wayne@riotousliving.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) class ModuleDocFragment(object): # Ansible Tower documentation fragment DOCUMENTATION = r''' options: tower_host: descr...
def main(): question = input("Please what type of variation is it ... |> ") if question == "direct": question = input("Please what is the value of the initial 1st variable => ").isdigit() if question: int(question) another_question = input("Please what is the value of the...
def Values_Sum_Greater(Test_Dict): return sum(list(Test_Dict.keys())) < sum(list(Test_Dict.values())) Test_Dict = {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5} print(Values_Sum_Greater(Test_Dict))
class Concept: ID = None descriptions = None definition = None def __init__(self, ID=None, descriptions=None, definition = None): self.ID = ID self.descriptions = [] if descriptions is None else descriptions self.definition = None class Description: ID = None concept_ID...
expected_output = { 'pvst': { 'a': { 'pvst_id': 'a', 'vlans': { 2: { 'vlan_id': 2, 'designated_root_priority': 32768, 'designated_root_address': '0021.1bff.d973', 'designated_root_max_ag...
t1 = (1, 2, 3, 'a') t2 = 4, 5, 6, 'b' t3 = 1, # print(t1[3]) # for v in t1: # print(v) # print(t1 + t2) n1, n2, *n = t1 print(n1) # Processo para mudar valor de uma tupla t1 = list(t1) t1[1] = 3000 t1 = tuple(t1) print(t1)
#! /root/anaconda3/bin/python # 例子一 g = 18 def f1(): g = 19 print(g) f1() print(g) # 例子二 def f2(): global g g = 20 print(g) f2() print(g) # 例子三 def f3(): g += 1 print(g) try: f3() except Exception as err: print(type(err)) print(err)
# Medium # for loop with twoSum class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: nums.sort() result = [] for i in range(len(nums)): if i>0 and nums[i] == nums[i-1]: continue tmp = self.twoSum(nums,i+1,0-nums[i]) ...
# You work at Len’s Slice, a new pizza joint in the neighborhood. You are going to use your knowledge of Python lists to organize some of your sales data. # Your code below: # Create a list called "toppings" to keep track of the kinds of pizzas you sell toppings = [["Pepperoni"], ["Pineapple"], ["Cheese"], ["Sausage"]...
def minion_game(string): string = string.lower() scoreStuart = 0 scoreKevin = 0 vowels = 'aeiou' for j, i in enumerate(string): if i not in vowels: scoreStuart += len(string) - j if i in vowels: scoreKevin += len(string) - j if scoreStuart > scoreKevin: ...