content
stringlengths
7
1.05M
# pycrc -- parameterisable CRC calculation utility and C source code generator # # Copyright (c) 2017 Thomas Pircher <tehpeh-web@tty1.net> # # 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 Soft...
# -*- coding: utf-8 -*- """ Created on Fri Oct 12 13:16:08 2018 @author: Kenneth Collins """ """colRecoder2(dataFrame, colName, oldVal, newVal): requires: pandas dataFrame, colName must be the columns name (e.g. df.colName), not a string effects: returns a copy of the column. Does NOT mutate data. Thus must be assign...
fname = input('Enter a file name:') try : fhand = open('ch07\\' + fname) except : print('File cannot be opened:',fname) quit() for str in fhand : print(str.upper().rstrip()) try : fhand.close() except : pass
n = int(input()) total = 1 while n != 0: total *= n n -= 1 print(n) print(total)
""" # REMOVE NTH NODE FROM END OF LINKED LIST Given the head of a linked list, remove the nth node from the end of the list and return its head. Follow up: Could you do this in one pass? Example 1: Input: head = [1,2,3,4,5], n = 2 Output: [1,2,3,5] Example 2: Input: head = [1], n = 1 Output: [] Example 3: Inpu...
# 数据集存放目录 DATASET_DIR = '/tcdata' # 初赛训练集路径 PREM_TRAIN_SET_PATH = DATASET_DIR + '/track1_round1_train_20210222.csv' # 初赛A榜测试集路径 PREM_TEST_SET_A_PATH = DATASET_DIR + '/track1_round1_testA_20210222.csv' # 初赛B榜测试集路径 PREM_TEST_SET_B_PATH = DATASET_DIR + '/track1_round1_testB.csv' # 复赛训练集路径 SEMI_TRAIN_SET_PATH = DATASET...
#!/usr/bin/env python3 # @AUTHUR: Kingsley Nnaji <kingsley.nnaji@gmail.com> # @LICENCE: MIT # Creation Date: 02.09.2019 def fib(n): """ fib(number) -> number fib takes a number as an Argurment and returns the fibonacci value of that number >>> fib(8) -> 21 >>> fib(6) -> 8 >>> fib(0) -> 1 ""...
# Marcelo Campos de Medeiros # ADS UNIFIP # Exercicios Com Strings # https://wiki.python.org.br/ExerciciosComStrings ''' 6- Data por extenso. Faça um programa que solicite a data de nascimento (dd/mm/aaaa) do usuário e imprima a data com o nome do mês por extenso. Data de Nascimento: 29/10/1973 Você nasceu e...
def cool_string(s: str) -> bool: """ Let's call a string cool if it is formed only by Latin letters and no two lowercase and no two uppercase letters are in adjacent positions. Given a string, check if it is cool. """ string_without_whitespace = ''.join(s.split()) if string_without_whitespace....
# https://leetcode.com/problems/matrix-diagonal-sum/ class Solution: def diagonalSum(self, mat: List[List[int]]) -> int: res = 0 i, j = 0, 0 while (j < len(mat)): #print(i,j) res += mat[i][j] i += 1 j += 1 i, j = 0, len(m...
def test(): print('\nNON-NESTED BLOCK COMMENT EXAMPLE:') sample = ''' /** * Some comments * longer comments here that we can parse. * * Rahoo */ function subroutine() { a = /* inline comment */ b + c ; } /*/ <-- tricky comments */ /** * Another comment. */ function s...
# -*- coding: utf-8 -*- { 'name': 'Slides', 'version': '1.0', 'sequence': 145, 'summary': 'Share and Publish Videos, Presentations and Documents', 'category': 'Website', 'description': """ Share and Publish Videos, Presentations and Documents' ====================================================...
class Solution: def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: window = collections.deque() ans = [] for i, num in enumerate(nums): while window and num >= window[-1][0]: window.pop() window.append((num, i)) if i - window...
#Tuples - faster Lists you can't change friends = ['John','Michael','Terry','Eric','Graham'] friends_tuple = ('John','Michael','Terry','Eric','Graham') print(friends) print(friends_tuple) print(friends[2:4]) print(friends_tuple[2:4])
# Desenvolva uma lógica que leia o peso e a altura de uma pessoa, calcule o IMC e mostre, de acordo com a tabela abaixo: # Abaixo de 18.5: Abaixo do peso; # Entre 18.5 e 25: Peso ideal; # 25 até 30: Sobrepeso; # 30 até 40: Obesidade; # Acima de 40: Obesidade mórbida. peso = float(input('Informe seu peso: (kg) ')) altur...
#הפונקציה מדפיסה את כל המוצרים שאינם חוקיים # מוצר אינו חוקי אם אורכו קטן מ-3 או שהוא כולל תווים שאינם אותיות #משימה 7 def M_7(): items=input("Please Type What Do You Want to Buy: ") splittedItems=items.split(",") for x in splittedItems: length_item=len(x) if length_item > 3 and x.isalpha():...
t1 = 0 t2 = 1 print(f'{t1} -> {t2} -> ', end='') for c in range(1, 21): t3 = t1 + t2 print(f'{t3} -> ', end='') t1 = t2 t2 = t3 print('FIM', end='')
# COLORS = ['V', 'I', 'B', 'G', 'Y', 'O', 'R'] EMPTY = "-" # DIRS = np.array([(1, 0), (0, -1), (-1, 0), (0, 1)]) RIGHTMOST = -1 def is_color(board, x, y, color): if min(x, y) < 0: return False if x >= len(board): return False if y >= len(board[0]): return False if board[x][y] !...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Exercise 6: String Lists. Ask the user for a string and print out whether this string is a palindrome or not. (A palindrome is a string that reads the same forwards and backwards.) Credits: http://www.practicepython.org/exercise/2014/03/12/06-string-lists.html """ ...
def solveQuestion(inputPath, minValComp, maxValComp): fileP = open(inputPath, 'r') fileLines = fileP.readlines() fileP.close() botMoves = {} botValues = {} for line in fileLines: line = line.strip('\n') isLowOutput = False isHighOutput = False if line[:...
class Solution: def numSquares(self, n: int) -> int: marked = [False for _ in range(n)] queue = [(0, n)] while queue: level, top = queue.pop(0) level += 1 start = 1 while True: residue = top - start * start if re...
def Mergesort(arr): n= len(arr) if n > 1: mid = int(n/2) left = arr[0:mid] right = arr[mid:n] Mergesort(left) Mergesort(right) Merge(left, right, arr) def Merge(left, right, arr): i = 0 j = 0 k = 0 while i < len(left) an...
a = [5, 4, 8, 3, 4, 14, 90, 45, 9, 3, 2, 4] for i in range(len(a), 0, -1): for j in range(0, i - 1): if a[j] > a[j + 1]: a[j], a[j + 1] = a[j + 1], a[j] print(a)
# MEDIUM # find smallest x, largest x, draw a line to split those two value # store all points in to a set([]) # check if every point in set can be matched by mirroring the y axis class Solution: def isReflected(self, points: List[List[int]]) -> bool: print(max(points),min(points)) check = set([(...
def is_prime(num): if num <= 1: return False d = 2 while d * d <= num and num % d != 0: d += 1 return d * d > num
#encoding=utf8 # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # 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 requi...
c = 0 arr = [8,7,3,2,1,8,18,9,7,3,4] for i in range(len(arr)): if arr.count(i) == 1: c += 1 print(c)
# coding=UTF8 # Processamento for num in range(100, 201): if num % 2 > 0: print(num)
## https://leetcode.com/submissions/detail/230651834/ ## problem is to find the numbers between 1 and length of the ## array that aren't in the array. simple way to do that is to ## do the set difference between range(1, len(ar)+1) and the ## input numbers ## hits 98th percentile in terms of runtime, though only ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Math.py: Just a sample file with a function. This material is part of this post: http://raccoon.ninja/pt/dev-pt/python-importando-todos-os-arquivos-de-um-diretorio/ """ def calc_sum(a, b): return a + b
player_1_score = 0 player_2_score = 0 LOOP_UNTIL_USER_CHOOSES_TO_EXIT_AFTER_A_ROUND = True while LOOP_UNTIL_USER_CHOOSES_TO_EXIT_AFTER_A_ROUND: player_1_shape = input('[PLAYER 1]: Choose "rock", "paper", or "scissors": ') player_2_shape = input('[PLAYER 2]: Choose "rock", "paper", or "scissors": ') ROCK_S...
#isdecimal n1 = "947" print(n1.isdecimal()) # -- D1 n2 = "947 2" print(n2.isdecimal()) # -- D2 n3 = "abx123" print(n3.isdecimal()) # -- D3 n4 = "\u0034" print(n4.isdecimal()) # -- D4 n5 = "\u0038" print(n5.isdecimal()) # -- D5 n6 = "\u0041" print(n6.isdecimal()) # -- D6 n7 = "3.4" print(n7.isdecimal()) # -- D7 n8 = "#$...
""" Package collecting modules defining discretized operators for different grids. These operators can either be used directly or they are imported by the respective methods defined on fields and grids. .. autosummary:: :nosignatures: cartesian cylindrical polar spherical """ # Package-wide constan...
def memoize(f): storage = {} def wrapper(*args): key = tuple(args) if storage.has_key(key): return storage[key] else: result = f(*args) storage[key] = result return result return wrapper def test_memoize(): @memoize def sil...
# Fitur .append() print(">>> Fitur .append()") list_makanan = ['Gado-gado', 'Ayam Goreng', 'Rendang'] list_makanan.append('Ketoprak') print(list_makanan) # Fitur .clear() print(">>> Fitur .clear()") list_makanan = ['Gado-gado', 'Ayam Goreng', 'Rendang'] list_makanan.clear() print(list_makanan) # Fitur .copy() print(">>...
#!/usr/bin/python # coding=utf-8 class BasicGenerater(object): def __init__(self): self.first_name = 'Jack' self.last_name = 'Freeman' def my_name(self): print('.'.join((self.first_name, self.last_name))) def __del__(self): print("call del") class AdvaceGenerator(BasicGe...
# -*- coding: utf-8 -*- """ ----------Phenix Labs---------- Created on Fri Jan 29 15:42:01 2021 @author: Gyan Krishna Topic: reverse tuple """ tup =(10,20,30,40,50,60,) rev = tup[::-1] print("original tuple ::", tup) print("reversed tuple ::", rev)
class Solution: def change(self, amount, coins): dp = [0 for i in range(amount + 1)] # for amount 0, you can have 1 combination, do not include any coin dp[0] = 1 for coin in coins: for i in range(coin, amount + 1): # add i - coin dp value, the number of c...
class UI: def __init__(self): ''' ''' print('Welcome to calculator v1') def start(self, controller): ''' We ask the user for 2 numbers and add them. ''' print('Please enter number1') number1 = input() print('Please enter number2') number2 = input() result = control...
""" ID: goundsada LANG: PYTHON3 TASK: friday """ fin = open ('friday.in', 'r') fout = open ('friday.out', 'w') n = int(fin.readline().encode()) count = [0,0,0,0,0,0,0] daysInMonth = (31,28,31,30,31,30,31,31,30,31,30,31) day = 0 for i in range(n): for j in daysInMonth: count[day % 7] += 1 if (j == 2...
DEBUG = True TESTING = False MONGODB_SETTINGS = [{ 'host':'localhost', 'port':27017, 'db':'REALTIME_APP' }]
class Measurement: def __init__(self, x, result, elapsed, timeout_error, other_error): """ :type x: dict :type result: object :type elapsed: float :type timeout_error: bool """ if not isinstance(x, dict): raise TypeError('x should be a dictionary!') self._x = x self._result = result self._elapse...
# Week-11 Challenge 1 And Extra Challenge x = open("Week-11/Week-11-Challenge.txt", "r") print(x.read()) x.close() print("\n-*-*-*-*-*-*") print("-*-*-*-*-*-*") print("-*-*-*-*-*-*\n") y = open("Week-11/Week-11-Challenge.txt", "a") y.write("\nThe best way we learn anything is by practice and exercise questions ") y =...
""" TODO: Add model code for your resource here. You'll want to change the file name to whatever your resource is called. To add persistence to your models, use App Engine's Datastore if you anticipate scaling to a high amount of data or traffic. The Python NDB module adds caching and some other features to Datastore. ...
# # The MIT License (MIT) # # Copyright 2019 AT&T Intellectual Property. All other rights reserved. # # 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 l...
''' Note: This kata is inspired by Convert a Number to a String!. Try that one too. Description We need a function that can transform a string into a number. What ways of achieving this do you know? Note: Don't worry, all inputs will be strings, and every string is a perfectly valid representation of an integral numb...
print(-1) print(-0) print(-(6)) print(-(12*2)) print(- -10)
# Problem Statement: https://leetcode.com/problems/valid-anagram/ class Solution: def isAnagram(self, s: str, t: str) -> bool: if len(s) != len(t): return False else: letter_cnt = {} for letter in s: if not letter in letter_cnt: ...
# -*- coding: utf-8 -*- description = 'detectors' group = 'lowlevel' # is included by panda.py display_order = 70 excludes = ['qmesydaq'] tango_base = 'tango://phys.panda.frm2:10000/panda/' devices = dict( timer = device('nicos.devices.entangle.TimerChannel', tangodevice = tango_base + 'frmctr2/timer...
''' You can find this exercise at the following website: https://www.practicepython.org/ 10. List Overlap Comprehensions: This week’s exercise is going to be revisiting an old exercise (see Exercise 5), except require the solution in a different way. Take two lists, say for example these two: a = [1, 1, 2, 3, 5, 8...
# -*- coding: utf-8 -*- """ Created on Mon Sep 2 17:52:35 2019 @author: Sarthak """
expected_output = { "key_chains": { "bla": { "keys": { 1: { "accept_lifetime": { "end": "always valid", "is_valid": True, "start": "always valid", }, ...
# Challenge 3 : Write a function called delete_starting_evens() that has a parameter named lst. # The function should remove elements from the front of lst until the front of the list is not even. # The function should then return lst. # Date : Sun 07 Jun 2020 07:21:17 AM IST def de...
def test(n): i = 0 res = 0 while i < n: i = i + 1 print(res) test(100)
# Online Python compiler (interpreter) to run Python online. # Write Python 3 code in this online editor and run it. vegetables = ["rucula", "tomate", "lechuga", "acelga"]; print(vegetables); print(len(vegetables)); print(str(type(vegetables))); print('-'*10); print(vegetables[0]); # Elemento 0 print(vegetables[1:]...
class DashboardMixin(object): def getTitle(self): raise NotImplementedError("You must override this method in a child class.") def getContent(self): raise NotImplementedError("You must override this method in a child class.")
class Solution: def getSmallestString(self, n: int, k: int) -> str: def toChar(n): return chr(97 + n - 1) ans = [''] * n i = 0 while i < n: # how many spaces left to fill? left = n - i if k < left: # you got `left` spac...
def version(): if __grains__['os'] == 'eos': res = __salt__['napalm.pyeapi_run_commands']('show version') return res[0]['version'] else: return 'Not supported on this platform' def model(): if __grains__['os'] == 'eos': res = __salt__['napalm.pyeapi_run_commands']('show vers...
class Solution(object): def numTrees(self, n): """ :type n: int :rtype: int """ ## DP solution dp=[1,1]+[None for _ in range(n-1)] for x in range(2, n+1): t=0 for y in range(x): i=y j=x-1-y ...
class digested_sequence: def __init__(ds, sticky0, sticky1, sequence): # Both sticky ends (left and right, respectively) encoded based on sticky stranded alphabet with respect to top sequence. ds.sticky0 = sticky0 ds.sticky1 = sticky1 # Top sequence between two sticky ends ds.sequence = sequence
class Publication: def __init__(self, title, price): self.title = title self.price = price class Periodical(Publication): def __init__(self, title, publisher, price, period): Publication.__init__(self, title, price) self.period = period self.publisher = publisher clas...
def configurations(): return { "components": { "kvstore": False, "web": True, "indexing": False, "dmc": True } }
""" Problem:https://www.hackerrank.com/challenges/triangle-quest-2/problem Author: Eda AYDIN """ for i in range(1, int(input()) + 1): print(((10 ** i) // 9) ** 2)
#!/bin/python3 if __name__ == '__main__': n = int(input()) english = list(map(int, input().split(' '))) b = int(input()) french = list(map(int, input().split(' '))) students = set(english).difference(french) print(len(students))
""" Loop while General form; while bool_expression: //execute loop Repeat until bool expression is True bool expression is all expression where the result is True or False Sample: num = 5 num < 5 # False num > 5 # False # sample 1 number = 1 while number < 10: # 1, 2, 3, 4, 5, 6, 7, 8, 9 print(number...
class Ssh: def __init__(self,user,server,port,mode): self.user=user self.server=server self.port=port self.mode=mode @classmethod def fromconfig(cls, config): propbag={} for key, item in config: if key.strip()[0] == ";": continue ...
# Verifique o parênteses da expressão parenteses = list() aberto = list() fechado = list() expressao = input('Digite a expressão: ') for pos, val in enumerate(expressao): if val == '(': aberto.append(pos) elif val == ')': fechado.append(pos) if len(aberto) != len(fechado): print('Expressão ...
def extractLizonkanovelsWordpressCom(item): ''' Parser for 'lizonkanovels.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('bestial blade by priest', ...
def debug( content ): print( "[*] " + str(content) , flush=True) def bad( content ): print( "[-] " + str(content) , flush=True) def good( content ): print( "[+] " + str(content) , flush=True) # sample output: # [*] Gimme yo money # [-] Money taken by chad. # [+] Chad receives the money.
nome = input('Qual é o seu nome: ') print('Prazer em te conhecer {:20}!'.format(nome)) print('Prazer em te conhecer {:>20}!'.format(nome)) print('Prazer em te conhecer {:<20}!'.format(nome)) print('Prazer em te conhecer {:=^20}!'.format(nome)) n1 = float(input('Digite o primeiro número ')) n2 = float(input('Digite o s...
# API Error Codes AUTHORIZATION_FAILED = 5 # Invalid access token PERMISSION_IS_DENIED = 7 CAPTCHA_IS_NEEDED = 14 ACCESS_DENIED = 15 # No access to call this method INVALID_USER_ID = 113 # User deactivated class VkException(Exception): pass class VkAuthError(VkException): pass class VkA...
def read_ims_legacy(name): data = {} dls = [] #should read in .tex file infile = open(name + ".tex") instring = infile.read() ##instring = instring.replace(':description',' :citation') ## to be deprecated soon instring = unicode(instring,'utf-8') meta = {} metatxt = instri...
# encoding: utf-8 # module Grasshopper.Kernel.Geometry.ConvexHull calls itself ConvexHull # from Grasshopper,Version=1.0.0.20,Culture=neutral,PublicKeyToken=dda4f5ec2cd80803 # by generator 1.145 """ NamespaceTracker represent a CLS namespace. """ # no imports # no functions # classes class Solver(object): ...
first_line = input().split() second_line = input().split() third_line = input().split() board_list = [ first_line, second_line, third_line ] first = '1' second = '2' empty = '0' first_win = [first] * 3 second_win = [second] * 3 is_first_player = False is_second_player = False diagonal...
"""Exercício Python 4: Faça um programa que leia algo pelo teclado e mostre na tela o seu tipo primitivo e todas as informações possíveis sobre ele.""" n = input('Digite algo: ') print(f'O tipo primitivo desse valor é {type(n)}') print(f'Só tem espaços? {n.isspace()}') print(f'É um número? {n.isnumeric()}') print(f'É...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Ввести список А из 10 элементов. Определить количество элементов, кратных 3 и индексы #последнего такого элемента. if __name__ == '__main__': u = tuple(map(int, input('Введите 10 чисел -->').split(maxsplit=10))) s = 0 for i in u: if i % 3 ==...
try: count = int(input("Give me a number: ")) except ValueError: print("That's not a number!") else: print("Hi " * count)
#Codigo: Variaveis #Autora: Carla Edila Silveira #Finalidade: exemplo de parte do codigo de um jogo da forca - curso Python Quick Start #Data: 21/09/2021 #começo do jogo da forca tentativas = 10 #variavel representa quantidade total de tentativas do jogo print(tentativas) #jogador 2 faz 1a tentativa tentativas -= 1 #...
def parse_frame_message(msg:str): """ Parses a CAN message sent from the PCAN module over the serial bus Example: 't1234DEADBEEF' - standard (11-bit) identifier message frame 'R123456784' - extended (29-bit) identifier request frame Returns a tuple with type, ID, size, and message Ex...
""" News: main.py module """ def news_page_link(html_soup): """ Returns -> [str] link of news page. Params -> [requests.HTML object] HTML of web page. """ # Container div with all top news and p tag(at last) with more link news_div = html_soup.find("div#news_event", first=True) more_news_...
# -*- coding: utf-8 -*- ''' File name: code\long_products\sol_452.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #452 :: Long Products # # For more information see: # https://projecteuler.net/problem=452 # Problem Statement ''' Define ...
[ { 'date': '2018-01-01', 'description': 'Ano Novo', 'locale': 'pt-PT', 'notes': '', 'region': '', 'type': 'NF' }, { 'date': '2018-02-13', 'description': 'Carnaval', 'locale': 'pt-PT', 'notes': '', 'region': '', ...
""" Ex 27 - make a program that reads from the keyboard the first and last name of a person """ name = str(input('Type your full name:')).upper().strip() pri = name.find(' ') ult = name.rfind(' ') print(f'Your first name is: {name[:pri]}') print(f'Your last name is: {name[ult:]}') input('Enter to exit')
x = int(input()) dentro = fora = 0 for y in range(0, x, 1): num = int(input()) if num >= 10 and num <= 20: dentro += 1 else: fora += 1; print('{} in'.format(dentro)) print('{} out'.format(fora))
# # PySNMP MIB module NNCFRINTSTATISTICS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NNCFRINTSTATISTICS-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:23:02 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (d...
class StylusButtonEventArgs(StylusEventArgs): """ Provides data for the System.Windows.UIElement.StylusButtonDown and System.Windows.UIElement.StylusButtonUp events. StylusButtonEventArgs(stylusDevice: StylusDevice,timestamp: int,button: StylusButton) """ @staticmethod def __new__(self,stylusDevice,tim...
def betterSurround(st): st = list(st) if st[0]!= '+' and st[len(st)-1]!= '=': return False else: for i in range(0,len(st)): if st[i].isalpha(): if not (st[i-1]=='+' or st[i-1]=='=') and (st[i+1] == '+' or st[i+1] == '='): return false ...
for i in range(4): outfile = 'paramslist.txt' params = [0, 1, 2] with open(outfile, 'a+') as f: for param in params: f.write(str(param)) f.write(' ') f.write('\n')
def mye(level): if level < 1: raise Exception("Invalid level!") # 触发异常后,后面的代码就不会再执行 try: mye(0) # 触发异常 except Exception as err: print(1, err) else: print(2)
# ParPy: A python natural language # parser based on the one used # by Zork, for use in Python games # Copyright (c) Finn Lancaster 2021 # This file contains the BASE action words # accepted by the users program. For example # , take, move, etc. # ParPy handles similar entries and conversion # to program-accepted one...
config = { 'matrikkel_zip_files': [{ 'zip_name': 'Y:/kartdata/Matrikkeldata/SOSIuttrekk/07_Vestfold/0709_Larvik/UTM32_Euref89/Shape/32_Matrikkeldata_0709.zip', 'target_shape_prefix': '32_0709adresse_punkt' },{ 'zip_name': 'Y:/kartdata/Matrikkeldata/SOSIuttrekk/07_Vestfold/0706_Sandefjord/UTM32_Euref89/Shape/32_...
"""PatchmatchNet dataset module reference: https://github.com/FangjinhuaWang/PatchmatchNet """
# 606. 根据二叉树创建字符串 # # 20200801 # huao # 递归 # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def tree2str(self, t: TreeNode) -> str: if t == None: return "" if t.left ...
#!/usr/bin/env python class ColumnIdentifierError(Exception): """ Exception raised when the user supplies an invalid column identifier. """ def __init__(self, msg): self.msg = msg class XLSDataError(Exception): """ Exception raised when there is a problem converting XLS data. """ ...
''' Gets memory usage of Linux python process Tyson Jones, Nov 2017 tyson.jones@materials.ox.ac.uk ''' _FIELDS = ['VmRSS', 'VmHWM', 'VmSize', 'VmPeak'] def get_memory(): ''' returns the current and peak, real and virtual memories used by the calling linux python process, in Bytes ''' # read i...
class Time(): current_world = None current_time_step = None @staticmethod def get_current_world(): return Time.current_world @staticmethod def get_current_time_step(): return Time.current_time_step @staticmethod def reset(): Time.current_world = None Ti...
# Progressão aritimética (PA) é toda sequência númerica em que cada um de seus termos, # a partir do segundo, é igual ao anterior somado a uma CONSTANTE r, denominada razão da # progressão aritimética. Para descobrimos qual é a razão de uma PA, basta subtrairmos um # termo qualquer do seu antecessor. print('='*25) prin...
class InvalidPasswordException(Exception): pass class InvalidValueException(Exception): pass
class Graph: """ convert层继承Graph后,将数据放到__init__中之后,执行父类run方法,得到填充好的数据 """ def __init__(self): pass def get_graph(self): """ 根据传过来的参数找合适的图 """ pass def fill_graph(self): """ 拿到format后的数据,天道graph里面 """ pass def _get_dat...
# abrir y leer archivo f = open ('input.txt','r') mensaje = f.read() f.close() # almacenar los números en una lista list_numbers = mensaje.split('\n') list_numbers = list(map(int,list_numbers)) #print(list_numbers) increased = 0 for x in range(len(list_numbers)-3): previous = list_numbers[x] + list_...