content stringlengths 7 1.05M |
|---|
# -*- coding: utf-8 -*-
# 修改默认抓取数据,进行数据优化
class ElementConstant:
def __init__(self):
self.data_constant = {}
self.init_source_data()
index = 0
def init_source_data(self):
#
#self.data_constant['序号'] = 0 # 第一个需要进行排序操作
# 链家编号 链家编号
self.data_constant['链家编... |
class Receiver1:
# action
def step_left(self):
print("Receiver1 steps left")
def step_right(self):
print("Receiver1 steps right")
class Receiver2:
# action
def step_forward(self):
print("Receiver2 steps forward")
def step_backward(self):
print("Receiver2 ste... |
l1 = int(input('Digite o lado L1: '))
l2 = int(input('Digite o lado L2: '))
l3 = int(input('Digite o lado L3: '))
if l1 + l2 > l3 and l1 + l3 > l2 and l2 + l3 > l1:
resp = 'Sim, pode formar um triângulo.'
if (l1 == l2 and l1 != l3) or (l1 == l3 and l2 != l3) or (l2 == l3 and l2 != l1):
resp2 = 'Triângul... |
numero = int(input('Digite um numero: '))
if numero % 5 == 0:
print('Buzz')
else:
print(numero)
|
class WinData():
def __init__(self, wins=0, games=0):
assert games >= wins
self.wins = wins
self.games = games
def win_pct(self):
return f'{self.wins/self.games:.3%}' if self.games > 0 else 'N/A'
def incre_wins(self):
self.wins += 1
def incre_games(self):
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 12 17:32:07 2021
@author: JohnZhong
"""
#Mad libs generator 2021/10/12
print("Tell us something about you and we can create a story just for you!")
print("Let's begin!")
noun1 = input("Enter a pet: ")
noun2 = input("Enter a noun: ")
if noun1 in ["dog", "DOG", "Dog"]:
... |
#https://aonecode.com/amazon-online-assessment-zombie-matrix
ZOMBIE = 1
HUMAN = 0
DIRECTIONS = [[-1, 0], [1, 0], [0, -1], [0, 1]]
def humanDays(matrix):
"""
:type matrix: List[List[int]]
:rtype: int
"""
M = len(matrix)
if (M == 0):
return -1
N = len(matrix[0])
if (N == ... |
def exibirLista(lista):
for item in lista:
print(item)
numeros = [1, 56, 5, 7, 29]
exibirLista(numeros)
print("Ordenados")
numeros.sort()
exibirLista(numeros)
|
class Solution:
def fib(self, n: int) -> int:
fib_0, fib_1 = 0, 1
if n == 0:
return 0
if n == 1:
return 1
for i in range(2, n+1):
fib_0, fib_1 = fib_1, fib_0+fib_1
return fib_1
|
#
# PySNMP MIB module GRPSVCEXT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/GRPSVCEXT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:19:53 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... |
class TracableObject:
def __init__(self, object_id, centroid):
# store the object ID, then initialize a list of centroids
# using the current centroid
self.object_id = object_id
self.centroids = [centroid]
# initializa a boolean used to indicate if the object has
# already been ... |
# Pytathon if Stement
# if Statement
sandwich_order = "Ham Roll"
if sandwich_order == "Ham Roll":
print("Price: $1.75")
# if else Statement
tab = 29.95
if tab > 20:
print("This user has a tab over $20 that needs to be paid.")
else:
print("This user's tab is below $20 that does not require immediate payment.")
... |
""" MOTOR PARAMETERS """
b_step_per_mm = 80
d_step_per_mm = 80
p_step_per_mm = 80
step_len_us = 1 # NOT CURRENTLY USED
disp_move_mm = 104
disp_vel_mmps = 50
disp_acc_mmps2 = 100
pusher_move_mm = 68
pusher_vel_mmps = 520
pusher_acc_mmps2 = 12500
bin_vel_mmps = 400
bin_acc_mmps2 = 3500
bin_heights_load_mm = [2.5, 1... |
# Leetcode 198. House Robber
#
# Link: https://leetcode.com/problems/house-robber/
# Difficulty: Medium
# Solution using DP
# Complexity:
# O(N) time | where N represent the number of homes
# O(1) space
class Solution:
def rob(self, nums: List[int]) -> int:
rob1, rob2 = 0, 0
for n in nums:
... |
# %% [6. ZigZag Conversion](https://leetcode.com/problems/zigzag-conversion/)
class Solution:
def convert(self, s: str, numRows: int) -> str:
lst = [[] for _ in range(numRows)]
for cc in use(s, numRows):
for i, c in enumerate(cc):
lst[i].append(c)
return "".join("... |
# Desafio 022 -> Crie um programa que leia o nome completo de uma pessoa e mostre:
# O nome com todas as letras maiúsculas
# O nome com todas minúsculas
# Quantas letras ao to do (sem considerar espaços).
# quantas letras tem o primeiro nome
nco = (in... |
"""
Response to
https://www.reddit.com/r/Python/comments/fwq1f3/procedurally_generated_object_attribute/
"""
class Products(object):
"""Sale unit object for GoodPaws' products.
"""
def __init__(self):
self.df = get_sheets(scopes, sheet_id, range_name, creds_path)
self.df = self.df.set_index... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
def get_tensor_shape(tensor):
shape = []
for dim in tensor.type.tensor_type.shape.dim:
shape.append(dim.dim_value)
if len(shape) == 4:
shape = [shape[0], shape[2], shape[3], shape[1]]
return shape
|
#!/usr/bin/env python
# encoding: utf-8
def run(whatweb, pluginname):
whatweb.recog_from_content(pluginname, "/app/home/skins/default/style.css")
|
def hormigon():
cantidad = float(input("¿Cuántos metros cúbicos de hormigón quieres?:"))
cantidad_por_metro = [322,689,1177,156]
tipo_material = ["Cemento","Arena","Grava","Agua"]
materiales = {}
for i in tipo_material:
materiales[i] = cantidad_por_metro[tipo_material.index(i)]*cantidad
re... |
class PluginNotInitialisableException(BaseException):
pass
class PluginNotActivatableException(BaseException):
pass
class PluginNotDeactivatableException(BaseException):
pass
class PluginAttributeMissingException(BaseException):
pass
class PluginRegistrationException(BaseException):
pass
|
# generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/xtark/ros_ws/install/include;/home/xtark/ros_ws/devel/lib/rtabmap-0.19/../../include/rtabmap-0.19;/opt/ros/kinetic/include/opencv-3.3.1-dev;/opt/ros/kinetic/include/opencv-3.3.1-dev/opencv".split... |
class Typography(object):
""" Provides access to a rich set of OpenType typography properties. """
@staticmethod
def GetAnnotationAlternates(element):
"""
GetAnnotationAlternates(element: DependencyObject) -> int
Returns the value of the
System.Windows.Documents.Typography.AnnotationAlterna... |
"""Trait Browser App.
This app handles displaying, searching, and browsing through information on
source traits and harmonized traits.
"""
default_app_config = 'trait_browser.apps.TraitBrowserConfig'
|
# ------------------------------------
# CODE BOOLA 2015 PYTHON WORKSHOP
# Mike Wu, Jonathan Chang, Kevin Tan
# Puzzle Challenges Number 7
# ------------------------------------
# INSTRUCTIONS:
# Using only 1 line, write a function
# to reverse a list. The function is
# passed a list as an argument.
# EXAMPLE:
#... |
# Copyright 2013 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
"""Top-level presubmit script for appengine/components/.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for
details ... |
__all__ = ['UserScript']
class UserScript:
def __init__(self, id=None, activations=None):
self.functions = []
self._function_by_name = {}
self.id = id
self.activations = [] if activations is None else activations
def __len__(self):
return len(self.functions)
def _... |
class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
n=len(nums);
c=[0]*n
ans=list()
for i in range(n):
c[nums[i]-1]+=1
for i in range(n):
if(c[i]==2):
ans.append(i+1)
return ans;
|
def is_isogram(s):
if isinstance(s, str):
s = [i for i in s.lower() if i.isalpha()]
return len(s) == len(set(s))
else:
raise TypeError("This doesn't look like a string.") |
# Copyright (c) 2020-2021 Matematyka dla Ciekawych Świata (http://ciekawi.icm.edu.pl/)
# Copyright (c) 2020-2021 Robert Ryszard Paciorek <rrp@opcode.eu.org>
#
# MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Soft... |
def zero_initializer(n):
assert isinstance(n, int) and n > 0
return [0] * n
def zeros_initializer(n, n_args):
if n_args == 1:
return zero_initializer(n)
return map(zero_initializer, [n] * n_args) |
## Gerador de tabuada.
canGenerateTabuada = False
#print("Tabuada de: ")
vInput = int(input("Tabuada de: "))
canGenerateTabuada = vInput >= 1 and vInput <= 10
while not canGenerateTabuada:
print("Digite um valor de 1 a 10.")
vInput = int(input("Tabuada de: "))
canGenerateTabuada = vInput >= 1 and vInput <... |
# Space: O(n)
# Time: O(n!)
class Solution:
def combine(self, n: int, k: int):
if k > n: return []
data = [i for i in range(1, n + 1)] # list all numbers
status = [False for _ in range(len(data))] # identify if current item has been used or not
def dfs(data, index, temp_res, r... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# Approach 1
# O(N) - Space
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
hashmap = set()
node = head
while node:
if nod... |
"""
# Zdoom Textures Writer (zdtw)
"""
__version__ = "1.0"
__author__ = "GianptDev"
__date__ = '14-2-2022' # Revisioned.
# will not include default properties in PatchData and TextureData, output will become smaller.
compact_mode = True
# ----------------------------------------
class PatchData():
... |
# c_diccionarios.py
# muestra ejemplos de operaciones con diccionarios
# los diccionarios son pares de claves y valores encerrados entre {},
# y, al igual que los conjuntos, no admiten duplicados, PERO ENTRE SUS CLAVES
agenda = {'Ana': 43782348, 'Beto': 45872394, 'Charly': 47893489}
print(f'\nTenemos una agenda: {ag... |
###############################################################################################################
# DESAFIO: 002
# TÍTULO: Respondendo ao Usuário
# AULA: 04
# EXERCÍCIO: Faça um programa que leia o nome de uma pessoa e mostre uma mensagem de boas-vindas.
################################################... |
#!/Users/philip/opt/anaconda3/bin/python
a = [ "aa", "bb", "cc" ]
print ( "".join(a) )
|
class Solution:
def fairCandySwap(self, A: List[int], B: List[int]) -> List[int]:
total_a = sum(A)
total_b = sum(B)
set_b = set(B)
for candy in A:
swap_item = candy + (total_b - total_a) / 2
if swap_item in set_b:
return [candy, candy + (total_... |
# Shortest Unsorted Continuous Subarray
"""
Find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order.
Return length of the shortest subarray.
Example 1: nums = [2,6,4,8,10,9,15]
o/p:- 5
Explanation: You need to sort [6, 4, 8, 10, 9] in... |
def sanduiche (*toppings):
"""Monta o sanduiche"""
print("\n Sanduíche composto de :")
for toppping in toppings:
print("\t"+toppping)
sanduiche('queijo','maionese','presunto')
sanduiche('pasta de amendoin','geleia')
sanduiche('manteiga', 'queijo', 'oregano','tomate') |
class ARMAModel():
def __init__(self, gamma=0.15, beta=0.8):
self.gamma_param = gamma
self.beta_param = beta
def predict(self, x):
x_simplified = x[0, 0, :] # convert to a simple array, ignoring batch size
return (self.beta_param * x_simplified[-1]) + \
(self.gam... |
"""Debug flag."""
ON: bool = False
|
# Write a program to check whether a given number is an ugly number.
# Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
# Example 1:
# Input: 6
# Output: true
# Explanation: 6 = 2 × 3
# Example 2:
# Input: 8
# Output: true
# Explanation: 8 = 2 × 2 × 2
# Example 3:
# Input: 14
# Output: f... |
somaidade = 0
médiaidade = 0
maioridadehomem = 0
nomevelho = ''
totmulher20 = 0
for p in range(1, 5):
print('---- {}ª PESSOA ---- '.format(p))
Nome = str(input('Nome: ')).strip()
Idade = int(input('Idade: '))
Sexo = str(input('Sexo [M/F] ')).strip()
somaidade += Idade
if p == 1 and Sexo in 'Mm':... |
class InterpretationParser:
def __init__(self, socketio):
self.interpreter = None
self.entity_intent_map = {'item_attribute_query': {'attribute': None, 'entity': None},
'batch_restriction_query': {'attribute': None, 'class': None},
... |
list_of_users=[] # it stores the list of usernames in form of strings
def fun(l1):
global list_of_users
list_of_users=l1
def fun2():
return list_of_users |
# Scrapy settings for gettaiex project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/topics/settings.html
#
BOT_NAME = 'gettaiex'
BOT_VERSION = '1.0'
SPIDER_MODULES = ['gettaiex.spiders']
NEWSPIDER_MODULE... |
penctutions = ".,;?()[]{}&_-@%<>:!~1234567890/*+$#^/"
newt = "" #text without penctutions
List2 = []
text = str("Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin prof... |
"""
Demonstration of defining functions.
"""
def sayhello():
"""
Prints "hello".
"""
print("hello")
# Call the function
sayhello()
def double(value):
"""
Return twice the input value
"""
return value * 2
# Call the function and assign the result to a variable
result = double(6)
print... |
_base_ = './rr_yolov3_d53_416_coco.py'
# model settings
model = dict(
type='SingleStageDetector',
pretrained=None,
backbone=dict(type='RRTinyYolov4Backbone'),
neck=None,
bbox_head=dict(
type='RRTinyYolov4Head',
num_classes=80,
in_channels=[512, 256],
out_channels=[256... |
# Time: O(logn) = O(1)
# Space: O(1)
# 29
# Divide two integers without using multiplication, division and mod operator.
# Return the quotient after dividing dividend by divisor.
#
# The integer division should truncate toward zero.
# - Both dividend and divisor will be 32-bit signed integers.
# - The divisor will ne... |
def isWordGuessed(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: boolean, True if all the letters of secretWord are in lettersGuessed;
False otherwise
'''
# FILL IN YOUR CODE HERE...
... |
class Solution:
def permute(self, nums: list) -> list:
# ans = []
# n = len(nums)
# tmp = []
# def backtrack(nums):
# for k in range(len(nums)):
# tmp.append(nums[k])
# if len(tmp) == n:
# ans.append(tmp)
# ... |
def extractNadenadeshitai(item):
"""
Nadenadeshitai
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol or frag) or 'preview' in item['title'].lower():
return None
if item['title'].startswith('Command Chapter '):
return buildReleaseMessageWithType(item, 'Command So... |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root is None:
return []
st... |
v = float(input('Qual é a velocidade atual do seu carro: ')) #Recebe a velocidade atual
if v > 80.0:
print('MULTADO. Você excedeu o limite permitido que é de 80 Km/h.')
multa = (v - 80) * 7.0
print('Você deve pagar uma multa de R$ {:.2f}'.format(multa))
print('Tenha um bom dia. Dirija com segurança!') |
"""
Find whether string s is divisible by string t.
A string s divisible by string t if string t can be concatenated some number of times to obtain the string s.
If s is divisible, find the smallest string u such that it can be concatenated
some number of times to obtain both s and t.
If it is not divisible, set t... |
#!/usr/bin/env python3
'''
This is a
multiline
comment
'''
print("This is some dummy code") # Hi # This shouldn't count as another comment '''neither should this'''
|
class Pessoa:
olhos = 2
def __init__(self, *filhos, nome=None, idade=35):
self.nome = nome
self.idade = idade
self.filhos = list(filhos)
def cumprimentar(self):
return f'Olá meu nome é {self.nome}'
@staticmethod
def metodo_estatico():
return 42
@classm... |
"""
FastAPI uses data models (pydantic) to
validate data types
For each resource (data), describe how it
should look and behave at various stage
""" |
def sock_merchant(n, ar):
stock = set()
pairs = 0
for socks in ar:
if socks in stock:
stock.remove(socks)
pairs += 1
else:
stock.add(socks)
return pairs
n = int(input("Number of socks: "))
ar = list(
map(int, input("Different socks (spaces in betw... |
class Solution:
def halveArray(self, nums: List[int]) -> int:
halfSum = sum(nums) / 2
ans = 0
runningSum = 0.0
maxHeap = [-num for num in nums]
heapq.heapify(maxHeap)
while runningSum < halfSum:
maxValue = -heapq.heappop(maxHeap) / 2
runningSum += maxValue
heapq.heappush(ma... |
# TODO BenM/assessor_of_assessor/pick this up later; it isn't required for the
# initial working solution
class TestPyxnatSession:
def __init__(self, project, subject, session, scans, assessors):
self.scans_ = scans
self.assessors_ = assessors
self.project = project
self.subject = ... |
def Main():
"""
:return:
"""
a = 1
c = 3
a += c
b = 10
b -= a
d = 2
b *= d
b /= c
b %= 3
f = b + 20
# f |= 34 # this doesn't curretly work
return f # expect 21
|
def operation(first,second,operator):
if(operator == 1):
return first + second
if(operator == 2):
return first - second
if(operator == 3):
return first / second
if(operator == 4):
return first * second
return "invalid selection or input"
print("Welcome to calcu... |
class NoDataForTrigger(ValueError):
"""An error that's raised when a trigger is passed
a data point that cannot be handled due to an incompatible
value being stored"""
pass
class IncompatibleTriggerError(NoDataForTrigger):
"""An error that's raised when a trigger is passed
a data point that c... |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
class PyYarl(PythonPackage):
"""The module provides handy URL class for URL parsing and changing."""
homepage = ... |
mod, maxn, cur, ans, r = 998244353, 1000005, 10, 0, 0
dp, x, a = [0] * maxn, [0] * maxn, [0] * 12,
x[1] = 1
dp[0] = 1
for i in range(2 , maxn):
x[i] = mod - (mod // i) * x[mod % i] % mod
n, k = map(int, input().split())
n = n // 2
p = [0] * k
for u in map(int, input().split()):
cur = min(cur, u)
p[r] = u
... |
def nomina(salario, horasNormales, horasExtra):
if horasNormales+horasExtra>=36 and horasNormales+horasExtra<=43:
salario=salario+horasExtra*1.25
elif horasNormales+horasExtra>=44:
salario=salario+horasExtra*1.5
else:
salario=salario
return print(salario)
nomina(1500,35,0)
|
# Exercise 051 - Arithmetic Progression
"""Develop a program that reads the first term and reason of an AP.
At the end, show the first 10 terms of this progression."""
# To facilitate your viewing:
first_term = int(input("What is the first term of this Arithmetic Progression?: "))
r = int(input("What is the common d... |
#Fix the code below 👇
'''
print(Day 1 - String Manipulation")
print("String Concatenation is done with the "+" sign.")
print('e.g. print("Hello " + "world")')
print(("New lines can be created with a backslash and n.")
'''
print("Day 1 - String Manipulation")
print("String Concatenation is done with the \"+\" sign.... |
"""
map
"""
def multiply(value, times=1):
return value * times
a = list(map(multiply, [1, 2, 3]))
print(a)
print()
a = list(map(multiply, [1, 2, 3], [1, 2, 3]))
print(a)
|
print('The choice coin voting session has started!!!!!')
print('------------------------------------------------')
print ('should we continue with the proposal method')
nominee_1 = 'yes'
nominee_2 = 'no'
nom_1_votes = 0
nom_2_votes = 0
votes_id = [1,2,3,4,5,6,7,8,9,10]
num_of_voter = len(votes_id)
... |
sal = float(input('Digite seu salário atual:\n'))
if sal >= 1200:
aum = sal + (sal*0.15)
print('Seu salário vai de R${} para R${}.'.format(sal, aum))
else:
aum = sal + (sal*0.2)
print('Seu salário vai de R${} para R${}.'.format(sal, aum))
print('Agora vai lá comemorar comendo umas puta')
|
''' The complete Intcode computer
N. B. Someone wrote an intcode computer in intcode
https://www.reddit.com/r/adventofcode/comments/e7wml1/2019_intcode_computer_in_intcode/
'''
fin = open('input_13.txt')
temp = fin.readline().split(',')
fin.close()
program_template = [int(x) for x in temp]
# program_template = [109, 1... |
# Original Solution
def additionWithoutCarrying(param1, param2):
smaller = min(param1,param2)
larger = max(param1,param2)
small_list = list(str(smaller))
large_list = list(str(larger))
output = []
print(param1,param2)
print(small_list,large_list)
index_2= 0
for index,i in enumer... |
def soma (x,y):
return x+y
def subtrai (x,y):
return x-y
def mult():
pass
|
# 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... |
if __name__ == '__main__':
N = int(input())
Output = [];
for i in range(0,N):
ip = input().split();
if ip[0] == "print":
print(Output)
elif ip[0] == "insert":
Output.insert(int(ip[1]),int(ip[2]))
elif ip[0] == "remove":
Output.remove(int(ip... |
def capacity(K, weights):
if sum(weights) < K:
return None
weights = sorted(weights, reverse=True)
def solve(K, i):
print("Solve({0}, {1})".format(K, i))
if K == 0:
return []
while i < len(weights) and weights[i]> K:
i += 1
if i == len(weights):
return None
subK = K - weights[i]
subI ... |
def main():
n = int(input())
for case in range(1, n + 1):
d = int(input())
guys = [int(s) for s in input().split(" ")]
# print(d, guys)
guys = sorted(guys, reverse=True)
# print(d, guys)
print("Case #{}: {}".format(case, cal_move(d, guys)))
def cal_move(d, guys... |
"""
9. Дана последовательность натуральных чисел (одно число в строке), завершающаяся двумя
числами 0 подряд. Определите, сколько раз в этой последовательности встречается число 1.
Числа, идущие после двух нулей, необходимо игнорировать.
В этой задаче нельзя использовать глобальные переменные и параметры, передаваем... |
flatmates = [
{
'name': "Fred",
'telegram_id': "930376906"
},
{
'name': "Kata",
'telegram_id': "1524429277"
},
{
'name': "Daniel",
'telegram_id': "1145198247"
},
... |
#!/usr/bin/python
"""Programa que implementa el algoritmo de ordenamiento por insercion."""
def InsertionSort(lista):
"""Algoritmo de ordenamiento por insercion."""
for j in range(1, len(lista)):
key = lista[j]
# Inserta lista[j] en la secuecia ordenada lista[0.. j]
i = j - 1
... |
# callback handlers: reloaded each time triggered
def message1(): # change me
print('BIMRI') # or could build a dialog...
def message2(self):
print('Nil!') # change me
self.method1() # access the 'Hello' instance...
|
class Solution:
def largestNumber(self, num):
num_str = map(str, num)
num_str.sort(cmp=lambda str1, str2: -1 if str1 + str2 > str2 + str1 else 1)
if len(num_str) >= 2 and num_str[0] == num_str[1] == "0":
return "0"
return "".join(num_str)
|
name = input("Enter file:")
if len(name) < 1:
name = "mbox-short.txt"
handle = open(name)
emails = dict()
for line in handle:
words = line.split()
if not line.startswith('From') or len(words) < 3:
continue
email = words[1]
emails[email] = emails.get(email, 0) + 1
max = 0
max_email = N... |
# -*- coding: utf-8 -*-
# @Time : 2021/8/25 4:25
# @Author : pixb
# @Email : tpxsky@163.com
# @File : main_model.py.py
# @Software: PyCharm
# @Description:
class main_model(object):
pass
|
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 22 17:32:32 2020
@author: abhi0
"""
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
count=0
i=0
s=sorted(s)
while i<len(g): #greed factor for childrens
for j in range(len(s)): ... |
response.title = settings.title
response.subtitle = settings.subtitle
response.meta.author = '%(author)s <%(author_email)s>' % settings
response.meta.keywords = settings.keywords
response.meta.description = settings.description
response.menu = [
(T('Index'),URL('default','index')==URL(),URL('default','index'),[]),
(T('... |
print('===== DESAFIO 90 =====')
aprov = {}
aprov['nome'] = str(input('Nome: '))
aprov['media'] = float(input(f'Média de {aprov["nome"]}: '))
print(f'Nome é igual a {aprov["nome"]}')
print(f'Média é igual a {aprov["media"]}')
if aprov['media'] >= 7:
print('Situação é igual a APROVADO')
else:
print('Situação é ig... |
DEFAULT_GEASE_FILE_NAME = ".gease"
DEFAULT_RELEASE_MESSAGE = "A new release via gease."
NOT_ENOUGH_ARGS = "Not enough arguments"
KEY_GEASE_USER = "user"
KEY_GEASE_TOKEN = "personal_access_token"
MESSAGE_FMT_RELEASED = "Release is created at: %s"
|
def paint_calc(height,width,cover):
number_of_cans = round((height * width) / coverage)
print(f"You'll need {number_of_cans} cans of paint.")
height = int(input("Height of Wall :\n"))
width = int(input("Width of wall : \n"))
coverage = 5
paint_calc(height=height,width=width,cover=coverage)
|
class Tokenizer:
def __init__(self):
self.on_token_funcs = []
def read(self, chunk):
raise NotImplementedError
def token_fetched(self, token):
for func in self.on_token_funcs:
func(token)
def on_token_fetched(self, func):
self.on_token_funcs.append(func)
... |
# GETTER (Obtem o valor) e SETTER(Configura o valor)
#Getters : - Estes são os métodos usados em Programação Orientada a Objetos (OOPS) que ajudam a
# acessar os atributos privados de uma classe .
#Setters : - Estes são os métodos usados no recurso OOPS que ajuda a definir o valor para atributos
# privados em uma cla... |
DEFAULT_FIT_VAR_NAMES = tuple(['beta0', 'c_reduction'])
DEFAULT_FIT_GUESS = {
'beta0': 0.025,
'c_reduction': 0.5
}
DEFAULT_FIT_BOUNDS = {
'beta0': [0., 1.],
'c_reduction': [0., 1.]
}
|
for n in range(2, 100):
for x in range(2, n):
if n % x == 0:
print(n, '==', x, '*', n//x)
break
else:
print(n, 'is prime!')
|
'''
@author: Kittl
'''
def exportExternalNets(dpf, exportProfile, tables, colHeads):
# Get the index in the list of worksheets
if exportProfile is 2:
cmpStr = "ExternalNet"
elif exportProfile is 3:
cmpStr = ""
idxWs = [idx for idx,val in enumerate(tables[exportProfile-1]) if... |
class DefaultQuotaPlugin(object):
def get_default_quota(self, user, provider):
raise NotImplementedError("Validation plugins must implement a get_default_quota function that "
"takes two arguments: 'user' and 'provider")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.