content stringlengths 7 1.05M |
|---|
class Stack:
"""
Stack data structure using list
"""
def __init__(self,value):
"""
Class initializer: Produces a stack with a single value or a list of values
"""
self._items = []
if type(value)==list:
for v in value:
self._items.append... |
# __version__ is for deploying with seed.
# VERSION is to keep the rest of the app DRY.
__version__ = '0.1.18'
VERSION = __version__
|
#Desafio: Crie um programa que leia nome e duas notas de vários alunos e guarde tudo em uma lista composta.
#No final, mostre um boletim contendo a média de cada um e permita que o usuário possa mostrar as notas de cada aluno individualmente.
lista = list()
while True:
nome = str(input('Nome: '))
n1 = float(i... |
class Vehicle(object):
def __init__(self, vehicle_id, company, location):
self.vehicle_id = vehicle_id
self.company = company
self.location = location
# def __str__(self):
# return str( P["id":+str(self.id) + " company: " + str(self.company)+
# str(self.location)+ " loca... |
# -*- coding: utf-8 -*-
"""
Copyright 2022 Mitchell Isaac Parker
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 ... |
"""
CBMPy: MiriamIds module
=======================
Constraint Based Modelling in Python (http://pysces.sourceforge.net/cbm)
Copyright (C) 2009-2017 Brett G. Olivier, VU University Amsterdam, Amsterdam, The Netherlands
This program is free software: you can redistribute it and/or modify
it under the terms of th... |
'''
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143?
'''
def largest_prime_factor(n):
f = 2
while f**2 <= n:
while n % f == 0:
n //= f
f += 1
return max(f-1, n)
print(largest_prime_factor(600851475143)) |
def selectionSort(alist):
for fillslot in range (len(alist)-1, 0, -1):
positionofMax = 0;
for location in range(1,fillslot+1):
if alist[location] > alist[positionofMax]:
positionofMax = location
temp = alist[fillslot]
alist[fillslot] = alist[positionofMax]
alist[positionofMax] = temp
a = [54,26,93,1... |
#!/usr/bin/env python
a = 1000000000
for i in xrange(1000000):
a += 1e-6
a -= 1000000000
print(a)
|
# -*- coding: utf-8 -*-
"""Top-level package for Creating the Docs."""
__author__ = """Barry J. Whiteside"""
__email__ = 'barrywhiteside@gmail.com'
__version__ = '0.1.0'
|
class EnviadorDeSpam():
def __init__(self, sessao, enviador):
self.sessao = sessao
self.enviador = enviador
def enviar_emails(self, remetente, assunto, corpo):
for usuario in self.sessao.listar():
self.enviador.enviar(
remetente,
usuario.email... |
"""A helper class for pygame colors."""
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY = (80, 80, 80)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
ORANGE = (255, 165, 0)
|
class DDAE_Hyperparams:
drop_rate = 0.5
n_units = 1024
activation = 'lrelu'
final_act = 'linear'
f_bin = 257
class CBHG_Hyperparams:
#### Modules ####
drop_rate = 0.0
normalization_mode = 'layer_norm'
activation = 'lrelu'
final_act = 'linear'
f_bin = 257
##... |
SIZE_BOARD = 10
# Tipo de navios na forma "tipo": tamanho
TYPES_OF_SHIPS = {
"1": 5,
"2": 4,
"3": 3,
"4": 2
} |
x = input("input a letter : ")
if x == "a" or x == "i" or x == "u" or x == "e" or x == "o":
print("This is a vowel!")
elif x == "y":
print("Sometimes y is a vowel and sometimes y is a consonant")
else:
print("This is a consonant!")
|
class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
max_count = 0
count = 0
for i in nums:
if i == 1:
count += 1
else:
count = 0
max_count = max(max_count, count)
return max_count
|
# This file declares all the constants for used in this app
MAIN_URL = 'https://api.github.com/repos/'
ONE_DAY = 1
|
cor_do_alien = 'vermelho'
if cor_do_alien == 'verde':
pontos = 5
elif cor_do_alien == 'amarelo':
pontos = 10
elif cor_do_alien == 'vermelho':
pontos = 15
print(f'Você acabou de ganhar {pontos} pontos!')
|
# The guess API is already defined for you.
# @param num, your guess
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
# def guess(num: int) -> int:
class Solution:
def guessNumber(self, n: int) -> int:
l, h = 1, n
while l <= h:
m = l + (h - l) // 2
... |
class Dosya():
def __init__(self,dosya_ismi):
with open(dosya_ismi,"r",encoding = "utf-8") as file:
dosya_icerigi = file.read()
kelimeler = dosya_icerigi.split()
self.sade_kelimeler = list()
for kelime in kelimeler:
kelime = kelime.strip()... |
def make_shirt(text, size = 'large'):
print('You can buy a ' + size + ' size t-shirt with written ' + text + ' written on it.')
make_shirt(text = 'yepa')
|
metros = float(input('Digite uma distância em metros: '))
print('A medida de {}m corresponde a '.format(metros))
print('{}km'.format(metros * .001))
print('{}hm'.format(metros * .01))
print('{:.1f}dam'.format(metros * .1))
print('{:.0f}dm'.format(metros * 10))
print('{:.0f}cm'.format(metros * 100))
print('{:.0f}mm'.fo... |
###########################################################
# This module is used to centralise messages
# used by the self service bot.
#
###########################################################
class ErrorMessages:
BOT_ABORT_ERROR = "Aborting Self Service Bot"
BOT_INIT_ERROR = "ERROR reported during init... |
class Solution:
def maxChunksToSorted(self, arr):
intervals = {}
for i in range(len(arr)):
if i < arr[i]:
minVal, maxVal = i, arr[i]
else:
minVal, maxVal = arr[i], i
if minVal in intervals:
if maxVal > intervals[ min... |
x = int(input())
if x%2 == 0:
print("É par!")
else:
print("É ímpar!")
|
"""
Desempacotamento de listas em Python
"""
lista = [1, 2, 3, 4, 5, 6, 7, 8, 9]
v1, v2, v3, v4, v5, *lista_2, ultimo = lista
# v1, v2, v3 ... são variaveis baseadas nos índices da lista
# "*" faz a contagem ser ao contrario e previne o erro de ter itens demais para desempacotar
print(v1, v4)
print(lista_2)
|
class Solution:
def maxIncreaseKeepingSkyline(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
r=len(grid)
c=len(grid[0])
matrix=[[101 for j in range(c)] for i in range(r)]
for i in range(r):
m=max(grid[i])
... |
def bubble_sort(alist):
for i in range(len(alist)-1, 0, -1):
for j in range(i):
if alist[j] > alist[j+1]:
temp = alist[j]
alist[j] = alist[j+1]
alist[j+1] = temp
return alist
list_to_sort = [147, -16, 18, 91, 44, 1, 8, 54, 31, 18]
bubble_so... |
class MenuItem():
def __init__(self, itemID, itemName, itemPrice):
self.itemID = itemID
self.itemName = itemName
self.itemPrice = itemPrice
self.itemMods = list()
def getItemID(self):
return self.itemID
def setItemID(self, itemID):
self.itemID = s... |
example_string = '我是字符串'
example_list = ['我', '是', '列', '表']
example_tuple = ('我', '是', '元', '组')
print('1.取第一个元素 >', example_string[0], example_list[0], example_tuple[0])
print('2.取下标为2的元素(第三个元素)>', example_string[2], example_list[2], example_tuple[2])
print('3.取最后一个元素 >', example_string[-1], example_list[-1], example... |
def find_highest_number(numbers):
highest_number = 0
for num in numbers:
if num > highest_number:
highest_number = num
return highest_number
|
# [17CE023] Bhishm Daslaniya
'''
Algorithm!
--> Build a list of tuples such that the string "aaabbc" can be squashed down to [("a", 3), ("b", 2), ("c", 1)]
--> Add to answer all combinations of substrings from these tuples which would represent palindromes which have all same letters
--> traverse this list to specific... |
"""
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum
equals the given sum.
For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 ... |
# Copyright 2019 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
config_type='sweetberry'
revs = [5]
inas = [
('sweetberry', '0x40:3', 'pp975_io', 7.7, 0.100, 'j2', True), # R111
('sweetberry', '0x40:1'... |
class A:
def __init__(self):
print("In A __init__")
def feature1(self):
print("Feature 1")
def feature2(self):
print("Feature 2")
# class B(A):
class B:
def __init__(self):
super().__init__()
print("In B __init__")
def feature3(... |
"""Conversion tools for Python"""
def dollars2cents(dollars):
"""Convert dollars to cents"""
cents = dollars * 100
return cents
def gallons2liters(gallons):
"""Convert gallons to liters"""
liters = gallons * 3.785
return liters
|
# fastq handling
class fastqIter:
" A simple file iterator that returns 4 lines for fast fastq iteration. "
def __init__(self, handle):
self.inf = handle
def __iter__(self):
return self
def next(self):
lines = {'id': self.inf.readline().strip(),
'seq': self.i... |
vowels = ['a' , 'o' , 'u' , 'e' , 'i' , 'A' , 'O' , 'U' , 'E' , 'I']
string = input()
result = [s for s in string if s not in vowels]
print(''.join(result)) |
# Given a binary string (ASCII encoded), write a function that returns the equivalent decoded text.
# Every eight bits in the binary string represents one character on the ASCII table.
# Examples:
# csBinaryToASCII("011011000110000101101101011000100110010001100001") -> "lambda"
# 01101100 -> 108 -> "l"
# 01100001 ->... |
"""
A modern, Python3-compatible, well-documented library for communicating
with a MineCraft server.
"""
__version__ = "0.5.0"
SUPPORTED_MINECRAFT_VERSIONS = {
'1.8': 47,
'1.8.1': 47,
'1.8.2': 47,
'1.8.3': 47,
'1.8.4': 47,
'1.8.5': 47,
'1.8.6': 4... |
# 5/1/2020
# Elliott Gorman
# ITSW 1359
# VINES - STACK ABSTRACT DATA TYPE
class Stack():
def __init__(self):
self.stack = []
#set stack size to -1 so when first object is pushed
# its reference is correct at 0
self.size = -1
def push(self, object):
sel... |
# Motor
MOTOR_LEFT_FORWARD = 20
MOTOR_LEFT_BACK = 21
MOTOR_RIGHT_FORWARD = 19
MOTOR_RIGHT_BACK = 26
MOTOR_LEFT_PWM = 16
MOTOR_RIGHT_PWM = 13
# Track Sensors
TRACK_LEFT_1 = 3
TRACK_LEFT_2 = 5
TRACK_RIGHT_1 = 4
TRACK_RIGHT_2 = 18
# Button
BUTTON = 8
BUZZER = 8
# Servos
FAN = 2
SEARCHLIGHT_SERVO = 23
CAMERA_SERVO_H = 1... |
"""base class for user transforms"""
class UserTransform:
"""base class for user transforms, should express taking a set of k inputs to k outputs independently"""
def __init__(self, treatment):
self.y_aware_ = True
self.treatment_ = treatment
self.incoming_vars_ = []
self.deri... |
# Selection Sort
# Time Complexity: O(n^2)
# A Implementation of a Selection Sort Algorithm Through a Function.
def selection_sort(nums):
# This value of i corresponds to each value that will be sorted.
for i in range(len(nums)):
# We assume that the first item of the unsorted numbers is the smallest... |
input = """
att_val(perGrant,name,nameCG).
att_val(perGrant,name,nameGrant).
att_val(nameCG,lastName,"Grant").
att_val(nameGrant,lastName,"Leach").
acted(perGrant,m12).
involved(P,M) :- acted(P,M).
matchingMovie(q1, m12).
inferred_topic(X5, X1) :- matchingMovie(X5, X4), involved(X3, X4), att_val(X3... |
"""
File: class_reviews.py
Name:
-------------------------------
At the beginning of this program, the user is asked to input
the class name (either SC001 or SC101).
Attention: your program should be case-insensitive.
If the user input -1 for class name, your program would output
the maximum, minimum, and average among... |
# -*- coding: utf-8 -*-
"""
custom resp-code
"""
class RET(object):
OK = "0"
DBERR = "4001"
DATAEXIST = "4002"
DATAERR = "4003"
INVALIDCODE = "4004"
PARAMERR = "4005"
THIRDERR = "4006"
IOERR ... |
prompt = """
I translate python code into english descriptions. I say what I will do if I were to execute them, precising what tools and function calls I will use.
I flag behaviours that seem weird or dangerous by preceeding them with "DANGER:".
If the code seems to be deceptive or does not do what it says it does, I... |
"""
Estruturas Lógicas: and (e), or (ou), not (não), is (é)
Operadores unários:
- not
Operadores binários:
- and, or, is
"""
ativo = True
logado = True
if ativo and logado:
print('Bem-vindo usuário!')
else:
print('Você precisa ativar sua conta. Por favor, cheque seu e-mail')
|
arguments = ["self", "info", "args"]
minlevel = 3
helpstring = "enable <plugin>"
def main(connection, info, args) :
"""Enables a plugin"""
if args[1] not in ["disable", "enable", "*"] :
if args[1] not in connection.users["channels"][info["channel"]]["enabled"] :
connection.users["channels"]... |
# Solution to problem 7 #
#Student: Niamh O'Leary#
#ID: G00376339#
#Date: 10/03/2019#
#Write a program that takes a positive floating point number as input and outputs an approximation of its square root#
#Note: for the problem please use number 14.5.
num = 14.5
num_sqrt = num ** 0.5 #calulates the... |
'''
The MIT License (MIT)
Copyright (c) 2016 WavyCloud
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 without restriction, including without limitation the rights
to use, copy, modify, merge, p... |
class Categories:
def __init__(self, category_name, money_allocated, index_inside_list):
self.category_name = category_name
self.money_allocated = money_allocated
self.index_inside_list = index_inside_list
|
class Solution:
def fib(self, N: int) -> int:
self.seen = {}
self.seen[0] = 0
self.seen[1] = 1
return self.dfs(N)
def dfs(self, n):
if n in self.seen:
return self.seen[n]
self.seen[n] = self.dfs(n - 1) + self.dfs(n - 2)
return self.se... |
# Program to find whether given input string has balanced brackets or not
def isBalanced(s):
a=[]
for i in range(len(s)):
if s[i]=='{' or s[i]=='[' or s[i]=='(':
a.append(s[i])
if s[i]=='}':
if len(a)==0:
return "NO"
else:
... |
nome = input("Com quem estou falando? ")
print("foi um prazer te conhecer ", nome)
idade = input("quantos anos você tem, " + nome)
print("então você tem ",idade," ", nome)
|
#Requests stress Pod resources for a given period of time to simulate load
#deploymentLabel is the Deployment that the request is beings sent to
#cpuCost is the number of threads that the request will use on a pod
#execTime is how long the request will use those resource for before completing
class Request:
def __ini... |
"""
datos de entrada
sueldo--->s--->int
ventas realizadas departamento 1--->vrd1--->int
ventas realizadas departamento 2--->vrd2--->int
ventas realizadas departamento 3--->vrd3--->int
"""
#entradas
s=int(input("ingrese el sueldo base: "))
vrd1=int(input("ingrese el numero de ventas realizadas por departamento 1: "))
vr... |
valores = []
while True:
valores.append(int(input("Digite um valor")))
resp = str(input("Quer continuar?"))
if resp in 'Nn':
break
print(f"Você digitou {len(valores)} valores. \n")
valores.sort(reverse= True)
print(f"Os valores em ordem decrescente são {valores}.\n")
if 5 in valores:
print(f"O v... |
dc_shell_setup_tcl = {
############
# default
############
'default': """
set BRICK_RESULTS [getenv "BRICK_RESULTS"];
set TSMC_DIR [getenv "TSMC_DIR"];
set DESIGN_NAME "%s"; # The name of the top-level design.
#############################################################
... |
# Constants and functions for Marsaglia bits ingestion
# constants
FILE_BASE = '/media/alxfed/toca/bits.'
FILE_NUMBER_MIN = 1
FILE_NUMBER_MAX = 60
# pseudo-constants
FILE_EXTENSION = [str(i).zfill(2) for i in range(FILE_NUMBER_MIN, FILE_NUMBER_MAX + 1)]
# starts with 0 element and ends with 59, that's why the dance i... |
#!/usr/bin/env python
#pylint: skip-file
# This source code is licensed under the Apache license found in the
# LICENSE file in the root directory of this project.
class Field(object):
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and the value is a... |
#!/usr/bin/env python
# -*- coding=utf-8 -*-
aString = 'hello world'
print(aString)
aString = aString + ' Python' # 可以拼接
print(aString)
aString = 'huangxiang' # 也可以重新赋值
print(aString)
"""输出结果
hello world
hello world Python
huangxiang
"""
|
ENV_PARAMS = ("temperature", "salinity", "pressure", "sound_speed", "sound_absorption")
CAL_PARAMS = {
"EK": ("sa_correction", "gain_correction", "equivalent_beam_angle"),
"AZFP": ("EL", "DS", "TVR", "VTX", "equivalent_beam_angle", "Sv_offset"),
}
class CalibrateBase:
"""Class to handle calibration for a... |
# Leetcode 138. Copy List with Random Pointer
#
# Link: https://leetcode.com/problems/copy-list-with-random-pointer/
# Difficulty: Medium
# Complexity:
# O(N) time | where N represent the number of elements in the linked list
# O(1) space
"""
# Definition for a Node.
class Node:
def __init__(self, x: int, next... |
def organise(records):
# { user: {shop -> {day -> counter}}}
res = {}
for person, shop, day in records:
if person and shop and (0 < day < 8):
if person not in res:
res[person] = {}
if shop not in res[person]:
res[person][shop] = {}
... |
n1=int(input('digite um valor'))
d=n1*2
t=n1*3
r=n1**(1/2)
print('O dobro do valor {} é {}, o triplo é {} e a raiz quadrada é {}'.format(n1,d,t,r)) |
"""
70.49%
"""
class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
if n == 0 or n == 1:
return True
x = [n]
curr = n
ishappy = False
while True:
digits = list(str(curr))
curr = 0
... |
"""
Crie um Programa que leia nome, sexo e idade de várias pessoas, guardando os dados de cada pessoa em um dicionário, e
todos os dicionários em uma lista. No final, mostre:
- Quantas pessoas foram cadastradas
- A média de Idade do grupo
- Uma lista com todas as mulheres
- Uma lista com todas as pessoas com idade acim... |
"""
.. Copyright (c) 2016 Marshall Farrier
license http://opensource.org/licenses/MIT
Constants for working with an options database
"""
LOG = {
'format': "%(asctime)s %(levelname)s %(module)s.%(funcName)s : %(message)s",
'path': 'mfstockmkt/options/db'
}
DB = {
'dev': {
... |
"""
File for global constants used in the program.
"""
# a constant
nsensors_taska = 5
nsensors_luke = 19
nsensors = nsensors_luke
nencoded = nsensors_luke
nfeat = 1
nelectrodes = 300
|
'''
Convenience wrappers to make using the conf system as easy and seamless as possible
'''
def integrate(hub, imports, override=None, cli=None, roots=None, home_root=None, loader='json'):
'''
Load the conf sub and run the integrate sequence.
'''
hub.pop.sub.add('pop.mods.conf')
hub.conf.integrate... |
#!/usr/bin/env python
# create pipeline
#
reader = vtk.vtkDataSetReader()
reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/RectGrid2.vtk")
reader.Update()
# here to force exact extent
elev = vtk.vtkElevationFilter()
elev.SetInputConnection(reader.GetOutputPort())
elev.Update()
outline = vtk.vtkRectilinea... |
# Find the 10001st prime using the Sieve of Eratosthenes
def sieve(n):
sieve = [True] * (n + 1)
sieve[0] = sieve[1] = False
for i in range(2, (n + 1)):
if sieve[i]:
for j in range(i*i, (n + 1), i):
sieve[j] = False
return sieve
prime_sieve = sieve(400000);
primes =... |
class Node:
# Constructor to initialize the node object
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
# Function to insert a new node at the beginning
de... |
def bubble(alist):
for first in range(len(alist)-1,0,-1):
for sec in range(first):
if alist[sec] > alist[sec+1]:
tmp = alist[sec+1]
alist[sec+1] = alist[sec]
alist[sec] = tmp
def test_bubble():
alist = [1,7,2,5,9,12,5]
bubble(alist)
as... |
"""
>>> from datetime import datetime, timedelta
>>> from django.utils.timesince import timesince
>>> t = datetime(2007, 8, 14, 13, 46, 0)
>>> onemicrosecond = timedelta(microseconds=1)
>>> onesecond = timedelta(seconds=1)
>>> oneminute = timedelta(minutes=1)
>>> onehour = timedelta(hours=1)
>>> oneday = timedelta(da... |
#
# PySNMP MIB module TPLINK-ETHERNETOAM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TPLINK-ETHERNETOAM-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:17:08 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... |
class ParticleInstanceModifier:
axis = None
object = None
particle_system_index = None
position = None
random_position = None
show_alive = None
show_dead = None
show_unborn = None
use_children = None
use_normal = None
use_path = None
use_preserve_shape = None
use_size... |
"""
Author: 陈天翼(Apollo Chen)
Date: 2019-02-18
Description: 学习重点:随机函数,字符串函数,汉字处理,字体函数,列表
"""
lines = []
def setup() :
global lines, img
size(1024, 576)
strings = [u"2019 新年快乐!", u"Happy New Year!", u"不用熬夜,心想事成。", u"多写程序,万事如意:-)", u"学业有成,找到朋友:-P", u"玩个痛快,老师再见:-("]
#lines = new ArrayList<Line>(strings.le... |
def FlagsForFile(filename, **kwargs):
return {
'flags': ['-x', 'c++', '-std=c++14', '-Wall', '-Wextra', '-Werror'
,'-I','C:/Program Files (x86)/Microsoft Visual Studio/2017/Community/VC/Tools/MSVC/14.13.26128/include'
,'-I','C:/Program Files (x86)/Microsoft Visual Studio/2017/Community/VC/Tools/MSVC/14.13.2612... |
passOne = input(": ")
passTwo = input(": ")
if len(passOne) < 8:
print("Короткий!")
elif "123" in passOne:
print("Простой!")
elif passOne == passTwo:
print("OK")
else:
print("Различатся.")
|
n = int(input('Digite um valor para calcular seu fatorial: '))
f = 1
print(f'Calculando {n}! = ', end =' ')
for i in range(1, n+1):
print(f'{n}', end = ' ')
print(' x ' if n > 1 else ' = ', end = ' ')
f *= i
n -= 1
print(f) |
class TestTable:
def __init__(self):
self.id = None
self.code = None
DDLCOMMAND = """
CREATE TABLE TestTable (
id INTEGER CONSTRAINT pk_role PRIMARY KEY,
code INTEGER
);
"""
|
def most_common(lst):
return max(lst, key=lst.count)
|
# https://leetcode.com/problems/defanging-an-ip-address
class Solution:
def defangIPaddr(self, address):
if not address:
return ""
ls = address.split(".")
return "[.]".join(ls)
|
BOT = "b"
EMPTY = "-"
DIRT = "d"
def dist(pos1, pos2):
return abs(pos1[0] - pos2[0]) + abs(pos1[1] - pos2[1])
def is_dirt(pos, board):
if min(pos) < 0:
return False
if pos[0] >= len(board):
return False
if pos[1] >= len(board[0]):
return False
if board[pos[0]][pos[1]] != ... |
SMALL = 1
MEDIUM = 2
LARGE = 3
ORDER_SIZE = (
(SMALL, u'Small'),
(MEDIUM, u'Medium'),
(LARGE, u'Large')
)
MARGARITA = 1
MARINARA = 2
SALAMI = 3
ORDER_TITLE = (
(1, u'margarita'),
(2, u'marinara'),
(3, u'salami')
)
RECEIVED = 1
IN_PROCESS = 2
OUT_FOR_DELIVERY = 3
DELIVERED = 4
RETURNED = 5
ORD... |
word = input("Введите строку: ")
if len(word) > 5:
print(len(word))
elif len(word) < 5:
print("Need more!")
elif len(word) == 5:
print("It's five")
|
# I decided to write a code that generates data filtering object from a list of keyword parameters:
class Filter:
"""
Helper filter class. Accepts a list of single-argument
functions that return True if object in list conforms to some criteria
"""
def __init__(self, functions):
self... |
def fatorial(n):
num = 1
while n >= 1:
num = num * n
n = n - 1
return num
digit = int(input('numero para mostra o fatorial '))
print(fatorial(digit)) |
# Time: O(n^2)
# Space: O(n)
class Solution(object):
def minSkips(self, dist, speed, hoursBefore):
"""
:type dist: List[int]
:type speed: int
:type hoursBefore: int
:rtype: int
"""
def ceil(a, b):
return (a+b-1)//b
dp = [0]*((len(dist)-1... |
#!/usr/bin/python3
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
cars.sort(reverse=True)
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
print("\nHere is the sorted list(reverse=True):")
print(sorted(cars, reverse = True))
print("\nHere is the original list:")
print(cars)
pri... |
#
# PySNMP MIB module CISCO-CBP-TARGET-TC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-CBP-TARGET-TC-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:52:40 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 ... |
lanche = ('Hambúrguer', 'Suco', 'Pizza', 'Pudim', 'Batata Frita')
a = (5, 7, 3, 9, 2)
print(sorted(lanche))
print(sorted(a))
# COLOCA A TUPLA EM ORDEM
# TRANSFORMANDO () EM [] => OU SEJA, TRANSFORMANDO A TUPLA EM LISTA (para que possa ser "mutável")
|
o = c50 = c20 = c10 = r = 0
while True:
o = int(input('Quanto voce deseja sacar? '))
r = o
while r >= 50:
c50 += 1
r = r - 50
while r >= 20:
c20 += 1
r = r - 20
while r > 10:
c10 += 1
r = r - 10
if r < 10:
break
print(f'Para o valor de R$ {... |
__version__ = "3.12.1"
CTX_PROFILE = "PROFILE"
CTX_DEFAULT_PROFILE = "default"
|
"""Mark this test directory as a package.
See https://github.com/python/mypy/issues/4008 for more info.
"""
|
"""
{{package}} module.
---------------
{{description}}
Author: {{author}}
Email: {{email}}
"""
|
class Query:
def __init__(self, data, res={}):
self.res = res
self.data = data
def clear(self):
self.res = {}
def get(self):
return self.res
def documentAtTime(self, query, model):
self.data.clearScore()
# pLists = {}
query = query.split()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.