content stringlengths 7 1.05M |
|---|
#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ /... |
class Solution:
"""
@param candidates: A list of integers
@param target: An integer
@return: A list of lists of integers
"""
def combinationSum(self, candidates, target):
# write your code here
if not candidates: return [[]]
nums = sorted(candidates)
res = []
... |
def create_mine_field(n, m, mines):
mine_field = [
[0 for _ in range(m)
] for _ in range(n)
]
for mine in mines:
x, y = mine
mine_field[x-1][y-1] = '*'
return mine_field
def neighbours(i, j, m):
nearest = [m[x][y] for x in [i-1, i, i+1] for y in [j-1, j, j+1]
... |
'''
Что покажет приведенный ниже фрагмент кода?
'''
s = 'i Learn Python language'
print(s.capitalize()) |
line = '-'*39
blank = '|' + ' '*37 + '|'
print(line)
print(blank)
print(blank)
print(blank)
print(blank)
print(blank)
print(line)
|
print('*' * 47)
print('DIGITE 2 NÚMEROS ABAIXO PARA COMPARAR O MAIOR!')
print('*' * 47)
num1 = float(input('1º Número: '))
num2 = float(input('2º Número: '))
if num1 > num2:
print('O 1º valor é MAIOR!')
elif num2 > num1:
print('O 2º valor é MAIOR!')
else:
print('Os 2 valores são EQUIVALENTES!')
|
"""Iteration utilities"""
class Batch:
"""Yields batches (groups) from an iterable
Modified from:
http://codereview.stackexchange.com/questions/118883/split-up-an-iterable-into-batches
Args:
iterable (iterable) any iterable
limit (int) How many items to include per group
"""
d... |
"""
Created on February 17 2021
@author: Andreas Spanopoulos
Contains custom Exceptions classes that can be used for debugging purposes.
"""
class GameIsNotOverError(Exception):
""" Custom exception raised when the outcome of a game that has not yet finished is queried """
def __init__(self, *args):
... |
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
if len(a:=nums1) > len(b:=nums2):
a, b = b, a
n = len(a)
m = len(b)
median, i, j = 0, 0, 0
min_index = 0
max_index = n
... |
so={'1':'Windows Server','2':'Unix','3':'Linux','4':'Netware','5':'Mac OS','6':'Outro'}
dados={'voto':0,'maiorx':'','maiory':0,'final':''}
contagem={'Windows Server':0,'Unix':0,'Linux':0,'Netware':0,'Mac OS':0,'Outro':0}
ordem={}
print('Qual o melhor Sistema Operacional para uso em servidores?')
print('''
1- Windows Se... |
'''
Python function to check whether a number is divisible by another number.
Accept two integers values form the user.
'''
def multiple(m, n):
return True if m % n == 0 else False
print(multiple(20, 5))
print(multiple(7, 2))
|
def be_shy(say):
say('そんなこと言われたら照れるぱっちょ:denpaccho_upper_left::denpaccho_upper_right:')
def i_am_not_alexa(say):
say('誰に向かって言ってるぱっちょ:oni_paccho::punch:\n明日からキミの分は打刻しない:paccho:')
def i_am_not_siri(say):
say('誰に向かって言ってるぱっちょ:oni_paccho::punch:\nキミの有給1日減らす:paccho::denpaccho_kakusei:')
def you_know_secret_c... |
def extractSabishiidesu(item):
"""
Sabishii desu!
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol or frag) or 'preview' in item['title'].lower():
return None
if 'tags' in item['tags']:
return None
tagmap = [
('Sono-sha. Nochi ni. . .', ... |
#
# PySNMP MIB module MISSION-CRITICAL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MISSION-CRITICAL-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:12:55 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
def assert_has_size(output_bytes, value, delta=0):
"""Asserts the specified output has a size of the specified value"""
output_size = len(output_bytes)
assert abs(output_size - int(value)) <= int(delta), "Expected file size was %s, actual file size was %s (difference of %s accepted)" % (value, output_size, ... |
'''
Copyright (©) 2019 - Randall Simpson
pi-iot
This base sensor class.
'''
class Sensor:
def __init__(self, source, metric_prefix, output):
self.source = source
self.metric_prefix = metric_prefix
self.output = output
self.metrics = []
def get_info():
return None
d... |
num = 111
num = 222
num = 333333
num = 333
num4 = 44444
|
__author__ = "hoongeun"
__version__ = "0.0.1"
__copyright__ = "Copyright (c) hoongeun"
__license__ = "Beer ware"
|
# Function arguments ...
#
# Class instances can be pass as arguments to functions
class Point:
""" a 2D point """
p = Point()
p.x = 1
p.y = 2
def print_point(point):
print('(%s, %s)' % (point.x, point.y))
print_point(p) # (1, 2) |
def test1():
inp="0 2 7 0"
inp="4 10 4 1 8 4 9 14 5 1 14 15 0 15 3 5"
nums = list(map(lambda x: int(x), inp.split()))
hist = [ nums ]
step = 1
current = nums[:]
while True:
#print('step', step, 'current', current)
#search max
m = max(current)
#max index
idx = current.index(m)
current[idx] = 0
... |
#!/usr/bin/env python
#
# @Author: Dalmasso Giovanni <gioda>
# @Date: 09-Feb-2018
# @Email: giovanni.dalmasso@embl.es
# @Project: python_utils
# @Filename: colors.py
# @Last modified by: gioda
# @Last modified time: 15-Mar-2018
# @License: MIT
"""Collection of basic colors as RGB for plotting (inspired by "Table... |
"""
На вход подается число n, верните разность n и 21. При этом если n больше 21, верните удвоенную разность.
diff21(19) → 2
diff21(10) → 11
diff21(21) → 0
diff21(50) → 58
diff21(-2) → 23
diff21(-1) → 22
diff21(2) → 19
diff21(0) → 21
diff21(30) → 18
"""
def diff(num):
return 0
|
##functions-question1
# def ask_questions():
# print("who is the the founder of facebook?")
# print(" - Mark Zuckerberg\n# - Bill Gates\n# - Steve Jobs\n# - Larry Page")
#ask_questions()
# ask_questions()
# ask_questions()
# ask_questions()
# ask_questions()
# ask_questions()
## called function 100 time using lo... |
# test floor-division and modulo operators
@micropython.viper
def div(x:int, y:int) -> int:
return x // y
@micropython.viper
def mod(x:int, y:int) -> int:
return x % y
def dm(x, y):
print(div(x, y), mod(x, y))
for x in (-6, 6):
for y in range(-7, 8):
if y == 0:
continue
d... |
# -*- coding: utf-8 -*-
def func(precess_data, x):
precess_data = list(range(0, 100, 3))
low = 0
high = 34
guess = int((low + high) / 2)
while precess_data[guess] != x:
if precess_data[guess] < x:
low = guess
elif precess_data[guess] > x:
high ... |
while True:
n = input('Texto errado, digite tudo em maiúscula: ')
if n.isupper():
print('Texto correto')
break
#https://pt.stackoverflow.com/q/433623/101
|
# setup_function 每个测试函数执行之前被调用
# teardown_function 每个测试函数执行之后被调用
def setup_function():
print('setup function')
def teardown_function():
print('teardown function')
def test_1():
print('test 1')
def test_2():
print('test 2')
def test_3():
print('test 3')
|
velocidade = float(input("Qual a velocidade Atual do carro em km/h-->"))
def result(velocidade):
if velocidade > 80:
print("MULTADO")
print("MULTADO,Por execeder o limite permitido de 80km/h")
multa = 90 +((velocidade - 80)*5)
print("o Valor da multa é de R${:.2f}!".format(multa) )
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
We have two functions in this class.
one to collect data from the winner and store in a text file,
and one to print this data on a scoreboard.
"""
class Highscore():
"""Highscore class."""
def show_score_board(self, filename):
"""Read textfile, for... |
'''
Created on 08.06.2014
@author: ionitadaniel19
'''
map_selenium_objects={
"SUSER":"name=login",
"SPWD":"name=password",
"SREMEMBER":"id=remember_me",
"SSUBMIT":"name=commit",
"SKEYWORD":"id=q... |
linesize = int(input())
table = [[0 for x in range(4)] for y in range(linesize)]
queue = []
for i in range(linesize):
entry = input().split(' ')
# print(entry, 'pushed')
country = (int(entry[1]),int(entry[2]),int(entry[3]),str(entry[0]))
queue.append(country)
out = sorted(queue, key = lambda x: x[3])
o... |
print('-='*20)
print('Analisador de triângulo')
print('-='*20)
a = float(input('Qual o valor das reta 1: '))
b = float(input('Qual o valor da reta 2: '))
c = float(input('Qual o valor da reta 3: '))
# if a < b + c and b < a + c and c < a + b
if (b-c) <a < (b + c):
if (a- c) <b < (a + c):
if (a - b) <c < (a... |
#SOMA SIMPLES #1003
#Leia dois valores inteiros, no caso para variáveis A e B. A seguir, calcule a soma entre elas e atribua à variável SOMA. A seguir escrever o valor desta variável.
#Accepted
a = int(input())
b = int(input())
soma = a + b
print("SOMA = {}".format(soma)) |
name = input('Enter your Name: ')
sen = "Hello "+ name +" ,How r u today??"
print(sen)
para = ''' hey , this is a
multiline comment.Lets see how
it works.'''
print(para)
|
x, y = map(float, input().split())
exp = 0.0001
count = 1
while y - x > exp:
x += x * 0.7
count += 1
print(count) |
#!/usr/bin/python
class helloworld:
def __init__(self):
print("Hello World!")
helloworld()
|
def init():
return {
"ingest": {
"outputKafkaTopic": "telemetry.ingest",
"inputPrefix": "ingest",
"dependentSinkSources": [
{
"type": "azure",
"prefix": "raw"
},
{
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
RECOVER_ITEM = [
("n 't ", "n't ")
]
def recover_quotewords(text):
for before, after in RECOVER_ITEM:
text = text.replace(before, after)
return text
|
names = [
'Christal',
'Ray',
'Ron'
]
print(names)
|
# * N <= 1e9, A <= N, P <= 6000000
# * 20 คะแนน : N <= 100
# * 10 คะแนน : A = 1
# * 10 คะแนน : P = 2
# * 20 คะแนน : P <= 50000
# * 40 คะแนน : ไม่มีเงื่อนไขเพิ่มเติม
def useGenerator(gen):
gen("s1", "Sample 1", 8, 3, 4)
gen("s2", "Sample 2", 8, 6, 4)
gen(1, "Cocoa", 40, 4, 5)
gen(2, "Chino", 100, 17,... |
def solution(numBottles,numExchange):
finalsum = numBottles
emptyBottles = numBottles
numBottles = 0
while (emptyBottles >= numExchange):
numBottles = emptyBottles // numExchange
emptyBottles -= emptyBottles // numExchange * numExchange
finalsum += numBottles
empt... |
def undistort_image(image, objectpoints, imagepoints):
# Get image size
img_size = (image.shape[1], image.shape[0])
# Calibrate camera based on objectpoints, imagepoints, and image size
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objectpoints, imagepoints, img_size, None, None)
# Call cv2.u... |
"""
The :mod:`fatf.utils.data` module holds data tools and data sets.
"""
# Author: Kacper Sokol <k.sokol@bristol.ac.uk>
# License: new BSD
|
largest=None
smallest=None
while True:
number=input("Enter a number:")
if number == "done":
break
try:
number=int(number)
if largest == None:
largest = number
elif largest < number:
largest = number
if ... |
class UsdValue(float):
def __init__(self, v) -> None:
super().__init__()
class UsdPrice(float):
def __init__(self, v) -> None:
super().__init__() |
def filter(fname,data):
list=[]
for i in range(len(data)):
f=fname(data[i])
if f==True:
list.append(data[i])
return list
def map(fname,newdata):
list=[]
for i in range(len(newdata)):
f=fname(newdata[i])
list.append(f)
... |
class Vehicule:
annee_production = 0
def demarrer(self):
print("VROOM")
class Voiture(Vehicule): # voiture hérite de véhicule
couleur = ""
clio_de_sophie = Voiture()
clio_de_sophie.annee_production = 2000
clio_de_sophie.demarrer()
clio_de_sophie.couleur = "Bleu"
|
class script(object):
START_MSG = """ഹായ് {}
ഞാൻ Ma Cartoonzz ഗ്രൂപ്പിൽ വർക്ക് ചെയ്യുന്ന ഒരു പാവം ഓട്ടോഫിൽട്ടർ ബോട്ടാണ്. എന്ന് കരുതി എന്നെ മറ്റ് ഗ്രൂപ്പിൽ ആഡ് ആക്കാൻ പറ്റില്ല.
പിന്നെ എന്തായാലും ഇവിടെ വരെ വന്നതല്ലേ ഞങ്ങളുടെ കാർട്ടൂൺ ഗ്രൂപ്പിൽ ഒന്ന് ജോയിൻ ആയേര്😎😎.
"""
HELP_MSG = """hmm...
എനിക്ക് നിൻ്റ... |
#!/usr/bin/env python3
#coding: utf-8
"""
pythonic way
"""
print(input('Введите строку:')[::-1])
|
#
numbers = [str(x) for x in range(32)]
letters = [chr(x) for x in range(97, 123)]
crate = '''
sandbox crate
map {boot: @init}
/*initialize utility vars and register vars*/
service init {
writer = 0
alpha = 0
beta = 0
status = 0'''
for letter in letters:
crate += '\n ' + letter + ' = 0'
crate +=... |
# coding: utf-8
# http://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser
DEFAULT_PARSER = 'lxml'
ALLOWED_CONTENT_TYPES = [
'text/html',
'image/',
]
FINDER_PIPELINE = (
'haul.finders.pipeline.html.img_src_finder',
'haul.finders.pipeline.html.a_href_finder',
'haul.finders.pipelin... |
# pythran export _brief_loop(float64[:,:], uint8[:,:],
# intp[:,:], int[:,:], int[:,:])
def _brief_loop(image, descriptors, keypoints, pos0, pos1):
for k in range(len(keypoints)):
kr, kc = keypoints[k]
for p in range(len(pos0)):
pr0, pc0 = pos0[p]
... |
factors = {
1:{
1:"I",5:"I",9:"I",13:"I",17:"I",21:"I",25:"I",29:"I",33:"I",37:"I",41:"I",45:"I",49:"I",53:"I",57:"I"
, 2:"S", 6:"S", 10:"S", 14:"S", 18:"S", 22:"S", 26:"S",30:"S" ,34:"S",38:"S",42:"S",46:"S",50:"S",54:"S",58:"S"
, 3:"T", 7:"T" , 11:"T", 15:"T", 19:"T",23:"T"... |
"""
You can modify any option in this file. :-)
您可以修改此檔案中的任何選項 :-)
"""
# 您可以在 lang 資料夾中找到您語言的語系檔案。
# 只需要複製所需的檔案名稱即可。 :-D
#
# You can find the locale file of your language
# in "lang" folder.
# Just copy the filename of the locale file of your language
# to here. :-D
# or directly read "lang/README", but it may not lat... |
wkidInfo = {
'4326':{'type':'gcs', 'path':'World/WGS 1984.prj'},
'102100':{'type':'pcs', 'path':r'World/WGS 1984 Web Mercator (auxiliary sphere).prj'},
'3857' : {'type':'pcs', 'path':r'World/WGS 1984 Web Mercator (auxiliary sphere).prj'}
} |
#import ctypes
#import GdaImport
#import matplotlib.pyplot as plt
# getting example
# gjden
def GDA_MAIN(gda_obj):
per='the apk permission:\n'
# per+=gda_obj.GetAppString()
# per+=gda_obj.GetCert()
# per+=gda_obj.GetUrlString()
#
per+=gda_obj.GetPermission()
gda_... |
# Copyright 2016 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.
{
'targets': [
{
'target_name': 'control_bar',
'dependencies': [
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
... |
# -*- coding: utf-8 -*-
# @Project: fluentpython
# @Author: xuzhiyi
# @File name: example
# @Create time: 2021/8/1 20:21
"""有一个记录学生分数的类,要求分数不能负数"""
class Score(object):
def __init__(self, math):
if math < 0:
raise ValueError("分数不能为负数")
self.math = math
"""此处在初始化后重新给math属性赋值为-10后并没有抛出... |
# Part 1 of the Python Review lab.
def hello_world():
print("hello world")
pass
def greet_by_name(name):
print("please enter your name")
name = input
print
pass
def encode(x):
pass
def decode(coded_message):
pass |
# coding:utf-8
# example 02: single_linked_list.py
class Node(object):
def __init__(self, val=None):
self.val = val
self.next = None
class SingleLinkedList(object):
def __init__(self, maxsize=None):
self.maxsize = maxsize # None 表示不限大小;数字表示上限大小
self.root = Node()
self... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4
"""
django-fhir
FILE: __init__.py
Created: 1/6/16 5:07 PM
"""
__author__ = 'Mark Scrimshire:@ekivemark'
# Hello World is here to test the loading of the module from fhir.settings
# from .settings import *
#from fhir_io_hapi.views.get import... |
# -*- coding: utf-8 -*-
class Personaje:
"""
Clase donde se guarda la informacion sobre personajes
Args:
"""
def __init__(self):
self.__nombres= dict()
self.__pospers = dict()
self.lennombres = dict()
self.__numapar = 0
... |
pizzas = ["triple carne", "extra queso", "suprema"]
friend_pizzas = ["triple carne", "extra queso", "suprema"]
pizzas.append("baggel")
friend_pizzas.append("hawaiana")
print("Mis pizzas favoritas son:")
for i in range(0,len(pizzas)):
print(pizzas[i])
print()
print("Las pizzas favoritas de mi amigo son:")
for i ... |
"""Crie um programa que vai ler vários números e colocar em uma lista.
Depois disso,
crie duas listas extras que vão conter apenas os valores pares e os valores ímpares digitados, respectivamente.
Ao final, mostre o conteúdo das três listas geradas."""
lista1 = []
lista2 = []
lista3 = []
v = 1
sair = 'S'
while sair == ... |
# -*- coding: utf-8 -*-
GITHUB_STRING = 'https://github.com/earaujoassis/watchman/archive/v{0}.zip'
NAME = "agents"
VERSION = "0.2.4"
|
def first(arr, low , high):
if high >= low:
mid = low + (high - low)//2
if (mid ==0 or arr[mid-1] == 0) and arr[mid] == 1:
return mid
elif arr[mid] == 0:
return first(arr, mid+1, high)
else:
return first(arr, low, mid-1)
return -1
def row_with... |
class Solution:
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
if not digits:
return [1]
carry = (digits[-1] + 1) // 10
digits[-1] = (digits[-1] + 1) % 10
for i in reversed(range(len(digits) - 1)):
... |
def infer_mask_from_batch_data(batch_data):
"""
Create binary mask for all non-empty timesteps
:param batch_data: BatchSize x SequenceLen x Features
:return: BatchSize x SequenceLen
"""
return batch_data.abs().sum(-1) > 0
def infer_lengths_from_mask(mask):
"""
Get array of lengths from... |
def get_path_components(path):
path = path.strip("/").split("/")
path = [c for c in path if c]
normalized = []
for comp in path:
if comp == ".":
continue
elif comp == "..":
if normalized:
normalized.pop()
else:
raise Va... |
#Belajar String Method
#https://docs.python.org/3/library/stdtypes.html#string-methods
nama = "muhammad aris septanugroho"
print(nama)
print(nama.upper()) #Huruf besar semua
print(nama.capitalize()) #Huruf besar kata pertama
print(nama.title()) #Huruf besar tiap kata
print(nama.split(" ")) #Memisah data me... |
rm = input("Insira seu RM")
idade = input("Insira sua idade")
if int(idade) >= 18:
print("Sua participação foi autorizada, aluno de RM {}!".format(rm))
print("Mais informações serão enviadas para seu e-mail cadastrado!")
else:
print("Sua participação não foi autorizada por causa da sua idade") |
# Code adapted from Corey Shafer
"""Note: generators are more performat because they don't hold
all the values at the same time! Way better in memory, altho execution
will be a bit slower"""
def square_numbers(nums):
for i in nums:
# yield makes this a generator
# Returns one result at a time
yield(i * i)
my_... |
class Solution:
# def maxProduct(self, nums):
# """
# :type nums: List[int]
# :rtype: int
# """
# for i in range(1, len(nums)):
# nums[i] = max(nums[i], nums[i] * nums[i - 1])
# return max(nums)
def maxProduct3(self, nums):
if not nums:
... |
def product_left_recursive(alist, result=None):
if alist == []:
return result
g = result[-1] * alist[0]
result.append(g)
return product_left_recursive(alist[1:], result)
def product_left(alist):
new_list = [1]
for index in range(1, len(alist)):
value = new_list[-1] * alist[inde... |
# coding: utf-8
# pragma: no cover
class Transformator:
"""Rule to transform values"""
def __init__(self, *args, **kwargs):
pass
class TransformatorList(list):
"""Wrapper for all registered Transformators"""
def __init__(self, settings, *args, **kwargs):
super(TransformatorList, self... |
fileName = ["nohup_2", "nohup_1", "nohup_4", "nohup"]
Fo = open("new nohup", "w")
for fil in fileName:
lineNum = 0
with open(fil) as F:
for line in F:
if lineNum % 10 == 0:
Fo.write(",\t".join(line.split()))
Fo.write("\n")
lineNum += 1
Fo.w... |
#DICIONÁRIOS
#Há duas maneiras de declarar um dicionário:
variavel = dict()
variavel = {}
#Dentro do dicionário, eu posso adicionar elementos. Esses elementos são conhecidos como chaves (keys) e valores (values):
variavel = {'nome':'Pedro', 'idade':25}
print(variavel['nome'])
#Vale lembrar que para declarar uma key (... |
title('Counting words')
count = dict()
text = '''Ex servente de ladrilheiro que largou o canteiro de obras para realizar um sonho de infância, a tal sonhada
sonhada formação acadêmica. Formado em engenharia de controle e automação em 2019, com um dos melhores rendimentos da turma
agregei valores e informações precio... |
"""
There's an algorithms tournament taking place in which teams of programmers compete against each other to solve algorithmic problems as fast as possible. Teams compete in a round robin, where each team faces off against all other teams. Only two teams compete against each other at a time, and for each competition... |
'''
Laçoes de repetição:
laço variável no intervalo(0,x) --> for variavel in range(0,x)
'''
'''
for a in range(0, 5):
print('Oi')
print('Fim')
for b in range(1, 6): #Conta de 1 a 5, se colocar (0,6) conta de 0 a 6
print(b)
print('Fim')
for c in range(5, 0, -1): #Para contar ao contrário.
print(c)
print('Fi... |
# Python - 3.6.0
test.assert_equals(last([1, 2, 3, 4, 5]), 5)
test.assert_equals(last('abcde'), 'e')
test.assert_equals(last(1, 'b', 3, 'd', 5), 5)
|
class Student:
def __init__(self,m1,m2):
self.m1 = m1
self.m2 = m2
def sum(self, a = None, b = None, c = None):
addition = 0
if a!=None and b!=None and c!=None:
addition = a + b + c
elif a!=None and b!= None:
addition = a + b
... |
a = int(input("Enter number of elements in set A "))
A = set(map(int,input("# Spaced Separated list of elements of A ").split())) # Spaced Separated list of elements of A
n = int(input("Number of sets ")) # Number of sets
for i in range(n):
p = input("Enter the operation and number of elements in set"+i).split()
... |
class Solution:
def sqrt(self, x):
low = 0
high = 65536
best = 0
while high > low:
mid = (high + low) / 2
sqr = mid ** 2
if sqr > x:
high = mid
elif sqr == x:
return mid
else... |
def palindrome(word, ind):
if word == word[::-1]:
return f"{word} is a palindrome"
if word[ind] != word[len(word) - 1 - ind]:
return f"{word} is not a palindrome"
return palindrome(word, ind + 1)
print(palindrome("abcba", 0))
print(palindrome("peter", 0))
|
#NETWORK
LOCALHOST = "127.0.0.1"
PI_ADDRESS = "192.168.0.1"
PORT = 5000
#STATE
MOVEMENT_MARGIN = 2
KICK_TIMEOUT = 1
LAST_POSITION = -1
PLAYER_LENGTH = 2
NOISE_THRESHOLD = 3
MIN_VELOCITY_THRESHOLD = 300
OPEN_PREP_RANGE = -30
BLOCK_PREP_RANGE = 100
OPEN_KICK_RANGE = -20
BLOCK_KICK_RANGE = 60
KICK_ANGLE = 55
PREP_ANGL... |
#! /usr/bin/env python3.6
#a = 'str'
a = '32'
print(f'float(a) = {float(a)}')
print(f'int(a) = {int(a)}')
if(isinstance(a, str)):
print("Yes, it is string.")
else:
print("No, it is not string.")
|
class TreeNode:
def __init__(self, val):
self.left = None
self.right = None
self.val = val
def is_valid_BST(node, min, max):
if node == None:
return True
if (min is not None and node.val <= min) or (max is not None and max <= node.val):
return False
return is_va... |
# 由两个栈组成的队列【题目】编写一个类,用两个栈实现队列,
# 支持队列的基本操作(add、poll、peek)。
# 【难度】尉 ★★☆☆
class TwoStacksQueue:
def __init__(self):
self.stackPush = []
self.stackPop = []
def pushToPop(self):
if not self.stackPop:
while self.stackPush:
self.stackPop.append(self.stackP... |
"""Heisenbridge
An alternative to https://github.com/matrix-org/matrix-appservice-irc/issues
"""
|
class lagrange(object):
def __init__(self, eval_x = 0):
self._eval_x = eval_x
self._extrapolations = []
def add_point(self, x, y):
new_extraps = [(y, x)]
for past_extrap, x_old in self._extrapolations:
new_val = ((self._eval_x - x) * past_extrap \
+ (... |
# -*- coding: utf-8 -*-
__version__ = '1.0.0'
default_app_config = 'webmap.apps.WebmapConfig'
|
#Get a string which is n (non-negative integer) copies of a given string
#
#function to display the string
def dispfunc(iteration):
output=str("")
for i in range(iteration):
output=output+entry
print(output)
#
entry=str(input("\nenter a string : "))
displaynumber=int(input("how many times must it be... |
spaces = int(input())
steps =0
while(spaces > 0):
if(spaces >= 5):
spaces -= 5
steps += 1
elif(spaces >= 4):
spaces -= 4
steps += 1
elif(spaces >= 3):
spaces -= 3
steps += 1
elif(spaces >= 2):
spaces -= 2
steps += 1
elif(spaces >= 1):
... |
# Straightforward implementation of the Singleton Pattern
class Logger(object):
_instance = None
def __new__(cls):
if cls._instance is None:
print('Creating the object')
cls._instance = super(Logger, cls).__new__(cls)
# Put any initialization here.
return cl... |
load("@rules_pkg//:providers.bzl", "PackageFilesInfo", "PackageSymlinkInfo", "PackageFilegroupInfo")
def _runfile_path(ctx, file, runfiles_dir):
path = file.short_path
if path.startswith(".."):
return path.replace("..", runfiles_dir)
if not file.owner.workspace_name:
return "/".join([runfil... |
# You can also nest for loops with
# while loops. Check it out!
for i in range(4):
print("For loop: " + str(i))
x = i
while x >= 0:
print(" While loop: " + str(x))
x = x - 1
|
##list of integers
student_score= [99, 88, 60]
##printing out that list
print(student_score)
##printing all the integers in a range
print(list(range(1,10)))
##printing out all the integers in a range skipping one every time
print(list(range(1,10,2)))
## manipulating a string and printting all the modifications
x =... |
def harmonic(a, b):
return (2*a*b)/(a + b);
a, b = map(int, input().split())
print(harmonic(a, b))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by PyCharm
# @author : mystic
# @date : 2017/11/11 21:01
"""
Override Configuration
"""
configs = {
'db': {
'host': '127.0.0.1'
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.