content stringlengths 7 1.05M |
|---|
#moveable_player
class MoveablePlayer:
def __init__(self, x=2, y=2, dir="FORWARD", color="170"):
self.x = x
self.y = y
self.direction = dir
self.color = color
|
# =============================================================================================
#
# =============================================================================================
#
# 2 16 20 3 4 21 # GPIO Pin number
# | | | | | |
# --... |
# -*- coding: utf-8 -*-
class Trial(object):
'''
Created Fri 2 Aug 2013 - ajl
Last edited: Sun 4 Aug 2013 - ajl
This class contains all variables and methods associated with a single trial
'''
def __init__(self, trialid = 0, staircaseid = 0,
conditi... |
## Q2: What is the time complexity of
## O(n), porque es un for de i=n hasta i=1
# Algoritmo
# for (i = n; i > 0; i--) { # n
# statement; # 1
# }
n = 5
for i in range(n, 0, -1): # n
print(i); # 1 |
# pylint: disable=redefined-outer-name,protected-access
# pylint: disable=missing-function-docstring,missing-module-docstring,missing-class-docstring
def test_can_construct_author(author):
assert isinstance(author.name, str)
assert isinstance(author.url, str)
assert isinstance(author.github_url, str)... |
# ------------------------------------------------------------------------------
# Program: The LDAR Simulator (LDAR-Sim)
# File: LDAR-Sim input mapper sample
# Purpose: Example input mapper
#
# Copyright (C) 2018-2021 Intelligent Methane Monitoring and Management System (IM3S) Group
#
# This program is... |
#%% VARIABLES
'Variables'
# var1 = 10
# var2 = "Hello World"
# var3 = None
# var4 = 3.5
# if 0:
# print ("hello world 0") #el 0 fnciona como Falsey
# if 1:
# print ("hello world 1") #el 1 funciona como Truthy
# x1 = 100
# x2 = 20
# x3 = -5
# y = x1 + x2 + x3
# z = x1 - x2 * x3
# w = (x1+x2+x3) - (x1-... |
# Given inorder and postorder traversal of a tree, construct the binary tree.
# Note:
# You may assume that duplicates do not exist in the tree.
# For example, given
# inorder = [9,3,15,20,7]
# postorder = [9,15,7,20,3]
# Return the following binary tree:
# 3
# / \
# 9 20
# / \
# 15 7
# Definit... |
# Copyright 2015 Google Inc. 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 required by applicable law or ... |
#Ler 80 números e informar quantos estão no intervalo entre 10 (inclusive) e 150 (inclusive).
nums = []
quantia = str(input("Quantos números você deseja inserir (deixe em branco para 80)? "))
def addNumber():
newNumber = int(input("Insira o Número: "))
if newNumber >= 10 and newNumber <= 150:
nums.append(newNumb... |
# Time: O(m * n)
# Space: O(1)
class Solution(object):
def findDiagonalOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if not matrix or not matrix[0]:
return []
result = []
row, col, d = 0, 0, 0
dirs = [(-1, ... |
class PingPacket:
def __init__(self):
self.type = "PING"
self.serial = 0
def read(self, reader):
self.serial = reader.readInt32()
|
n = int(input())
for teste in range(n):
m = int(input())
lista = [int(x) for x in input().split()]
impares = []
for x in lista:
if x%2 == 1:
impares.append(x)
impares.sort()
laercio = []
while len(impares) > 0:
laercio.append(impares.pop())
i... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
"""Define nodejs and yarn dependencies"""
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "build_bazel_rules_nodejs",
sha256 = "a09edc4ba3931a856a5ac6836f248c302d55055d35d36e390a0549799c33145b",
urls = ["https://github.com/bazelbuild/rules_nodejs/releases/download... |
# encoding: utf-8
# =========================================================================
# ©2017-2018 北京国美云服科技有限公司
# -------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this work except in compliance with the ... |
class Matrix:
def __init__(self, *args, **kwargs):
if len(args) > 0:
if isinstance(args[0], Matrix):
m = args[0].copy()
else:
m = {'vals': [], 'w': 0, 'h': 0}
self.vals = m.vals
self.w = m.w
self.h = m.h
def copy(self):
new_m = Matrix()
for i in self.vals:
new... |
#
# @lc app=leetcode id=67 lang=python3
#
# [67] Add Binary
#
# @lc code=start
class Solution:
def addBinary(self, a: str, b: str) -> str:
m = len(a)
n = len(b)
i = m - 1
j = n - 1
extra = 0
res = ''
while i >=0 or j >= 0:
if i < 0:
... |
#
# @lc app=leetcode id=136 lang=python3
#
# [136] Single Number
#
# https://leetcode.com/problems/single-number/description/
#
# algorithms
# Easy (60.26%)
# Likes: 3294
# Dislikes: 128
# Total Accepted: 600.9K
# Total Submissions: 961.2K
# Testcase Example: '[2,2,1]'
#
# Given a non-empty array of integers, ev... |
def test():
# if an assertion fails, the message will be displayed
# --> must have the output in a comment
assert "Mean: 5.0" in __solution__, "Did you record the correct program output as a comment?"
# --> must have the output in a comment
assert "Mean: 4.0" in __solution__, "Did you record the cor... |
# 17. Distinct strings in the first column
# Find distinct strings (a set of strings) of the first column of the file. Confirm the result by using cut, sort, and uniq commands.
def removeDuplicates(list):
newList = []
for i in list:
if not(i in newList):
newList.append(i)
return... |
name = input("Enter your name: ")
date = input("Enter a date: ")
adjective = input("Enter an adjective: ")
noun = input("Enter a noun: ")
verb = input("Enter a verb in past tense: ")
adverb = input("Enter an adverb: ")
adjective = input("Enter another adjective: ")
noun = input("Enter another noun: ")
noun = input("Ent... |
input=__import__('sys').stdin.readline
n,m=map(int,input().split());g=[list(input()) for _ in range(n)];c=[[0]*m for _ in range(n)]
q=__import__('collections').deque();q.append((0,0));c[0][0]=1
while q:
x,y=q.popleft()
for nx,ny in (x+1,y),(x-1,y),(x,y+1),(x,y-1):
if 0<=nx<n and 0<=ny<m and g[nx][ny]=='... |
##============================ ea_config_ex_1.py ================================
# Some of the input parameters and options in order to select the settings of the
# evolutionary algorithm are given here for the minimization of the De Jong’s fifth
# function or Shekel’s foxholes using Genetic Algorithms.
EA_type = 'G... |
# normalize data 0-1
def normalize(data):
normalized = []
for i in range(len(data[0])):
col_min = min([item[i] for item in data])
col_max = max([item[i] for item in data])
for q, item in enumerate([item[i] for item in data]):
if len(normalized) > q:
normal... |
'''
You are given a linked list with one pointer of each node pointing to the next node just like the usual.
Every node, however, also has a second pointer that can point to any node in the list.
Now write a program to deep copy this list.
Solution 1:
First backup all the nodes' next pointers node to another array.
n... |
class PointCloudObject(RhinoObject):
# no doc
def DuplicatePointCloudGeometry(self):
""" DuplicatePointCloudGeometry(self: PointCloudObject) -> PointCloud """
pass
PointCloudGeometry=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: PointCloudGeometry(self: PointCloudObject) ->... |
'''
Kattis - lineup
Compare list with the sorted version of the list.
Time: O(n log n), Space: O(n)
'''
n = int(input())
arr = [input() for _ in range(n)]
if arr == sorted(arr):
print("INCREASING")
elif arr == sorted(arr, reverse=True):
print("DECREASING")
else:
print("NEITHER") |
"""
quick_sort.py
Implementation of quick sort on a list and returns a sorted list.
Quick Sort Overview:
------------------------
Uses partitioning to recursively divide and sort the list
Time Complexity: O(n**2) worst case
Space Complexity: O(n**2) this version
Stable: No
Psue... |
somaidade = 0
mediaidade = 0
nomehomem = ''
idadehomem = 0
totmulher20 = 0
''' Desenvolva um programa que leia o nome, idade e sexo de 4 pessoas. No final do programa, mostre: a média de idade do grupo, qual é o nome do homem mais velho e quantas mulheres têm menos de 20 anos.'''
for p in range (1,5):
print... |
# coding=utf-8
def test_method(param):
"""
Should not show up
:param param: any param
:return: None
"""
return None
|
#program to find the single element appears once in a list where every element
# appears four times except for one.
class Solution_once:
def singleNumber(self, arr):
ones, twos = 0, 0
for x in arr:
ones, twos = (ones ^ x) & ~twos, (ones & x) | (twos & ~x)
assert twos == 0
... |
'''
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
[1,1,2] have the following unique permutations:
[1,1,2], [1,2,1], and [2,1,1].
'''
class Solution(object):
def permuteUnique(self, nums):
"""
:type nums: List[int]
... |
class Bank:
def __init__(self,owner,balance):
self.owner=owner
self.balance=balance
def deposit(self,d):
self.balance=d+self.balance
print("amount : {}".format(d))
print("deposit accepted!!")
return self.balance
def withdraw(self,w):
... |
dt = input('coloque uma data no formato dd/mm/aaaa : ')
try:
if dt[2] == '/' and dt[5] == '/':
dia = int(dt[0]+dt[1])
mes = int(dt[3]+dt[4])
if dia > 31 or mes > 12:
print('invalido, dia ou mes errados')
else:
print(' a data {} é valida... |
"""
Various constants used to build bazel-diff
"""
DEFAULT_JVM_EXTERNAL_TAG = "3.3"
RULES_JVM_EXTERNAL_SHA = "d85951a92c0908c80bd8551002d66cb23c3434409c814179c0ff026b53544dab"
BUILD_PROTO_MESSAGE_SHA = "50b79faec3c4154bed274371de5678b221165e38ab59c6167cc94b922d9d9152"
BAZEL_DIFF_MAVEN_ARTIFACTS = [
"junit:junit... |
#
# @lc app=leetcode id=206 lang=python3
#
# [206] Reverse Linked List
#
# https://leetcode.com/problems/reverse-linked-list/description/
#
# algorithms
# Easy (65.21%)
# Likes: 6441
# Dislikes: 123
# Total Accepted: 1.3M
# Total Submissions: 2M
# Testcase Example: '[1,2,3,4,5]'
#
# Given the head of a singly li... |
# Bubble Sort
#
# Time Complexity: O(n*log(n))
# Space Complexity: O(1)
class Solution:
def bubbleSort(self, array: [int]) -> [int]:
dirty = False
for i in range(len(array)):
for j in range(0, len(array) - 1 - i):
if array[j] > array[j + 1]:
di... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-03-07
Last_modify: 2016-03-07
******************************************
'''
'''
Given a **singly linked list** where eleme... |
# -*- coding: utf-8 -*-
"""
repoclone.exceptions
-----------------------
All exceptions used in the repoclone code base are defined here.
"""
class RepocloneException(Exception):
"""
Base exception class. All Cookiecutter-specific exceptions should subclass
this class.
"""
|
inputFile = str(input("Input file"))
f = open(inputFile,"r")
data = f.readlines()
f.close()
runningFuelSum = 0
for line in data:
line = line.replace("\n","")
mass = int(line)
fuelNeeded = (mass//3)-2
runningFuelSum += fuelNeeded
while(fuelNeeded > 0):
fuelNeeded = (fuelNeeded//3)-2
... |
class Settings:
def __init__(self):
self.screen_width, self.screen_height = 800, 300
self.bg_color = (225, 225, 225) |
class Solution:
def sortColors(self, nums: List[int]) -> None:
zero = -1
one = -1
two = -1
for num in nums:
if num == 0:
two += 1
one += 1
zero += 1
nums[two] = 2
nums[one] = 1
nums[zero] = 0
elif num == 1:
two += 1
one += 1
... |
"""This problem was asked by Two Sigma.
You’re tracking stock price at a given instance of time.
Implement an API with the following functions: add(), update(), remove(),
which adds/updates/removes a datapoint for the stock price you are tracking.
The data is given as (timestamp, price), where timestamp is specifie... |
"""
dictionary unpacking => It unpacks a dictionary as named arguments to a function.
"""
class User:
def __init__(self, username, password):
self.username = username
self.password = password
@classmethod
def from_dict(cls, data):
return cls(data['username'], data['password'])
def __repr__(self)... |
'''
* Concatenação: operadores e métodos
* Repositório: Lógica de Programação e Algoritmos em Python
* GitHub: @michelelozada
'''
# 1 - Operador +
nome = 'Denzel' + ' ' + 'Washington'
profissao = 'ator e produtor norte-americano'
print(nome) # Denzel Washington
print(nome + ', ' + profissao) # Denzel Washingto... |
# an ex. of how you might use a list in practice
colors = ["green", "red", "blue"]
guess = input("Please guess a color:")
if guess in colors:
print ("You guessed correctly!")
else:
print ("Negative! Try again please.")
|
# Do not edit this file directly.
# It was auto-generated by: code/programs/reflexivity/reflexive_refresh
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def backwardCpp():
http_archive(
name="backward_cpp" ,
build_file="//bazel/deps/backward_cpp:build.BUILD" ,
sha256... |
'''
Largest product in a grid
Problem 11
In the 20×20 grid below, four numbers along a diagonal line have been marked in red.
08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 ... |
print('~'*30)
print('BANCOS AVORIK')
print('~'*30)
nt50 = nt20 = nt10 = nt1 = 0
saque = int(input('Quantos R$ deseja sacar?\n'))
resto = saque
while True:
if resto > 50:
nt50 = resto // 50
resto = resto % 50
print(f'{nt50} nota(s) de R$ 50.')
if resto > 20:
nt20 = resto // 20
... |
s = set(r"""~!@#$%^&*()_+|`-=\{}[]:";'<>?,./ """)
while True:
up = True
low = True
digit = True
special = True
a = input()
b = input()
t = len(a)
if a != b:
print('Password settings are not consistent.')
elif a == 'END':
break
else:
if not 8 <= t <= 12:
... |
"""Modules for integration between Sans-I/O protocols and I/O drivers.
Modules:
_trio: integration between Sans-I/O protocols and trio I/O.
"""
|
ButtonA, ButtonB, ButtonSelect, ButtonStart, ButtonUp, ButtonDown, ButtonLeft, ButtonRight = range(8)
class Controller:
def __init__(self):
self.buttons = [False for _ in range(8)]
self.index = 0
self.strobe = 0
def set_buttons(self, buttons):
self.buttons = buttons
def... |
userid_country = {
60: ("US", "United States", "アメリカ合衆国"),
71: ("CL", "Chile", "チリ"),
95: ("CL", "Chile", "チリ"),
95: ("BR", "Brazil", "ブラジル"),
95: ("PE", "Peru", "ペルー"),
95: ("PT", "Portugal", "ポルトガル"),
170: ("US", "United States", "アメリカ合衆国"),
219: ("CN", "China", "中華人民共和国"),
219: ("PH", "Philippines", "フィリピン"... |
# wordCalculator.py
# A program to calculate the number of words in a sentence
# by Tung Nguyen
def main():
# declare program function:
print("This program calculates the number of words in a sentence.")
print()
# prompt user to input the sentence:
sentence = input("Enter a phrase: ")
... |
"""Result - Data structure for a result."""
# Is prediction before game is played, then actual once game ahs been played
# Return the outcome Briers score, home/away goals scored, Predictions if available, and actual
# result if game has been played
class Result:
"""Result - Data structure for a result."""
d... |
cargo = input().lower().strip()
tempo = int(input())
salarioAtual = float(input())
if salarioAtual < 1039:
print('Salário inválido!')
else:
if cargo == 'gerente':
if tempo <= 3:
reajuste = salarioAtual * 0.12
elif tempo <= 6:
reajuste = salarioAtual * 0.13
else:
... |
"""
Author: Ao Wang
Date: 08/12/19
Description: Caesar cipher encryption and decryption, also a reverse encryption
"""
# The function reverses the string parameter
def reverse(plain_text):
cipher_text = ""
for letter in range(len(plain_text)):
# starts at the end of the string, -1 and moves its... |
class LexHelper:
offset = 0
def get_max_linespan(self, p):
defSpan = [1e60, -1]
mSpan = [1e60, -1]
for sp in range(0, len(p)):
csp = p.linespan(sp)
if csp[0] == 0 and csp[1] == 0:
if hasattr(p[sp], "linespan"):
csp = p[sp].line... |
settings = {}
settings['version'] = "0.1"
settings['port'] = 36000
settings['product'] = "MOPIDY-PLEX"
settings['debug_registration'] = False
settings['debug_httpd'] = False
settings['host'] = ""
settings['token'] = None
|
# = atribuição, == comparação
car='panamera'
print(car=='panamera')
car='audi'
print(car=='panamera') |
def is_leap(year):
if year >= 1900 and year <= pow(10,5):
leap = False
if year%4 == 0:
if year%100 == 0:
if year%400 == 0:
leap = True
else:
leap = False
else:
leap = True
return l... |
# Copyright 2017 The Bazel 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 required by applicable la... |
def test_load_case(case_obj, adapter):
## GIVEN a database with no cases
assert adapter.case_collection.find_one() is None
## WHEN loading a case
adapter._add_case(case_obj)
## THEN assert that the case have been loaded with correct info
assert adapter.case_collection.find_one()
def test_lo... |
'''
Leia um valor inteiro entre 1 e 12, inclusive. Correspondente a este valor, deve ser apresentado como resposta o mês
do ano por extenso, em inglês, com a primeira letra maiúscula.
Entrada = A entrada contém um único valor inteiro.
Saída = Imprima por extenso o nome do mês correspondente ao número existente na entr... |
def threshold_distance_mask(r, h):
return r < h
|
load("@bazel_tools//tools/build_defs/repo:jvm.bzl", "jvm_maven_import_external")
_default_server_urls = ["https://repo.maven.apache.org/maven2/",
"https://mvnrepository.com/artifact",
"https://maven-central.storage.googleapis.com",
"http://gitblit... |
#!/usr/bin/env python
"""
Definitions of classes to work with molecular data.
The mol_info_table class is used to store and manipulated
information about a molecule.
The mol_xyz_table class is used to store and manipulated
the xyz coodinate of a molecule.
The functions defined here are basically wrappers to
MySQL e... |
class OptionsStub(object):
def __init__(self):
self.debug = True
self.guess_summary = False
self.guess_description = False
self.tracking = None
self.username = None
self.password = None
self.repository_url = None
self.disable_proxy = False
self... |
# Copyright 2019 AUI, Inc. Washington DC, USA
#
# 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 ... |
# Attempt I: 贪心的思路,方法错。维护一个静态dict不能保证每次remove后余下的序列仍保持有序。
# class Solution:
# def findMinArrowShots(self, points):
# """
# :type points: List[List[int]]
# :rtype: int
# """
# left = 10000
# right = -10000
# for i in range(len(points)):
# left = mi... |
"""__init__.py - A command-line utility that checks for best practices in Jinja2.
"""
NAME = 'j2lint'
VERSION = '0.1'
DESCRIPTION = __doc__
__author__ = "Arista Networks"
__license__ = "MIT"
__version__ = VERSION
|
def binary_search(S, left, right, key):
# Find smallest element that's >= key
while left <= right:
# find midpoint
mid = left + (right - left) // 2
# if element found move lower.
if S[mid] >= key:
right = mid - 1
else:
left = mid + 1
# smallest... |
class Solution:
def searchInsert(self, nums, target: int) -> int:
"""
二分法查找,若目标不存在,则返回它将会被按顺序插入的位置。
"""
low = 0
high = len(nums) - 1
while low <= high:
mid = int((low + high) / 2)
if target == nums[mid]:
return mid
e... |
service_dict = {
'NetworkService':{
'getTargetsWithRelationshipTypeForResourceById':{},
'getTargetsByRelationshipForSourceId':{},
'getSourcesWithThisTargetByRelationshipCount':{},
'deleteResource':{},
'getSourceURIWithThisTargetByRelatiobnshipForResourceId':{},
'getAl... |
# 练习:使用学生列表封装以下三个列表中数据
class Student:
def __init__(self, name="", age=0, sex=""):
self.name = name
self.age = age
self.sex = sex
list_student_name = ["悟空", "八戒", "白骨精"]
list_student_age = [28, 25, 36]
list_student_sex = ["男", "男", "女"]
list_students = []
for item in zip(list_student_name,... |
def test_a_cohama_adb(style_checker):
"""Style check test against a-cohama.adb."""
style_checker.set_year(2006)
p = style_checker.run_style_checker('trunk/gnat', 'a-cohama.adb')
style_checker.assertEqual(p.status, 0, p.image)
style_checker.assertRunOutputEmpty(p)
def test_a_cohamb_adb(style_checke... |
### Stupid, but extensible spam detector
STOP_SPAM_WORDS = ["Loan", "Lender", ".trade", ".bid", ".men", ".win"]
def is_spam(request):
if 'email' in request.form:
if any(
[ word.upper() in request.form['email'].upper()
for word in STOP_SPAM_WORDS]):
return True
if 'username' in request.f... |
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'findadoctor2@gmail.com'
EMAIL_HOST_PASSWORD = 'Qwerty1@'
EMAIL_USE_TLS = True |
#! /usr/bin/env Python3
list_of_tuples = []
list_of_tuples_comprehension = ([(i, j, i * j) for i in range(1, 11) for j in range(1, 11)])
for i in range(1, 11):
for j in range(1, 11):
list_of_tuples.append((i, j, i * j))
print(list_of_tuples)
print('************')
print(list_of_tuples_comprehension)
|
TARGET_BAG = 'shiny gold'
def get_data(filepath):
return [line.strip() for line in open(filepath).readlines()]
def parse_rule(rule):
rule = rule.split(' ')
adj, color = rule[0], rule[1]
container_bag = '%s %s' % (adj, color)
bags_contained = {}
if rule[4:] == ['no', 'other', 'bags.']:
... |
class Instance:
def __init__ (self, alloyfp):
self.bitwidth = '4'
self.maxseq = '4'
self.mintrace = '-1'
self.maxtrace = '-1'
self.filename = alloyfp
self.tracel = '1'
self.backl = '0'
self.sigs = []
self.fields = []
def add_sig(self, sig... |
# Find square root using newton raphson
num = 987
eps = 1e-6
iteration = 0
sroot = num/2
while abs(sroot**2-num)>eps:
iteration+=1
if sroot**2==num:
print(f'At Iteration {iteration} : Found It!, the cube root for {num} is {sroot}')
break
sroot = sroot - (sroot**2-num)/(2*sroot)
print(f'... |
"""
https://www.practicepython.org
Exercise 14: List Remove Duplicates
2 chilis
Write a program (function!) that takes a list and returns a new list that
contains all the elements of the first list minus all the duplicates.
Extras:
- Write two different functions to do this - one using a loop and constructing
a li... |
HEADLINE = "time_elapsed\tsystem_time\tyear\tmonth\tday\tseasonal_factor\ttreatment_coverage_0_1\ttreatment_coverage_0_10\tpopulation\tsep\teir\tsep\tbsp_2_10\tbsp_0_5\tblood_slide_prevalence\tsep\tmonthly_new_infection\tsep\tmonthly_new_treatment\tsep\tmonthly_clinical_episode\tsep\tmonthly_ntf_raw\tsep\tKNY--C1x\tKNY... |
# -*- coding: utf-8 -*-
"""
mongoop.default_settings
~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2015 by Lujeni.
:license: BSD, see LICENSE for more details.
"""
mongodb_host = 'localhost'
mongodb_port = 27017
mongodb_credentials = None
mongodb_options = None
frequency = 10
threshold_timeout = 60
o... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
a, b = headA, headB
while a != b:
a = a.next if a else headB
b =... |
# -*- coding: utf-8 -*-
# @Author : LG
"""
执行用时:108 ms, 在所有 Python3 提交中击败了96.06% 的用户
内存消耗:15.8 MB, 在所有 Python3 提交中击败了25.37% 的用户
解题思路:
先在树中找到与链表第一个节点相同值的 树节点
然后以这些树中节点为根的子树中寻找是否存在链表
"""
class Solution:
def isSubPath(self, head: ListNode, root: TreeNode) -> bool:
def Sub(root, head): # 递归在子树中判断... |
class DriverMeta(type):
def __instancecheck__(cls, __instance) -> bool:
return cls.__subclasscheck__(type(__instance))
def __subclasscheck__(cls, __subclass: type) -> bool:
return (
hasattr(__subclass, 'create') and callable(__subclass.create)
) and (
... |
# Simple example using ifs
cars = ['volks', 'ford', 'audi', 'bmw', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
# Comparing Values
#
# requested_toppings = 'mushrooms'
# if requested_toppings != 'anchovies':
# print('Hold the Anchovies')
#
#
# ... |
class Squad():
def __init__(self, handler, role, hold_point):
self.handler = handler
if len(handler.squads[role]) > 0:
self.id = handler.squads[role][-1].id + 1
else:
self.id = 1
self.units = {
handler.unit.MARINE: [],
handler... |
# https://leetcode.com/problems/unique-binary-search-trees-ii/
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def generateTrees(self, n):
"""
:type n: int
... |
infile=open('pairin.txt','r')
n=int(infile.readline().strip())
dic={}
for i in range(2*n):
sn=int(infile.readline().strip())
if sn not in dic:
dic[sn]=i
else:
dic[sn]-=i
maxkey=min(dic,key=dic.get)
outfile=open('pairout.txt','w')
outfile.write(str(abs(dic[maxkey])))
outfile.close... |
"""
Queue via Stacks
Implement a MyQueue class which implements a queue using two stacks.
Questions and Assumptions:
Model 1: Back to Back ArrayStacks
MyQ
stack1 stack2
t2 t1
[ ][ x1 x2 x3 x4]
f ? b
1. Interface:
... |
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
workingset = set()
for n in nums:
if n not in workingset:
workingset.add(n)
else:
workingset.remove(n)
... |
'''
Created on Dec 4, 2017
@author: atip
'''
def getAdjSquareSum():
global posX, posY, valMatrix
adjSquareSum = 0
adjSquareSum += valMatrix[maxRange + posX + 1][maxRange + posY]
adjSquareSum += valMatrix[maxRange + posX + 1][maxRange + posY + 1]
adjSquareSum += valMatrix[maxRange + posX][maxRange ... |
#
# @lc app=leetcode id=77 lang=python3
#
# [77] Combinations
#
# @lc code=start
class Solution:
def combine(self, n, k):
self.ans = []
nums = [num for num in range(1, n + 1)]
if n == k:
self.ans.append(nums)
return self.ans
else:
ls = []
... |
# Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/
#
# 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,... |
"""
Linear search is used on a collections of items. It relies on the technique of traversing a list from
start to end by exploring properties of all the elements that are found on the way.
The time complexity of the linear search is O(N) because each element in an array is compared only once.
"""
def linear_search(... |
METR_LA_DATASET_NAME = 'metr_la'
PEMS_BAY_DATASET_NAME = 'pems_bay'
IN_MEMORY = 'mem'
ON_DISK = 'disk'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.