content
stringlengths
7
1.05M
__author__ = 'Chirag' text = "" file_name = input("Please provide a file name : ") # "fileWriteDemo1.txt" try: my_file = open(file_name, 'r') except IOError: print("cannot open ", file_name) else: lines = my_file.readlines() # list of individual lines for line_num, line in enumerate(lines): print(f"{line_nu...
class Selector: def __init__(self, options): self._index = 0 self._options = options self._option_pad = 16 for option in options: if len(option) + 7 > self._option_pad: self._option_pad = len(option) + 7 def cursor_left(self): self._index = (self._index - 1) % len(self._options)...
class EndpointException(Exception): pass
__author__ = 'Chirag' """ just like raise, assert is used to raise an AssertionError when certain conditions are not met usually it to 'assert' inputs are of a certain kind and if they are not. An Exception is raised""" def avg(grades): assert not len(grades) == 0 return sum(grades)/len(grades) print(avg([14, 17...
def iswinner(board, piece: str) -> int: """ piece - string - Either an "X" or "O" Checks if win conditions are met. Could check only relevant squares but not as readable. """ # Checks each row, then each col, and then the diagonals for line in [[x + 3 * y for x in range(3)] for y in range(3)...
stylesheet = """ QPushButton{ border :2px solid ; border-radius: 10; border-color : qlineargradient( x1:0 y1:0, x2:1 y2:0, stop:0 #d60cf0, stop:1 #9a08ed); color: qlineargradient( x1:0 y1:0, x2:1 y2:0, stop:0 #d60cf0, stop:1 #9a08ed); font-size: 20px; font-weight: bold; } QPushButton:pressed...
name = input("Your name: ") print ('hi',name) print('Enter only numbers') print('Enter a value') y = input('y: ') print('Thank you enter value 2') x = input('x: ') sum = int(x) + int(y) print('Answer', sum) print("thank you for using this bot") print("produced by 1to5PC")
# Funções aprofundadas em Python '''Reescreva a função leiaint() que fizemos no ex104 (que está no pacote uteis, módulo dados), incluindo agora a possibilidade da digitação de um número de tipo inválido. Aproveite e crie também uma função leiafloat() com a mesma funcionalidade''' def leiaint(msg): while True: ...
class Solution: def numberOfPatterns(self, m, n): """ :type m: int :type n: int :rtype: int """ skip = [[0] * 10 for _ in range(10)] skip[1][3] = skip[3][1] = 2 skip[1][7] = skip[7][1] = 4 skip[3][9] = skip[9][3] = 6 skip[7][9] = skip[9...
#put the radius number r=float(input("Radius: ")) A=3.14*r*r print(A)
""" our task is to make a function that can take any non-negative integer as a argument and return it with its digits in descending order. Essentially, rearrange the digits to create the highest possible number. Examples: Input: 21445 Output: 54421 Input: 145263 Output: 654321 Input: 1254859723 Output: 9875543221 "...
class BadRequestError(Exception): pass class ServerError(Exception): code = 500 message = "Server error." def __init__(self): super().__init__({"code": self.code, "message": self.message}) class EmailAlreadyExist(BadRequestError): code = 422 message = "Email already exist." def...
def str_to_int(input_str): output_int = 0 if input_str[0] == '-': start_idx = 1 is_negative = True else: start_idx = 0 is_negative = False for i in range(start_idx, len(input_str)): place = 10 ** (len(input_str) - (i + 1)) digit = ord(input_str[i]) - ord...
# # PySNMP MIB module ALCATEL-IND1-NTP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ALCATEL-IND1-NTP-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:18:42 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (defau...
# codingrooms.com assignments EXcercise 03 print(''' codingrooms.com assignments EXcercise 03 Create a program using maths and f-Strings that tells us how many days, weeks, months we have left if we live until 90 years old. It will take your current age as the input and output a mes...
# Essa classe representa um requisito atômico, isto é, # um requisito que não depende de outros requisitos. class Requirement(): def __init__(self): self._dados = None self._nome = None def dados(self): return self._dados def nome(self): return self._nome
for num in range(2,50): for x in range(2,num): if num % x == 0: print(str(num)+ 'not prime') break else: print(str(num) + 'prime')
""" Dicionários """ """ parte 1 dicionario = {1: 'Valor 1', 2: 'Valor 2', 3: 'Valor3'} dicionario['str'] = 'valor' dicionario['1'] = 'Agora existe' if dicionario.get('str') is not None: # Retorna um valor none, mas como existe nn retorna um valor None print(dicionario.get('str')) print(dicionario) del dicionario['...
expected_output = { "tunnel": { "150.0.5.1": { "remote": { "150.0.0.1": { "src_port": 12346, "dst_port": 12346, "ipsec": { "ipsec_decrypt_inbound": 0, "ipsec_rx_auth_failu...
# functions def blow(time): cnt = 0 for s in staff: cnt += time // s return cnt # input n, m = map(int, input().split()) staff = tuple(map(int, input().split())) # process ''' 시간 최소 >> bisect_left의 원리 x분 동안 k개의 풍선을 만든다고 할 때 k >= M: x를 줄여야 함. k < M: x를 늘려야 함. right := 가장 빨리 부는 사람이 혼자 다 불 때 걸리는 시간 ''' left = 1 righ...
""" Title: 347. Top K Frequent Elements 347. 前 K 个高频元素 Address: https://leetcode-cn.com/problems/top-k-frequent-elements/ """ class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: dic = dict() for num in nums: dic.setdefault(num, 0) dic[n...
# Inner Functions def parent(num): def first_child(): return "First Child" def second_child(): return "Second Child" if num == 1: # Return a reference to the inner function first_child return first_child else: return second_child first = parent(1) second = pa...
# Display the Properties content print (P4DProps) # Get single property print (P4DProps.Value['date1']) print (P4DProps.Value['date2']) print (P4DProps.Value['date3']) # Put single property P4DProps.Value['date1'] = ["01.01.2017",""] P4DProps.Value['date2'] = ["","31.12.2017"] P4DProps.Value['date3'] = ["01.01.2017","...
{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "id_final 21743\n" ] } ], "source": [ "from SimpleGraphics import *\n", "from quantum_rules import *\n", "from ...
''' All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA. Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. Exam...
""" Crie um programa que leia vários números inteiros pelo teclado. O programa só vai parar quanto o usuário digitar o valor 999, que é a condição de parada. No final mostre quantos números foram digitados e qual foi a soma entre eles. (Desconsiderando o flag) """ contador_de_vezes_o_usuario_digitou = 0 conta...
# -*- coding: utf-8 -*- INPUT = (2959251, 4542595) def calculate_loop_size(public_key): """ >>> calculate_loop_size(5764801) 8 >>> calculate_loop_size(17807724) 11 """ subject_number = 7 value = 1 loop_size = 0 while value != public_key: value *= subject_number ...
#ParentesisValido.py def parentesisValido (cadena) : # Comprueba los pares de parentesis validos que abren y cierran # Devuelve el numero de parentesis sobrantes stack =[] for val in cadena: if val == ")": if len(stack) != 0 and stack[-1] == "(": stack.pop...
#__variables__ # Simple propositional conditions: never_count = ( 'LET', 'SPEC', 'TSW', 'VZ(fin', 'VNW(pers,pron,nomin', 'VNW(vb,pron,stan', 'VNW(pers,pron,stan', 'VNW(recip,pron,dial)', 'VNW(pers,pron,dial', 'VNW(recip,pron,obl', 'VNW(pers,pron,obl', 'VNW(pr', 'VNW(aanw,pron,stan', 'VNW(refl', ...
class Solution: def removeDuplicates(self, nums: [int]) -> int: if(len(nums)<=2):return len(nums) i=2 a=2 while(i<len(nums)): if nums[i]!=nums[a-2]: nums[a]=nums[i] a=a+1 i=i+1 return a
# -*- coding:utf-8 -*- class ChinaMacroItem(object): def __init__(self, site_name, site_sort, content): self.site_name = site_name self.site_sort = site_sort self.content = content def __str__(self): return f"sitename:{self.site_name},sitesort:{self.site_sort},content:{self.cont...
# Base Classes class SRWDiagnostic (Exception): """ Base Diagnostic Class""" code = 0 description = "" details = "" surrogate = 0 fatal = 1 def __str__(self): return "%d [%s]: %s" % (self.code, self.description, self.details) class GeneralDiagnostic (SRWDiagnostic): pass cl...
givenString = str.lower(input("Enter a string:")) vowels = ['a', 'e', 'i', 'o', 'u'] vowelcount = 0 for character in givenString: if character in vowels: vowelcount += 1 print("The given string has "+ str(vowelcount) + " vowels")
# Do not edit this file! # VUID ranges reserved for branches # Key is branch name, value is [ start, end, nextfree ] vuidCounts = { 'branch-vuids': [ 4000, 4999, 4052 ], 'devel': [ 3000, 3999, 3570 ], 'master': [ 4000, 4999, 4052 ], }
r1 = float(input('Primeira reta: ')) r2 = float(input('Segunda reta: ')) r3 = float(input('Terceira reta: ')) if (r2-r3) < r1 < (r2+r3) and (r1-r3) < r2 < (r1+r3) and (r1-r2) < r3 < (r1+r2): print('As três retas PODEM formar um triângulo.') else: print('As três retas NÃO PODEM forma um triângulo')
state = {"verbose": False} def main(verbose: bool = False): """ Manage container images """ if verbose: state["verbose"] = True
# -*- coding: utf-8 -*- # @Time : 2020/1/30 0030 16:56 # @Author : Erichym # @Email : 951523291@qq.com # @File : 400.py # @Software: PyCharm """ 在无限的整数序列 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...中找到第 n 个数字。 注意: n 是正数且在32为整形范围内 ( n < 2^31)。 示例 1: 输入: 3 输出: 3 示例 2: 输入: 11 输出: 0 说明:...
# Python program to find the sum of natural numbers up to n where n is provided by user # change this value for a different result num = 160 # uncomment to take input from the user #num = int(input("Enter a number: ")) if num < 0: print("Enter a positive number") else: sum = 0 # use while loop t...
def subsequences(L,n): return [L[i:i+n] for i in range(len(L)-n+1)] def sumallsubsqn(L): New = [] for n in range(1,len(L)+1): N = (subsequences(L,n)) for i in N: New.append(i) C = [] for i in New: C.append(sum(i)) return C def...
class Activity(dict): fields = [ 'start_index', 'distance', "moving_time", "elapsed_time", "average_watts", "min_watts", "max_watts", "average_watts_kg", "max_watts_kg", "intensity", "w5s_variability", "weighted_average_...
__author__ = 'daniel' class TrialJob: def __init__(self): self.real_time = 1 self.core_affinity = 1 self.reps = 1 class EchoTrialJob(TrialJob): def __init__(self): TrialJob.__init__(self) # in nanoseconds (for now :-/) self.delay = 100 self.target_host...
class Publisher(object): def publish(self, payload): raise NotImplemented def read(self, buffer): raise NotImplemented
# Source : https://leetcode.com/problems/serialize-and-deserialize-binary-tree/ # Author : henrytine # Date : 2020-08-18 ##################################################################################################### # # Serialization is the process of converting a data structure or object into a sequence of ...
""" A module providing a class for playing cards This implementation is adapted from chapter 18 of the course text, _Think Python_, by Allen B. Downey. Authors: Walker White (wmw2), Steve Marschner (srm2), and Lillian Lee (ljl2) Date: October 20, 2019 """ class Card(object): """ A class to represent a st...
# Refaça o DESAFIO 009, mostrando a tabuada de um número que o usuário escolher, só que agora utilizando um laço for. n = int(input('Digite um número inteiro qualquer: ')) for c in range(1, 11): print('{} x {} = {}'.format(n, c, n*c))
age = int(input()) yleft= 90 -age days = yleft*365 weeks = yleft*52 month= yleft*12 print(f"you have left {days} {weeks} {month}")
def update_field(raw_message, flag, new_value, SOH="\x01"): msg_fields = raw_message.split(SOH) for i, field in enumerate(msg_fields): if field.startswith(flag + "="): msg_fields[i] = flag + "=" + str(new_value) break new_message = SOH.join(msg_fields) return new_messag...
def listToString(alist2): alist = [str(x) for x in alist2] s = '' for i in range(len(alist)): if i != len(alist)-1: s += alist[i] + ", " else: s += "and " + alist[i] print(s)
soma = 0 for num in range(0, 10): soma += num print('Soma atual: ', soma) print('Soma final: ', soma)
# http://codingbat.com/prob/p148853 def extra_end(str): return str[-2:] + str[-2:] + str[-2:]
class TestLogin: def test_login1(self): assert 2 def test_login2(self): assert 2 def test_login3(self): assert 2
# Create a class called Account. Upon initialization, it should receive an id (number), a name (string), and a balance # (integer; optional; 0 by default). The class should also have 3 additional instance methods: # - credit(amount) - adds the amount to the balance and returns the new balance # - debit(amount) - if the...
__version__ = "0.7" __title__ = "foodme_eval" __description__ = "Run evaluation from FooDMe" __author__ = "Gregoire Denay" __author_email__ = 'gregoire.denay@cvua-rrw.de' __licence__ = 'BSD License'
"""This problem was asked by Facebook. Given a string consisting of parentheses, single digits, and positive and negative signs, convert the string into a mathematical expression to obtain the answer. Don't use eval or a similar built-in parser. For example, given '-1 + (2 + 3)', you should return 4. """
# # @lc app=leetcode id=60 lang=python3 # # [60] Permutation Sequence # # @lc code=start class Solution: def getPermutation(self, n: int, k: int) -> str: fac = [1] for i in range(1, n): fac.append(fac[-1] * i) # a list [1, 1, 2, 6..., (n-1)!] res = '' nums = list(ran...
OnEp = input("Δώσε Ονοματεπώνυμο: ") odos = input("Δώσε τη Διεύθυνση σου: ") poli = input("Δώσε την πόλη σου: ") nomos = input("Δώσε τον νομό σου: ") tk = input("Δώσε τον ΤΚ σου: ") til = input("Δώσε το τηλέφωνό σου: ") tmima = input("Δώσε το τμήμα στο οποίο σπουδάζεις: ") print(OnEp) print(odos, poli, nomos, t...
# -*- coding: utf-8 -*- def sum_digit(number): return sum(list(map(int, list(str(number))))) def main(): n = int(input()) count = 0 ans = list() # f(x) = n - xと変形 # f(x)による増加分は,制約条件から多くても9 * 19 < 200 # 探索範囲を絞る for x in range(max(1, n - 200), n + 1): if x + su...
# pylint: disable=missing-function-docstring, missing-module-docstring, unused-variable def fib_caller(x : int): def fib(n : int) -> int: if n < 2: return n i = fib(n-1) j = fib(n-2) return i + j m = fib(x) return m
for _ in range(int(input())): n,a,b=map(int,input().split()) l,r=1,n ans=[] if a+b>n-2 or abs(a-b)>1: print(-1) else: if a==b: h,v=0,0 ans.append(l) l+=1 while h<a: ans.append(r) r-=1 ans....
def separar(cadena): resultado=[] subcadena="|" contador=0 for i in range (len(cadena)-len(subcadena)+1): if cadena[i:i+len(subcadena)]==subcadena: resultado.append(cadena) contador=contador+1 return resultado print(separar("uno|dos|tres"))
#!/usr/bin/env python # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # Jiao Lin # California Institute of Technology # (C) 2007 All Rights Reserved # # {LicenseText} # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~...
# Open page, scroll in object, press in first newsletter, open page, go to first page def test_openNewsletter(app): app.page_operation.open_page("https://athletictrainers.inloop.com") app.newsletter.scroll_to_newsletter() app.newsletter.click_in_first_newsletter() app.tab_operation.test_jump_to_page("ht...
# SQlite queries for the Gold database. # The values are inserted at the ? by cursor.execute(query, (val1, val2, val3)) # Get allocation usage data for all institutes for all time. # Order by allocation start, end and then project name # (as first allocation all starts on same date). def gold_by_all_allocation_period...
# General DEVICE_MODEL_NUMBER_LENGTH = 4 DEFAULT_BLUETOOTH_INTERFACE = 0 # 0 is hci0, 1 is hci1, etc. BLUETOOTH_ADDRESS_TYPE_PUBLIC = "public" # Same as bluepy.btle.ADDR_TYPE_PUBLIC BLUETOOTH_ADDRESS_TYPE_RANDOM = "random" # Same as bluepy.btle.ADDR_TYPE_RANDOM DEFAULT_BLUETOOTH_ADDRESS_TYPE = BLUETOOTH_ADDRESS_TYP...
class DataModel: """holds the data for STL models""" def __init__(self): """add doc""" self.header = None self.triangles = [] self.nr_of_faces = 0 class Triangle: """each Triangle object holds coordinates for normals and vertexes""" def __init__(self): """add d...
a=[] total_data=0 print("Enter the bucket size: ") bs=input() print("Enter no of packets: ") np=input() i=0 for i in range(int(np)): if (i<int(bs)): a.append(int(input())) total_data=total_data+a[i]; else: print("Bucket is full. Further packets will overflow") print("Enter bits of da...
_robot_target_comm = None def set_global_robot_target_comm(robot_target_comm): global _robot_target_comm _robot_target_comm = robot_target_comm def get_global_robot_target_comm(): return _robot_target_comm
q = input() for f in ['<[', ']>', '=>> ((???))', '!']: q = q.replace(f, '').strip() print('question:', q) num = [] oper = [] for idx, this in enumerate(q.split(' ')): if idx%2!=0: # operater oper.append(this) else: # num num.append(int(this)) print(num, oper) ans = num[0] for i in range(4):...
def partition(a,first,last): pivot = a[last] wall = first-1 for i in range(first,last): if a[i] < pivot: wall += 1 if i != wall: a[i], a[wall] = a[wall], a[i] a[wall+1], a[last] = a[last], a[wall+1] print(" ".join(map(str, a))) return wal...
# Space: O(n) # Time: O(n) # Solution without collections library class LRUCache: def __init__(self, capacity: int): self.capacity = capacity self.storage = {} self.key_stack = [] self.status = 0 def get(self, key: int) -> int: if key in self.storage: sel...
# # PySNMP MIB module INTERFACETOPN-MIB (http://pysnmp.sf.net) # ASN.1 source http://mibs.snmplabs.com:80/asn1/INTERFACETOPN-MIB # Produced by pysmi-0.0.7 at Sun Feb 14 00:17:25 2016 # On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose # Using Python version 3.5.0 (default, Jan 5 2016, 17:11:5...
#!/usr/bin/env python3 # coding=utf-8 """ @author: guoyanfeng @software: PyCharm @time: 18-12-25 下午2:08 """ __all__ = ("Error", "HttpError", "ClientError", "ClientResponseError", "ClientConnectionError", "FuncArgsError", "JsonRPCError") class Error(Exception): """ 异常基类 """ def __init__(s...
def ksintegrate(u, Lx, dt, Nt) : """ksintegrate: integrate kuramoto-sivashinsky equation (Python) u_t = -u*u_x - u_xx - u_xxxx, domain x in [0,Lx], periodic BCs inputs u = initial condition (vector of u(x) values on uniform gridpoints)) Lx = domain length dt = time step ...
''' You are given coordinates, a string that represents the coordinates of a square of the chessboard Below is a chessboard for your reference. Return true if the square is white, and false if the square is black. The coordinate will always represent a valid chessboard square. The coordinate will always have the l...
class NotConfigured(Exception): """Indicates a missing configuration situation""" pass class UsageError(Exception): """To indicate a command-line usage error""" def __init__(self, *a, **kw): self.print_help = kw.pop('print_help', True) super(UsageError, self).__init__(*a, **kw)
# Ejercicio 5 def textInMark(texto): # Dado un string la funcion retorna otro string # con las palabras colocadas en un marco length = len(texto) line1 = ("*")*(length + 2) + "\n" line2 = "*" + " "*length + "*\n" line3 = "*" + texto + "*\n" print(line1 + line2 + line3 + line2 + line1) tex...
class Server: def __init__(self): self._status = None self._response_headers = [] def start_response(self, status, response_headers, exc_info=None): self._status = status; self._response_headers = response_headers @property def status(self): return self._status ...
__author__ = 'Raquel G. Alhama' #Path to store temporary results TMP = "../../../tmp/" #Probabilities won't sum up to 1 due to floating point arithmetic; this is the allowed deviation \ # when checking for probabilities. TOLERANCE_PROB = 0.001 #Languages LANGS = ("hb", "es", "en") langstr = dict(zip(LANGS, ("Hebrew...
"""empty message Revision ID: de021a1ca60d Revises: ('0b1f1ab473c0', 'cefabc8f7d38') Create Date: 2018-12-18 22:45:55.783083 """ # revision identifiers, used by Alembic. revision = 'de021a1ca60d' down_revision = ('0b1f1ab473c0', 'cefabc8f7d38', '3e1b21cd94a4') def upgrade(): pass def downgrade(): pass
# !/usr/bin/env python # -*-coding:utf-8 -*- # Warning :The Hard Way Is Easier """ 给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a**2 + b**2 = c。 只需要验证1-c的平方根的整数部分的区间 """ def Solution(t: int): if int(t ** 0.5) == t ** 0.5: # 0 , t** 0.5 return True end = int(t ** 0.5) start = 1 while start <=...
def simpleArraySum(ar): acc = 0 for i in ar: acc += i return acc
# -*- coding: utf-8 -*- """Top-level package for Basic Find.""" __author__ = """Richard Seldon""" __email__ = 'arcseldon@gmail.com' __version__ = '0.0.3'
### TODO: Add numbers, lowercase letters, and punctuation toLED = {'A' :[ [0,1,1,1,0], [1,0,0,0,1], [1,0,0,0,1], [1,0,0,0,1], [1,1,1,1,1], [1,0,0,0,1], [1,0,0,0,1], [1,0,0,0,1] ], 'B' : [ [1,1,1,1,0], [1,0,0,0,1], [1,0,0,0,1], [1,1,1,1,0], [1,0,0,0,1], [1,0,0,0,1], [1,0,0,0,1], [1,...
""" Lecture 15: Linear Programming Flow Network ------------ Below is a class that will be used as a data structure representing a residual flow network which will be used for finding the maximum flow allowable through a flow network. See lecture 13-14 for more information. This data structure is used in linprog.py f...
#!/usr/bin/env python # encoding: utf-8 name = "T3" shortDesc = "" longDesc = """ ARC v1.1.0 ARC project T3 Levels of theory used: Conformers: wb97xd/def2svp TS guesses: wb97xd/def2svp Optimization: b3lyp/6-311+g(3df,2p) (using a fine grid) Frequencies: b3lyp/6-311+g(3df,2p) Single point: b3...
# Bubble sort # Time: O(n^2); Space: O(1) def sort_colors(nums): for i in range(len(nums)): for j in range(i + 1, len(nums)): if nums[i] > nums[j]: nums[j], nums[i] = nums[i], nums[j] # Counting sort # Time: O(n^2) or O(n) ?; Space: O(1) def sort_colors2(nums): count = [0] ...
def split_and_check(pw_input): counts, symbol, pw = pw_input.split(' ') symbol = symbol[:-1] lower_bound, upper_bound = counts.split('-') occurrence_count = pw.count(symbol) if int(lower_bound) <= occurrence_count <= int(upper_bound): return 1 else: return 0 pw_file = open('dat...
# -*- coding: utf-8 -*- VERSION = (0, 5, 2) __version__ = '.'.join(map(str, VERSION)) default_app_config = 'warthog.app_config.WarthogAppConfig'
# 贵阳 -> 贵州 COV_LIST = [ "北京", "天津", "辽宁", "甘肃", "福建", "山东", "湖北", "四川", "江苏", "河北", "云南", "山西", "广东", "台湾", "广西", "宁夏", "香港", "上海", "重庆", "吉林", "青海", "浙江", "安徽", "湖南", "陕西", "江西", "河南", "贵州", "海南", "...
#!/usr/bin/env python """ Utils ===== """ def get_n_features(matrix, min_=2): """Get the number of features in a matrix. Args: matrix : ndarray A numeric numpy array. Features are assumed to be the columns. min_ : int The smallest number of features that ...
class Sample: def __init__(self): self.data = None self.label = None
# Imported Python Transfer Function @nrp.NeuronMonitor(nrp.brain.record, nrp.spike_recorder) def all_neurons_monitor(t): return True ##
#!/usr/bin/env python # file: $nedc_nfc/class/python/nedc_sys_tools/nedc_text_tools.py # # revision history: # 20170716 (JP): Upgraded to using the new annotation tools. # 20170709 (JP): Initial version. # # usage: # import nedc_text_tools as ntt # # This file contains some useful Python functions and classes that ...
class Solution(object): def gameOfLife(self, board): """ :type board: List[List[int]] :rtype: void Do not return anything, modify board in-place instead. """ def neighbor(board, i, j): cnt = 0 for a in xrange(i-1, i+2): for b in xrange(...
# coding=utf-8 """ README GENERATOR Readme content variables Autor: Pablo Pizarro R. @ ppizarror.com Licencia: The MIT License (MIT) Copyright 2017 Pablo Pizarro R. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Soft...
""" Given an integer array nums sorted in ascending order, and an integer target. Suppose that nums is rotated at some pivot unknown to you beforehand (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). You should search for target in nums and if found return its index, otherwise return -1. Example 1: Input: nums ...
# [8 kyu] 5 Without Numbers!! # # Author: Hsins # Date: 2019/11/28 def unusual_five(): return len(" ")
""" Pytest versus Unittest Unitest versus Pytest em Português Homepage and documentation: https://github.com/python-marcus-mariano/Tutorial-unittest-vs-pytest Copyright (c) 2019, Marcus Mariano. License: MIT (see LICENSE for details) """ class DBBase: """Template.""" _counter = None _open_msg = None ...
# Score categories. # Change the values as you see fit. YACHT = "YACHT" ONES = "ONES" TWOS = "TWOS" THREES = "THREES" FOURS = "FOURS" FIVES = "FIVES" SIXES = "SIXES" FULL_HOUSE = "FULL_HOUSE" FOUR_OF_A_KIND = "FOUR_OF_A_KIND" LITTLE_STRAIGHT = "LITTLE_STRAIGHT" BIG_STRAIGHT = "BIG_STRAIGHT" CHOICE = "CHOICE" little_st...
f=open('t.txt','r') l=f.readlines() d={} for i in (l): k = i.strip() m = list(k) if (m[0] == '>'): s = k.lstrip('>') d[s] = '' j = s else: d[j] += k for i in d.keys(): suf = d[i][len(d[i])-3: ] for j in d.keys(): if(j!=i): pre = d[j][0:3] ...