content stringlengths 7 1.05M |
|---|
'''
Sugar syntax
Para crear listas de manera más pythonica
'''
list_comprehens = [x for x in range(10)]
print (list_comprehens)
list_comprehens = [(x,y)
for x in range(2)
for y in range(2)] # Estoy devolviendo u n par ordenado, cuenta un valor dentro de otro.
'''
(0, 0), (0... |
"""
Utilities that are not kartothek-specific but are required to archive certain tasks.
"""
__all__ = ()
|
# DESAFIO 003 - 2
# Crie um script Python que leia dois números e TENTE mostrar
# a soma entre eles. CORRIGIDO!
#
# -------------------------------------- Mundo I / Aula 06 ----
num1 = int(input('Primeiro número: '))
num2 = int(input('Segundo número: '))
print('O resultado da soma dos números', num1, 'e', nu... |
"""
Conversion functions between fahrentheit and centrigrade
This module shows off two functions for converting temperature back and forth
between fahrenheit and centigrade. It also shows how to use variables to
represent "constants", or values that we give a name in order to remember them
better.
Author: Walker M. ... |
#!/usr/bin/env python
# coding: utf-8
template = """<!DOCTYPE html>
<html lang="en">
<head>
<title>RoadScanner result</title>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; ... |
class Solution:
def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int:
"""Array.
Running time: O(n^2 + AB) where is n is the length of img1, A is the number of 1s in img1 and B is the number of 1s in img2.
"""
n = len(img1)
pimg1 = []
pimg2 = ... |
class MWB:
"""MainWidgetBase"""
def __init__(self, params):
self.parent_node_instance = params
def get_data(self):
data = {}
return data
def set_data(self, data):
pass
def remove_event(self):
pass
class IWB:
"""InputWidgetBase"""
def __init__(self... |
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright © 2020, SAS Institute Inc., Cary, NC, USA. 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.apa... |
# GYP file to build unit tests.
{
'includes': [
'apptype_console.gypi',
'common.gypi',
],
'targets': [
{
'target_name': 'tests',
'type': 'executable',
'include_dirs' : [
'../src/core',
'../src/gpu',
],
'sources': [
'../tests/AAClipTest.cpp',
... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:joel
# time:2018/8/14 15:36
def headerstool(p):
"""deal with the request headers"""
with open(p + '_new.txt', 'w') as fw:
with open(p, 'r') as fr:
for line in fr.readlines():
if not line.endswith('\n'):
... |
class UserAlreadyEnteredError(Exception):
pass
class NoUsersEnteredError(Exception):
pass
class WrongTimeFormatError(Exception):
pass
#custom error just for readability |
'''
Given an integer n, return the next bigger permutation of its digits.
If n is already in its biggest permutation, rotate to the smallest permutation.
case 1
n= 5342310
ans=5343012
case 2
n= 543321
ans= 123345
'''
n = 5342310 # case 1
# n = 543321 # case 2
a = list(map(int, str(n)))
i = len(a)-... |
# function test
# test 1
def println ( str ) :
print ( str )
return
println ( "Hello World" )
# test 2
def printStu ( name, age ):
print ("%s, %d" % (name, age))
return
printStu (age = 19, name = "Inno")
# test 3
def printInfo ( who, sex = 'male' ):
print ("%s/%s" % (who, sex))
return
printInfo (... |
'''
Input
t – the number of test cases, then t test cases follows.
* Line 1: Two space-separated integers: N and C
* Lines 2..N+1: Line i+1 contains an integer stall location, xi
Output
For each test case output one integer: the largest minimum distance.
Example
Input:
1
5 3
1
2
8
4
9
Output:
3
'''
#finding the la... |
#
# PySNMP MIB module HM2-PWRMGMT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HM2-PWRMGMT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:18:36 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... |
"""
Main.class
javac Main.java .
"""
constant_pool = list()
def is_class(magic_code):
return magic_code == 'cafebabe'
def read_constant_class(f, tag, index):
name_index = int(f.read(2).hex(), 16)
return {
'tag': tag,
'name_index': name_index,
'index': index,
}
def read_con... |
'''
Leetcode
7. Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Note:
The input is assumed to be a 32-bit signed integer.
Your function should return 0 when the reversed integer overflows.
'''
def reverse(p):
"""
:type x: int
:rtype: int
... |
# -*- coding: utf-8 -*-
# Copyright © 2019-2021 Taylor C. Richberger
# This code is released under the license described in the LICENSE file
data = dict(
name='asyncinotify',
version='2.0.2',
author='Taylor C. Richberger',
description='A simple optionally-async python inotify library, focused on simpli... |
"""
This package contains the sphinx extensions used by barak.
The `numpydoc` module is derived from the documentation tools numpy
and scipy use to parse docstrings in the numpy/scipy format. The
other modules are dependencies for `numpydoc`.
"""
|
# key = DB quest string, value = quest timer in days
quests = {
'AugmentationBlankGemAcquired': ('Aug Gem: Bellas', 6),
'BlankAugLuminanceTimer_0511': ('Aug Gem: Luminance', 14),
'PickedUpMarkerBoss10x': ('Aug Gem: Diemos', 6),
'SocietyMasterStipendCollectionTimer': ('Stipend - Society', 6),
'Stipen... |
# Initialization of n*n grid
def create_grid():
global n
n = int(input("Enter grid size: "))
global grids
grids = []
for i in range(0, n):
grids.append([])
for i in range(0, n):
for j in range(0, n):
grids[i].append(j)
grids[i][j] = - 1
grid_def()... |
'''
By a length in meters you can check how it is in kilometer, hectometer
decimeter, centimeter and millimeter
'''
m = float(input('Type a length in meters: '))
km = m / 1000
hm = m / 100
dam = m / 10
dm = m * 10
cm = m * 100
mm = m * 1000
print('The value in kilometer is {:.3f}. \nThe value in hectometer is {:.2f}.... |
glob_cnt = {}
def key_or_incr(word):
if glob_cnt.has_key(word):
glob_cnt[word]+=1
else:
glob_cnt.update({word:1})
if __name__=='__main__':
# Reads a paragraph of text
para = open("para.txt","r")
word_list = para.read().split(" ")
# update the count entries for each word
fo... |
MODEL_EXTENSIONS = (
'.egg',
'.bam',
'.pz',
'.obj',
)
PANDA_3D_RUNTIME_PATH = r'C:\Panda3D-1.10.9-x64' |
class Key:
def __init__(self, m, e):
self.modulus = m
self.exponent = e
def set_modulus(self, m):
self.modulus = m
def set_exponent(self, e):
self.exponent = e
def get_modulus(self):
return self.modulus
def get_exponent(self):
return self.exponent
|
# 13. Write a program that asks the user to enter two strings of the same length. The program
# should then check to see if the strings are of the same length. If they are not, the program
# should print an appropriate message and exit. If they are of the same length, the program
# should alternate the characters of th... |
#!/usr/bin/env python
# table auto-generator for zling.
# author: Zhang Li <zhangli10@baidu.com>
kBucketItemSize = 4096
matchidx_blen = [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7] + [8] * 1024
matchidx_code = []
matchidx_bits = []
matchidx_base = []
while len(matchidx_code) < kBucketItemSize:
for bit... |
#!/usr/bin/env python3
def chmin(dp, i, *x):
dp[i] = min(dp[i], *x)
INF = float("inf")
# dp[i] := min 消耗する魔力 to H -= i
h, n = map(int, input().split())
dp = [0] + [INF] * h
for _ in [None] * n:
a, b = map(int, input().split())
for j in range(h + 1):
chmin(dp, min(j + a, h), dp[j] + b)
print(dp[h])
|
# Designer bot
## Prepares the information from Journalist_bot in order to send it to Towncrier_bot
class Designer:
def __init__(self):
pass
def dailyMessage(self, data):
return [f"""
*Rapport Quotidien des Conditions*
_{data['info_time']}_
Conditions:
- Surface: {data['conditions']['surfa... |
# NOTE: the agent holds items as a list where
# items[idx] is the number of items collected of type 'idx'
# IMPORTANT: if the original item config is changed/reodered, this file will
# likely have to be updated to reflect new item positions.
def all_item_reward(ai_r=1):
# awards +ai_r for every new item collected
... |
"""
Given a positive integer n and you can do operations as follow:
If n is even, replace n with n/2.
If n is odd, you can replace n with either n + 1 or n - 1.
What is the minimum number of replacements needed for n to become 1?
Example 1:
Input:
8
Output:
3
Explana... |
tuplas = (1,2,3,4,5,6,7,8,9,0)
print(tuplas[0])
# seleccion invertida
print(tuplas[-1])
# sub tuplas
sub = tuplas[:9:2]
print(sub)
# no puede ser modificada, por lo que
sub[1] = 30
|
# Define a Python subroutine to colour atoms by B-factor, using predefined intervals
def colour_consurf(selection="all"):
# Colour other chains gray, while maintaining
# oxygen in red, nitrogen in blue and hydrogen in white
cmd.color("gray", selection)
cmd.util.cnc()
# These are constants
mi... |
"""
Module: 'flowlib.units._makey' on M5 FlowUI v1.4.0-beta
"""
# MCU: (sysname='esp32', nodename='esp32', release='1.11.0', version='v1.11-284-g5d8e1c867 on 2019-08-30', machine='ESP32 module with ESP32')
# Stubber: 1.3.1
MAKEY_I2C_ADDR = 81
class Makey:
''
def _available():
pass
def _updateValue... |
fName = input("\nwhat is your first name? ").strip().capitalize()
mName = input("\nwhat is your middle name? ").strip().capitalize()
lName = input("\nwhat is your last name? ").strip().capitalize()
print(f"\nHello World, My name is {fName:s} {mName:.1s} {lName:s}, Happy to see you.")
|
class Player:
def __init__(self, amount):
if amount < 1:
print('You do not have money')
self.amount = 100
self.hand_bet = None
self.suit_bet = 0
self.amount_bet = 0
self.sinput = None
self.binput = None
self.badb_bet = 0
de... |
"""
Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*' where:
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
Example 1:
Input: s = "aa", p = "a"
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*
ONION_ADDR = {
"patient": "xwjtp3mj427zdp4tljiiivg2l5ijfvmt5lcsfaygtpp6cw254kykvpyd.onion"
}
# TODO:
LOGGER = {
"user": {
"password": "",
"rooms": [] # rooms are mapped to topics in mqtt
}
}
LOGGER = {
"!qKGqWURPTdcyFQHFjJ:casper.magi.sys":... |
host = 'localhost'
user = 'dongeonguard'
password = 'SuchWow'
db = 'imagedongeon'
|
def myfunction1():
x = 60 # This is local variable
print("Welcome to Fucntions")
print("x value from func1: ", x)
myfunction2()
return None
def myfunction2():
print("Thank you!!")
print("x value form fucn2:", x)
return None
x = 10 # This is global variable
myfunction1()
# Note : Priority is given to Local va... |
frase = input('Digite a frase: ').strip()
print(frase.lower().count('a'))
print(frase.lower().find('a'))
print(frase.lower().rfind('a')) |
'''
@Date: 2019-12-22 20:33:28
@Author: ywyz
@LastModifiedBy: ywyz
@Github: https://github.com/ywyz
@LastEditors : ywyz
@LastEditTime : 2019-12-22 20:38:20
'''
strings = input("Enter the first 9 digits of an ISBN-10 as a string: ")
temp = 1
total = 0
for i in strings:
total += int(i) * temp
temp += 1
total %=... |
"""
This test package was created separately to see the behavior of retrieving the
Override rules declared on a registry where @handle_urls is defined on another
package.
"""
|
"""Test dummy."""
class TestDummy:
"""Test à supprimer/modifier."""
def test_version(self) -> None:
"""Function de test."""
assert 1 + 1 == 2
|
""" Veri Türleri ."""
"""Temel Veri Türleri
Sayısal Türler: int, float, complex
Boole Türü: bool (True&False)
Gelişmiş Türler
Metinsel Tür: list, tuple, range
Dizi Türleri: dict
Eşleme Türleri: set, frozenset
İkili Türler: Bytes, bytearray, memoryview
"""
Veri = froz... |
def solution(num):
answer = 0
while num != 1:
if num % 2 == 0:
num = int(num // 2)
else:
num = num * 3 + 1
answer += 1
if answer >= 500:
return -1
return answer
print(solution(626331)) |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class CircularLinkedList:
def __init__(self):
self.head = None
def insertAtHead(self, x):
if self.head is None:
self.head = ListNode(x)
self.head.next = self.head
el... |
#T# opposite numbers are calculated with the minus - operator
#T# create a number and find its opposite
num1 = 5
num2 = -num1 # -5
num1 = -5
num2 = -num1 # 5 |
class Vector2D(object):
def __init__(self, vec2d):
"""
Initialize your data structure here.
:type vec2d: List[List[int]]
[
[1,2],
[10],
[4,5,6]
]
"""
self.lists = vec2d
self.curr_list = None
self.curr_ele... |
X = int(input())
while True:
Z = int(input())
if Z > X:
break
count = 0
summ = 0
for i in range(X,Z+1):
summ += i
count += 1
if summ > Z:
break
print(count) |
"""
File contains the constants used by the sensor modules.
"""
# Power sensor
INA219_PATH = "/sys/class/i2c-dev/i2c-0/device/i2c-dev/i2c-0/device/0-0040/hwmon/hwmon0/"
INA219_CURRENT = "/sys/class/i2c-dev/i2c-0/device/i2c-dev/i2c-0/device/0-0040/hwmon/hwmon0/curr1_input"
INA219_RESISTOR = "/sys/class/i2c-dev/i2c-0/de... |
# Copyright (c) 2021, Omid Erfanmanesh, All rights reserved.
class EncoderTypes:
CUSTOM = 0
LABEL = 1
ORDINAL = 2
ONE_HOT = 3
BINARY = 4
|
# 1
#1 1
#1 1 1
p = int(input("Ingrese un numero: "))
for n in range(1,p):
print(" "*(p-1) + "1")
if(p != 1):
print(" 1 1 ") |
# -*- coding: utf-8 -*-
NETWORK_ERROR="很抱歉,网络连接不正常。"
CANNOT_FIND_MC_DIR="很抱歉,未能检测到MC所在目录"
CANNOT_FIND_MODS_DIR="很抱歉,未能检测到Mods文件夹"
UNZIP_MSG="正在解压..."
DOWNLOADING_MSG="正在下载.."
RAM_INPUT="请输入数字选择内存大小:"
RAM_EXAMPLE="单位为M,范围512-4096,例如: 512"
SETTING="设置: "
INPUT_CORRECT="输入不正确"
SET_NAME="设置昵称: "
CHOOSE_MSG="请输入数字以选择: "... |
# Copyright 2021 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... |
# first_list_example.py
#
# Illustrates two ways to iterate through a list (examine every
# element in a list).
# CSC 110
# Fall 2011
stuff = [7, 17, -4, 0.5] # create a list filled with integers
print(stuff) # prints in "list" form (with square brackets and commas)
# This loop visits every element of the list,... |
# other column settings -> http://bootstrap-table.wenzhixin.net.cn/documentation/#column-options
columns_criar_eleicao = [
{
"field": "pessoa", # which is the field's name of data key
"title": "Pessoa", # display as the table header's name]
"sortable":True
},
{
"field": "... |
def coro1():
"""定义一个简单的基于生成器的协程作为子生成器"""
word = yield 'hello'
yield word
return word # 注意这里协程可以返回值了,返回的值会被塞到 StopIteration value 属性 作为 yield from 表达式的返回值
def coro2():
"""委派生成器,起到了调用方和子生成器通道的作用,请仔细理解下边的描述。
委派生成器会在 yield from 表达式处暂停,调用方可以直接发数据发给子生成器,
子生成器再把产出的值发给调用方。
子生成器返回后, 解释器抛出 St... |
class cell:
def __init__(self, y, x, icon, cellnum, board):
self.chricon = icon
self.coords = [y, x]
self.evopoints = 0
self.idnum = cellnum
self.playable = False
self.learnedmutations = {
'move' : False,
'sight' : False,
... |
#
# PySNMP MIB module A3COM-HUAWEI-ACL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM-HUAWEI-ACL-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:03:47 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
#
# PySNMP MIB module VMWARE-ESX-AGENTCAP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/VMWARE-ESX-AGENTCAP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:34:50 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 ... |
def test(seq, target_seq):
scorer = CodonFreqScorer()
scorer.set_codon_freqs_from_seq(target_seq)
print(scorer.score(seq))
|
#!/usr/bin/env python3
class State():
def __init__(self, e, pos, dist=float('inf'), prev=None):
self.e = e
self.pos = pos
self.dist = dist
self.prev = prev
# we need a good hash that is the same for all (g,m)-pair permutations
# this hash will be used to index the dictiona... |
"""
Faça um Programa que peça dois números e imprima a soma.
"""
num1 = int(input('Informe o primeiro número:'))
num2 = int(input('Informe o segundo número:'))
soma = num1 + num2
print(f'A soma dos números são: {soma}') |
################
# 66. Plus One
################
class Solution:
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
digits = digits[::-1]
last = 1
for i in range(len(digits)):
digits[i], last = (digits[i] + last) % 10, int... |
def sum_numbers(numbers=None):
if numbers == None:
return sum(range(101))
else:
return sum(numbers)
|
# Desafio 040 -> Crie um programa que leia duas notas de um aluno e calculer sua média,
# mostrando uma msg no final, de acordo com a média atingida:
# - abaixo de 5.0 = REPROVADO
# - média entre 5.0 e 6.9 = RECUPERAÇÃO
# - média 7.0 ou superior = APROVADO
nota1 = float(in... |
"""A RESTful Wagtail enclosure"""
__version__ = '0.2.2'
default_app_config = 'wagtailnest.apps.WagtailnestConfig'
|
class Task():
def __init__(self, target=None, args=[], kwargs={}):
self.target = target
self.args = args
self.kwargs = kwargs
def execute_task(self):
return self.target(*self.args, **self.kwargs)
class TaskManager():
def __init__(self, tasks):
"""Add tasks in r... |
COLUMNS = [
'EventId',
'DER_mass_MMC',
'DER_mass_transverse_met_lep',
'DER_mass_vis',
'DER_pt_h',
'DER_deltaeta_jet_jet',
'DER_mass_jet_jet',
'DER_prodeta_jet_jet',
'DER_deltar_tau_lep',
'DER_pt_tot',
'DER_sum_pt',
'DER_pt_ratio_lep_tau',
'DER_met_phi_centrality',
... |
class MetadataError(Exception):
pass
class CopyError(RuntimeError):
pass
class _BaseZarrError(ValueError):
_msg = ""
def __init__(self, *args):
super().__init__(self._msg.format(*args))
class ContainsGroupError(_BaseZarrError):
_msg = "path {0!r} contains a group"
def err_contains... |
class Solution:
def longestStrChain(self, words: List[str]) -> int:
dp = {}
for word in sorted(words, key=len):
dp[word] = max(dp.get(word[:i] + word[i + 1:], 0) +
1 for i in range(len(word)))
return max(dp.values())
|
# Integer Break
class Solution:
def integerBreak(self, n):
dp = [0] * (max(7, n + 1))
dp[2] = 1
dp[3] = 2
dp[4] = 4
dp[5] = 6
dp[6] = 9
if n <= 6:
return dp[n]
mod = n % 3
if mod == 0:
return dp[6] * 3 ** ((n - 6) // ... |
class ParseError(Exception):
def __init__(self,mes:str="")->None:
super().__init__()
self.mes = mes
def __str__(self)->str:
return f"ParseError: {self.mes}"
class Flag:
def __init__(self,flag:str,options:int,second_flag:str=None,flag_symbol:str="-")->None:
self.flag=flag
... |
RUNNING_NODE_CONFIG = {
"pid": 58701,
"version": "main",
"network": "localnet"
}
LOG_PATH = "{}/forge/localnet/main/logs/2021-12-22-10:21:00.884707.txt"
MNEMONIC_INFO = """
name: validator
type: local
address: pb14rclwq9xych9t0vqzdf7flw2dmhmqv3sxjjru8
pubkey: '{"@type":"/cosmos.crypto.... |
# SPDX-License-Identifier: Apache-2.0
# Copyright Contributors to the OpenTimelineIO project
VIEW_STYLESHEET = """
QMainWindow {
background-color: rgb(27, 27, 27);
}
QScrollBar:horizontal {
background: rgb(21, 21, 21);
height: 15px;
margin: 0px 20px 0 20px;
}
QScrollBar::handle:horizontal {
backg... |
"""
Урок 1. Знакомство с Python
"""
# однострочный
print('Hello world!')
# Арифметические операции
# Ctrl 2 раза, второй раз держим кнопку + стрелки
print(37 + 7)
print(37 - 7)
print(37 * 7)
print(37 / 7)
print(37 // 7)
print(37 % 7)
print(37 ** 7)
# Логические операции
# ctrl + D
print(5 > 6)
print(5 < 6)
print(5 ... |
numero_tabu = int(input("Qual o número que você quer ver a tabuada?:"))
print("="*20)
print("{} X 0 = {}".format(numero_tabu,numero_tabu*0))
print("{} X 1 = {}".format(numero_tabu,numero_tabu*1))
print("{} X 2 = {}".format(numero_tabu,numero_tabu*2))
print("{} X 3 = {}".format(numero_tabu,numero_tabu*3))
print("{} X 4 ... |
'''
u are given pointer to the root of the binary search tree and two values and . You need to return the lowest common ancestor (LCA) of and in the binary search tree.
image
In the diagram above, the lowest common ancestor of the nodes and is the node . Node is the lowest node which has nodes and as descendan... |
# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\filters\demographics_filter_term_mixin.py
# Compiled at: 2018-12-11 03:52:40
# Size of source mod 2*... |
def main():
max_id = -1
with open("data.txt") as f:
for line in f:
line = line.strip()
if len(line) == 0:
continue
if len(line) != 10:
raise ValueError(f"unexpected line {line} in input file")
max_id = max(max_id, int("".joi... |
def format_composition(attribute, features):
if attribute == 'key':
return format_key(features)
if attribute == 'tempo':
return format_tempo(features)
if attribute == 'signature':
return format_signature(features)
def format_signature(features):
return str(features['time_signat... |
def binary_search(arr, n):
return _binary_search(sorted(arr), n, 0, len(arr) - 1)
def _binary_search(arr, n, start, end):
if start > end:
return 0
mid = int((start + end) / 2)
if n == arr[mid]:
return 1
elif n < arr[mid]:
return _binary_search(arr, n, start, mid - 1)
else:
return _binary_search(arr, n, ... |
# URI Online Judge 1178
X = float(input())
N = [X]
print('N[{}] = {:.4f}'.format(0, N[0]))
for i in range(1, 100):
N.append(N[i-1]/2)
print('N[{}] = {:.4f}'.format(i, N[i-1]/2))
|
FILTERS = [
"Vous apprendrez",
"Vous recevrez",
"Vous recevrez également",
"Vous allez être la cible du sort suivant",
"Vous pourrez choisir une de ces récompenses",
"Lors de l'achèvement de cette quête vous gagnerez",
"Objet fourni",
"temp text 02"
]
|
# Global variables representing colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
# Global variable used for sizing
ICON_SIZE = 24
|
"""
Given a non-empty, singly linked list with head node head, return a middle node of linked list.
If there are two middle nodes, return the second middle node.
Example 1:
Input: [1,2,3,4,5]
Output: Node 3 from this list (Serialization: [3,4,5])
The returned node has value 3. (The judge's serialization of this n... |
#Tendo como dado de entrada a altura (h) de uma pessoa, construa um algoritmo que calcule seu peso ideal, utilizando as seguintes fórmulas:
#Para homens: (72.7*h) - 58
#Para mulheres: (62.1*h) - 44.7
print('calculo de peso ideal 2')
h=float(input('Digite sua altura: '))
sexo=int(input('digite seu sexo 1 para masculi... |
#LeetCode problem 112: Path Sum
# 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 hasPathSum(self, root: TreeNode, sum: int) -> bool:
if root is N... |
blacklisted_generators = [
'latitude',
'geo_coordinate',
'longitude',
'time_delta',
'date_object',
'date_time',
'date_time_between',
'date_time_ad',
'date_time_this_decade',
'date_time_between_dates',
'time_object',
'date_time_this_year',
'date_time_this_century',
... |
class NoSolutionError(Exception):
"""Exception returned when a DnaOptimizationProblem aborts.
This means that the constraints are found to be unsatisfiable.
"""
def __init__(self, message, problem, constraint=None, location=None):
"""Initialize."""
Exception.__init__(self, message)
... |
class Node:
def __init__(self,data):
self.data = data
self.next = None
class Solution:
def display(self,head):
current = head
while current:
print(current.data,end=' ')
current = current.next
def insert(self, head, data):
if head is None:
... |
general_option = ('option MIP = CPLEX;'
'option NLP = IPOPTH;'
'option threads = 1;'
'option optcr = 0.001;'
'option optca = 0.0;'
'GAMS_MODEL.nodLim = 1E8;'
'option domLim = 1E8;'
'option iterL... |
def binary_search(a, val, start, end):
mid = (start + end)//2
if start >= end:
return val == a[mid]
if val == a[mid]:
return True
elif val < a[mid]:
return binary_search(a, val, start, mid - 1)
elif val > a[mid]:
return binary_search(a, val, mid + 1, end)
def main()... |
class HashLinearProbe:
def __init__(self):
self.hashtable_size = 10
self.hashtable = [0] * self.hashtable_size
def hashcode(self, key):
return key % self.hashtable_size
def lprobe(self, element):
i = self.hashcode(element)
j = 0
while self.hashtable[(i+j) % ... |
noteValues = ['C0', 'Cs0', 'Db0', 'D0', 'Ds0', 'Eb0', 'E0', 'F0', 'Fs0',
'Gb0', 'G0', 'Gs0', 'Ab0', 'A0', 'As0', 'Bb0', 'B0',
'C1', 'Cs1', 'Db1', 'D1', 'Ds1', 'Eb1', 'E1', 'F1', 'Fs1',
'Gb1', 'G1', 'Gs1', 'Ab1', 'A1', 'As1', 'Bb1', 'B1',
'C2', 'Cs2', 'Db2', 'D2'... |
'''
Implement int sqrt(int x).
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated
and only the integer part of the result is returned.
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8
Output: 2
Explanatio... |
def test_greeter(chain):
greeter, _ = chain.provider.get_or_deploy_contract('Greeter')
greeting = greeter.call().greet()
assert greeting == 'Hello'
def test_custom_greeting(chain):
greeter, _ = chain.provider.get_or_deploy_contract('Greeter')
set_txn_hash = greeter.transact().setGreeting('Guten ... |
# -*- coding: utf-8 -*-
"""
Created on Mon May 27 19:14:10 2019
@author: jercas
"""
"""
leetcode-136: 只出现一次的数字 EASY
'位运算' '哈希表'
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
"""
"""
Thinking:
1. 首先想到暴力双循环,以判断位来判断是否重复来找出结果,但时间复杂度 O(n^2),超时
2. 再次想到运用py中set去重,随后遍历set并利... |
def test_something(setup):
assert setup.timecostly == 1
def test_something_more(setup):
assert setup.timecostly == 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.