content
stringlengths
7
1.05M
""" @file @brief `vis.js <https://github.com/almende/vis>`_ The script was obtained from the `release page <https://github.com/almende/vis/tree/master/dist>`_. """ def version(): "version" return "4.21.1"
def count_letters(id=''): # chars = id.split('') counts = {} for char in id: if char in counts: counts[char] = counts[char] + 1 else: counts[char] = 1 # print('id = {}, counts = {}'.format(id, counts)) return counts f = open('input.txt', 'r') ids = [line.st...
Contents = """ POS MV V5 User Interface Control Document Document # : PUBS-ICD-004089 Revision: 10 Date: 23 August 2017 The information contained herein is proprietary to Applanix corporation. Release to third parties of this publication or of information contained herein is prohibited without the prior written conse...
# # PySNMP MIB module APPN-DLUR-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/APPN-DLUR-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:24:11 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...
def add(x, y): """adds two numbers""" return x+y def subtract(x,y): """subtract x from y andreturn value""" return y-x
class ExtractedNoti: def __init__(self, title, date, href): self.title = title self.date = date self.href = href class ExtractedNotiList: def __init__(self): self.numOfNoti = 0 self.category = '' self.extractedNotiList = []
#!python3 def main(): with open('16.txt', 'r') as f, open('16_out.txt', 'w') as f_out: line = f.readline() dance_moves = line.strip().split(',') letters = [chr(c) for c in range(97, 113)] # Part 1 programs = letters.copy() # programs = ['a', 'b', 'c', 'd', 'e'] ...
# https://leetcode.com/problems/nim-game/ # # algorithms # Medium (55.8%) # Total Accepted: 189,849 # Total Submissions: 340,261 class Solution(object): def canWinNim(self, n): """ :type n: int :rtype: bool """ if n % 4 == 0: return False return True...
""" You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. Example 1: coins = [1, 2, 5], amount = 11 return 3 (1...
a=int(input('enter a?')); b=int(input('enter b?')); c=int(input('enter c?')); if a>b and a>c: print('a is largest'); if b>a and b>c: print('b is largest'); if c>a and c>b: print('c is largest');
# -*- coding: utf-8 -*- """ Created on Sun Apr 23 23:04:01 2017 @author: LI YUXIN """ ''' ResNet Placeholder '''
# -*- coding: utf-8 -*- """ 119. Pascal's Triangle II Given an integer rowIndex, return the rowIndexth row of the Pascal's triangle. Notice that the row index starts from 0. In Pascal's triangle, each number is the sum of the two numbers directly above it. Follow up: Could you optimize your algorithm to use only O...
class Solution: def missingNumber(self, nums: List[int]) -> int: arr = list(range(0, len(nums), 1)) for i in range(0, len(nums), 1): if nums[i] in arr: arr.remove(nums[i]) else: continue try: return arr[0] except Ind...
""" The MIT License (MIT) Copyright (c) 2017 Roland Jaeger Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge...
''' Created on Sep 26, 2016 @author: matth ''' #plan # auto find com port (atelast ask for port number) # verify that port is good # background thread the serial read ''' import serial import threading from threading import Thread from queue import Queue import AFSK.afsk as afsk class AudioTNC(): def...
#!/usr/bin/python3 #Copyright 2018 Jim Van Fleet #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 ...
__author__ = 'Elias Haroun' class Node(object): def __init__(self, data, next, previous): self.data = data self.next = next self.previous = previous def getData(self): return self.data def getNext(self): return self.next def getPrevious(self): return ...
# #1 # def generateShape(int): # str = [] # for i in range(int): # str.append('+' * int) # return "\n".join(str) # #2 # def generateShape(n): # return "\n".join("+" * n for i in range(n)) def generateShape(int): # 3 return (("+" * int + "\n") * int)[:-1]
#!/usr/bin/env python # -*- mode: python; coding: utf-8; fill-column: 80; -*- """Simple linked list implementation. """ class CircDblLnkList: """Circular, doubly linked list.""" def __init__(self): """Instantiate a circular, doubly linked list.""" self.__head = None self.__tail = None...
''' Created on 2019/02/14 @author: tom_uda ''' def search4letters(phrase:str,letters:str) -> set: return set(letters).intersection(set(phrase))
# # PySNMP MIB module SYMMCOMMON10M (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/neermitt/Dev/kusanagi/mibs.snmplabs.com/asn1/SYMMCOMMON10M # Produced by pysmi-0.3.4 at Tue Jul 30 11:34:48 2019 # On host NEERMITT-M-J0NV platform Darwin version 18.6.0 by user neermitt # Using Python version 3.7.4 (default, J...
class DataExtracter(): def extract(self): """ override for own implementation """
''' Parameters of this project. This file is used for storing the parameters that would not be changed frequently. ''' # Lengths of input and output traces num_input = 2500 num_output = 2500 # Batch size batch_size = 16 # Zoom range, should be in the range of (1, num_output) zoom_range = (500, 1000) # Input and out...
# region easy approach for basic task def main(): numberset = [n for n in range(1, 11)] print(numberset) for n in numberset: rst = find_minmul(n) print(f"{n} {rst[0]} {n} x {rst[1]}") def find_minmul(num: int): """B10이 0과 1로만 이루어진 경우 B10, 및 곱수 반환""" mulnum = 1 while not isok(...
class ReskinUnlockPacket: def __init__(self): self.type = "RESKINUNLOCK" self.skinID = 0 self.isPetSkin = 0 def read(self, reader): self.skinID = reader.readInt32() self.isPetSkin = reader.readInt32()
class Crafting: def __init__(self, json=None): self.discipline = None self.rating = None self.active = None if(json is not None): self.load_from_json(json) def load_from_json(self, json: dict): self.discipline = json.get("discipline", None) self.rati...
""" # Copyright 2022 Red Hat # # 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 agr...
"""Line Encoding Given a string, return its encoding defined as follows: First, the string is divided into the least possible number of disjoint substrings consisting of identical characters Next, each substring with length greater than one is replaced with a concatenation of its length...
num = int(input("Digite um numero: ")) if (num % 2 == 0) and (num != 2): print("O numero não é primo") else: print("O numero é primo")
''' Created on Apr 15, 2016 @author: dj ''' # Use Meta class to help. class Product(object): def __init__(self): self.name = None self.internal_name = None print("class, name, internal_name = {0}, {1}, {2}".format( self.__class__.__name__, self.name, self.inte...
""" Python的标准库 heapq:从小从大排序的 heap。 heap[0] 就是 smallest。 0) heapify 1)push 2) pop """ class KthLargest: def __inti__(self, k: int, nums: List[int]): self.k = k self.heap = nums heapq.heaqpfiy(nums) while len(leap) > k: heapq.heappop(self.heap) def add(self, val:...
print('hello world, hello 经理') num = 10 num2 = 20 num3 = 30
class Solution: def maxChunksToSorted(self, arr): max_so_far = arr[0] result = 0 for i, num in enumerate(arr): max_so_far = max(max_so_far, num) if max_so_far == i: result += 1 return result
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Sep 1 22:47:54 2018 @author: tanjeremy """ def network_forward(network, input_data, label_data=None, phase='train'): for layer in network: if type(layer) is not SoftmaxOutput_CrossEntropyLossLayer: input_data = layer.forward(inp...
clock.addListener("clockStarted", "python", "clock_start") def clock_start(): print("The clock has started")
class PreflightFailure(Exception): pass class MasterTimeoutExpired(Exception): pass
class UniqueStringFinder: def find_unique(self, list_of_strings: list): list_of_strings.sort(key=lambda element: element.lower()) sorted_list = [set(element.lower()) for element in list_of_strings] if sorted_list.count(sorted_list[0]) == 1 and str(sorted_list[0]) != 'set()': ret...
def main(): with open('../data/states.txt') as f: lines = f.read().splitlines() states = [line.split('\t')[0] for line in lines] states_with_spaces = [state for state in states if ' ' in state] # Print the states_with_spaces list for i, state_name in enumerate(states_with_spaces, 1): ...
power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power gating': 0.0259246, 'Gate...
def taumBday(b: int, w: int, bc: int, wc: int, z: int) -> int: if abs(bc-wc)<=z: return b*bc+w*wc elif bc < wc: return b * bc + w * (bc + z) else: return w*wc+b*(wc+z) if __name__ == "__main__": for _ in range(int(input())): b,w = (int(x) for x in input().split()) ...
x = 1 y = 2 def f1(): x, y = 3, 4 print [x, y] def f2(): global y x, y = 5, 6 print [x, y] def f3(): global x x, y = 7, 8 print [x, y] def f4(): global x, y x, y = 9, 10 print [x, y] print [x, y] f1() print [x, y] f2() print [x, y] f3() print [x, y] f4() print [x, y]
hour = int(input()) day = input() if day == "Monday" or day == "Tuesday" or day == "Wednesday" or day == "Thursday" or day == "Friday" \ or day == "Saturday": if hour == 10 or hour == 11 or hour == 12 or hour == 13 or hour == 14 or hour == 15 \ or hour == 16 or hour == 17 or hour == 18: print("op...
__author__ = 'gk' # Implements look up Table for user to ID and ID to user, as the end Result class for storing user rank and score class ScreenNameIndex: nameToIdMap = dict() idToNameMap = dict() def __init__(self,screen_names): super().__init__() id = 0 for item in screen_names:...
# Two to One.py #! python3 ''' Take 2 strings s1 and s2 including only letters from a to z. Return a new sorted string, the longest possible, containing distinct letters, each taken only once - coming from s1 or s2. Examples: a = 'xyaabbbccccdefww' b = 'xxxxyyyyabklmopq' longest(a, b) -> 'abcdefklmopqwxy' a = 'abcdefg...
'''Faça um programa que calcule a soma entre todos os números ímpares que são múltiplos de três e que se encontram no intervalo de 1 até 500.''' soma = 0 for c in range(1, 501, 2): if c % 3 == 0: soma = soma + c print(c, end=' ') print('\nA soma dos números acima é {} '.format(soma))
def trobarra(numero): """troca / por \ e tem q apagar os espaços depois""" num=numero.replace('/',"\\") return num def quadro(escrita): '''faz um quadro de apresentação para a escrita''' print("-" * (len(escrita)+4)) print(f"{f'{escrita}':^{len(escrita)+2}}") print("-" * (len(escrita)+4))
# # PySNMP MIB module CISCO-MODEM-MGMT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-MODEM-MGMT-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:07:52 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (defau...
pay = float(input('Enter your salary: ')) if pay <= 1250: newpay1 = pay + (pay * 0.15) print('Your new salary is {:.2f}'.format(newpay1)) else: newpay2 = pay + (pay * 0.10) print('Your new salary is {:.2f}'.format(newpay2))
__numerals = {'零': 0, '一': 1, '二': 2, '两': 2, '三': 3, '四': 4, '五': 5, '六': 6, '七': 7, '八': 8, '九': 9, '十': 10, '百': 100, '千': 1000, '万': 10000, '亿': 100000000} def decode_chinese_integer(text: str) -> int: """ 将中文整数转换为int :param text: 中文整数 :return: 对应int """ ans = 0 radix = 1...
################### 3 UZD ################################################### def get_city_year(population_now, perc, delta, population_to_reach, verbose=False): perc = perc / 100 years = 0 population_prev = population_now if population_now < population_to_reach: # if delta < 0: # i...
# 1373. 二叉搜索子树的最大键值和 # # 20200809 # huao # CSP不能马上看结果来修改是真的难... # 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 maxSumBST(self, root: TreeNode) -> int: ...
# Game that generates a story from random user input color = input("Enter a color: ") pluralNoun = input("Enter a noun plural: ") celebrity = input("Enter a celebrity: ") print("Roses are red ", color) print(pluralNoun, " are blue ") print("I love ", celebrity)
while True: n = input() if n == '0': break cnt = len(n)+1 for i in n: if i == '1': cnt += 2 elif i == '0': cnt += 4 else: cnt += 3 print(cnt)
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: if not nums: return [] res, i, start = [], 0, 0 while i < len(nums)-1: if nums[i]+1 != nums[i+1]: res.append(self.printRange(nums[start], nums[i])) ...
class Solution: def reverse(self, x): """ :type x: int :rtype: int """ flag = False if x < 0: flag = True if flag: n = int("-" + str(x)[1:][::-1]) else : n = int(str(x)[::-1]) if n < -2**31 or n ...
# * Exercício Python 087: Aprimore o desafio anterior, mostrando no final: # * A) A soma de todos os valores pares digitados. # * B) A soma dos valores da terceira coluna # * C) O maior valor da segunda linha soma_terceira_coluna = soma_pares = 0 matriz = [ [0, 0, 0], [0, 0, 0], [0, 0, 0] ] for i in ran...
DICE_FMT = '<dice_fmt>' PLAYER = '<player>' TRAIT = '<trait>' ITEM_ID = '<item_id>' PLAYERS_ITEM = '<players_item>' ABILITY_ID = '<ability_id>' PLAYERS_ABILITY = '<players_ability>' EFFECT_ID = '<effect_id>' PLAYERS_EFFECT = '<players_effect>' ANY_ID = '<any_id>' VALUE = '<value>' OBJ_TYPE = '<obj_type>'
EXCLUDE_LIST = ("C:\\Program Files\\Veritas\\NetBackup\\bin\\*.lock", "C:\\Program Files\\Veritas\\NetBackup\\bin\\bprd.d\\*.lock", "C:\\Program Files\\Veritas\\NetBackup\\bin\\bpsched.d\\*.lock", "C:\\Program Files\\Veritas\\Volmgr\\misc\\*", "C:\\Progra...
class Solution: """ @param nums: the given array @param k: the given k @return: the k most frequent elements """ def topKFrequent(self, nums, k): countMap = {} uniqueNums = []; for num in nums : if num in countMap : countMap[num] += 1 ...
"""aiocasambi errors.""" class AiocasambiException(Exception): """Base error for aiocasambi.""" class RequestError(AiocasambiException): """Unable to fulfill request. Raised when host or API cannot be reached. """ class ResponseError(AiocasambiException): """Invalid response.""" class Unauth...
# Copyright 2019 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
''' base class for a WES Client''' class WESClient: def __init__(self, api_url_base): self.api_url_base = api_url_base def runWorkflow(self, fileurl): # use a temporary file to write out the input file inputJson = {"md5Sum.inputFile":fileurl} return None
def enumize(obj, enum_type): if isinstance(obj, enum_type): return obj else: try: return enum_type(obj) except ValueError as exc: try: return enum_type[obj] except KeyError: raise exc def deenumize(obj): return obj.value if hasattr(obj, "value") else obj def norm_...
# remainder Of any number while True: a = int(input("Enter The Dividend Number : ")) b = int(input("Enter The Divisor Number : ")) Quotient = "Quotient Number", (a / b) % 2 * 2 print(Quotient)
class Solution: def longestPalindrome(self, s): """ :type s: str :rtype: str """ def helper(l, r): "Compute longest palindrome substring centered at index (l, r)." while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1 r +...
class NoRulesForTaskException(Exception): def __init__(self, message="at least one rule needs to be defined for task"): super().__init__(message) self.message = message class NoValidActionFoundException(Exception): def __init__(self, message="rule at least has to have one valid action"): ...
v = [int(input()) for x in range(20)] maior, menor = v[0], v[0] for i in range(20): if v[i] < menor: menor = v[i] elif v[i] > maior: maior = v[i] print(f'Menor: {menor}\nMaior: {maior}')
class MockMessage: def __init__( self, exchange=None, routing_key=None, queue=None): """__init__ :param exchange: mock exchange name :param routing_key: mock routing key :param queue: mock queue """ self.state = "NOTRU...
# 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 # Time Complexity: O(N), N is the number of nodes # Space Complexity: O(h), h is the height of the tree class Solution: ...
GMUSIC_EMAIL = 'g_email' GMUSIC_PASSWORD = 'g_password' SPOTIFY_CLIENT_ID = 'id' SPOTIFY_CLIENT_SECRET = 'secret' SPOTIFY_REDIRECT_URI = 'redirect' SPOTIFY_USER = 's_user'
class Term(object): literal = None def __init__(self, literal): self.literal = literal # Here be extensions (as per the task) def __eq__(self, other): if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ # Dictionary of class m...
# Operators a = 5 b = 7 r = a + b print("r:", r, type(r)) r = a * b print("r:", r, type(r)) r = a / b print("r:", r, type(r)) a = 2 * b r = a / b print("r:", r, type(r))
# Changing and adding Dictionary Elements my_dict = {'name': 'Nguyen Khang', 'age': 17} # update value my_dict['age'] = 18 #Output: {'name': 'Nguyen Khang', 'age': 18} print(my_dict) # add item my_dict['address'] = 'Ho Chi Minh' # Output: {'name': 'Nguyen Khang', 'age': 18, 'address': 'Ho Chi Minh'} print(my_dict)
class Solution: def exist(self, board: List[List[str]], word: str) -> bool: visited = set() for i in range(len(board)): for j in range(len(board[0])): if board[i][j] == word[0]: visited.add((i, j)) if self._dfs(board, word, 1, i, j,...
# MenuTitle: Enable Alignment for Selected Glyphs __doc__ = """ Enables automatic alignment for all components in all selected glyphs. """ thisFont = Glyphs.font # frontmost font listOfSelectedLayers = ( thisFont.selectedLayers ) # active layers of selected glyphs def process(thisLayer): for thisComp in ...
BRIGHTON = 2151001 sm.setSpeakerID(2151001) sm.sendNext("What is it?\r\n\r\n#L0##bI want to talk to you.") sm.sendNext("Well... I'm not really that good with words, you see... I'm not the best person to hang around with.")
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]: def dfs( node, par=None ): if no...
RAMSIZE=128 iochannel = CoramIoChannel(idx=0, datawidth=32) ram = CoramMemory(idx=0, datawidth=32, size=RAMSIZE, length=1, scattergather=False) channel = CoramChannel(idx=0, datawidth=32, size=16) def main(): sum = 0 addr = iochannel.read() read_size = iochannel.read() size = 0 while size < read_s...
# Copyright 2017 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, ...
class Animal(object): def run(self): print(self.__class__.__name__, ' is running...') class Dog(Animal): pass class Cat(Animal): pass dog = Dog() dog.run() cat = Cat() cat.run() print(isinstance(dog, Dog)) print(isinstance(dog, Animal)) print(isinstance(dog, Cat)) class Plant: def run(...
text = "Order: pizza, fries, milkshake" encoded = text.replace("pizza", "1").replace("fries", "2").replace("milkshake", "3") print(encoded) # Order: 1, 2, 3 codes = {"pizza": "1", "fries": "2", "milkshake": "3"} text = "Order: pizza, fries, milkshake" encoded = text for value, code in codes.items(): encoded = en...
def scan_dependencies(project, env, files): if 'USE_DEP_SCANNER' not in env.toolchain_options: with open(f'{project.build_dir}/skipped_files.txt', 'w') as out: out.write('none') return files deps = {f: [] for f in files} def strip_name(name): return name.split('/')...
# -*- coding: utf-8 -*- description = "Denex common detector setup" group = "lowlevel" includes = ["counter", "shutter", "detector_sinks"] tango_base = "tango://phys.maria.frm2:10000/maria/" devices = dict( full = device("nicos.devices.generic.RateChannel", description = "Full detector cts and rate", ...
# Arna risinajums 2. uzd pilnais my_text = input( "ievadiet tekstu (bez pieturzīmēm, lieliem/maziem burtiem nav nozīmes): ") if all(x.isalpha() or x.isspace() for x in my_text) and not my_text.isspace(): my_text = my_text.lower() hidden_text = "" for c in my_text: if c == " ": hidden...
# NAME AGE FUNCTION: def str_spaces(fstring,sstring): print(fstring + ' ' + sstring) mstring = input() nstring = input() str_spaces(mstring,nstring) def nage(string,string2): print(string,end=' ') print(string2,end='') nstr = input() astr = input() nage(nstr,astr) #REVERSE STRING 39: def revstr(fstri...
class GenericObj: def __init__(self, obj): self.type = obj['type'] self.id = obj['id'] self.uri = obj['uri'] self.tracks = obj['tracks'] class GenericAlbumObj: def __init__(self, album): self.id = album['id'] self.uri = album['uri'] self.name = album['na...
#: E201:5 spam( ham[1], {eggs: 2}) #: E201:9 spam(ham[ 1], {eggs: 2}) #: E201:14 spam(ham[1], { eggs: 2}) # Okay spam(ham[1], {eggs: 2}) #: E202:22 spam(ham[1], {eggs: 2} ) #: E202:21 spam(ham[1], {eggs: 2 }) #: E202:10 spam(ham[1 ], {eggs: 2}) # Okay spam(ham[1], {eggs: 2}) result = func( arg1='some value', ...
""" Base classes and utilities for TGN applications classes. @author yoram@ignissoft.com """ class TgnApp: """ Base class for all TGN applications classes. """ def __init__(self, logger, api_wrapper): self.logger = logger self.api = api_wrapper
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseKGroup(self, head: ListNode, k: int) -> ListNode: dummyhead = ListNode(None) dummyhead.next = head start, end = head, dummyhead ...
# OpenWeatherMap API Key weather_api_key = "164b9f7c3b721e89f1f4f14974c7b483" # Google API Key g_key = "AIzaSyAayBobFwssdE52dGXGCHY1_vddvDVUX34"
# # @author: pj4dev.mit@gmail.com # @desc: Positional Indexes Intersection # @comment: written in Python 2.7.x # @ref: http://nlp.stanford.edu/IR-book/html/htmledition/positional-indexes-1.html # def docID(plist): return plist[0] def position(plist): return plist[1] # p is a dollar list # dollar = [[1, [8,...
diasAlugados = int(input('Quantos dias alugados? ')) diasRodados = float(input('Quantos Km rodados? ')) dias = diasAlugados * 60 km = diasRodados * 0.15 pago = dias + km print(f'Preço R${pago:.2f}')
def duplicate_encode(word): #your code here b=[] word = word.lower() for char in word: if word.count(char) == 1: b.append('(') else: b.append(')') result = "".join(b) return result
#!/usr/bin/env python # # description: First Unique Character in a String # difficulty: Easy # leetcode_num: 387 # leetcode_url: https://leetcode.com/problems/first-unique-character-in-a-string/ # # Given a string s, return the first non-repeating character in it and return # its index. If it does not exist, return -1....
# !/usr/bin/python # -*- coding: utf-8 -*- """ 装饰器是一个很著名的设计模式,经常被用于有切面需求的场景,较为经典的有插入日志、性能测试、事务处理等。 装饰器是解决这类问题的绝佳设计,有了装饰器,我们就可以抽离出大量函数中与函数功能本身无关的雷同代码并继续重用。 概括的讲,装饰器的作用就是为已经存在的对象添加额外的功能 Python装饰器(decorator)在实现的时候,被装饰后的函数其实已经是另外一个函数了(函数名等函数属性会发生改变),为了不影响,Python的functools包中提供了一个叫wraps的decorator来消除这样的副作用。写一个decorator的时候,最...
def handler(context, inputs): greeting = "Hello, {0}!".format(inputs["target"]) print(greeting) outputs = { "greeting": greeting } return outputs
# # PySNMP MIB module WWP-LEOS-8021X-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WWP-LEOS-8021X-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:30:55 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, ...
""" Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None """ class Solution: """ @param: root: The root of the BST. @param: p: You need find the successor node of p. @return: Successor of p. ""...
def regEX(ref, char_comp): test_passed = True for i in ref: if i == char_comp: test_passed = False return test_passed
#desafio-038 num1 = int(input('Digite um numero inteiro: ')) num2 = int(input('Digite outro numero inteiro: ')) if num1 > num2: print('O primeiro é maior que o Segundo') elif num1 < num2: print('O Segundo é maior que o primeiro ') elif num1 == num2: print('Não existe valor maior os dois são iguais ') ...