content stringlengths 7 1.05M |
|---|
def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(' ')
return words
def sort_words(words):
"""Sorts the words."""
return sorted(words)
def print_first_word(words):
"""Prints the first word after popping it off."""
word = words.pop(0)
print(word... |
def orderedSequentialSearch(alist, item):
pos = 0
found = False
stop = False
while pos < len(alist) and not found and not stop:
if alist[pos] == item:
found = True
elif alist[pos] > item:
stop = True
else:
pos += 1
return found
if __nam... |
# LTD simulation models / perturbances
# Attribute name case sensitive.
# Commented and empty lines are ignored during parsing.
# Double quoted variable names in model parameters also ignored
# Perturbances
mirror.sysPerturbances = [
#'load 9 : ramp P 2 40 10 per',
]
mirror.NoiseAgent = ltd.perturbance.LoadN... |
# Python - 3.4.3
def z(iter, num):
lst = [ [] for i in range(num) ]
r, dr = 0, 1
for n in iter:
lst[r].append(n)
if (r <= 0 and dr == -1) or (r >= (num - 1) and dr == 1):
dr *= -1
r += dr
result = []
for e in lst:
result += e
return result
... |
# -*- coding: utf-8 -*-
tg_key = "XYZ" # telegram bot api key
zbx_tg_prefix = "zbxtg" # variable for separating text from script info
zbx_tg_tmp_dir = "/var/tmp/" + zbx_tg_prefix # directory for saving caches, uids, cookies, etc.
zbx_tg_signature = False
zbx_tg_update_messages = True
zbx_tg_update_graph_messages ... |
# this file of 100 random fictitious people was generated from
# Random User Generator with the following API call:
# https://randomuser.me/api/?results=100&nat=us&inc=gender,name,location,dob,id,picture
# the format is JSON, but Python can handle this as an array of dictionaries
PEOPLE = [
{"gender":"female","name":{... |
{
"targets": [{
"target_name": "leveldown"
, "conditions": [
["OS == 'win'", {
"defines": [
"_HAS_EXCEPTIONS=0"
]
, "msvs_settings": {
"VCCLCompilerTool": {
"RuntimeTypeInfo": "false"
... |
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
lists = [[] for _ in range(numRows)]
row = 0
orient = 0 # 0表示down,1表示up
for i in range(len(s)):
lists[row].append(s[i])
if orient == 0:
... |
nama = [ 0 ]* 5
for i in range( 5 ):
nama[i] = input()
for i in range( 4 ):
for j in range( 4 ):
if nama[j] > nama[j+1]:
tmp = nama[j]
nama[j] = nama[j+1]
nama[j+1] = tmp
print(nama)
|
expected_output = {
'vpn_id':{
1:{
'ethernet_segment_id':{
'0012.1212.1212.1212.1212':{
'es_index':{
1:{
'encap':'SRv6',
'ether_tag':'0',
'internal_id... |
def memoize(f):
"""memoization decorator for a function taking one or more arguments"""
class memodict(dict):
def __getitem__(self, *key):
return dict.__getitem__(self, key)
def __missing__(self, key):
ret = self[key] = f(*key)
return ret
return memodic... |
content = '''
<script>
function display_other_page() {
var x = document.getElementById("testdetails");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
var x = document.getElementById("... |
M = 9999991
N = 1
class Node:
def __init__(self, key, value):
self.key = key
self.value = value
self.next = None
self.valid = True
def hash_func(n):
return n % M
def init():
global values
values = [None for i in range(M)]
with open("input") as file:
for... |
"""
Gauged
https://github.com/chriso/gauged (MIT Licensed)
Copyright 2014 (c) Chris O'Hara <cohara87@gmail.com>
"""
class Aggregate(object):
SUM = 'sum'
MIN = 'min'
MAX = 'max'
MEAN = 'mean'
STDDEV = 'stddev'
PERCENTILE = 'percentile'
MEDIAN = 'median'
COUNT = 'count'
ALL = set([... |
input_line = input()
dict_ref = {}
while input_line != "end":
splited_line = input_line.split(" = ")
if splited_line[1].isnumeric():
dict_ref[splited_line[0]] = splited_line[1]
else:
if splited_line[1] in dict_ref.keys():
dict_ref[splited_line[0]] = dict_ref[splited_line[1]]
... |
def calculo_mul(valor1,valor2):
mul = valor1 * valor2
return mul
def calculo_div(valor1,valor2):
div = valor1 / valor2
return div
def calculo_sub(valor1,valor2):
sub = valor1 - valor2
return sub
def calculo_soma(valor1,valor2):
soma = valor1 + valor2
return soma
def calculo_div_int(v... |
class OidcEndpointError(Exception):
pass
class InvalidRedirectURIError(OidcEndpointError):
pass
class InvalidSectorIdentifier(OidcEndpointError):
pass
class ConfigurationError(OidcEndpointError):
pass
class NoSuchAuthentication(OidcEndpointError):
pass
class TamperAllert(OidcEndpointError)... |
# -*- coding: utf-8 -*-
"""
Spyder Editor
@auther: syenpark
Python Version: 3.6
"""
def fancy_divide(list_of_numbers, index):
denom = list_of_numbers[index]
return [simple_divide(item, denom) for item in list_of_numbers]
def simple_divide(item, denom):
try:
return item / denom
except ZeroDivis... |
a = 0.0
def setup():
global globe
size(400, 400, P3D)
world = loadImage("bluemarble01.jpg")
globe = makeSphere(150, 5, world)
frameRate(30)
def draw():
global globe, a
background(0)
translate(width/2, height/2)
lights()
with pushMatrix():
rotateX(radians(-25))
r... |
config = {
'timeToSleepWhenNoMovement': 1,
'timeToWaitWhenNoMovementBeforeSleep': 5,
'frameDifferenceRatioForMovement': 1,
'hand': {
'hsv_min_blue': [0, 0, 0],
'hsv_max_blue': [255, 255, 255],
'hsv_dec_blue': [255, 55, 32],
'hsv_inc_blue': [255, 255, 255],
'timeTo... |
class Movie:
'''
Movie class to define movie objects
'''
def __init__(self, id, title, overview, poster, vote_average, vote_count):
self.id = id
self.title = title
self.overview = overview
self.poster = 'https://image.tmdb.org/t/p/w500/'+poster
self.vote_average ... |
'''
Copyright 2018 Dustin Roeder (dmroeder@gmail.com)
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 b... |
train_cfg = {}
test_cfg = {}
optimizer_config = dict() # grad_clip, coalesce, bucket_size_mb
# yapf:disable
# yapf:enable
# runtime settings
dist_params = dict(backend='nccl')
cudnn_benchmark = True
log_level = 'INFO'
load_from = None
resume_from = None
workflow = [('train', 1)]
# model settings
model = dict(
typ... |
your_name = ["Heisenberg"]
myname = "dero"
def say_my_name () :
print(your_name)
class Fridge :
vegetables = [5]
@staticmethod
def print_vegetables () :
print(Fridge.vegetables)
Σfruits = [6]
@staticmethod
def Σprint_fruits () :
print(Fridge.Σfruits)
soft_... |
# -*- coding: utf-8 -*-
urlpatterns = patterns('',
url(r'^galleries/', include('porticus.urls', namespace='porticus')),
) + urlpatterns
|
#
# Elias Coding performs prefix-free(variable-length) encode/decode for integer stream
#
def elias_encoder(N:int):
assert N > 0, "Cannot encode non-positive number!"
if N == 1:
return str(N)
# 1. initialization, base case(binary rep for N)
binary_N:str = BinaryRep(N)
L:int = len(binary_... |
TEXT_GET_COMMAND = """
Seleccione una opción:
[a] Agregar nuevo contacto
[b] Mostrar contactos
[x] Salir
"""
TEXT_GET_ID_TYPE = """
Seleccione tipo de identificación:
[cc] Cédula
[ce] Cédula de extranjería
[pp] Pasaporte
"""
TEXT_GET_ID_NUMBER = """
Ingrese número de documento:
"""
TEXT_GET_ID_EXP_DATE = """
Ingre... |
RAWDATA_DIR = '/staging/as/skchoudh/re-ribo-datasets/hg38/SRP103009'
OUT_DIR = '/staging/as/skchoudh/re-ribo-analysis/hg38/SRP103009'
GENOME_FASTA = '/home/cmb-06/as/skchoudh/genomes/hg38/fasta/Homo_sapiens.GRCh38.dna_sm.primary_assembly.fa'
CHROM_SIZES = '/home/cmb-06/as/skchoudh/genomes/hg38/fasta/Homo_sapiens.GRCh38... |
class carro:
nome = None
ano = None
cor = None
veloc_max = None
veloc_atual = 0
ligado = False
def __init__(self, nome, cor, velocidade_maxima, ligado):
self.nome = nome
self.cor = cor
self.veloc_max = velocidade_maxima
self.ligado = ligado
def ligar(sel... |
def code_function():
#function begin############################################
global code
code="""
`include "{0}_agent.sv"
`include "{0}_scoreboard.sv"
class {0}_model_env extends uvm_env;
//---------------------------------------
// agent and scoreboard instance
//------------------... |
{
"conditions": [
["OS=='mac'", {
"variables": { "oci_version%": "11" },
}, {
"variables": { "oci_version%": "12" },
}],
],
"targets": [
{
"target_name": "oracle_bindings",
"sources": [ "src/connection.cpp",
"src/oracle_bindings.cpp",
"... |
a = 0
while(a < 5):
a = (a + 1) * 2 % 3
if(a == 2):
while(b):
execute(a)
else:
a = mogrify()
else:
a = -(c and d) == -1 != get() + escape_string(a)
a = get()
execute(a) |
#
# PySNMP MIB module VERTICAL16-IPTEL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/VERTICAL16-IPTEL-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:34:14 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
def lin(msg):
print('-' * len(msg))
print(msg)
print('-' * len(msg))
lin('Controle de Terrenos')
def area(larg, comp):
a = larg * comp
print(f'A área de um terreno {larg} x {comp} é de {a}m².')
l = float(input('LARGURA (m): '))
c = float(input('COMPRIMENTO (m): '))
area(l, c)
|
minha_lista_de_compras = ['Sabão', 'Sabonete', 'Arroz', 'Feijão', 10, [1, 2, 3]]
for coisa in minha_lista_de_compras:
print(coisa)
#Slice
print(minha_lista_de_compras[0])
print(minha_lista_de_compras[1])
print(minha_lista_de_compras[1:])
print(minha_lista_de_compras[3:])
print(minha_lista_de_compras[:3])
#Exempl... |
first_value = input('First Number: ')
second_value = input('Second Number: ')
if first_value.isnumeric() == False or second_value.isnumeric() == False:
print('Please enter numbers only.')
exit()
first_value = int(first_value)
second_value = int(second_value)
sum = first_value + second_value
print('Sum: ' + ... |
DEBUG = True
ASSETS_DEBUG = True
# GRANO_HOST = 'http://localhost:5000'
# GRANO_APIKEY = '7a65f180d7b898822'
# GRANO_PROJECT = 'kompromatron_C'
GRANO_HOST = 'http://beta.grano.cc/'
GRANO_APIKEY = 'GHtElTYOQUPKPik'
GRANO_PROJECT = 'kompromatron'
|
#Chapter 2 - Exploratory data analysis
#pandas line plots
# Create a list of y-axis column names: y_columns
y_columns = ['AAPL','IBM']
# Generate a line plot
df.plot(x='Month', y=y_columns)
# Add the title
plt.title('Monthly stock prices')
# Add the y-axis label
plt.ylabel('Price ($US)')
# Displa... |
a=int(input("enter a year:"))
if(a%4==0):
print("{0} is a leap year".format(a))
elif(a%400==0):
print("{0} is a leaf year".format(a))
else:
print("{0} is not a leap year".format(a))
|
# This program saves a list of strings to a file.
def main():
# Create a list of strings.
cities = ['New York', 'Boston', 'Atlanta', 'Dallas']
# Open a file for writing.
outfile = open('cities.txt', 'w')
# Write the list to the file.
for item in cities:
outfile.write(item +... |
class FabricArea(Element,IDisposable):
""" An object that represents an Fabric Area Distribution within the Autodesk Revit project. It is container for Fabric Sheet elements. """
def CopyCurveLoopsInSketch(self):
"""
CopyCurveLoopsInSketch(self: FabricArea) -> IList[CurveLoop]
Creates copies of the ... |
__all__ = ['edition_to_deckbox']
def edition_to_deckbox(edition):
if edition == 'GRN Guild Kit':
edition = 'Guilds of Ravnica Guild Kit'
if edition == 'RNA Guild Kit':
edition = 'Ravnica Allegiance Guild Kit'
if edition == 'Time Spiral Timeshifted':
edition = 'Time Spiral "Timesh... |
# --------------------------------------------------------
# (c) Copyright 2014, 2020 by Jason DeLaat.
# Licensed under BSD 3-clause licence.
# --------------------------------------------------------
""" Provides monad classes with operators.
The operators module overrides all base monad types and their aliases
with ... |
# CPU: 0.05 s
n_judges, n_ratings = map(int, input().split())
sum_ = 0
for _ in range(n_ratings):
sum_ += int(input())
print((sum_ + (n_judges - n_ratings) * -3) / n_judges, (sum_ + (n_judges - n_ratings) * 3) / n_judges)
|
# -*- coding: utf-8 -*-
"""
Created on Sun May 15 2016
@author: Matthew Carse
"""
#@ Uses virtual potentials (Aires-de-Sousa, J., & Aires-de-Sousa, L. (2003). Representation of DNA sequences
#@ with virtual potentials and their processing by (SEQREP) Kohonen self-organizing maps. Bioinformatics, 19(1), 30-36.)
#@ to... |
class AnalysisModule(object):
def __init__(self, config_section, *args, **kwargs):
assert isinstance(config_section, str)
self.config = config_section
def analyze_sample(self, filepath='', tags=[]):
'''
Called to start the analysis for the module.
:param filepath: The ... |
hexa = {
"a" : 10,
"b" : 11,
"c" : 12,
"d" : 13,
"e" : 14,
"f" : 15,
}
print(hexa['a'])
hexa_to_dec = {
"0": 0,
"1": 1,
"2": 2,
"3": 3,
"4": 4,
"5": 5,
"6": 6,
"7": 7,
"8": 8,
"9": 9,
"A": 10,
"B": 11,
"C": 12,
"D": 13... |
"""
Connection types are specified here:
https://code.google.com/p/selenium/source/browse/spec-draft.md?repo=mobile#120
Value (Alias) | Data | Wifi | Airplane Mode
-------------------------------------------------
0 (None) | 0 | 0 | 0
1 (Airplane Mode) | 0 | 0 | 1
2 (... |
class Restaurant():
def __init__(self, nombre, tipo):
self.nombre = nombre.title()
self.tipo = tipo
def desc(self):
print("\nEl mejor restaurant de todos! ---> " + self.nombre + " comida: " + self.tipo)
def abierto(self):
print("\n" + self.nombre + " esta abierto")
|
string = "My name is Lucas"
string_lower_case = string.lower() #Toda minúscula
string_upper_case = string.upper() #Toda maiúscula
print(string, string_lower_case, string_upper_case)
first_programmer = "ada lovelace"
print(first_programmer.title()) #Primeira maiúscula e demais minúsculas
first_name = "miguel"
second_... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
@File : __init__.py
@Author: ChenXinqun
@Date : 2019/1/18 16:26
''' |
palavras = ('arvore',
'casa',
'carro',
'parada',
'hospital',
'imobiliaria',
'faca',
'comida')
for palavra in palavras:
print(f'\nNa palavra {palavra.upper()} temos vogais ', end='')
for letra in palavra:
if letra in 'aei... |
file = open("abc.txt", "w")
#file.read()
#print(a)
#file.readline()
#print(b)
for line in file:
print(line,end="")
|
# -*- coding: utf-8 -*-
"""
Created on 2020/2/11 11:01
@Project -> File: ruima_galvanization_optimization -> operation.py
@Author: luolei
@Email: dreisteine262@163.com
@Describe:
"""
def sort_dict_by_keys(adict: dict, reverse=False) -> dict:
"""将dict按照键进行排序"""
adict = dict(sorted(adict.items(), key=lambd... |
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def desc_make():
head = Node(0)
this = head
for i in range(1, 10):
this = Node(i, this)
return this
def asc_make():
head = Node(0)
this = head
for i in range(1, 10):
... |
def parse_geneinfo_taxid(fileh):
for line in fileh:
if line.startswith("#"):
# skip header
continue
taxid = line.split("\t")[0]
yield {"_id" : taxid}
|
class Solution:
def validPalindrome(self, s: str) -> bool:
def check_palin(string):
return string == string[::-1]
start = 0
end = len(s) - 1
while start < end:
if s[start] == s[end]:
start += 1
end -= 1
else:
... |
"""9. Imprima la posicion del Pais de Mexico"""
archivo = open("paises.txt", "r")
lista = []
paises = []
for i in archivo:
a = i.index(":")
for r in range(0, a):
lista.append(i[r])
a = "".join(lista)
paises.append(a)
lista = []
x = paises.index("México")+1
print(x)
archivo.close()
|
class TrieNode:
def __init__(self):
self.children = {}
self.is_word = False
self.word = None
class Trie:
def __init__(self):
self.root = TrieNode()
def add(self, word):
node = self.root
for ch in word:
if ch not in node.children:
... |
def foo():
print("foo")
def moduleb_fn():
print("import_moduleb.moduleb_fn()")
class moduleb_class(object):
def __init__(self):
pass
def msg(self,val):
return "moduleb_class:"+str(val)
|
test = {
'name': 'Problem 2',
'points': 3,
'suites': [
{
'cases': [
{
'answer': 'A single tile that an Ant can be placed on and that connects to other Places',
'choices': [
r"""
A single tile that an Ant can be placed on and that connects to
... |
marks=int(input("Enter marks -> "))
if marks>=90:
print("O")
elif marks>=80:
print("A")
elif marks>=70:
print("B")
elif marks>=60:
print("C")
elif marks>=50:
print("D")
elif marks>=40:
print("E")
else:
print("F")
|
'''def old_macdonal(name):
if(len(name)>3):
return name[:3].capitalize()+name[3:].capitalize()
else:
return 'Name is too short'
print(old_macdonal('macdonal'))
def old_macdonald(name):
letters = list(name)
for index in range(len(name)):
if index == 0:
letters[index] ... |
def convert_deciliter_to(capacity_to: str, amout: float):
if capacity_to == 'litro(s)':
value = amout / 10
if capacity_to == 'quilolitro(s)':
value = amout / 10000
if capacity_to == 'hectolitro(s)':
value = amout / 1000
if capacity_to == 'decalitro(s)':
value = amout / 10... |
# SWEA 2063
n = int(input())
arr = list(map(int, input().split()))
arr.sort()
print(arr[len(arr) // 2]) |
UTILS = [
"//utils/osgiwrap:osgi-jar",
"//utils/osgi:onlab-osgi",
"//utils/junit:onlab-junit",
"//utils/misc:onlab-misc",
"//utils/rest:onlab-rest",
]
API = [
"//core/api:onos-api",
]
CORE = UTILS + API + [
"//core/net:onos-core-net",
"//core/common:onos-core-common",
"//core/store... |
__author__ = 'alexander'
# TODO: It has to be an abstract class in the future. Read `abc — Abstract Base Classes`
class ITaskCache:
def get(self, user, remove_finished):
"""
Gets a dictionary of tasks for the user
:param user: User whose tasks we're looking for
:param remove_finis... |
# # --- CityCulture ---
# #
# # - Deals with cities and their interactions with cultures
# #
# # --- --- --- ---
# --- Constants ---
DIVERGENCE_THRESHOLD = 27
MERGE_THRESHOLD = 18
# ------
def diverge(target):
target.divergencePressure = 0
oldMax = target.maxCulture
newCulture = None
# Try a subcul... |
"""Build definitions for Ruy that are specific to the open-source build."""
# Used for targets that #include <thread>
def ruy_linkopts_thread_standard_library():
# In open source builds, GCC is a common occurence. It requires "-pthread"
# to use the C++11 <thread> standard library header. This breaks the
#... |
def hello(name):
print('Hello ' + name)
hello('Alice')
hello('Bob')
|
''' python version limits '''
MINIMUM_VERSION = (3, 5, 0)
VERSION_LIMIT = (9999, 9999, 9999)
|
'''
Pixel.py
Essentially just holds color values in an intelligent way
Author: Brandon Layton
'''
class Pixel:
red = 0
green = 0
blue = 0
alpha = 0
def __init__(self,red=0,green=0,blue=0,alpha=255,orig=None):
if orig!=None:
self.red = orig.red
self.green = orig.green
self.blue = orig.blue
self... |
def drop_dataframe_values_by_threshold(dataframe, axis=1, threshold=0.75):
# select axis to calculate percent of missing values
mask_axis = 1 if axis == 0 else 0
# boolean mask to filter dataframe based on threshold
mask = (
(dataframe.isnull().sum(axis=mask_axis) / dataframe.shape[mask_ax... |
class Queue:
def __init__(self):
self.items = []
def enqueue(self,item):
self.items.insert(0,item)
def dequeue(self):
return self.items.pop()
def isEmpty(self):
return self.items == []
def size(self):
return le... |
# List in py is mutable collection
# Concatinaton of list
# list is zero indexed
# Can hold multiple data types
# List supports negative indexing
l = ['Jack', 1000, 20.3, True]
print(l) #['Jack', 1000, 20.3, True]
#l[0] == l[-4] (Negative indexing last element is indexed -1)
print(l[0], l[-4]) #Jack Jack
#Concatinat... |
#!/usr/bin/env python
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Jiao Lin
# California Institute of Technology
# (C) 2005 All Rights Reserved
#
# {LicenseText}
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... |
def lengthOfLongestSubstring(s: str) -> int:
"""Given a string, find the length of the longest substring without repeating characters
Solution:
We use a window approach here so we can optimize and iterate just once through the list. When we find a repeat
character, we keep the part of the subst... |
class QueueNode(object):
def __init__(self, next_node, prev_node,
data):
self.next_node = next_node
self.prev_node = prev_node
self.data = data
class Queue(object):
def __init__(self, first=None, last=None):
self.first = first
self.last = last
de... |
squares = lambda n: (i ** 2 for i in range(1, n + 1)) # generator expression
print(list(squares(5)))
def squares(n):
i = 1
while i <= n:
yield i ** 2
i += 1
print(list(squares(5))) |
'''
Escreva um algoritmo que leia certa quantidade de números e imprima o maior deles e quantas vezes o maior número
foi lido. A quantidade de números a serem lidos deve ser fornecida pelo usuário
'''
n1 = int(input('Quantos números deseja inserir: '))
n2 = 0
maior = n3 = int(input('Digite um número qualquer: '))
cont... |
# coding: UTF-8
# 函数的输入是一个列表[Id1, Id2, Id3, ...]
# 因为expr长度有限制,最长为1800个字符,所以一个OR嵌套的字符串里的Id数量限定最多70个
# 函数输出就是嵌套的字符串的列表,输出是列表的原因是输入的Id列表里的Id数目可能大于70个
def make_or_queries(ids):
if ids:
if len(ids)>1:
return [make_an_or_query('Id', map(str, chunk), len(chunk)) for chunk in chunks(ids, 70)]
... |
#################################
## ##
## 2021 (C) Amine M. Remita ##
## ##
## Laboratoire Bioinformatique ##
## Pr. Abdoulaye Diallo Group ##
## UQAM ##
## ##
#################################
__author__ = ... |
"""If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000."""
def multipliers(muls):
arr=[];
for mul in range(1,muls+1):
if((mul%3==0) or (mul%5==0)):
arr.append(mul)
prin... |
'''
@author : CodePerfectPlus
@python
'''
class dog():
def __init__(self, name, age):
self.name= name
self.age = age
def speak(self):
print(f"I am {self.name} and my age is {self.age}.")
one = dog("Tuktuk", 12)
two = dog("Tyson",4)
three = dog("Mike", 5)
one.speak()
two.speak()
... |
__author__ = 'Patrizio Tufarolo'
__email__ = 'patrizio.tufarolo@studenti.unimi.it'
'''
Project: testagent
Author: Patrizio Tufarolo <patrizio.tufarolo@studenti.unimi.it>
Date: 21/04/15
'''
|
numbers = list(map(int,input().split()))
index = input()
count = 0
while index != 'End':
index = int(index)
if index < len(numbers):
count +=1
shoot_position_num = numbers[index]
for n in range(len(numbers)):
if numbers[n] < 0:
continue
if number... |
class Solution:
def totalHammingDistance(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ans = 0
for i in range(32):
cnt = 0
for num in nums:
if (num >> i) & 1:
cnt += 1
ans += cnt * (len(n... |
class AudioFrame:
''
def copyfrom():
pass
def is_playing():
pass
def play():
pass
def stop():
pass
|
#!/usr/bin/env python
def iter_block(check,r):
"""
Iterates through 'r', yielding a block in list form of items in r since the
prior True result tested against the 'check' function.
"""
bunch = []
try:
tr = iter(r)
bunch.append(next(tr))
while True:
a = next(... |
class ItemResult():
source = None # ie, amazon, etc
itemurl = None
imageurl = None
small_image_url = None
medium_image_url = None
large_image_url = None
isbn = None
|
num = int(input())
factorial = 1
if num == 0:
print("1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print(factorial) |
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
stack = []
heights.append(0)
mx = 0
for i, h in enumerate(heights):
while stack and h < heights[stack[-1]]:
height = heights[stack.pop()]
if stack:
... |
def is_prime(x):
if x > 2:
for i in range(2, x):
if x % i == 0:
return False
return True
elif x == 0 or x == 1:
return False
elif x == 2:
return True
print(is_prime(9))
|
#047 - Contagem de pares
for n in range(2, 51, 2):
print(n, end=' ')
print('acabou')
|
class Inventory:
def __init__(self):
self.stuff = []
def add(self, item):
self.stuff.append(item)
def drop(self, item):
self.stuff.remove(item)
return item
def has(self, item):
return item in self.stuff
def all(self):
return self.stuff
|
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for c in range(0, 3):
for p in range(0, 3):
matriz[c][p] = int(input(f'Digite um valor para a posição [{c}, {p}]: '))
print(f'''[ {matriz[0][0]} ] [ {matriz[0][1]} ] [ {matriz[0][2]} ]
[ {matriz[1][0]} ] [ {matriz[1][1]} ] [ {matriz[1][2]} ]
[ {matriz[2][0]} ] [ {matriz[... |
"""
__version__.py
~~~~~~~~~~~~~~
Information about the current version of the package.
"""
__title__ = 'AI'
__description__ = 'Simple Image Classificator Models'
__version__ = '0.0.1'
__author__ = 'Yast.AI'
__author_email__ = 'yastai.data@gmail.com'
__license__ = 'MIT License'
__url__ = 'https://github.com/yast-ia/Y... |
s=input()
i=0
while i<len(s):
if s[i]=='-' and s[i+1]=='-':
print("2",end="")
i+=2
elif s[i]=='-' and s[i+1]=='.':
print("1",end="")
i+=2
else:
print("0",end="")
i+=1
|
def inc_hash(the_hash,the_key):
try:
the_hash[the_key]
except:
the_hash[the_key] = 0
pass
finally:
the_hash[the_key] += 1
def inc_double_key_hash(the_hash,the_key1,the_key2):
try:
the_hash[the_key1]
except:
the_hash[the_key1] = {}
pass
t... |
"""
Programa principal onde será executado a Ordenação Externa.
"""
def main():
print("Iniciando programa Main...")
input("Digite ENTER para sair do programa...")
if __name__ == '__main__':
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.