content stringlengths 7 1.05M |
|---|
# Copyright (c) 2021 - present / Neuralmagic, 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 b... |
"""
Module for build utilities to distiguish different tensorflow versions.
"""
load("@org_tensorflow//tensorflow:tensorflow.bzl", "VERSION_MAJOR")
def if_v2(a):
if VERSION_MAJOR == "2":
return a
else:
return []
def if_not_v2(a):
if VERSION_MAJOR == "2":
return []
else:
... |
# -*- coding: utf8 -*-
"""
Validation logic
"""
def validate_temperature_mode(mode): # TODO more type specific validation
"""Ensures the temperature mode
has the right data schema
"""
errors = []
schema = {
'target': 'Target temperature mode value.',
'logs': [
{
... |
config = dict(
model=dict(
type='deeplabv3plus',
params=dict(
encoder=dict(
type='deeplab_encoder',
params=dict(
resnet_encoder=dict(
resnet_type='resnet50',
include_conv5=True,
... |
__all__ = ['LoginFailedException', 'NoElementException']
class LoginFailedException(Exception):
"""Raise when login failed"""
def __init__(self, arg):
self.strerror = arg
self.args = {arg}
class NoElementException(Exception):
"""Raise when required elements cannot be found"""
def _... |
# -*- python -*-
# This software was produced by NIST, an agency of the U.S. government,
# and by statute is not subject to copyright in the United States.
# Recipients of this software assume all responsibilities associated
# with its operation, modification and maintenance. However, to
# facilitate maintenance we as... |
def descend_density_tree(data_point, node):
"""given some test data and decision tree, assign the correct label using a decision tree"""
if data_point[node.split_dimension] < node.split_value:
if node.left is not None: # no leaf node
return descend_density_tree(data_point, node.left)
... |
BLACKLISTS_MAPPING = {
'blacklists_add': {
'resource': 'blacklists/add.json',
'docs': 'https://disqus.com/api/docs/blacklists/add/',
'methods': ['POST'],
},
'blacklists_list': {
'resource': 'blacklists/list.json',
'docs': 'https://disqus.com/api/docs/blacklists/list/'... |
"""
This PEP proposes re-designing the buffer interface
(PyBufferProcs function pointers) to improve the way
Python allows memory sharing in Python 3.0
In particular, it is proposed that the character buffer
portion of the API be eliminated and the
multiple-segment portion be re-designed
in conjunction with allow... |
"""Kata url: https://www.codewars.com/kata/56fa3c5ce4d45d2a52001b3c."""
def xor(a: bool, b: bool) -> bool:
return a ^ b
|
class Deck(object):
def __init__(self, name, archetype=None, legality=None):
self.name = name
self.archetype = archetype
self.legality = legality
self.mainboard = {}
self.sideboard = {}
def addCardToMainboard(self, name, amount=1):
if name not in self.mainboar... |
# -*- coding: utf-8 -*-
"""
In this problem, we want to rotate the matrix elements by 90, 180, 270 (counterclockwise)
Discussion in stackoverflow:
https://stackoverflow.com/questions/42519/how-do-you-rotate-a-two-dimensional-array
"""
def rotate_90(matrix: [[]]):
"""
>>> rotate_90([[1, 2, 3, 4], [5, 6,... |
#! python
"""How many Sundays fell on the first of the month during the
twentieth century (1 Jan 1901 to 31 Dec 2000)?"""
# Instead of using datetime module I wanted to create the function from scratch
DAYS = (0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
def date(day, month, year):
"""Returns the number of ... |
API_ERROR_CODE = {
-40101: 'SYSTEM',
-40102: 'EXPT',
-40103: 'NOMEMORY',
-40104: 'INVEVT',
-40105: 'CODE',
-40106: 'INVINSTRUCT',
-40107: 'FORBID',
-40108: 'NOECHO',
-40109: 'SYSBUSY',
-40110: 'NODEVICE',
-40201: 'OVERFLOW',
-40202: 'TOOLONG',
-40203: 'ENTRYEXIST',
... |
# model settings
# norm_cfg = dict(type='SyncBN', requires_grad=True)
norm_cfg = dict(type='BN', requires_grad=True)
# decide data directory by home name
# please remove these lines and directly set data_root for your training
# import os
# if '/home/feng' in os.getcwd():
# pretrain_path = '/home/feng/work_mmseg/c... |
__MAJOR__ = "0"
__MINOR__ = "0"
__PATCH__ = "0"
__SUFFIX__ = "dev"
__version__ = "{}.{}.{}".format(__MAJOR__, __MINOR__, __PATCH__)
if __SUFFIX__:
__version__ = "{}_{}".format(__version__, __SUFFIX__)
|
def sift_up(heap, index) -> int:
if index == 1:
return index
parent_idx = index // 2
if heap[parent_idx] < heap[index]:
heap[index], heap[parent_idx] = heap[parent_idx], heap[index]
index = sift_up(heap, parent_idx)
return index
|
def to_ini(databases = []):
"""
Custom ansible filter to print out pgbouncer database connection settings
from a list of variable objects.
"""
s = ''
for db in databases:
for alias, config in db.items():
s = s + str(alias) + ' = '
for key, value in config.items():... |
print("""
038) Escreva um programa que leia dois números inteiros e compare-os,
mostrando na tela uma mensagem:
- O primeiro valor é maior
- O segundo valor é maior
- Não existe valor maior, os dois são iguais
""")
num1 = int(input('Digite o Primeiro Valor: ').strip())
num2 = int(input('Digite o Segundo Valor: ').strip... |
"""
This problem was asked by Dropbox.
Given a string s and a list of words words, where each word is the same length,
find all starting indices of substrings in s that is a concatenation of every word in words exactly once.
For example, given s = "dogcatcatcodecatdog" and words = ["cat", "dog"], return [0, 13],
sin... |
user= input('what are you doing?')
print(user.upper())
print(user.lower())
print(user.swapcase())
|
'''
Write a Python program to get the difference between a given number and 17, if the number is greater than 17 return double the absolute difference.
'''
def difference(num):
const = 17
if num > const:
print(str(abs(num - const) * 2))
else:
print(str(abs(num - const)))
difference(22)
d... |
class Sweepstakes_Stack_Manager:
def __init__(self, stack):
self.sweepstakes_stack_manager = Sweepstakes_Stack_Manager
self.stack = stack
def insert_sweepstakes(sweepstakes): pass
def get_sweepstakes(): Sweepstake |
# File: skybox_consts.py
#
# Copyright (c) 2020 Splunk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... |
# declare the list of users
lst = ['joe', 'sue', 'hani', 'sophie']
# # complexity: time and space
# O(n) O(40000)
# O(1)
# O(log(n))
# get user input
# login = input('Enter your id: ')
# login.lower()
# check if user exists in list
# method 1
# for item in lst:
# if item == login:
# print(f'Login: {login} \
# ... |
__title__ = 'compas_rpc_example'
__description__ = 'examples for using cpython functions in gh/rhino via compas_rpc'
__url__ = 'https://github.com/yijiangh/compas_rpc_examples'
__version__ = '0.0.1'
__author__ = 'Yijiang Huang'
__author_email__ = 'yijiangh@mit.edu'
__license__ = 'MIT license'
__copyright__ = 'Copyright... |
def sort_scores(unsorted_scores, highest_possible_score):
# initialize a new list score_count to the size of highest_possible_score plus one
score_count = [None] * (highest_possible_score + 1)
# initialize sorted_scores to an empty list
sorted_scores = []
# loop through every score in unsorted_scor... |
""" Rolução 1 - modulo math
from math import factorial
n = int(input("Digite um número para calcular seu fatorial: "))
f = factorial(n)
print('O fatorial de {} e {}'.format(n, f))"""
n = int(input('Digite um número para calcular seu Fatorial: '))
c = n
f = 1
print("Calculando {}! = ".format(n), end='')
# while c > 0:
... |
# Poisson Distribution II
lambda_1, lambda_2 = map(float, input().split())
cost_1 = 160 + 40 * (lambda_1 + lambda_1 ** 2)
cost_2 = 128 + 40 * (lambda_2 + lambda_2 ** 2)
print(f'{cost_1:.3f}')
print(f'{cost_2:.3f}')
|
def helloworld():
print("Hello, world!")
def board():
pion = '|'.join([' ']*3)
poziom = '\n{}\n'.format('-'*8)
print(pion,pion,pion,sep=poziom)
def tictactoe():
pion = 'H'.join([' | | ']*3) + '\n'
poziom ='H'.join(['--+--+--']*3) + '\n'
blok = pion.join([poziom]*3)
separator = ... |
# -*- coding: utf-8 -*-
"""Track earth satellite TLE orbits using up-to-date 2010 version of SGP4
This Python package computes the position and velocity of an
earth-orbiting satellite, given the satellite's TLE orbital elements
from a source like `Celestrak <http://celestrak.com/>`_. It implements
the most recent ver... |
"""
This module is automatically generated by SGQLC using introspective queries
on a conservator instance.
The rest of the conservator library is built on top of this autogenerated API.
Run ``generate.sh`` to update these files.
"""
|
"""
Object Oriented Programming
"""
s = "this is a string"
a = "one more string"
s.upper()
s.lower()
print(type('s'))
print(type('a'))
print(type([1, 2, 3])) |
SERVICE_NAME = "org.bluez"
AGENT_IFACE = SERVICE_NAME + ".Agent1"
ADAPTER_IFACE = SERVICE_NAME + ".Adapter1"
DEVICE_IFACE = SERVICE_NAME + ".Device1"
OBJECT_IFACE = "org.freedesktop.DBus.ObjectManager"
PROPERTIES_IFACE = "org.freedesktop.DBus.Properties"
INTROSPECT_IFACE = "org.freedesktop.DBus.Introspectable"
|
# Smallest in v2
b=int(input())
while 1:
b+=1
if 4==len(set(str(b))):
print(b)
break
|
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 16 16:09:11 2014
@author: crousse
"""
class Note(object):
def __init__(self, notesData):
self.folder = notesData['vars']['F_Folder'][0]
self.stim = notesData['vars']['F_Stim'][0]
self.startTime = notesData['vars']['F_Tbgn'][0]
... |
class BuilderStepError(Exception):
pass
class HttpAdapterError(Exception):
pass
|
# EXERCICIO 099 - FUNÇÃO QUE DESCOBRE O MAIOR
def maior(*num):
cont = maior = 0
for n in num:
if cont == 0 or n > maior:
maior = n
cont += 1
print(f'Foram digitados {cont} números e o maior foi {maior}')
maior(2,6,7,3,5,7)
maior(0,4,63,2)
maior(1,2,3)
maior()
|
#!/usr/bin/env python
# coding: utf-8
# In[277]:
############################
# Traffic Light Checker
#
# C. Morgenstern | 16.07.21
############################
# In[278]:
# prompt user for input sequence
inp = input('Traffic light sequence: ')
# In[279]:
# specify traffic light codes
code = ['R', 'Y', 'G',... |
#!/usr/bin/env python3
#https://codeforces.com/problemset/problem/1196/B
#贪心构建..
#比想象的复杂...可能是逻辑不够简练..
#tc2错了好多次
#tc3又超时, 不能用sum?? python的问题? 换成python3就好了,因为PyPy处理输入太慢!
def f(l1,l):
n,k = l1
if sum(l)%2!=k%2:
return [['NO']]
dl = []
s = 0
for i in range(n):
s += l[i]
if ... |
# the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025−385=2640
# Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
def vsota_kvadratov(n):
""" Vrne vsoto kvadratov naravnih števil do n.... |
# -*- coding: utf-8 -*-
VERSION = (0, 5, 0, "dev0")
__version__ = '.'.join(str(x) for x in VERSION)
__all__ = []
|
london = [[0, [], [], [], []],
[1, [8, 9], [58, 46], [46], []],
[2, [10, 20], [], [], []],
[3, [4, 11, 12], [22, 23], [], []],
[4, [3, 13], [], [], []],
[5, [15, 16], [], [], []],
[6, [7, 29], [], [], []],
[7, [6, 17], [42], [], []],
... |
def score(input):
if (input[2]) <= (2.449999988079071):
var0 = [1.0, 0.0, 0.0]
else:
if (input[3]) <= (1.75):
if (input[2]) <= (4.950000047683716):
if (input[3]) <= (1.6500000357627869):
var0 = [0.0, 1.0, 0.0]
else:
... |
"""
All the request/response classes.
"""
class trigger_request():
def __init__(self) :
self.trigger_type = str()
self.machine = str()
return
|
"""
Determine index of characters that differs from the others in respect to
being alphanumeric or not.
alphanumeric == abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
Examples:
['A', 'f', '.', 'Q', 2] # returns index 2 (dot differs as non-alphanumeric)
['.', '{', ' ^', '%', 'a'] # returns index 4 ('... |
#Intented convert a binary number to your decimal equivalent.
class Binary:
def __init__(self, binary_number):
#Intented convert a binary number to your decimal equivalent.
self.binary_number = binary_number
self.check_character()
self.check_qty_character()
self.bi... |
def gcd(a, b):
if b > a:
if b % a == 0:
return a
else:
return gcd(b % a, a)
else:
if a % b == 0:
return b
else:
return gcd(b, a % b)
def find_d(phi_n, e):
k = 1
mod0 = False
while not mod0:
... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
#递归的方法,考虑每种情况
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
if (not root.left) and (not root.right):
... |
a = 'aa'
valor = 0
print(type(a))
if type(a) == int:
valor = int
print(valor)
print('numero')
if type(a) == str:
valor = str
print('letras')
print(valor)
p = valor(input('Digite algo: '))
print(p) |
'''
QRCode Facade.
=============
The :class:`QRCode` is to provide suite of tools for handling QR codes
in your desktop devices.
It currently supports scanning code, reading file, encode qr and
getting available qr data type list.
Custom Requirements
-------------------
OSX: qrtools, zbar, pypng
Linux: qrtool... |
'''
Author: Chuanbin Wang - wcb@sloong.com
Date: 1970-01-01 08:00:00
LastEditTime: 2021-01-28 20:28:46
LastEditors: Chuanbin Wang
FilePath: /crawler/src/rules/onvshen.py
Copyright 2015-2020 Sloong.com. All Rights Reserved
Description:
'''
baseurl = 'http://www.situge.ooo/archiver/' # 需要爬数据的网址
domain = 'http://www.si... |
a=float(input())
b=float(input())
media = (a*0.6) + (b*0.4)
print(f'Média final: {media:.1f}')
|
__author__ = 'nikaashpuri'
'''
from tastypie.resources import ModelResource
from machine.models import Device
from tastypie.authentication import ApiKeyAuthentication
from tastypie.authorization import Authorization
from django.contrib.auth.models import User
class DeviceResource(ModelResource):
class Meta:
... |
def fib(i):
if i <= 0:
return 0
elif i == 1:
return 1
return fib(i-1) + fib(i-2)
def fib_m_(i, memo):
if i <= 0:
return 0
elif i == 1:
return 1
elif i in memo:
return memo[i]
a = fib_m_(i-1, memo)
memo[i-1] = a
b = fib_m_(i-2, memo)
memo... |
# Este código tem como objetivo retornar a hora local do destino quando o usuário informa:
# - A hora de Saída;
# - O tempo de Viagem;
# - E o fuso horário de destino em relação à origem.
# ----------------Regras-----------------------
def validaPartida(partida) :
if (partida >= 0 and partida <=23):
... |
#calculo de uma média de duas notas
num = int(input('Por favor digite o número de alunos da sala : '))
for i in range(0,num):
nota1=float(input('Digite a primeira nota: '))
nota2=float(input('Digite a segunda nota: '))
mean = (nota1+nota2)/2
if mean > 7:
print('Aluno Aprovado')
elif mean >= ... |
class Array:
def __init__(self,name) -> None:
self.name=name
pass
def gen_array(self,length):
self.name=[None for i in range(length)]
def gen_2D_array(self,width=10,height=10):
self.name=[[None for i in range(width)] for j in range(height)]
def add_array(... |
class NumberComputer:
def reachable_nodes(self, n):
result = set()
stack = [n]
while len(stack) != 0:
node = stack.pop()
assert (node in self.interval)
if node in result:
continue
result.add(node)
for succ in self.succ_func(node):
if succ in self.interval:
stack.append(succ)
# sa... |
#!/usr/bin/env python
class LinkedList:
def __init__(self):
self.first_n = None
def get_smallest(self):
if self.first_n != None:
return self.first_n.get_item()
else:
return None
def insert_item(self, item):
if self.first_n == None: ... |
__author__ = 'Kwame'
print("massive!!!")
|
class EulerTour:
"""Abstract base class for performing Euler tour of a tree.
_hook_previsit ans _hook_postvisit may be overriden by subclasses.
"""
def __init__(self,tree):
"""Prepare an Euler tour template for given tree."""
self._tree = tree
def tree(self):
"""Return refe... |
class Solution(object):
def reverseWords(self, s: str) -> str:
s = [x for x in s.split(" ") if len(x) > 0]
print(s)
i = 0
j = len(s) - 1
while i < j:
s[i], s[j] = s[j], s[i]
i += 1
j -= 1
return " ".join(s) if len(s) > 0 else ""
|
# Some meta data for conversion, etc.
# TODO: need a way to match skeleton
# personnel / girl / trooper
skel1 = [
"foot_r", "calf_r", "thigh_r", "thigh_l", "calf_l",
"foot_l", "pelvis", "neck_01", None, None,
"hand_r", "lowerarm_r", "upperarm_r", "upperarm_l", "lowerarm_l",
"hand_l"
]
skel_edge = [
... |
# Keys in the extracted lexicon
# These are also the keys used to parse the NIH lexicon, although keys
# that are only used for parsing and don't end up in the final are not
# included here.
class SKey(object):
# The "categories", aka Part-of-Speech in Lexicon
NOUN = 'noun'
ADJ = 'adj'
AD... |
# Given nums = [3,2,2,3], val = 3,
# Your function should return length = 2, with the first two elements of nums being 2.
class RemoveElement:
def __init__(self, nums, val):
self.nums = nums
self.val = val
def remove_element(self):
count = 0
for i in range(len(self.nums)):
... |
frase = str(input("Digite uma frase qualquer: "))
frase_original = frase.strip().replace(" ", "").upper()
frase_nova = ""
frase_nova = frase_original[::-1]
'''for c in range(len(frase_original), 0, -1):
frase_nova += frase_original[c - 1]'''
print("O inverso de {0} e {1}.".format(frase_original, frase_nova))
if(... |
def go (array):
if len(array)==1:
return array[0]
else:
count = 0
for i in range(0,len(array),2):
array[i]=0
count +=1
for i in range(count):
array.remove(0)
return go(array)
lis = list(range(1,int(input())+1,1)... |
def to8BitUnsigned(value):
return value.to_bytes(length=1, byteorder='little', signed=False)
def to16BitUnsigned(value):
return value.to_bytes(length=2, byteorder='little', signed=False)
def to16BitSigned(value):
return value.to_bytes(length=2, byteorder='little', signed=True)
def to32BitUnsigned(value):
retu... |
class Pipeline:
def __init__(self, *args):
self.__steps = list(args)
def apply_to(self, text):
for step in self.__steps:
text = step.annotate(text)
return text
def add_step(self, step):
self.__steps.append(step)
|
# lists
line = [2, 1, 5, 6, 3, 4, 11]
# functions
len(line) #7 lenght of
min(line) #1 max value
max(line) #11 min value
sum(line) #32 sum whole list
sorted(line) #[1, 2, 3, 4, 5, 6, 11] sorted
#slices
line[0:2] # [2, 1]
line[2:4] # [5, 6]
line[4:6] # [3, 4]
line[0:7] # [2, 1, 5, 6, 3, 4, 11]
line[2:] # [5, 6, 3, 4, 1... |
'''
Given a sequence of integers, where each element is distinct and satisfies . For each where , find any integer such that and print the value of on a new line.
Function Description
Complete the permutationEquation function in the editor below. It should return an array of integers that represent the values of... |
"""
Copia los elementos que están desde el 44 y el 55 (no incluido) en la tupla,
creando una nueva tupla. Usamos ínidices positivos y negativos, según las necesidades
tupla = (1, 2, 3, 44, 66, 77, 78, 2, 1, 55, 90, 100)
nueva_tupla = (44, 66, 77, 78, 2, 1)
"""
tuple_list = (1, 2, 3, 44, 66, 77, 78, 2, 1, 55, 90, 100)... |
'''
Created on 19 июн. 2019 г.
@author: krtkr
'''
class DrawItem(object):
'''
classdocs
'''
NO_FILL = 'N'
FILLED_SHAPE = 'F'
FILLED_WITH_BG_BODYCOLOR = 'f'
def __init__(self, unit = 0, convert = 0, filltype = NO_FILL):
self.unit = unit
self.convert = convert
self.... |
'''
https://leetcode.com/problems/largest-rectangle-in-histogram/
84. Largest Rectangle in Histogram
Given an array of integers heights representing the histogram's bar height where the
width of each bar is 1, return the area of the largest rectangle in the histogram.
'''
'''
Brute force: we cons... |
PAGE_TITLE = "Data Submission"
SECTION_TITLE = "Data Submission"
SUBJECT_TYPE = "Register a new clinic"
|
cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
print("There are", cars, "cars available.")
print("There are only", drivers, "drivers available.")
p... |
"""
----------------------------------------------
PIXEL_FORMAT
----------------------------------------------
"""
def get_pixel_format(subsampling, depth):
""" helper to set pixel format from subsampling, assuming full range,
for converting source to yuv prior to encoding
"""
pixel_format = None
... |
# ! Useful math library
def sqr(a):
"""Mettre au carré"""
return a*a
|
MESSAGES_STARBOARD_MESSAGE = """CREATE UNIQUE INDEX IF NOT EXISTS
messages_starboard_message
ON messages (starboard_message_id)"""
ALL_INDEXES = [MESSAGES_STARBOARD_MESSAGE]
|
class Solution(object):
mem={}
def canWin2(self, s):
"""
:type s: str
:rtype: bool
"""
# check mem first
if s in self.mem:
return self.mem[s]
# can I win? if no moves to go then return False since I cannot win.
nextMove=self.moves(s)
... |
"""
John McDonough
github - movinalot
Advent of Code 2020
"""
# pylint: disable=invalid-name
TESTING = 0
TESTFILE = 0
DEBUG = 0
DAY = "06"
YEAR = "2020"
PART = "2"
ANSWER = None
PUZZLE_DATA = None
def process_puzzle_input(ext=".txt"):
""" Process puzzle input """
with open("puzzle_data_" +... |
def lcm(a: int, b: int) -> int:
"""Return a LCM (Lowest Common Multiple) of given two integers
>>> lcm(3, 10)
30
>>> lcm(42, 63)
126
>>> lcm(40, 80)
80
>>> lcm(-20, 30)
60
"""
g = min(abs(a), abs(b))
while g >= 1:
if a % g == 0 and b % g == 0:
break
... |
username = 'billgates@microsoft.com'
password = 'i-love-cortana'
home_path = '~/chromedriver'
app_name = 'myapp_v01'
subscription = 'azure-subscription-dropdown'
authoring_resource = "your-authoring-resource"
|
class OmnikassaException(Exception):
pass
class InvalidResponseCode(OmnikassaException):
def __init__(self, data):
self.data = data
def __str__(self):
return 'Got responseCode {}'.format(self.data['responseCode'])
class InvalidSeal(OmnikassaException):
def __init__(self, data):
... |
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dct = {}
for i in range(len(nums)):
if (dct.get(target-nums[i], -1) == -1):
dct[nums[i]] = i
else:
return [dct.get(target-nums[i]), i] |
# -*- coding: utf-8 -*-
# @Time : 2019-08-06 14:19
# @Author : Kai Zhang
# @Email : kai.zhang@lizhiweike.com
# @File : 01-stack.py
# @Software: PyCharm
# 自定义栈空异常
class StackEmptyError(ValueError):
def __str__(self):
return 'The Stack Object is Empty.'
# 栈的模拟实现
class Stack(object):
# 初始化栈为空 ... |
class Solution:
# keep pre-computed fibs around.
fibs = [
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610,
987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368,
75025, 121393, 196418, 317811, 514229, 832040, 1346269,
2178309, 3524578, 5702887, 9227465, 14930352, 24157... |
with open("data/modelnet40_normal_resampled/modelnet40_test_orig.txt") as f:
lines = f.readlines()
lines = lines[::13]
with open("data/modelnet40_normal_resampled/modelnet40_test.txt", 'w') as f2:
for line in lines:
f2.write(line)
|
cidade = str(input("insira o nome da cidade que você nasceu: ")).strip()
print(cidade[:5].upper() == "SANTO")
# remove o as strip da string e então com upper coloca tudo em maiuscula para identificar o código.
|
#############################################################
# 2016-09-26: MessageIdType.py
# Author: Jeremy M. Gibson (State Archives of North Carolina)
#
# Description: Implementation of message-id-type
##############################################################
class MessageId:
""""""
def __init__(sel... |
'''29 Escreva um programa que leia a velocidade de um carro.
Se ele ultrapassar 80Km/h, mostre uma mensagem dizendo que ele foi multado.
A multa vai custar R$7,00 por cada Km acima do limite.'''
velocidade = int(input("Digite a velocidade: "))
if velocidade <= 80:
print("Tenha um bom dia! Dirija com segurança!"... |
class Keys:
"""Remap the keypresses from numbers to variables."""
UP = 259
DOWN = 258
LEFT = 260
RIGHT = 261
ENTER = 10
SPACE = 32
ESC = 27
W = 119
A = 97
S = 115
D = 100
# DEFAULT KEYS
Q = 113
TAB = 9
PG_... |
#!/usr/bin/env python3
# -*- coding: utf8 -*-
class BaseCrawler:
start_url = ''
browser = None
dir_path = ''
def __init__(self, browser, dir_path):
self.browser = browser
self.dir_path = dir_path
self.crawl(self.start_url)
def get_html(self, url):
self.browser.ge... |
# Given an array, sort it using mergesort
def merge(a, start, mid, end, aux):
for i in range(len(a)):
aux[i] = a[i]
left = start
right = mid+1
i = left
while left <= mid and right <= end:
if aux[left] < aux[right]:
a[i] = aux[left]
left += 1
i += 1
else:
a[i] = aux[right]
right += 1
i ... |
n = int(input())
s = [list(map(int, input().split())) for _ in [0] * n]
s = sorted(s, key=lambda x: x[0])
c = 0
for i in range(10):
i = 0
while (i != len(s)-1 and i < len(s)):
if s[i][1] >= abs(s[i][0] - s[i+1][0]):
c += 1
s.pop(i)
i += 1
print(n-c)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 切片 slice 对list,tuple和字符串进行截取
L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
# L[0:3]表示从0开始取,直到索引3为止,但不包括3
print(L[0:3])
# 如果是从0开始,0还可以省略
print(L[:3])
# 从索引1取到3
print(L[1:3])
# 支持取倒数第几个元素
# 倒数第2个元素到最后一个元素
print(L[-2:])
# 倒数第2个元素到最后一个元素(不含最后一个元素)
print(L[-2:-1])
L ... |
name = input('please input your name:')
sql = 'select * from dome where name="%s"' % name
print(sql)
name = 'zr;drop database demo'
sql = 'select * from dome where name="%s"' % name
print(sql)
name = 'zr;drop database demo'
initname = [name]
#csl = 'connect mysqldb successful:'.cursor()
#sql = csl.excu... |
'''
我们在导入一个包时,实际上是导入了它的__init__.py文件
这样我们可以在__init__.py文件中批量导入我们所需要的模块,而不再需要一个一个的导入
__init__.py的第一个作用就是package的标识.如果没有该文件,该目录就不会认为是package
Root目录->Pack1目录(->Pack1Class.py),Pack2目录(->Pack2Class.py)
Python中的包和模块有两种导入方式:精确导入和模糊导入:
精确导入:
from Root.Pack1 import Pack1Class
import Root.Pack1.Pack1Class
模糊导入:
from Root.P... |
class SecurePathProxy:
"""
This class is a good way to change directories without having to remember to go back later.
Use with 'with'!
There's also a very nice method to apply any callable entity in all children folders recursivilly
"""
def __init__(self, os_interfaced_object, path):
se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.