content stringlengths 7 1.05M |
|---|
# An algorithm to reconstruct the queue.
# Suppose you have a random list of people standing in a queue.
# Each person is described by a pair of integers (h,k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h.
class Solution:
de... |
# statements that used at the start of defenition or in statements without columns
defenition_statements = {
"DROP": "DROP",
"CREATE": "CREATE",
"TABLE": "TABLE",
"DATABASE": "DATABASE",
"SCHEMA": "SCHEMA",
"ALTER": "ALTER",
"TYPE": "TYPE",
"DOMAIN": "DOMAIN",
"REPLACE": "REPLACE",
... |
def kmp(P, T):
# Compute the start position (number of chars) of the longest suffix that matches a prefix,
# and store them into list K, the first element of K is set to be -1, the second
#
K = [] # K[t] store the value that when mismatch happens at t, should move Pattern P K[t] characters ahead
t ... |
class _FuncStorage:
def __init__(self):
self._function_map = {}
def insert_function(self, name, function):
self._function_map[name] = function
def get_all_functions(self):
return self._function_map
|
A=int(input("dame int"))
B=int(input("dame int"))
if(A>B):
print("A es mayor")
else:
print("B es mayor")
|
# !/usr/bin/env python3
# Author: C.K
# Email: theck17@163.com
# DateTime:2021-03-15 00:07:14
# Description:
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
result = set()
for i in range(0, len(nums) - 1):
# Reduce the problem to two sum(0)
two_sum =... |
bluelabs_format_hints = {
'field-delimiter': ',',
'record-terminator': "\n",
'compression': 'GZIP',
'quoting': None,
'quotechar': '"',
'doublequote': False,
'escape': '\\',
'encoding': 'UTF8',
'dateformat': 'YYYY-MM-DD',
'timeonlyformat': 'HH24:MI:SS',
'datetimeformattz': 'YY... |
# FROM THE OP PAPER-ISH
MINI_BATCH_SIZE = 32
MEMORY_SIZE = 10**6
BUFFER_SIZE = 100
LHIST = 4
GAMMA = 0.99
UPDATE_FREQ_ONlINE = 4
UPDATE_TARGET = 2500 # This was 10**4 but is measured in actor steps, so it's divided update_freq_online
TEST_FREQ = 5*10**4 # Measure in updates
TEST_STEPS = 10**4
LEARNING_RATE = 0.00025
G_... |
# author: jamie
# email: jinjiedeng.jjd@gmail.com
def Priority (c):
if c == '&': return 3
elif c == '|': return 2
elif c == '^': return 1
elif c == '(': return 0
def InfixToPostfix (infix, postfix):
stack = []
for c in infix:
if c == '(':
stack.append('(')
elif c =... |
class Ciclo:
def __init__(self):
self.cicloNew = ()
self.respu = ()
self.a = ()
self.b = ()
self.c = ()
def nuevoCiclo(self):
cicloNew = []
print(" ")
print("Formulario de ingreso de ciclos")
print("-----------------------------------")
... |
__version__ = 'unknown'
try:
__version__ = __import__('pkg_resources').get_distribution('django_richenum').version
except Exception as e:
pass
|
CHARACTERS_PER_LINE = 39
def break_lines(text):
chars_in_line = 1
final_text = ''
skip = False
for char in text:
if chars_in_line >= CHARACTERS_PER_LINE:
if char == ' ':
# we happen to be on a space, se we can just break here
final_text += '\n'
... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def nextLargerNodes(self, head: ListNode) -> List[int]:
nums = []
while head:
nums.append(head.val)
head = head.next
... |
def is_field(token):
"""Checks if the token is a valid ogc type field
"""
return token in ["name", "description", "encodingType", "location", "properties", "metadata",
"definition", "phenomenonTime", "resultTime", "observedArea", "result", "id", "@iot.id",
"resultQ... |
"""Exception utilities."""
class ParsingException(Exception):
pass
class EnvVariableNotSet(Exception):
def __init__(self, varname: str) -> None:
super(EnvVariableNotSet, self).__init__(f"Env variable [{varname}] not set.")
class InvalidLineUp(Exception):
pass
class UnsupportedLineUp(Exceptio... |
# (major, minor, patch, prerelease)
VERSION = (0, 0, 6, "")
__shortversion__ = '.'.join(map(str, VERSION[:3]))
__version__ = '.'.join(map(str, VERSION[:3])) + "".join(VERSION[3:])
__package_name__ = 'pyqubo'
__contact_names__ = 'Recruit Communications Co., Ltd.'
__contact_emails__ = 'rco_pyqubo@ml.cocorou.jp'
__homep... |
# -*- coding: utf-8 -*-
basic_table = dict(map(lambda s: s.split(u'\t'), u'''
あ a
い i
う u
え e
お o
か ka
き ki
く ku
け ke
こ ko
さ sa
し si
す su
せ se
そ so
た ta
ち ti
つ tu
て te
と to
な na
に ni
ぬ nu
ね ne
の no
は ha
ひ hi
ふ hu
へ he
ほ ho
ま ma
み mi
む mu
め me
も mo
や ya
ゆ yu
よ yo
ら ra
り ri
る ru
れ re
ろ ro
わ wa
を wo
ぁ a
ぃ i
ぅ u
ぇ e
ぉ o
が... |
dis = float(input('Digite a distância da sua viagem em Km: '))
if dis <= 200:
print('O valor da sua passagem será {:.2f} reais'.format(dis * 0.5))
else:
print('O valor da sua passagem será {:.2f} reais'.format(dis * 0.45))
|
#033: ler tres numeros e dizer qual o maior e qual o menor:
print("Digite 3 numeros:")
maiorn = 0
n = int(input("Numero 1: "))
if n > maiorn:
maiorn = n
menorn = n
n = int(input("Numero 2: "))
if n > maiorn:
maiorn = n
if n < menorn:
menorn = n
n = int(input("Numero 3: "))
if n > maiorn:
maiorn = n... |
#!/usr/bin/python3
#coding=utf-8
def cc_debug():
print(__name__) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-03-23
Last_modify: 2016-03-23
******************************************
'''
'''
Say you have an array for which the ith el... |
def drop(i_list: list,n:int) -> list:
"""
Drop at multiple of n from the list
:param n: Drop from the list i_list every N element
:param i_list: The source list
:return: The returned list
"""
assert(n>0)
_shallow_list = []
k=1
for element in i_list:
if k % n != 0:
... |
#!/usr/bin/python3
"""
Given a binary tree, we install cameras on the nodes of the tree.
Each camera at a node can monitor its parent, itself, and its immediate children.
Calculate the minimum number of cameras needed to monitor all nodes of the tree.
Example 1:
Input: [0,0,null,0,0]
Output: 1
Explanation: One c... |
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
DEPS = [
'adb',
'depot_tools/bot_update',
'depot_tools/gclient',
'goma',
'recipe_engine/context',
'recipe_engine/json',
'recipe_engine/path',
... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
##
# Copyright 2017 FIWARE Foundation, e.V.
# 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.apach... |
class Solution:
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
if numRows == 0: return []
rls = [[1]]
for i in range(2, numRows+1):
row = [1] * i
for j in range(1, i-1):
row[j] = rls[-1][... |
def maxProfitWithKTransactions(prices, k):
n = len(prices)
profit = [[0]*n for _ in range(k+1)]
"""
t := number of transactions
d := day at which either buy/sell stock
profit[t][d] = max ( previous day profit = profit[t][d-1] ,
profit sold at this day + max(buy for th... |
# 11. Replace tabs into spaces
# Replace every occurrence of a tab character into a space. Confirm the result by using sed, tr, or expand command.
with open('popular-names.txt') as f:
for line in f:
print(line.strip().replace("\t", " "))
|
""" Test data"""
stub_films = [{
"id": "12345",
"title": "This is film one",
},{
"id": "23456",
"title": "This is film two",
}]
stub_poeple = [{
"name": "person 1",
"films": ["url/12345", "url/23456"]
},{
"name": "person 2",
"films": ["url/23456"]
},{
"name": "person 3",
"film... |
"""
Melhore o Desafio 061, perguntando para o usuário se ele quer mostrar mais alguns termos.
O programa encerra quando ele disser que quer mostrar 0 termos.
"""
primeiro = int(input('Digite o termo: '))
razao = int(input('Digite a razão: '))
termo = primeiro
cont = 1
total = 0
mais = 10
while mais != 0:
total = t... |
s = input()
num = [0] * 26
for i in range(len(s)):
num[ord(s[i])-97] += 1
for i in num:
print(i, end = " ")
if i == len(num)-1:
print(i)
|
# %% [1189. *Maximum Number of Balloons](https://leetcode.com/problems/maximum-number-of-balloons/)
# 問題:textから'ballon'を構成できる数を返せ
# 解法:collections.Counterを用いる
class Solution:
def maxNumberOfBalloons(self, text: str) -> int:
c = collections.Counter(text)
return min(c[s] // n for s, n in collections.C... |
# Source : https://leetcode.com/problems/binary-tree-tilt/description/
# Date : 2017-12-26
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def findTilt(self, root):
"""
... |
class Order():
def __init__(self, side, pair, size, price, stop_loss_price, id):
self.side = side
self.pair = pair
self.size = size
self.price = price
self.stop_loss_price = stop_loss_price
self.id = id
self.fills = []
def define_id(self, id):
se... |
# Ler um número em metros e mostrar seu valor em cm e mm:
m = float(input('Digite o valor em metros: '))
dm = m * 10
cm = m * 100
mm = m * 1000
km = m/1000
hm = m/100
dam = m/10
print('O valor em cm é {}' .format(cm))
print('O valor em milímetros é {}' .format(mm))
print('O valor em dm é {}' .format(dm))
print('O val... |
word = input('Type a word: ')
while word != 'chupacabra':
word = input('Type a word: ')
if word == 'chupacabra':
print('You are out of the loop')
break |
# Copyright 2021 The Pigweed Authors
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
class Programa:
def __init__(self, nome, ano):
self._nome = nome.title()
self.ano = ano
self._likes = 0
@property
def likes(self):
return self._likes
def dar_like(self):
self._likes += 1
@property
def nome(self):
return self._nome
@nome.set... |
def factorial(n):
fact = 1
for i in range(2,n+1):
fact*= i
return fact
def main():
n = int(input("Enter a number: "))
if n >= 0:
print(f"Factorial: {factorial(n)}")
else:
print(f"Choose another number")
if __name__ == "__main__":
main()
|
users = []
class UserModel(object):
"""Class user models."""
def __init__(self):
self.db = users
def add_user(self, fname, lname, email, phone, password, confirm_password, city):
""" Method for saving user to the dictionary """
payload = {
"userId": len(self.db)+1,
... |
#Задачи на циклы и оператор условия------
#----------------------------------------
'''
Задача 1
Вывести на экран циклом пять строк из нулей, причем каждая строка должна быть пронумерована.
'''
for i in range(1, 6):
print(i, '0000000000000000000000000000000000000000000')
'''
Задача 2
Пользователь в цикле вводит 1... |
#DATOS DE ENTRADA
ANIMAL= int(input("¿De cual animal quiere conocer la caracteristicas? 1.Leon 2.Ballena 3.Tucan? "))
class Animal:
def __init__(self, ANIMAL):
self.ANIMAL = ANIMAL
def acciones_comun():
comun = "Comer"
return comun
def sentido_vista():
vista = ... |
"""
Entradas:
lectura actual--->float--->lect2
lectura anterior--->float--->lect1
valor kw--->float--->valorkw
Salidas:
consumo--->float--->consumo
total factura-->flotante--->total
"""
lect2 = float ( entrada ( "Digite lectura real:" ))
lect1 = float ( entrada ( "Digite lectura anterior:" ))
valorkw = float ( input ( ... |
data = input()
courses = {}
while ":" in data:
student_name, id, course_name = data.split(":")
if course_name not in courses:
courses[course_name] = {}
courses[course_name][id] = student_name
data = input()
searched_course = data
searched_course_name_as_list = searched_course.split("_")
se... |
nums = list()
while True:
nStr = input('Enter a number: ')
try:
if nStr == 'done':
break
n = float(nStr)
nums.append(n)
except:
print('Invalid input')
continue
print('Maximum: ',max(nums))
print('Minimum: ',min(nums)) |
# to run this, add code from experiments_HSCC2021.py
def time_series_pulse():
path = Path(__file__).parent.parent / "data" / "real_data" / "datasets" / "basic_data"
filename1 = path / "pulse1-1.csv"
filename2 = path / "pulse1-2.csv"
filename3 = path / "pulse1-3.csv"
f1 = load_time_series(filename1,... |
#Day 1.3 Exercise!!
#First way I thought to do it without help
name = input("What is your name? ")
print(len(name))
#Way I found to do it from searching google
print(len(input("What is your name? "))) |
#-- THIS LINE SHOULD BE THE FIRST LINE OF YOUR SUBMISSION! --#
def tally(costs, discounts, rebate_factor):
cost = sum(costs)
discount = sum(discounts)
pre = (cost - discount) * rebate_factor
if pre < 0:
return 0
else:
return round(pre, 2)
#-- THIS LINE SHOULD BE THE LAST LINE OF ... |
def soma (a,b):
print(f'A = {a} e B = {b}')
s=a+b
print(f'A soma A + B ={s}')
#Programa Principal
soma(4,5)
|
def GCD(a,b):
if b == 0:
return a
else:
return GCD(b, a%b)
a = int(input())
b = int(input())
print(a*b//(GCD(a,b)))
|
# -*- coding:utf-8 -*-
"""
"""
__date__ = "14/12/2017"
__author__ = "zhaojm"
|
__author__ = 'Aaron Yang'
__email__ = 'byang971@usc.edu'
__date__ = '10/28/2020 4:52 PM'
# import re
#
#
# def format_qs_score(score_str):
# """
# help you generate a qs score
# 1 - 100 : 5
# 141-200 : 4
# =100: 4
# N/A 3
# :param score_str:
# :return:
# """
# score = 3
# if... |
def Linear_Search(Test_arr, val):
index = 0
for i in range(len(Test_arr)):
if val > Test_arr[i]:
index = i+1
return index
def Insertion_Sort(Test_arr):
for i in range(1, len(Test_arr)):
val = Test_arr[i]
j = Linear_Search(Test_arr[:i], val)
Test_arr.pop(i)
... |
class Wrapper(object):
wrapper_classes = {}
@classmethod
def wrap(cls, obj):
return cls(obj)
def __init__(self, wrapped):
self.__dict__['wrapped'] = wrapped
def __getattr__(self, name):
return getattr(self.wrapped, name)
def __setattr__(self, name, value):
set... |
height = int(input())
for i in range(1,height+1) :
for j in range(1, i+1):
m = i*j
if(m <= 9):
print("",m,end = " ")
else:
print(m,end = " ")
print()
# Sample Input :- 5
# Output :-
# 1
# 2 4
# 3 6 9
# 4 8 12 16
# 5 10 15 20 25
|
# Continuação do ex061 (Termos de PA)
print('Gerador de PA')
print('-=' * 10)
primeiro = int(input('Primeiro termo: '))
razão = int(input('Razão: '))
i = 0
n = 10
novos = 10
total = 0
while novos != 0:
total = total + novos
while i < total:
termo = primeiro + razão * i
i += 1
print(termo... |
"""WWUCS Bot module."""
__all__ = [
"__author__",
"__email__",
"__version__",
]
__author__ = "Reilly Tucker Siemens"
__email__ = "reilly@tuckersiemens.com"
__version__ = "0.1.0"
|
"""
=========== What is Matter Parameters ===================
"""
#tups = [(125.0, 1.0), (125.0, 1.5), (125.0, 2.0), (125.0, 2.5), (125.0, 3.0), (150.0, 1.0), (150.0, 1.5), (150.0, 2.0), (150.0, 2.5), (150.0, 3.0), (175.0, 1.0), (175.0, 1.5), (175.0, 2.0), (175.0, 2.5), (175.0, 3.0), (200.0, 1.0), (200.0, 1.5), (200.0,... |
x = 2
print(x)
# multiple assignment
a, b, c, d = (1, 2, 5, 9)
print(a, b, c, d)
print(type(str(a)))
|
"""
Conjuntos
— Conjunto em qualquer linguagem de programação, estamos fazendo referência à teoria de conjuntos da matemática
— Aqui no Python, os conjuntos são chamados de sets
Dito isto, da mesma forma que na matemática:
— Sets (conjuntos) não possuem valores duplicados;
— Sets (conjuntos) não possuem valores ordena... |
# OpenWeatherMap API Key
weather_api_key = "ae41fcf95db0d612b74e2b509abe9684"
# Google API Key
g_key = "AIzaSyCuF1rT6NscWq62bcBm0tZM7hKlaeWfONQ" |
"""File for holding the different verb forms for all of the verbs in the Total
English book series."""
verb_forms = {
'become' :
{
'normal' : 'become',
'present' : ['become','becomes'],
'past' : 'became',
'past participle' : 'become',
'gerund' : 'becoming',
},
'be':
{
'n... |
# SPDX-FileCopyrightText: © 2020 The birch-books-smarthome Authors
# SPDX-License-Identifier: MIT
BOOKSTORE_GROUND_FLOOR = 0x0007
BOOKSTORE_FIRST_FLOOR = 0x0008
BOOKSTORE_TERRARIUM = 0x0010
BOOKSTORE_BEDROOM = 0x0020
HOUSE_BASEMENT = 0x0040
HOUSE_GROUND_FLOOR = 0x0380
HOUSE_BEDROOM_LIGHT = 0x0400
HOUSE_BEDROOM_LAMP = ... |
"""Role testing files using testinfra"""
def test_config_directory(host):
"""Check config directory"""
f = host.file("/etc/influxdb")
assert f.is_directory
assert f.user == "influxdb"
assert f.group == "root"
assert f.mode == 0o775
def test_data_directory(host):
"""Check data directory""... |
def apply(con, target_language="E"):
dict_field_desc = {}
try:
df = con.prepare_and_execute_query("DD03T", ["DDLANGUAGE", "FIELDNAME", "DDTEXT"], " WHERE DDLANGUAGE = '"+target_language+"'")
stream = df.to_dict("records")
for el in stream:
dict_field_desc[el["FIELDNAME"]] = e... |
#AFTER PREPROCESSING AND TARGETS DEFINITION
newdataset.describe()
LET_IS.value_counts()
LET_IS.value_counts().plot(kind='bar', color='c')
Y_unica.value_counts()
Y_unica.value_counts().plot(kind='bar', color='c')
ZSN.value_counts().plot(kind='bar', color='c')
Survive.value_counts().plot(kind='bar', color='c')
|
def binarySearch(inputArray, searchElement):
minIndex = -1
maxIndex = len(inputArray)
while minIndex < maxIndex - 1:
currentIndex = (minIndex + maxIndex) // 2
currentElement = inputArray[currentIndex]
if currentElement < searchElement:
minIndex = currentIndex
... |
d_soldiers = []
class Soldier:
def __init__(self, id, name, team):
self.id = id
self.name = name
self.team = team
self.x = 0
self.y = 0
self.xVelo = 0
self.yVelo = 0
self.kills = 0
self.deaths = 0
self.alive = 'true'
self.driving = 'false'
self.gun = 0
self.ammo = 0
self.reloading = 'fa... |
#from http://rosettacode.org/wiki/Greatest_subsequential_sum#Python
#pythran export maxsum(int list)
#pythran export maxsumseq(int list)
#pythran export maxsumit(int list)
#runas maxsum([0, 1, 0])
#runas maxsumseq([-1, 2, -1, 3, -1])
#runas maxsumit([-1, 1, 2, -5, -6])
def maxsum(sequence):
"""Return maximum sum."... |
def task_clean_junk():
"""Remove junk file"""
return {
'actions': ['rm -rdf $(find . | grep pycache)'],
'clean': True,
}
|
def gfg(x,l = []):
for i in range(x):
l.append(i*i)
print(l)
gfg(2)
gfg(3,[3,2,1])
gfg(3)
|
"""Module help_info."""
__author__ = 'Joan A. Pinol (japinol)'
class HelpInfo:
"""Manages information used for help purposes."""
def print_help_keys(self):
print(' F1: \t show a help screen while playing the game'
' t: \t stats on/off\n'
' L_Ctrl + R_Alt + g... |
n = []
i = 0
for c in range(0, 5):
n1 = int(input('Digite um valor: '))
if c == 0 or n1 > n[-1]:
n.append(n1)
print(f'Adicionado na posição {c} da lista...')
else:
pos = 0
while pos < len(n):
if n1 <= n[pos]:
n.insert(pos, n1)
print... |
def format_sql(schedule, table):
for week, schedule in schedule.items():
print(f"UPDATE {table} SET `block`=0, `week`={week} WHERE `name`='{schedule.leader}';")
for block, staffs in schedule.staffs.items():
for staff in staffs:
print(f"UPDATE {table} SET `block`={block}, ... |
class Node(object):
# XXX: legacy code support
kind = property(lambda self: self.__class__)
def _iterChildren(self):
for name in self.childAttrNames:
yield (name, getattr(self, name))
return
children = property(_iterChildren)
def dump(self, stream, indent=0):
... |
friendly_camera_mapping = {
"GM1913": "Oneplus 7 Pro",
"FC3170": "Mavic Air 2",
# An analogue scanner in FilmNeverDie
"SP500": "Canon AE-1 Program"
}
|
# Defutils.py -- Contains parsing functions for definition files.
# Produces an organized list of tokens in the file.
def parse(filename):
f=open(filename, "r")
contents=f.read()
f.close()
# Tokenize the file:
#contents=contents.replace('\t', '\n')
lines=contents.splitlines()
outList=[]
... |
class Solution:
# @param s, a string
# @param wordDict, a set<string>
# @return a string[]
def wordBreak(self, s, wordDict):
n = len(s)
res = []
chars = ''.join(wordDict)
for i in xrange(n):
if s[i] not in chars:
return res
lw = s[-1]
... |
# -*- coding:utf-8 -*-
class BaseProvider(object):
@staticmethod
def loads(link_url):
raise NotImplementedError("Implemetion required.")
@staticmethod
def dumps(conf):
raise NotImplementedError("Implemetion required.")
|
session.forget()
def get(args):
if args[0].startswith('__'):
return None
try:
obj = globals(), get(args[0])
for k in range(1, len(args)):
obj = getattr(obj, args[k])
return obj
except:
return None
def vars():
"""the running controller function!"""
... |
# https://codegolf.stackexchange.com/a/11480
multiplication = []
for i in range(10):
multiplication.append(i * (i + 1))
for x in multiplication:
print(x) |
"""
PSET-7
Part 2: Triggers (PhraseTriggers)
At this point, you have no way of writing a trigger that matches on
"New York City" -- the only triggers you know how to write would be
a trigger that would fire on "New" AND "York" AND "City" -- which
also fires on the phrase "New students at York University love the
c... |
# flake8: noqa
# errmsg.h
CR_ERROR_FIRST = 2000
CR_UNKNOWN_ERROR = 2000
CR_SOCKET_CREATE_ERROR = 2001
CR_CONNECTION_ERROR = 2002
CR_CONN_HOST_ERROR = 2003
CR_IPSOCK_ERROR = 2004
CR_UNKNOWN_HOST = 2005
CR_SERVER_GONE_ERROR = 2006
CR_VERSION_ERROR = 2007
CR_OUT_OF_MEMORY = 2008
CR_WRONG_HOST_INFO = 2009
CR_LOCALHOST_... |
# -*- coding: utf-8 -*-
class HTTP:
BAD_REQUEST = 400
UNAUTHORIZED = 401
FORBIDDEN = 403
NOT_FOUND = 404
METHOD_NOT_ALLOWED = 405
CONFLICT = 409
UNSUPPORTED_MEDIA_TYPE = 415
|
resposta = 'Ss'
numeros = 0
listaTODOS = []
listaPAR = []
listaIMPAR = []
while resposta != 'N':
numeros = int(input('Digite um número: '))
resposta = str(input('Deseja continuar [S/N]? '))
if numeros % 2 == 0:
listaPAR.append(numeros)
elif numeros % 2 == 1:
listaIMPAR.append(numeros)
... |
"""
面试题 29:顺时针打印矩阵
题目:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
"""
def make_matrix(rows: int, cols: int) -> list:
res = []
k = 0
for i in range(rows):
tmp = []
for j in range(cols):
k += 1
tmp.append(k)
res.append(tmp)
return res
def print_matrix_clockwisely(m... |
"""EnvSpec class."""
class EnvSpec:
"""EnvSpec class.
Args:
observation_space (akro.Space): The observation space of the env.
action_space (akro.Space): The action space of the env.
"""
def __init__(self, observation_space, action_space):
self.observation_space = observation... |
#
# PySNMP MIB module CISCO-DIAMETER-BASE-PROTOCOL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-DIAMETER-BASE-PROTOCOL-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:54:20 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pyt... |
# problem 29
# Distinct powers
"""
Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:
2**2=4, 2**3=8, 2**4=16, 2**5=32
3**2=9, 3**3=27, 3**4=81, 3**5=243
4**2=16, 4**3=64, 4**4=256, 4**5=1024
5**2=25, 5**3=125, 5**4=625, 5**5=3125
If they are then placed in numerical order, with any repeats removed,... |
cantidad= input("Cuantas personas van a cenar?")
cant = int(cantidad)
print(cant)
if cant > 8:
print("Lo siento, tendran que esperar")
else:
print("La mesa esta lista")
|
def parse_cookie(query: str) -> dict:
res = {}
if query:
data = query.split(';')
for i in data:
if '=' in i:
res[i.split('=')[0]] = '='.join(i.split('=')[1:])
return res
if __name__ == '__main__':
assert parse_cookie('name=Dima;') == {'name': 'Dima'}
as... |
dbConfig = {
"user": "root",
"password": "123567l098",
"host": "localhost",
"database": "trackMe_dev"
} |
def pol_V(offset=None):
yield from mv(m1_simple_fbk,0)
cur_mono_e = pgm.en.user_readback.value
yield from mv(epu1.table,6) # 4 = 3rd harmonic; 6 = "testing V" 1st harmonic
if offset is not None:
yield from mv(epu1.offset,offset)
yield from mv(epu1.phase,28.5)
yield from mv(pgm.en,cur_mon... |
COGNITO = "Cognito"
SERVERLESS_REPO = "ServerlessRepo"
MODE = "Mode"
XRAY = "XRay"
LAYERS = "Layers"
HTTP_API = "HttpApi"
IOT = "IoT"
CODE_DEPLOY = "CodeDeploy"
ARM = "ARM"
GATEWAY_RESPONSES = "GatewayResponses"
MSK = "MSK"
KMS = "KMS"
CWE_CWS_DLQ = "CweCwsDlq"
CODE_SIGN = "CodeSign"
MQ = "MQ"
USAGE_PLANS = "UsagePlans... |
EDGE = '101'
MIDDLE = '01010'
CODES = {
'A': (
'0001101', '0011001', '0010011', '0111101', '0100011', '0110001',
'0101111', '0111011', '0110111', '0001011'
),
'B': (
'0100111', '0110011', '0011011', '0100001', '0011101', '0111001',
'0000101', '0010001', '0001001', '0010111'
... |
# List Comprehensions
#########################
### Basic List Comprehensions
#########################
# allow us to circumvent constructing lists with for loops
l = [] # The Old Way
for n in range(12):
l.append(n**2)
[n ** 2 for n in range(12)] # Comprehension way
# General Syntax:
# [ ... |
class network_x_utils:
"""
This class provides commonly used utils which are shared between all different types
of NetworkX nodes (Feed Items, Solutions, Myths). For each of these, we want to be
able to pull basic information like the IRI, Descriptions, Images, etc.
Include any generalized Networ... |
# -*- coding: utf-8 -*-
# Copyright: (c) 2015, Peter Sprygada <psprygada@ansible.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
class ModuleDocFragment(object):
# Standard files documentation fragment
DOCUMENTATION = r'''
options:
provider:
descriptio... |
class Display():
def __init__(self, width, height):
self.width = width
self.height = height
def getSize(self):
return (self.width, self.height)
|
# O(n ** 2)
def bubble_sort(slist, asc=True):
need_exchanges = False
for iteration in range(len(slist))[:: -1]:
for j in range(iteration):
if asc:
if slist[j] > slist[j + 1]:
need_exchanges = True
slist[j], slist[j + 1] = slist[j + 1], ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.