content
stringlengths
7
1.05M
#usuário deve digitar uma expressão matemática que use parênteses. #o programa deve analisar se a expressão está com parênteses # abertos ou fechados na ordem correta. expressao = (str(input('Informe uma expressão matemática: '))) simbolos = [] for s in expressao: if s == '(': simbolos.append('(') eli...
# -------------------------------------- #! /usr/bin/python # File: 977. Squared of a Sorted Array.py # Author: Kimberly Gao # My solution: (Run time: 132ms) (from website) # Memory Usage: 15.6 MB class Solution: def _init_(self,name): self.name = name # Only for python. Using function sort() # W...
""" 问题描述:给定整数N,返回斐波那契数列的第N项 补充题目:给定整数N,代表台阶数,一次可以跨2个或者1个台阶,返回有多少种走法。 补充题目2:假设农场中成熟的母牛每年会生一头小母牛,而且永远不会死。第一年农场有1只成熟的母牛,从第二年开始, 母牛开始生小母牛。每只小母牛3年之后成熟又可以生小母牛。给定整数N,求出N年后牛的数量。 要求:对以上所有问题,实现时间复杂度为O(logN)的解法 """ # 由于数学能力和理解能力有限,这里给出O(N)的解法 class FBNZ: @classmethod def classic_question(cls, n): if n < 1: ...
class GameStatus: OPEN = 'OPEN' CLOSED = 'CLOSED' READY = 'READY' IN_PLAY = 'IN_PLAY' ENDED = 'ENDED' class Action: MOVE_UP = 'MOVE_UP' MOVE_LEFT = 'MOVE_LEFT' MOVE_DOWN = 'MOVE_DOWN' MOVE_RIGHT = 'MOVE_RIGHT' ATTACK_UP = 'ATTACK_UP' ATTACK_LEFT = 'ATTACK_LEFT' ATTACK_D...
__name__ = "restio" __version__ = "1.0.0b5" __author__ = "Eduardo Machado Starling" __email__ = "edmstar@gmail.com"
class Solution: #Function to remove a loop in the linked list. def removeLoop(self, head): ptr1 = head ptr2 = head while ptr2!=None and ptr2.next!=None: ptr1 = ptr1.next ptr2 = ptr2.next.next if ptr1 == ptr2 : self.delete_loop(head,ptr1...
class ConsoleGenerator: def print_tree(self, indent=0, depth=99): if depth > 0: print(" " * indent, str(self)) self.descend_tree(indent, depth) def descend_tree(self, indent=0, depth=99): # do descent here, other classes may overload this pass @staticmet...
"""BFS in Python.""" GRAPH = {"A": set(["B", "C", "E", "F"]), "B": set(["A", "C", "D"]), "C": set(["A", "B"]), "D": set(["B"]), "E": set(["B", "A"]), "F": set(["A"])} def bfs(graph, start): """Return visited nodes.""" visited = set() queue = [start] while ...
# # PySNMP MIB module HH3C-LswINF-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-LswINF-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:26:01 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27...
dt = 1/10 a = gamma.pdf( np.arange(0,10,dt), 2.5, 0 ) t = np.arange(0,10,dt) # what should go into the np.cumsum() function? v = np.cumsum(a*dt) # this just plots your velocity: with plt.xkcd(): plt.figure(figsize=(10,6)) plt.plot(t,a,label='acceleration [$m/s^2$]') plt.plot(t,v,label='velocity [$m/s$]') plt....
__author__ = "Manuel Escriche <mev@tid.es>" class BacklogIssuesModel: def __init__(self): self.__entryTypes = ('Epic', 'Feature', 'Story', 'Bug', 'WorkItem') self.longTermTypes = ('Epic',) self.midTermTypes = ('Feature',) self.shortTermTypes = ('Story','Bug','WorkItem') @proper...
# Gitlab-UI: Settings -> General # https://python-gitlab.readthedocs.io/en/stable/gl_objects/projects.html # https://docs.gitlab.com/ce/api/projects.html#edit-project def configure_project_general_settings(project): print("Configuring general project settings:", project.name) # Set whether merge requests can only ...
# Birthday Chocolate # Given an array of integers, find the number of subarrays of length k having sum s. # # https://www.hackerrank.com/challenges/the-birthday-bar/problem # def solve(n, s, d, m): # Complete this function return sum(1 for i in range(len(s) - m + 1) if sum(s[i:i + m]) == d) n = int(input()...
# Test changing propagated properties def test_public_propagation_from_project(data_builder, as_admin): """ Tests: - 'public' is a propagated property """ project = data_builder.create_project() session = data_builder.create_session() acquisition = data_builder.create_acquisition() p...
logFile = open("log.log", "r") #print("score time") #line = logFile.readline() #line = "line" i = 0 for line in logFile: i += 1 if (i % 1 != 0): # Rendering all points takes time in LaTeX, skip some continue words = line.split() score = words[0] time = words[2].replace("s", "") minutes...
{ "variables": { "gypkg_deps": [ # Place for `gypkg` dependencies "git://github.com/libuv/libuv@^1.7.0 => uv.gyp:libuv", ], }, "targets": [ { "target_name": "latetyper", "type": "executable", "dependencies": [ "<!@(gypkg deps <(gypkg_deps))", # Place for local depende...
grid = [] for r in range(20): row = [int(x) for x in input().split(' ')] grid.append(row) mx = 0 for i in range(20): for j in range(17): prod = grid[i][j] * grid[i][j+1] * grid[i][j+2] * grid[i][j+3] if prod > mx: mx = prod prod = grid[j][i] * grid[j+1][i] * grid[j+2][i]...
""" Immutable data structures. The classes in this module have the prefix 'immutable' to avoid confusion with the built-in ``frozenset``, which does not have any modification methods, even pure ones. """ class immutabledict(dict): """ An immutable version of ``dict``. Mutating syntax (``del d[k]``, ``d[...
def problem4_1(wordlist): print(wordlist) wordlist.sort(key=str.lower) print(wordlist) #firstline = ["Happy", "families", "are", "all", "alike;", "every", \ # "unhappy", "family", "is", "unhappy", "in", "its", "own", \ # "way.", "Leo Tolstoy", "Anna Karenina"] #problem4_1(firstline)
# 1346. Check If N and Its Double Exist # Runtime: 40 ms, faster than 98.82% of Python3 online submissions for Check If N and Its Double Exist. # Memory Usage: 14.4 MB, less than 9.05% of Python3 online submissions for Check If N and Its Double Exist. class Solution: def checkIfExist(self, arr: list[int]) -> bo...
class Subject: def __init__(self): self.observers = [] def attach(self, observer): if observer not in self.observers: self.observers.append(observer) def detach(self, observer): try: self.observers.remove(observer) except Exception as e: ...
class PropertyCheckResult: def __init__(self, name: str): self.name = name def __str__(self): return self.name def __repr__(self): return f"PropertyCheckResult({self.name})" def __invert__(self): if self == UNSAT: return SAT if self == SAT: ...
d=dict(one=1,two=2,three=3) print(d) '''for k in d: print(k,d[k]) for k in sorted(d.keys()): #isme key ki help se d[k] nikaalre h print(k,d[k]) for k,v in sorted(d.items()): #k and v(value) dono ek hi baar lene h to without dictionary help print(k,v) for v in sorted(d.values()): print(v)...
# # Copyright (c) 2017 Amit Green. All rights reserved. # @gem('Gem.ErrorNumber') def gem(): require_gem('Gem.Import') PythonErrorNumber = import_module('errno') export( 'ERROR_NO_ACCESS', PythonErrorNumber.EACCES, 'ERROR_NO_ENTRY', PythonErrorNumber.ENOENT, )
class colors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' WHITE = '\033[1;97m' def banner(): version = "0.6.0" githublink = "https://github.com/f0lg0/Oncogene" ...
cube = [] for value in range(1, 11): cube_value = value**3 cube.append(cube_value) print(cube)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 字符串 print(ord('A')) print(ord('中')) print(chr(66)) # 编码 print(b'\xe4\xb8\xad\xff'.decode('utf-8', errors='ignore')) # 占位符 print('%2d-%02d' % (3, 1)) print('%.2f' % 3.1415926) # 数字转字符串 print("azxvc" + str(1111)) print(max(80, 100, 1000))
#! python3 # __author__ = "YangJiaHao" # date: 2018/2/26 # Definition for an interval. class Interval: def __init__(self, s=0, e=0): self.start = s self.end = e class Solution: def merge(self, intervals): """ :type intervals: List[Interval] :rtype: List[Interval] ...
# We create an arr dp which hold max val till that point. At each i, max_val = max(dp[i-2] + nums[i], dp[i-1]) class Solution: def rob(self, nums: List[int]) -> int: if not nums: return 0 if len(nums)<2: return max(nums) dp = [0]*len(nums) ...
def to_pascal_case(string): return ''.join([w.title() for w in string.split('_')])
print(''' ******************************************************************************* | | | | _________|________________.=""_;=.______________|_____________________|_______ | | ,-"_,="" `"=.| | |_______________...
""" ********************************************************************************** Name: constants Purpose: Holds common constants used throughout the application ********************************************************************************** """ #------------------------------------ # HTTP Response codes #-...
# Approach 3 - Two Pointers # Time: O(n^2) # Space: O(1) class Solution: def threeSumSmaller(self, nums: List[int], target: int) -> int: nums.sort() total = 0 for i in range(len(nums)-1): total += self.twoSumSmaller(nums, i + 1, target - nums[i]) r...
#Exercício013 x = float(input('Qual o seu salário? ')) print('Se o seu salário é {:.2f} reais\nEntão com 15% de aumento você passará a ganhar {:.2f} reais'.format(x, x+x*15/100)) print('xD')
alien_0 = {'color': 'green', 'points': 5} print(alien_0) print(alien_0['color']) print(alien_0['points']) new_points = alien_0['points'] print("You just earned " + str(new_points) + " points!")
A = int(input()) B = int(input()) C = int(input()) X = int(input()) count = 0 for a in range(A+1): for b in range(B+1): for c in range(C+1): if 500*a + 100*b + 50*c == X: count +=1 print(count)
def test_model_piecewise(classifier, filename, batch_size): """ same as test_model but reads input file line by line Predict class labels of given data using the model learned. INPUTS: classifier_trained: object of MLP, the model learned by function "train_model". filename: file locat...
class Solution(object): def reverse(self,s): return s[::-1] def reverseWords(self, s): """ :type s: str :rtype: str """ strs = s.split(' ') strs = map(self.reverse, strs) return ' '.join(strs)
class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ head = 0 temp = "" tail = len(s) - 1 while head < tail: temp = s[head] s[head] = s[tail] s[tail] = tem...
""" Interface with Pleiades """ class Pleiades: def __init__(self): return
a, b, c = map(int, input().split()) numbers = [a, b, c] numbers.sort() print(" ".join(str(number) for number in numbers))
""" Dada uma lista numérica "nums", retorne true se ela possuir uma tamanho de pelo menos "1" e o seu primeiro elemento coincidir com o último. """ def same_first_last(nums): return len(nums) >= 1 and nums[0] == nums[-1] print(same_first_last([1, 2, 3, 1]))
def binarySearch(ar, n, key): lb = 0 ub = n while lb <= ub: mid = int((lb + ub) / 2) if ar[mid] == key: return mid if ar[mid] > key: ub = mid - 1 else: lb = mid + 1 print('!!Value Not Found!!') return -1 # Test Code ar = [1, 4, 6...
#MAIN PROGRAM STARTS HERE: num = int(input('Enter the number of rows and columns for the square: ')) for x in range(num, 0, -1): for y in range(num, 0, -1): print ('%d ' % (y), end='') print()
def validBraces(string): while len(string) !=0: if '{}' in string or '[]' in string or '()' in string: string = string.replace('{}','').replace('()','').replace('[]','') else: return False return True
""" Tools to work with the webhooks data files. A copy of those data files is expected at the `openedx_webhooks.info.DATA_FILES_URL_BASE` location. """
def resolve(): ''' code here ''' N, M = [int(item) for item in input().split()] As = [[int(item) for item in input().split()] for _ in range(N)] memo = [0 for _ in range(M+1)] for k, *items in As: for item in items: memo[item] += 1 res = 0 for item in memo: ...
class CHaserException(Exception): """例外の基底クラス """ class GameFinished(CHaserException): """ゲーム終了 """
noc_config = [ ["c", "c"], ["c", "c"], ["n", "v"], #["c", "n"], ]
class Thing: def __init__(self, primary_noun, countable=True): self.primary_noun = primary_noun self.countable = countable class Container(Thing): def __init__(self, primary_noun, countable=True, preposition="on"): super().__init__(primary_noun, countable) self.preposition = pre...
# loops over all collection data, converts to true if collection - false if not part of collection def collection_to_boolean(data_frame): # Data should be available as str (see Kaggle Webpage) data_frame.belongs_to_collection = data_frame.belongs_to_collection.astype(str) # Looping over Data to convert to...
# ********************************* # Projet NSI : JEU DU PUISSANCE 4 # ********************************* # -------------------------------------- # -------- INITIALISATION -------------- # -------------------------------------- # Variables GLOBALE (pourront être utilisées à l'intérieur de toutes nos fon...
"""Modulo node.""" class Node: """Gerencia items da fila.""" def __init__(self, data): self.data = data self.next = None
#var 1 div1 = [num for num in range(1, 11) if num % 2 != 0 and num % 3 != 0] print(f"Not divisible by 2 and 3: {div1}") div2 = [num for num in range(1, 11) if num % 2 == 0] print(f"Divisible by 2: {div2}") div3 = [num for num in range (1, 11) if num % 3 == 0] print(f"Divisible by 3: {div3}") input() #var 2 for num i...
"""complex-valued trig functions adapted from SciPy's cython code: https://github.com/scipy/scipy/blob/master/scipy/special/_trig.pxd Note: The CUDA Math library defines the real-valued cospi, sinpi """ csinpi_definition = """ #include <cupy/math_constants.h> // Compute sin(pi*z) for complex arguments __device__ ...
pkgname = "traceroute" pkgver = "2.1.0" pkgrel = 0 build_style = "makefile" make_cmd = "gmake" make_build_args = ["prefix=/usr"] make_install_args = ["prefix=/usr"] hostmakedepends = ["gmake"] makedepends = ["linux-headers"] pkgdesc = "Traces the route taken by packets over an IPv4/IPv6 network" maintainer = "q66 <q66@...
# n = float(input('Digite um valor: ')) # n = str(input('Digite um valor: ')) # n = bool(input('Digite um valor: ')) # se tiver valor == True se não tiver == False n = input('Digite algo: ') # print(n.isnumeric()) # é numero? # print(n.isalpha()) # é letra? # print(n.isalnum()) # é numero ou letra? # print(n.isupper()...
a=int(input("enter the element")) b=int(input("enter the element")) c=int(input("enter the element")) n1=[] n2=[] n3=[] n1.append(a) n2.append(b) n3.append(c) if n1>n2 and n1>n3: print(n1,"maximum") elif n2>n1 and n2>n3: print(n2,"maximum") else: print(n3,"maximum")
# -*- coding: utf-8 -*- class FinicityConnectTypeEnum(object): """Implementation of the 'Finicity Connect Type' enum. TODO: type enum description here. Attributes: AGGREGATION: Aggregation Only - Used by PFM (Personal Financial Management) partners to grant access to a cust...
# Parameter로 받은걸 모두 더해주는 `sum`함수를 만들어라. # Parameter로 받은 모든걸? # 일단 리스트로 구현방법 def sum(number_list): total = 0 for i in number_list: total += i return total # 흠..리스트는 알겠는데 파라미터가 가변적이면? # e.g) sum(1, 2, 3) sum(1, 2, 4, 7) # unnamed => *args(tuple) => argument(args) def sum(*args): total = 0 fo...
{ 'name': 'test installation of data module', 'description': 'Test data module (see test_data_module) installation', 'version': '0.0.1', 'category': 'Hidden/Tests', 'sequence': 10, }
"""Functionality for computing the error between exact and approximate values.""" def absolute_error(x0, x): """ Compute absolute error between a value `x` and its expected value `x0`. :param x0: Expected value. :param x: Actual value. :return: Absolute error between the actual and expected value...
class Solution: @staticmethod def longest_palindromic(self, s: str) -> str: # Instead of taking the left and right edges of the string # We will start in the middle of the string # Making base function to help us in the method and pass in 'l' and 'r' parameters def baseFun ...
# model settings norm_cfg = dict(type='GN', num_groups=32, requires_grad=True) model = dict( type='CFADetector', pretrained='torchvision://resnet50', backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dic...
# -*- coding: utf-8 -*- class BaseContext: headers = {} def __init__(self, **kwargs): self.headers = {} def on_auth(self): pass def update_authkey(self, authkey): pass def set_authkey(self, authkey): self.headers["X-Authorization-Update"] = "Bearer {0}".format(a...
class BaseDeDados: def __init__(self):#init eh o mais proximo de um construtor e vamos adicionar ao dicionario o banco de dados self.dados = {} def inserir_cliente(self, id, nome): if 'clientes' not in self.dados:#se a informacao nao tiver na base de dados self.dados['clientes'] = {...
def langInit(jsonDir,json): fop=open(jsonDir,'r') lang=fop.read() fop.close() lang=json.loads(lang) #print(lang) return lang
class Solution: def combinationSum(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ def dfs(idx, csum): record.append(None) for i in range(idx, len(candidates)): record[-1...
# Entrada de dados anos = int(input('Qual a sua idade anos? ')) meses = anos * 12 dias = anos * 365 # Saída de dados print(f'Sua idade em dias é: {dias}')
class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ row, col = len(board), len(board[0]) def dfs(i, j): nonlocal row, col, board if i < 0 or i >= row or j < 0 or j >= ...
# Copyright 2018 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
# -*- coding: utf-8 -*- """ Created on Sat Aug 02 05:35:25 2014 @author: perez """ ## # MongoDB config config_mongoURI = 'mongodb://localhost:27017/' config_db_name = 'test_database' ## # Meteo API config config_openWeatherMapAPIKey = '53c2d72826f2215d60c154f657ddb923'
# closure Example def counter(n): def next(): nonlocal n r = n n -= 1 # print(next.__globals__) print(type(next.__globals__)) for val in next.__globals__: print(type(val), val) return r return next next = counter(10) print(next()) # print(...
TEXTO_PRINCIPAL = 'FonoaudiologaBot 🤖 es una robot que colabora optimizando el tiempo en el cálculo de desviaciones ' \ 'estándar, percentiles y puntajes en distintas pruebas.' \ ' Conoce como apoyar el desarrollo del proyecto en /apoyar\n\n' \ 'Las pruebas incluid...
# -*- coding: utf-8 -*- def fence_format(fence): """ 格式化经纬度坐标 lon1,lat1,lon2,lat2…… to [[lon1,lat1],[lon2,lat2]……] :param fence: :return: """ points = [] fence_list = fence.split(",") for i in range(len(fence_list))[::2]: points.append([float(fence_list[i]), float(fence_lis...
# # PySNMP MIB module IF-CAP-STACK-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IF-CAP-STACK-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:53:07 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar ...
# # PySNMP MIB module Nortel-MsCarrier-MscPassport-TrunksMIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-MsCarrier-MscPassport-TrunksMIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:19:50 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4...
class Solution: def findLatestStep(self, arr: List[int], m: int) -> int: n = len(arr) parent, size, result, bitsArray, count = [x for x in range(n)], [1] * n, -1, [0] * n, Counter() def find(x): if parent[x] == x: return x else: ...
def ask_name(): name = input("Write your name: ") return name def go_through(name): for i in name: print(i) print("\n") def go_Through_(name): for i in name: print(i.upper()) print("\n") def run(): n = ask_name() go_through(n) go_Through_(n) if __name__ =...
frase = str(input('Digite uma frase: ')).strip().upper() #strip elimina os espaços antes e depois da frase palavras = frase.split()#splitei para gerar uma lista( vetor) junto=''.join(palavras)# juntei alista para eliminar o epaços antes inverso = '' for letra in range(len(junto)-1,-1,-1): # usei o len para ir da ultima...
class Solution(object): def findLUSlength(self, strs): """ :type strs: List[str] :rtype: int """
# 2. Exercício Treino - # Crie um dicionário em que suas chaves correspondem # a números inteiros entre [1, 10] e cada valor associado é # o número ao quadrado. # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100} dicio = dict() or {1: None, 2: None, 3: None, 4: None, 5: None, 6: None,...
def generate_exclusion_list(hls_input_file,exclusion_list_file): file_lines = [] with open(hls_input_file,'r') as input_file: file_lines = input_file.readlines() r_list = [] with open(hls_input_file,'w') as clean_code: for i,x in enumerate(file_lines): if "@" in x: ...
# Easy # https://leetcode.com/problems/same-tree/ # 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) # Space Complexity: O(tree height) class Solutio...
# -*- coding: utf-8 -*- """ Auto-generated file 2022-04-22 09:25:28 UTC Resource: https://github.com/google/libphonenumber v8.12.47 """ PATTERNS = { "info": "libphonenumber v8.12.47", "data": { "AC": { "code": "247", "pattern": "((6[2-467][\\d]{3}))", "mobile": "((4...
stack = [] def isEmpty(stack): if stack == []: return True else: return False def push(stack): item = int(input("enter value")) stack.append(item) top = len(stack)-1 def pop(stack): if isEmpty(stack): print("underflow") else: item=stack.pop()...
"""515 · Paint House""" class Solution: """ @param costs: n x 3 cost matrix @return: An integer, the minimum cost to paint all houses """ def minCost(self, costs): # write your code here if not costs: return 0 m = len(costs) dp = [[0] * 3 for _ in range(m)...
class PyVEXError(Exception): pass class SkipStatementsError(PyVEXError): pass # # Exceptions and notifications that post-processors can raise # class LiftingException(Exception): pass class NeedStatementsNotification(LiftingException): """ A post-processor may raise a NeedStatementsNotifica...
#coding: latin1 #< full class CYKParser: def __init__(self, P: "IList<(str, str) or (str)>", S: "str", createMap: "IList<(str, str), int -> IMap<int, int, str>"=lambda P, n: dict()): self.P, self.S = P, S self.createMap = createMap def accepts(self, x: "str") -> "boo...
class Solution: def moveZeroes(self, nums: List[int]) -> None: z = 0 for i in range(1, len(nums)): if nums[i] != 0 and nums[z] == 0: nums[i], nums[z] = nums[z], nums[i] if nums[z] != 0: z += 1
#Victor Gabriel Castão da Cruz #11911ECP004 #Função que analisará as sequências def analise(matriz, C): #Identificar quantidade de linhas e colunas linhas = len(matriz) colunas = len(matriz[0]) #Lista que armazenará a quantidade de palitos de tamanho equivalente ao índice da lista comprimentos = ...
# problem 18 # Project Euler __author__ = 'Libao Jin' __date__ = 'July 17, 2015' string = ''' 75 95 64 17 47 82 18 35 87 10 20 04 82 47 65 19 01 23 75 03 34 88 02 77 73 07 63 67 99 65 04 28 06 16 70 92 41 41 26 56 83 40 80 70 33 41 48 72 33 47 32 37 16 94 29 53 71 44 65 25 43 91 52 97 51 14 70 11 33 28 77 73 17 78 39...
class MockCache(object): """ Simple cache to use for mocking Memcached """ def __init__(self): super(MockCache, self).__init__() self._cache = {} def set(self, k, v): self._cache[k] = v return True def get(self, k, default=None): return self._cache.get(k...
# File: T (Python 2.4) SKY_OFF = 0 SKY_LAST = 1 SKY_DAWN = 2 SKY_DAY = 3 SKY_DUSK = 4 SKY_NIGHT = 5 SKY_STARS = 6 SKY_HALLOWEEN = 7 SKY_SWAMP = 8 SKY_INVASION = 9 SKY_OVERCAST = 10 SKY_OVERCASTNIGHT = 11 SKY_CODES = { SKY_OFF: 'SKY_OFF', SKY_LAST: 'SKY_LAST', SKY_DAWN: 'SKY_DAWN', SKY_DAY: 'SKY_DAY', ...
LANG_LABEL_TO_SV = { "Swedish": "svenska", "Finland Swedish": "finlandssvenska", "Somali": "somaliska", "Faroese": "färöiska", "Old Norse": "fornnordiska", "Belarussian": "vitryska", "Bulgarian": "bulgariska", "Croatian": "kroatiska", "Czech": "tjeckiska", "Danish": "danska", ...
def main(): with open('triangles.txt') as f: lines = f.read().splitlines() counts = 0 for line in lines: points = line.split(',') points = [int(point) for point in points] A = points[:2] B = points[2:4] C = points[4:] P = (0, 0) if area(A, B, ...
# All system and subsystem related data info available_systems = ["ele", "mec"] electric_subsystems = { "bat": {"name": "Baterias", "worksheet_id": 447316715}, "pt": {"name": "Powertrain", "worksheet_id": 1129194817}, "hw": {"name": "Hardware", "worksheet_id": 1556464449}, "sw": {"name": "Software", "w...
# SinglyLinkedListNode: # int data # SinglyLinkedListNode next # # def findMergeNode(head1, head2): # the data on the linked list nodes might not be unique # we can't rely on just checking the data in each node # as with any node-based data structure, each node is a unique # region in memory ...
test = { 'name': '', 'points': 1, 'suites': [ { 'cases': [ { 'code': r""" >>> # Make sure your column labels are correct >>> estimates.labels == ('min estimate', 'mean-based estimate') True """, 'hidden': False, 'locked': Fal...
# -*- coding: utf-8 -*- r = range(0, 4) # 生成列表[0,1,2,3] for x in r: # 利用for循环来访问 print(x) print("List : ", list(range(0, 6, 2))) # 利用list()将range转为列表对象 print("Tuple : ", tuple(range(2, 9, 3))) # 利用tuple()将range转为元组对象 def func(i): """ :param i: :return: """ return i * i ...