content stringlengths 7 1.05M |
|---|
#common utilities for all module
def trap_exc_during_debug(*args):
# when app raises uncaught exception, print info
print(args) |
# Copyright 2011 Nicholas Bray
#
# 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 agreed to in writing... |
def optical_flow(img_stack):
"""
Given an image stack (N, H, W, C) calculate the optical flow
beginning from the center image (rounded down) towards either
end.
Returns the disparity maps stackes as (N, H, W, 2)
"""
pass
|
class Calculator(object):
def __init__(self, corpus, segment_size):
self.corpus = corpus
self.segment_size = segment_size
@staticmethod
def calc_proportion(matches, total):
"""
Simple float division placed into a static method to prevent Zero division error.
"""
... |
"""
ytsync.py
Synchronize YouTube playlists on a channel to local storage.
Downloads all videos using youtube-dl.
"""
|
def summation(number):
total = 0
for num in range(number + 1):
total += num
return total
if __name__ == "__main__":
print(summation(1000)) |
a = int(input('Informe um numero:'))
if a%2 == 0 :
print("Par!")
else:
print('Impar!') |
class Piece:
def __init__(self, board, square, white):
self.square = square
self.row = square[0]
self.col = square[1]
self.is_clicked = False #dk if i need this
self._white = white
self.pinned = False
#self.letter
def move(self):
pass
def che... |
print('please input the starting annual salary(annual_salary):')
annual_salary=float(input())
print('please input The portion of salary to be saved (portion_saved):')
portion_saved=float(input())
print("The cost of your dream home (total_cost):")
total_cost=float(input())
portion_down_payment=0.25
current_savings=0
nu... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
mylist = [ "a", 2, 4.5 ]
myotherlist = mylist[ : ]
mylist[1] = "hello"
print(myotherlist)
mytext = "Hello world"
myothertext = mytext
mytext = "Hallo Welt!"
#print(myothertext)
print(mylist[ : ])
|
'''
Pig Latin: Rules
if word starts with a vowel, add 'ay' to end
if word does not start with a vowel, put first letter at the end, then add 'ay'
word -> ordway
apple -> appleay
'''
def pig_latin(word):
initial_letter = word[0]
if initial_letter in 'aeiou':
translated_word = word + 'ay'
else:
translated_word... |
class Queryable:
"""This superclass holds all common behaviors of a queryable route of
MBTA's API v3"""
@property
def list_route(self):
raise NotImplementedError
class SingularQueryable(Queryable):
def __init__(self, id):
self._id = id
def __eq__(self, other):
return ... |
class Break:
def __init__(self, dbRow):
self.flinch = dbRow[0]
self.wound = dbRow[1]
self.sever = dbRow[2]
self.extract = dbRow[3]
self.name = dbRow[4]
def __repr__(self):
return f"{self.__dict__!r}" |
#coding: utf-8
"""
Faça um Programa que peça 2 números inteiros e um número real. Calcule e mostre:
A. o produto do dobro do primeiro com metade do segundo .
B. a soma do triplo do primeiro com o terceiro.
C. o terceiro elevado ao cubo.
"""
i1 = int(input("Digite o 1º número inteiro: "))
i2 = int(input("Digite o 2º núm... |
cont = 0
qtde = 10
print('Gerador de PA')
print('-=' * 10)
primeiro = int(input('Primeiro termo: '))
r = int(input('Razão da PA: '))
termo = primeiro
while cont < qtde:
cont += 1
print('{} → '.format(termo), end='')
termo += r
if cont == qtde:
print('PAUSA')
mais = int(input('Quantos ter... |
# -*- coding: utf-8 -*-
empty_dict = dict()
print(empty_dict)
d = {}
print(type(d))
#zbiory definuje sie set
e = set()
print(type(e))
# klucze nie moga sie w slowniku powtarzac
#w slowniku uporzadkowanie nie jest istotne, i nie jest uporzadkowane
pol_to_eng = {'jeden':'one', 'dwa':'two', 'trzy': 'th... |
class WordDictionary:
def __init__(self, cache=True):
self.cache = cache
def train(self, data):
raise NotImplemented()
def predict(self, data):
raise NotImplemented()
def save(self, model_path):
raise NotImplemented()
def read(self, model_path):
raise NotI... |
'''
Exercise 2: Odd Or Even
Ask the user for a number. Depending on whether the number is even or odd,
print out an appropriate message to the user. Hint: how does an even / odd
number react differently when divided by 2?
Extras:
If the number is a multiple of 4, print out a different message.
Ask the user for two nu... |
"Macros for loading dependencies and registering toolchains"
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
load("//lib/private:jq_toolchain.bzl", "JQ_PLATFORMS", "jq_host_alias_repo", "jq_platform_repo", "jq_toolchains_repo", _DEFAUL... |
# wwwhisper - web access control.
# Copyright (C) 2012-2018 Jan Wrobel <jan@mixedbit.org>
"""wwwhisper authentication and authorization.
The package defines model that associates users with locations that
each user can access and exposes API for checking and manipulating
permissions. It also provides REST API to logi... |
# Copyright 2017 Neural Networks and Deep Learning lab, MIPT
#
# 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 appli... |
#!/usr/bin/env python
# Copyright (c) 2019 VMware, Inc. All Rights Reserved.
# SPDX-License-Identifier: BSD-2 License
# The full license information can be found in LICENSE.txt
# in the root directory of this project.
SERVER_CONSTANTS = (
REQUEST_QUEUE_SIZE, PACKET_SIZE, ALLOW_REUSE_ADDRESS
) = (
100, 1024, Tr... |
class Formatting:
"""Terminal formatting constants"""
SUCCESS = '\033[92m'
INFO = '\033[94m'
WARNING = '\033[93m'
END = '\033[0m'
|
class Stack:
def __init__(self, stack=[], lim=None):
self._stack = stack
self._lim = lim
def push(self, data):
if self._lim is not None and len(self._stack) == self._lim:
print("~~STACK OVERFLOW~~")
return
self._stack.append(int(data))
def pop(self):... |
### Code is based on PySimpleAutomata (https://github.com/Oneiroe/PySimpleAutomata/)
# MIT License
# Copyright (c) 2017 Alessio Cecconi
# 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 with... |
def ab(b):
c=input("Term To Be Search:")
if c in b:
print ("Term Found")
else:
print ("Term Not Found")
a=[]
while True:
b=input("Enter Term(To terminate type Exit):")
if b=='Exit' or b=='exit':
break
else:
a.append(b)
ab(a)
|
n = int(input())
def weird(n):
string = str(n)
while n != 1:
if n%2 == 0:
n = n//2
string += ' ' + str(n)
else:
n = n*3 + 1
string += ' ' + str(n)
return string
print(weird(n)) |
PRICES = [0.01, 0.02, 0.05, 0.10, 0.20, 0.50, 1, 2]
QUESTIONS = [
"Voer het aantal 1 centen in:\n",
"Voer het aantal 2 centen in: \n",
"Voer het aantal 5 centen in: \n",
"Voer het aantal 10 centen in: \n",
"Voer het aantal 20 centen in: \n"... |
spec = {
'name' : "The devil's work...",
'external network name' : "exnet3",
'keypair' : "openstack_rsa",
'controller' : "r720",
'dns' : "10.30.65.200",
'credentials' : { 'user' : "nic", 'password' : "nic", 'project' : "nic" },
'Networks' : [
{ 'name' : "merlynctl" , "start": "172.1... |
# coding: utf-8
# fields names
BITMAP = 'bitmap'
COLS = 'cols'
DATA = 'data'
EXTERIOR = 'exterior'
INTERIOR = 'interior'
MULTICHANNEL_BITMAP = 'multichannel_bitmap'
ORIGIN = 'origin'
POINTS = 'points'
ROWS = 'rows'
TYPE = 'type'
NODES = 'nodes'
EDGES = 'edges'
ENABLED = 'enabled'
LABEL = 'label'
COLOR = 'color'
TEMPL... |
# Data taken from the MathML 2.0 reference
data = '''
"(" form="prefix" fence="true" stretchy="true" lspace="0em" rspace="0em"
")" form="postfix" fence="true" stretchy="true" lspace="0em" rspace="0em"
"[" form="prefix... |
# -*- coding: utf-8 -*-
# User role
USER = 0
ADMIN = 1
USER_ROLE = {
ADMIN: 'admin',
USER: 'user',
}
# User status
INACTIVE = 0
ACTIVE = 1
USER_STATUS = {
INACTIVE: 'inactive',
ACTIVE: 'active',
}
# Project progress
PR_CHALLENGE = -1
PR_NEW = 0
PR_RESEARCHED = 10
PR_SKETCHED = 20
PR_PROTOTYPED = 30
P... |
"""
This script allows you to hijack http/https networks. Before you start use this commands on Kali machine
1. Enable ip forwarding: echo 1 > /proc/sys/net/ipv4/ip_forward
2. Activate your packets Queues
- If want to test on your machine: iptables -I OUTPUT -j NFQUEUE --queue-num 0;iptables -I INPUT -j NFQUEUE --q... |
q = int(input())
e = str(input()).split()
indq = 0
mini = int(e[0])
for i in range(1, len(e)):
if int(e[i]) > mini:
mini = int(e[i])
elif int(e[i]) < mini:
indq = i + 1
break
print(indq)
|
__version__ = "1.8.0"
__all__ = ["epsonprinter","testpage"]
|
'''Classe Bola: Crie uma classe que modele uma bola:
Atributos: Cor, circunferência, material
Métodos: trocaCor e mostraCor
'''
class Bola:
def __init__(self, cor=None, circ=None, material=None):
self.cor = cor
self.circ = circ
self.material = material
def mostra_cor(self):
... |
class RequestExeption(Exception):
def __init__(self, request):
self.request = request
def badRequest(self):
self.message = "bad request url : %s" % self.request.url
return self
def __str__(self):
return self.message
|
class Solution:
def dieSimulator(self, n: int, rollMax: List[int]) -> int:
# dp[i][j]: how many choices we have with i dices and the last face is j
# again dp[i][j] means the number of distinct sequences that can be obtained when rolling i times and ending with j
MOD = 10 ** 9 + 7
dp... |
n1 = int(input('Digite um valor: '))
n2 = int(input('Digite um valor: '))
n3 = int(input('Digite um valor: '))
menor = n1
maior = n2
if n2 < n1 and n2 < 3:
menor = n2
if n3 < n1 and n3 < n2:
menor = n3
if n1 > n2 and n1 > n3:
maior = n1
if n3 > n1 and n3 > n2:
maior = n3
print(f'O maior valor digitado f... |
# a = ['a1','aa1','a2','aaa1']
# a.sort()
# print(a)
# print(2346/10)
def repeat_to_length(string_to_expand, length):
return (string_to_expand * (int(length/len(string_to_expand))+1))[:length]
for i in range(200):
if i > 10:
strnum = str(i)
tens = int(strnum[0:-1])
last = strnum[-1]
... |
'''
Given a binary string s (a string consisting only of '0's and '1's), we can split s into 3 non-empty strings s1, s2, s3 (s1+ s2+ s3 = s).
Return the number of ways s can be split such that the number of characters '1' is the same in s1, s2, and s3.
Since the answer may be too large, return it modulo 10^9 + 7.
... |
arr = [2,3,5,8,1,8,0,9,11, 23, 51]
num = 0
def searchElement(arr, num):
n = len(arr)
for i in range(n):
if arr[i] == num:
print("From if block")
return i
elif arr[n-1] == num:
print("From else if block")
return n-1
n-=1
print(searchElement... |
class MidiProtocol:
NON_REAL_TIME_HEADER = 0x7E
GENERAL_SYSTEM_INFORMATION = 0x06
DEVICE_IDENTITY_REQUEST = 0x01
@staticmethod
def device_identify_request(target=0x00):
TARGET_ID = target
SUB_ID_1 = MidiProtocol.GENERAL_SYSTEM_INFORMATION
SUB_ID_2 = MidiProtocol.DEVICE_IDE... |
"""Exceptions raised by flowpipe."""
class CycleError(Exception):
"""Raised when an action would result in a cycle in a graph."""
|
def get_chunks(start, value):
for each in range(start, 2000000001, value):
yield range(each, each+value)
def sum_xor_n(value):
mod_value = value&3
if mod_value == 3:
return 0
elif mod_value == 2:
return value+1
elif mod_value == 1:
return 1
elif mod_value == 0:
... |
#! /usr/bin/python
# -*- coding: utf-8 -*-
VER_MAIN = '3'
VER_SUB = '5'
BUILD_SN = '160809'
|
#4-9 Cube Comprehension
numberscube = [value ** 3 for value in range(1, 11)]
print(numberscube) |
#coding:utf-8
while True:
l_c = input().split()
x1 = int(l_c[0])
y1 = int(l_c[1])
x2 = int(l_c[2])
y2 = int(l_c[3])
if x1+x2+y1+y2 == 0:
break
else:
if (x1 == x2 and y1 == y2):
print(0)
elif ((x2-x1) == -(y2-y1) or -(x2-x1) == -(y2-y1)): ... |
# Definition for a binary tree node.
# class Node(object):
# def __init__(self, val=" ", left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def expTree(self, s: str) -> 'Node':
def process_op():
op = op_stack.pop()
... |
# Practice problem 1 for chapter 4
# Function that takes an array and returns a comma-separated string
def make_string(array):
answer_string = ""
for i in array:
if array.index(i) == 0:
answer_string += str(i)
# Last index word finishes with "and" before it
elif array.index(... |
class RCListener:
def __iter__(self): raise NotImplementedError()
class Source:
def listener(self, *args, **kwargs):
raise NotImplementedError()
def query(self, start, end, *args, types=None, **kwargs):
raise NotImplementedError()
|
class DataGridEditingUnit(Enum, IComparable, IFormattable, IConvertible):
"""
Defines constants that specify whether editing is enabled on a cell level or on a row level.
enum DataGridEditingUnit,values: Cell (0),Row (1)
"""
def __eq__(self, *args):
""" x.__eq__(y) <==> x==yx.__eq__(y)... |
for _ in range(int(input())):
n,q = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
for _ in range(q):
k = int(input())
sum = 0
# if(k == 0):k = 1
for i in range(0,n,k + 1):
sum += a[i]
print(sum) |
def front_back(s):
if len(s) > 1:
string = [s[-1]]
string.extend([i for i in s[1:-1]])
string.append(s[0])
return "".join(string)
else:
return s |
# twitter api data (replace yours here given are placeholder)
# if you have not yet, go for applying at: https://developer.twitter.com/
TWITTER_KEY=""
TWITTER_SECRET=""
TWITTER_APP_KEY=""
TWITTER_APP_SECRET=""
with open("twitter_keys.txt") as f:
for line in f:
tups=line.strip().split("=")
if tups[0] == "TWITTER_... |
def maximum_subarray_1(coll):
n = len(coll)
max_result = 0
for i in xrange(1, n+1):
for j in range(n-i+1):
result = sum(coll[j: j+i])
if max_result < result:
max_result = result
return max_result
def maximum_subarray_2(coll):
n = len(coll)
max_... |
lines = []
for i in xrange(3):
line = Line()
line.xValues = xrange(5)
line.yValues = [(i+1 / 2.0) * pow(x, i+1)
for x in line.xValues]
line.label = "Line %d" % (i + 1)
lines.append(line)
plot = Plot()
plot.add(lines[0])
inset = Plot()
inset.add(lines[1])
inset.hideTickLabels(... |
#!/usr/bin/env python3
# Corona-Info-App
# flexstring-Parser
# © 2020 Tobias Höpp.
#######################################
# DOCUMENTATION: flexstring (Funktion: flexstringParse(flexstring,configuration))
# Die funktion dient dem auswerten von flexstrings, also strings, die selbst variablen beinhalten, die konfigurie... |
file = open('csv_data.txt', 'r')
lines = file.readlines()
file.close()
lines = [line.strip() for line in lines[1:]]
for line in lines:
person_data = line.split(',')
name = person_data[0].title()
age = person_data[1]
university = person_data[2].title()
degree = person_data[3].capitalize()
prin... |
"""Top-level package for BioCyc and BRENDA in Python."""
__author__ = """Yi Zhou"""
__email__ = 'zhou.zy.yi@gmail.com'
__version__ = '0.1.0'
|
"""
问题描述: 在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例:
4->2->1->3 => 1->2->3->4
"""
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def sortList(self, head):
"""
:type head: ListNo... |
def media(n1, n2):
m = (n1 + n2)/2
return m
print(media(n1=10, n2=5))
def juros(preco, juros):
res = preco * (1 + juros/100)
return res
print(juros(preco=10, juros=50))
|
"""Multiply two arbitrary-precision integers. - [EPI: 5.3]. """
def multiply(num1, num2):
sign = -1 if (num1[0] < 0) ^ (num2[0] < 0) else 1
num1[0], num2[0] = abs(num1[0]), abs(num2[0])
result = [0] * (len(num1) + len(num2))
for i in reversed(range(len(num1))):
for j in reversed(range(len(nu... |
def test_session_interruption(ui, ui_interrupted_session):
ui_interrupted_session.click()
interrupted_test = ui.driver.find_element_by_css_selector('.item.test')
css_classes = interrupted_test.get_attribute('class')
assert 'success' not in css_classes
assert 'fail' not in css_classes
interrupted... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def sortedArrayToBST(self, nums):
return self.recurse(nums,0,len(nums)-1)
def recurse(self,nums,start,en... |
"""Helper function to save serializer"""
def save_serializer(serializer):
"""returns a particular response for when serializer passed is valid or not"""
serializer.save()
data = {
"status": "success",
"data": serializer.data
}
return data
|
Vivaldi = Goalkeeper('Juan Vivaldi', 83, 77, 72, 82)
Peillat = Outfield_Player('Gonzalo Peillat', 'DF', 70, 89, 78, 73, 79, 67)
Ortiz = Outfield_Player('Ignacio Ortiz', 'MF', 79, 78, 77, 80, 75, 81)
Rey = Outfield_Player('Matias Rey', 'MF', 81, 77, 74, 72, 87, 72)
Vila = Outfield_Player('Lucas Vila', 'FW', 87, 50, ... |
def factorial(x):
'''calculo de factorial
con una funcion recursiva'''
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 928
print('el factorial de: ', num ,'is ', factorial(num))
|
# prompting user to enter the file name
fname = input('Enter file name: ')
d = dict()
# catching exceptions
try:
fhand = open(fname)
except:
print('File does not exist')
exit()
# reading the lines in the file
for line in fhand:
words = line.split()
# we only want email addresses
if ... |
# crie um programa que tenha uma tupla unica com nomes de produtos e sesus respectivos preços
# no final mostre uma listagem de preços organizando os dados em forma tabular
listagem = ('Lápis', 1.75, 'Borracha', 2, 'Caderno', 15.90, 'Estojo', 25, 'Pendrive', 25, 'Fan', 11.25, 'Livro', 34.90)
print('~'*40)
print(f'{"LI... |
# Separando dígitos de um número
'''Faça um programa que leia um número de 0 a 9999
e mostre na tela cada um dos digitos separados
Ex: número: 1835; unidade: 4, dezena: 3, centena: 8, milhar: 1'''
n = int(input('Digite um número entre 0 e 9999: '))
u = n // 1 % 10
d = n // 10 % 10
c = n // 100 % 10
m = n // 1000 % 10
... |
'''
根据一棵树的前序遍历与中序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
# De... |
# Copyright 2014 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'skia_warnings_as_errors': 0,
},
'targets': [
{
'target_name': 'libpng',
'type': 'none',
'conditions': [
[ 'skia_android_framewor... |
_base_ = "./common_base.py"
# -----------------------------------------------------------------------------
# base model cfg for gdrn
# -----------------------------------------------------------------------------
MODEL = dict(
DEVICE="cuda",
WEIGHTS="",
# PIXEL_MEAN = [103.530, 116.280, 123.675] # bgr
... |
# -*- coding: utf-8 -*-
# dict key:原node, val:新node
# Definition for singly-linked list with a random pointer.
class RandomListNode(object):
def __init__(self, x):
self.label = x
self.next = None
self.random = None
class Solution(object):
def copyRandomList(self, head):
"""
... |
#This app does your math
addition = input("Print your math sign, +, -, *, /: ")
if addition == "+":
a = int(input("First Number: "))
b = int(input("Seccond Number: "))
c = a + b
print(c)
elif addition == "-":
a = int(input("First Number: "))
b = int(input("Seccond Number: "))
c = a - b
... |
class Solution:
def sequentialDigits(self, low: int, high: int) -> List[int]:
sequence, base, result = '123456789', 10, []
for length in range(len(str(low)), len(str(high)) + 1):
for start in range(base - length):
number = int(sequence[start : start + length])
... |
# -*- coding: utf-8 -*-
def range(start, stop, step=1.):
"""Replacement for built-in range function.
:param start: Starting value.
:type start: number
:param stop: End value.
:type stop: number
:param step: Step size.
:type step: number
:returns: List of values from `start` to `stop` in... |
""" from https://github.com/keithito/tacotron """
"""
Defines the set of symbols used in text input to the model.
The default is a set of ASCII characters that works well for English or text that has been run through Unidecode. For other data, you can modify _characters. See TRAINING_DATA.md for details. """ # ... |
class Solution(object):
def largestRectangleArea1(self, heights):
"""
:type heights: List[int]
:rtype: int
"""
self.ans = float('-inf')
def recurse(heights, l, r):
if l > r:
return 0
min_idx = l
# index r is inclu... |
# 問題URL: https://atcoder.jp/contests/abc134/tasks/abc134_d
# 解答URL: https://atcoder.jp/contests/abc134/submissions/24158327
n = int(input())
a = [int(i) for i in input().split()]
b = [0] * n
for i in range(n, 0, -1):
b[i - 1] = (sum(b[i - 1::i]) % 2) ^ a[i - 1]
print(sum(b))
print(*[i + 1 for i, bi in enumerate(b)... |
class PaceMaker():
"""
Class for a server that distributes the anonymized and
hashed contact traces.
Attributes:
connected_peers = []: List of peers to communicate with.
trace_buffer = {area: hashed_events}: Temporarily stored hashed events.
"""
def receive_hashed_trace(se... |
"""任意的参数列表
@see: https://docs.python.org/3/tutorial/controlflow.html#arbitrary-argument-lists
函数可以使用任意数量的参数来调用。这些参数将封装在一个元组中。
在可变数量的参数之前,可能会出现零个或多个普通参数。
"""
def test_function_arbitrary_arguments():
"""任意的参数列表"""
# 当出现 **name 的最后一个正式形参时,它将接收一个字典,其中包含除与正式形参对应的关键字参数外的所有关键字参数。
# 这可以与 *name 的形式参数结合使用,该形式参数接... |
# -*- coding: utf-8 -*-
# @Author : LG
"""
执行用时:40 ms, 在所有 Python3 提交中击败了84.24% 的用户
内存消耗:14.2 MB, 在所有 Python3 提交中击败了5.03%
解题思路:
递归
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:... |
while True:
try:
comprimento, eventos = [int(x) for x in input().split()]
except EOFError:
break
lucro, utilizado, estacionamento = 0, 0, {} # 'veic' : tamanho
for aux in range(0, eventos):
evento = input().split(' ')
if len(evento) == 3: # entrada veic
if c... |
class EmbeddedDocumentMixin:
_fields = {}
_db_name_map = {}
_dirty_fields = {}
def __init__(self, **kwargs):
self._values = {}
for name, value in kwargs.items():
if name in self._fields:
setattr(self, name, value)
self._make_clean()
def to_mongo(... |
with open("input.txt", "r") as input_file:
input = input_file.read().split("\n")
total = 0
group_answers = {}
for line in input:
if not line:
total += len(group_answers)
group_answers = {}
for char in line:
group_answers[char] = 1
total += len(group_answers)
print(total)
|
class Solution:
def calPoints(self, ops):
"""
:type ops: List[str]
:rtype: int
"""
opsstack = []
point = 0
for o in ops:
p = 0
if o == '+':
p = opsstack[-1] + opsstack[-2]
point += p
opss... |
# This file is implements of 'The elements of computer systesm'
# chap 6.Assembler
# author:gongqingkui AT 126.com
# date:2021-09-18
jumpTable = {
'null': '000',
'JGT': '001',
'JEQ': '010',
'JGE': '011',
'JLT': '100',
'JNE': '101',
'JLE': '110',
'JMP': '111'}
compTable = {
# a = 0 ... |
# -*- encoding: utf-8 -*-
'''
__author__ = "Larry_Pavanery
'''
class User(object):
def __init__(self, id, url_keys=[]):
self.id = id
self.url_keys = url_keys
|
#评价器
def create_critic_network(self, state_size, action_dim):
print("Now we build the model")
S = Input(shape=[state_size])
A = Input(shape=[action_dim], name='action2')
w1 = Dense(HIDDEN1_UNITS, activation='relu')(S)
a1 = Dense(HIDDEN2_UNITS, activation='linear')(A)
h1 = Dense(HIDDEN2_UNITS, a... |
def vmax(lista):
n = 0
for c in range(len(lista)):
for i in range(len(lista)):
if lista[i] > lista[c]:
n = i
return n
freq = []
num = int(input())
lista = list(range(2, num + 1))
n = num
n_1 = 0
c = 0
while True:
print(n_1)
if n_1 <= len(lista) - 1:
if n... |
mp = 'Today is a Great DAY'
print(mp.lower())
print(mp.upper())
print(mp.strip())
print(mp.startswith('w'))
print(mp.find('a'))
|
"""
Trie tree.
"""
class TrieNode:
def __init__(self, data: str):
self.data = data
self.children = [None] * 26
self.is_ending_char = False
class TrieTree:
def __init__(self):
self._root = TrieNode('/')
def insert(self, word: str) -> None:
p = self._root
... |
#!/usr/bin/env python3
class Node(object):
"""Node class for binary tree"""
def __init__(self, data=None):
self.left = None
self.right = None
self.data = data
class Tree(object):
"""Tree class for binary search"""
def __init__(self, data=None):
self.root = Node(data)
... |
# Copyright 2017 The Switch Authors. All rights reserved.
# Licensed under the Apache License, Version 2, which is in the LICENSE file.
"""
This package implements a transport model for the transmission network.
The core modules in the package are build and dispatch.
"""
core_modules = [
'switch_model.transmiss... |
# Conversão de Tempo
tempo=int(input())
h=tempo//3600
m=(tempo%3600)//60
s=(tempo%3600)%60
print('{}:{}:{}'.format(h,m,s))
|
# Programa que le a altura de uma parede em metros
# e calcule a sua area e a quantidade de tinta necessaria
# para pinta-la, sabendo que cada litro de tinta, pinta uma area
# de 2m^2
larg = float(input('Digite a largura da parede: '))
alt = float(input('Digite a altura da parede: '))
area = larg * alt
tinta = area / ... |
#----------* CHALLENGE 37 *----------
#Ask the user to enter their name and display each letter in their name on a separate line.
name = input("Enter your name: ")
for i in name:
print(i)
|
class Camera(object):
def __init__(self, macaddress, lastsnap='snaps/default.jpg'):
self.macaddress = macaddress
self.lastsnap = lastsnap |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.