content stringlengths 7 1.05M |
|---|
#!/usr/bin/python3
def simple_delete(a_dictionary, key=""):
if key is not '' and key in a_dictionary:
a_dictionary.pop(key)
return a_dictionary
|
"""
This module provides functions for processing station relative river
level data to identify high flood risk locations
"""
def stations_level_over_threshold(stations, tol):
"""
Returns a list of tuples, where each tuple holds
(i) a station (object) at which the latest relative water level is over tol and
(ii)... |
def merge(a, aux, lo:int, mid: int, hi:int):
#TODO: can we get rid of this?
for i in range(lo, hi+1):
aux[i] = a[i]
i = lo
j = mid+1
for k in range(lo, hi+1):
#if exhausted first half
if i > mid:
a[k] = aux[j]
j += 1
#else if exhausted second... |
#!/usr/bin/python3
delimeter = " : "
class MonitorMessage:
def __init__(self):
self._target_directory = ""
self._target_file = ""
self._additional_information = ""
self._event_type = 0
def __repr__(self):
return self.__combine_message()
def __str__(self):
r... |
#!/usr/bin/env python2.7
# Copyright 2017 gRPC authors.
#
# 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... |
def prod_esc_min(V, W):
producto = 0
Vm = sorted(V)[::-1]
WM = sorted(W)
for i in range(len(Vm)):
producto += Vm[i] * WM[i]
return(producto)
def main():
entrada = open("input.txt","r")
salida = open("output.txt","w")
T = int(entrada.readline())
x = 0
for i in range(T):... |
a = int(input())
b = int(input())
m = int(input())
powered_value = a ** b
print(powered_value)
print(powered_value % m)
|
# This question was asked by Zillow.
# You are given a 2-d matrix where each cell represents number of coins in that cell. Assuming we start at matrix[0][0], and can only move right or down, find the maximum number of coins you can collect by the bottom right corner.
# For example, in this matrix
# 0 3 1 1
# 2 1 0 4
# ... |
#Ejercicio prueba 3.8
print("Buen dia")
#Datos de entrada
años=int(input("Porfavor ingrese sus años de laborr en la empresa:"))
sueldo=float(input("Ingrese el sueldo que recibe por parte de la empresa:"))
bonoañomenor=0.20
bonoñormayor=0.30
sueldo1=0.25
sueldo2=0.15
sueldo3=0.10
bonosemi1=0.0
bonosemi2=0.0
bonofinal=0.... |
# 包含min函数的栈
# 定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
# 注意:保证测试中不会当栈为空的时候,对栈调用pop()或者min()或者top()方法。
# 注意:pop的时候会改变栈中数据,有可能min的结果也会改变
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.dataStack = []
self.minStack = []
def push(self, node):
# write code here
... |
def func(k, n):
ret = 0
for i in range(1, len(str(n)) + 1):
ret += int(n[-i]) * (k ** (i - 1))
return ret
k = int(input())
a, b = input().split()
print(func(k, a) * func(k, b))
|
def lambda_handler(event, context):
"""
:param event:
:param context:
:return:
"""
print(event)
print("*"*20)
print(context)
return
|
a, b, c, d = map(int, input().split())
if b/a == d/c:
print("DRAW")
elif b/a > d/c:
print("TAKAHASHI")
else:
print("AOKI")
|
N = int(input())
sub_populations = []
for x in range(N):
input_ = input().split()
if len(input_) == 1:
sub_populations.append([])
else:
sub_populations.append(input_[1:])
for i in range(0, len(sub_populations)-1):
cow1 = set(sub_populations[i])
for j in range(i+1, len... |
'''
(4) - Faça um programa para uma loja de tintas. O programa deverá pedir o tamanho em metros quadrados da área a
ser pintada. Considere que a cobertura da tinta é de 1 litro para cada 3 metros quadrados e que a tinta é vendida
em latas de 18 litros, que custam R$ 80,00. Informe ao usuário a quantidades de latas d... |
#!/usr/bin/env python
#
# Copyright 2014 - 2018 The BCE Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the license.txt file.
#
ABBREVIATION_DATABASE = {
"CHES": "C8H17NO3S",
"Val": "C5H11NO2",
"BOP": "C12H22F6N6OP2",
"CPD": "C5H6"... |
def main():
pass
if __name__ == '__main__.py':
main()
|
if exists("OK-1.png"):
click("OK-1.png")
else:
exit(1)
exit(0)
|
# -*- coding: utf-8 -*-
# 前收盘 , 开盘 , 最高 , 最低 , 收盘 , 成交量 , 成交金额, 成交笔数 ,持仓量, 单位净值
base_fields = ["pre_close","open","high","low","close","volume","amt"]
stock_fields = "dealnum"
future_fields = ... |
# esse programa tem como intuito verificar uma ferramente para facilitarmos
# operações com listas
# Seja essa lista
lista = ['Azul', 'Corolla', 'PS5']
# Em vez de digitarmos
# cor = lista[0]
# modeloCarro = lista[1]
# modeloJogo = lista[2]
# Podemos fazer:
cor, modeloCarro, modeloJogo = lista
print(cor)
print(model... |
n = int(input(""))
problem_matrix = []
for i in range(0,n):
problem_line = list(int(x) for x in input("").split(" "))
problem_matrix.append(problem_line)
output = 0
for l in problem_matrix:
if l.count(1) >= 2:
output += 1
print(output) |
'''
Ordinary Differential Equation (ODE) Solvers.
Copyright (c) Maurice H.T. Ling <mauriceling@acm.org>
Date created: 20th December 2014
'''
def boundary_checker(y, boundary, type):
'''
Private function - called by ODE solvers to perform boundary checking
of variable values and reset them to specific va... |
def update_ema_variables(model, ema_model, alpha=0.999, global_step=-1):
# Use the true average until the exponential average is more correct
alpha = min(1 - 1 / (global_step + 1), alpha)
for ema_param, param in zip(ema_model.parameters(), model.parameters()):
ema_param.data.mul_(alpha).add_(1 - a... |
class Store(object):
"""Serves as a container for the data about a single web store"""
def __init__(self, data):
if not data:
raise Exception("None argument")
self.name = data[0]
self.url = data[1]
# Prices
self.keyword_container = data[2]
self.keywo... |
print('==== DESAFIO 013 ====')
salario = float(input('qual é seu salário? R$'))
#aumento = salario + (salario * 4.1/100)
aumento = salario + (salario * 15/100)
print(f'o seu salário atual é de R${salario:.2f}, com o aumento de 15% ganhará R${aumento:.2f}')
|
class Token:
def __init__(self, number):
if number == 0:
self.color = 'G'
self.number = 0
else:
if number >= 1 and number <= 10:
self.color = 'B' if number % 2 == 0 else 'R'
self.number = number
elif number >= 11 and num... |
def get_data():
userin = input("Please enter 1 for a list, 2 for a frequency table or 3 for a stem and leaf. >>> ")
if userin == "1":
return [float(x) for x in input("Enter simple list separated by spaces >>> ").split(" ") if x]
elif userin == "2":
print("You should enter each row of the fre... |
class QueueRelay:
def __init__(self, lumbda, GPD1, GPD2):
self.Q = 0
self.Qx = 0
self.Qy = 0
self.Qz = 0
self.GPD1 = GPD1
self.GPD2 = GPD2
self.tau = pow(10,-3) # time slot τ,1ms
self.kmob = pow(10,-27) #本地cpu核有效电容参数
self.Li = 73... |
# The following example shows the populations for some animals
# over the years.
df = pd.DataFrame({
'pig': [20, 18, 489, 675, 1776],
'horse': [4, 25, 281, 600, 1900]
}, index=[1990, 1997, 2003, 2009, 2014])
lines = df.plot.line()
|
# Copyright (c) 2011 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.
inline = """
<map>
<name>adc_mux</name>
<doc>valid mux values for DUT's two banks of INA219 off PCA9540
ADCs</doc>
<params none="0" b... |
ACCOUNT_SID = '' # put your Twilio Account sid here
AUTH_TOKEN = '' # put your Twilio Auth token here
TWILIO_ALLOTED_NUMBER = '' # put your Twilio alloted number here
# Header if necessary otherwise Govt. API thinks request is coming from bot , not from actual browser and block your request.
HEADER = {
'user-age... |
"""Load dependencies needed to compile the protobuf library as a 3rd-party consumer."""
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
PROTOBUF_MAVEN_ARTIFACTS = [
"com.google.code.findbugs:jsr305:3.0.2",
"com.google.code.gson:gson:2.8.6",
"com.google.errorprone:error_prone_annotatio... |
# -*- coding: utf-8 -*-
class Foo(object):
pass
class Bar(Foo):
pass
class Baz(Bar):
pass
class Qux(Foo):
pass
|
"""
A collection of similarity measures between
items
"""
class EdgeSimilarityMeasure(object):
def compute_similarity(self, a, b):
"""
Computes the similarity between two tags.
:param a: the starting item
:param b: the target item
"""
qid_a = int(a.id[1:])
... |
#!/usr/bin/env python
# coding: utf-8
# # *section 3: Strings*
#
# ### writer : Faranak Alikhah 1954128
# ### 14.Merge the Tools! :
#
# In[ ]:
def merge_the_tools(string, k):
# your code goes here
sequ=[]
counter=0
delta=len(string)//k
for i in range(delta):
sequ.append(string[counter... |
# OpenWeatherMap API Key
weather_api_key = "86e091696d04e4636555f97b1ff31889"
# Google API Key
g_key = "YOUR KEY HERE!"
|
def unzip(L):
return [l[0] for l in L],[l[1] for l in L]
def busqueda_binaria(L, x):
primero = 0
ultimo = len(L)
while primero+1 < ultimo:
medio = (ultimo + primero)//2
if x < L[medio]:
ultimo = medio
else:
primero = medio
return L[primero] == x
if _... |
#Just a quick experiment with default arguments in python.
##########################################################
def default(x = 5, y = 5):
print(x)
print(y)
# Should print 5\n5
default()
#Prints 0\n5
default(0)
# Prints 0\n0
default(0, 0)
|
# MIT License
#
# Copyright (c) 2016 Anders Steen Christensen
#
# 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, mo... |
VERSION="1.8.2"
HOST="irc.twitch.tv"
PORT=6667
PASS="oauth:vpjvbm9kpvglh1i3j16d73qrwaaen5"
NICK="tanook_lebot"
CHANNEL="tanook_leduc"
MBALL=["Seule Faiscla connait la vérité","Essaye plus tard","Essaye encore","Pas d'avis","C'est ton destin","Le sort en est jeté","Une chance sur deux","Repose ta question","D'aprè... |
class MyStack():
def __init__(self):
self.v_stack = []
self.m_stack = []
def push(self, number: int):
self.v_stack.append(number)
if len(self.m_stack) == 0:
self.m_stack.append(number)
else:
if self.m_stack[-1] > number:
self.m_sta... |
#InnerObject.py
'''
作者:Dragon
时间:2020年1月6日
描述:学习python中的内置对象
知识补充:变量的命名规则,单行和多行注释的使用
'''
|
# Faça um programa que peça uma nota, entre zero e dez. Mostre uma mensagem caso o valor
# seja inválido e continue pedindo até que o usuário informe um valor válido.
# Pede para o usuário digitar a nota.
nota = int(input('Digite o valor da nota: '))
# Enquanto a nota for menor que 0 ou maior que 10...
while (nota ... |
'''
https://leetcode.com/problems/combination-sum/
Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.
The same number may be chosen from can... |
# Entrada de dados
n1 = float(input('Digite a sua idade:'))
# Processamento
n2 = n1 * 12
# Saída de dados
print(f'Com {n1} anos você viveu {n2} meses')
|
# https://projecteuler.net/problem=7
# 10001st prime
# Problem 7
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
# What is the 10001st prime number?
def is_prime(n):
# if n in primes:
# return True
f = 2
while f < n:
if n % f == 0 and ... |
class Field:
name: str
value: str
inline: bool
def __init__(self, name, value, inline=False):
self.name = name
self.value = value
self.inline = inline
self._validate(name)
self._validate(value)
def to_dict(self):
return self.__dict__
def _valid... |
num=int(input())
def LoadingBar(value=0):
barLength=value//10; bar=""
for k in range(1,11):
if k<=barLength:
bar+="%"
else:
bar+="."
if barLength<10:
return f"{barLength*10}% [{bar}]\nStill loading..."
else:
return f"{barLength*10}% Comp... |
# Colecoes: set e dictionary
# SET
# utiliza {},
# nao contabiliza itens repetidos
# lista nao ordenada
# LISTA utiliza []
frutas = {"maca", "laranja", "abacaxi"}
frutas.add("pera")
print(frutas)
frutas.remove("maca")
print(frutas)
frutas.pop() #como a lista nao eh ordenada ele nao remove o ultimo, mas sim um valor... |
#
# PySNMP MIB module DKSF-253-6-X-A-X (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DKSF-253-6-X-A-X
# Produced by pysmi-0.3.4 at Mon Apr 29 18:32:23 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... |
ENTER = """
<Press Enter to continue>"""
def print_messages(*messages):
"""Print a bunch of messages."""
for m in messages:
raw_input(m + ENTER)
WELCOME = '''
*******************************************************************************
><><><><><><><><><><><><><><><>PICKETT<><><><><><><><><><><><><><><><... |
def gcd( a, b ):
if (b == 0):
return a
else:
return gcd(b, a % b)
n = int(input())
a = list(map(int, input().split()))
ans = a[0]
for i in range(1, n):
ans = gcd(ans, a[i])
print(ans)
|
n1 = int(input('Digite o ano que deseja saber: '))
n2 = (n1 % 4)
if n2 == 0:
n3 = float(n1 % 100)
if n3 == 0:
n4 = float(n1 % 400)
if n4 == 0:
print('Esse ano é Bissexto! Tem 366 dias.')
else:
print('Esse ano não é Bissexto! (Ele tem 365 dias).')
else:
... |
class CandidateSet(object):
def __init__(self):
self.candidates_history = {}
self.candidates = []
self.costs = 0
self.iteration = 0
self.verbose = True
def removeAlreadyExistingGridPoints(self, grid, intersections):
gs = grid.getStorage()
return [gp for... |
class Participant:
def __init__(self):
self.name = ""
self.isStillIn = True
self.hasCheckedIn = False
def setFromLine(self, lineString):
# format of participants.txt line:
# name hasCheckedIn isStillIn
# e.g.:
# foobarbazblarg True True
words = li... |
"""
* Assignment: Builtin Function Average
* Complexity: easy
* Lines of code: 12 lines
* Time: 13 min
English:
1. Separate header and data
2. Define dict `result: dict[str, list]`, keys are column names from header
3. For each row in data, add values to proper lists in `result`
4. Define function `mea... |
class DGNImportOptions(BaseImportOptions,IDisposable):
"""
The import options used to import DGN format files.
DGNImportOptions(option: DGNImportOptions)
DGNImportOptions()
"""
def Dispose(self):
""" Dispose(self: BaseImportOptions,A_0: bool) """
pass
def ReleaseUnmanagedResources(self,*args):... |
def datastructure():
name = input('What\'s your name? ')
password = input('Digit your password: ')
password_length = len(password)
hidden_password = '*' * password_length
print(
f'{name}, your password {hidden_password} is {password_length} letters long'
) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
File: factorial.py
Author: tdoly
Description: http://en.wikipedia.org/wiki/Factorial
'''
def factorial(num):
if num < 0:
raise "the input number is error"
elif num == 0:
return 1
else:
return reduce((lambda x, y: x*y), [i for i in ... |
def field_keys(field):
return [
'count',
field + '_delta_avg',
field + '_delta_avg_abs',
field + '_delta_std_dev',
]
def map_keys(field):
return [
field + '_delta_avg_ad',
field + '_delta_abs_avg_ad',
field + '_delta_std_dev_ad'
]
|
test = {
"name": "q1",
"points": 1,
"hidden": True,
"suites": [
{
"cases": [
{
"code": r"""
>>> sample_population(new_tests).num_rows
348
""",
"hidden": False,
"locked": False,
},
{
"code": r"""
>>> sample_population(Table().with_columns("", np.arange(523)... |
coins = [1, 2, 5, 10, 20, 50, 100, 200]
def coin_sums(wanted_pence):
return _coin_sums(wanted_pence, coins, {})
def _coin_sums(wanted_pence, available_coins, computation_cache):
if wanted_pence == 0:
return 1
if not available_coins:
return 0
if (wanted_pence, len(available_coins)) in... |
# coding=utf-8
"""
basepkg: tests module.
Meant for use with py.test.
Organize tests into files, each named xxx_test.py
Read more here: http://pytest.org/
Copyright 2014, Stefan Braun
Licensed under MIT
""" |
class Solution:
def sortString(self, s: str) -> str:
charFrequencyMap, result, length = [0] * 26, [], len(s)
for c in s:
charFrequencyMap[ord(c) - ord('a')] += 1
while len(result) != length:
for index in range(26):
if charFrequencyMap[index] > 0:
... |
class Error(Exception):
def __init__(self, message='', stderr=None):
super().__init__(message)
self.stderr = stderr
|
PERnc_testValuesAndGrads = [
[[-0.00400827, -0.00400437, -0.0], 0.011, 0.010007, 0.0131],
[[-0.00400827, -0.00400437, 0.0], 0.011, 0.010007, 0.1031],
[[-0.00400827, -0.00400437, 2.04542e-39], 0.011, 0.010007, 0.5031],
[[-0.00400827, -0.00400436, 1.53851e-9], 0.011, 0.010007, 1.0031],
[[-0.00137552, ... |
#Fábio C. Nunes 08/05/2020
velocidade = float(input('Digite a velocidade do veículo: '))
if velocidade > 80:
print('VOCÊ FOI MULTADO!!!')
valor = float(velocidade-80)*7
print('O valor da multa é de R${} reais'.format(valor))
else:
print('Você está dirigindo dentro do limite, PARABÉNS') |
def trans_string(a):
return int(a)
print(trans_string('6')) |
#
# Example file for variables
#
# Declare a variable and initialize it
f = "0"
# print(f)
# # re-declaring the variable works
#f = "abc"
# print(f)
# # ERROR: variables of different types cannot be combined
#print("String words" + str(564))
# Global vs. local variables in functions
def someFunction():
globa... |
"""Store networking information for all node files to share"""
CLIENT_RECV_PORT = 5005
CLIENT_SEND_PORT = 5006
# Buffer size for socket
BUFFER_SIZE = 1048576
# IP to be used for local system
LOCAL_IP = '127.0.0.1'
# Time (in sec) after which it's assumed that a communicating node has crashed
CRASH_ASSUMPTION_TIME =... |
_base_ = './qdtrack-frcnn_r50_fpn_12e_bdd100k.py'
# model settings
model = dict(
type='QuasiDenseMaskRCNN',
pretrained='torchvision://resnet50',
roi_head=dict(
type='QuasiDenseSegRoIHead',
mask_roi_extractor=dict(
type='SingleRoIExtractor',
roi_layer=dict(type='RoIAli... |
"""
You are given two integers n and k and two integer arrays speed and efficiency both of length n. There are n engineers numbered from 1 to n. speed[i] and efficiency[i]
represent the speed and efficiency of the ith engineer respectively.
Choose at most k different engineers out of the n engineers to form a team wit... |
# Stub unicodedata module. Covers only the Latin-1 range.
# Copyright (c) 2005 Nokia Corporation
#
# 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/LICEN... |
favicon_ico = "AAABAAEAICAAAAEAIACoEAAAFgAAACgAAAAgAAAAQAAAAAEAIAAAAAAAABAAAMMOAADDDgAAAAAAAAAAAAA3LBr/Py8e/0M0I/9CNSP/QzYl/0xEM/9gWEj/cGVW/3xxYP+Lfmz/kYRz/5SHdv+TiXb/k4p2/5KKd/+Rinf/k4h1/4+Ecf+LgW3/iX5r/4Z7af+CdmX/fnJf/3dpWP9uYVH/ZltJ/1dOO/9KQS//QDUj/z0wHv88Lx7/OS0a/zguHf9DMyH/QjYk/1hSQ/+CfnL/lJKG/5qVhf+XiXf/j39t/39xX... |
__author__ = 'michaelokuboyejo'
class JusibeException(Exception):
"""
There was an ambiguous exception that occurred while attempting to fetch
your machine's public IP address from the Jusibe service.
"""
pass
class ServiceException(JusibeException):
"""
The request failed because the Ju... |
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(N):
# write your code in Python 3.6
biny = bin(N)[2:]
# print(N)
# print(biny)
stringy = list(str(biny))
# print(stringy)
max_count = 0
temp_count = 0
flip_occured = False
... |
def revrot(s, n, res=""):
if not s or n < 1 or n > len(s):
return ""
while len(s) >= n:
group = s[:n]
if sum([int(d)**3 for d in group]) % 2 == 0:
res += group[::-1]
else:
res += group[1:] + group[0]
s = s[n:]
return res
|
class Users:
"""
A class to store user log in details.
"""
user_list = [] # Blank user list to store user details
def __init__(self, username, password):
"""
Defining the init method (constructor) that will be used to create new user instances
"""
self.username = us... |
# Print largest old number, taking 10 input numbers
# num_inputs = []
# n = 10
# largest = None
# while n > 0:
# try:
# num_inputs.append(int(input("Enter a number: ")))
# except:
# print("NaN")
# continue
# n -= 1
# for num in num_inputs:
# if largest == None or num > largest:
# if nu... |
# coding: utf-8
class Solution:
# @param {char[]} string: An array of Char
# @param {int} length: The true length of the string
# @return {int} The true length of new string
def replaceBlank(self, string, length):
# Write your code here
if string is None:
return 0
ne... |
#Fibonacijev niz
def fibonaci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonaci(n-1) + fibonaci(n-2)
rezultat = fibonaci(0)
print("fibonaci(0) = ", rezultat)
rezultat = fibonaci(1)
print("fibonaci(1) = ", rezultat)
# <- fibonaci(2-1) + fibonaci(2-2)
# <- 1 + 0
re... |
x = int(input())
a = []
for i in range(x):
a.append(int(input()))
for i in range(x):
m = a[i]//2
for j in range(2,m+1):
if(a[i]%j==0):
print("not prime")
break
else:
print("prime")
|
def dfs(L, crt, remain):
if remain == 0:
L.append(crt[:])
else:
for i in range(1, 4):
crt.append(i)
if(remain - i >= 0):
dfs(L, crt, remain - i)
crt.pop()
N,K = map(int ,input().split())
L = []
crt = []
dfs(L, crt, N)
if K > len(L):
print... |
"""
Python example of
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort_with_shifting_bounds
based on
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort#Python
"""
def cocktailshiftingbounds(A):
beginIdx = 0
endIdx = len(A) - 1
while beginIdx <= endIdx:
n... |
# @jxvtrl #
arq = open('B:\FACULDADE\Programacao\G2\P2\Q1\paciente.txt','r')
lista = {}
for contaPacientesMedicos in arq:
pos = contaPacientesMedicos[0:-1].split(',')
c,e = pos[0],pos[2]
controle = 0
if e not in lista:
lista[e] = []
if c not in lista[e]:
lista[e].append(c)
... |
time = raw_input().strip()
hh = time[0:2]
period = time[-2:]
if period=='AM':
if hh=='12':
newtime='00'+time[2:len(time)-2]
else:
newtime=time[0:len(time)-2]
elif period=='PM':
if hh=='12':
newtime=time[0:len(time)-2]
else:
newtime=str(int(hh) + 12)+ time[2:len(time)-2]
... |
# Author: @Iresharma
# https://leetcode.com/problems/maximum-subarray/
"""
Runtime: 60 ms, faster than 90.50% of Python3 online submissions for Maximum Subarray.
Memory Usage: 15 MB, less than 36.41% of Python3 online submissions for Maximum Subarray.
"""
class Solution:
def maxSubArray(self, nums: List[int]) -> ... |
# -*- coding: utf-8 -*-
class Solution:
def __str__(self):
return "SpeedCamera Codility Challenge"
|
"""
filename: minutes_response.py
description: Response messages for members module.
created by: Omar De La Hoz (oed7416@rit.edu)
created on: 10/11/17
"""
class Response():
# General Responses
InvalidData = {"error": "Input data is not correct."}
PermError = {"error": "User doesn't have permissions to com... |
class MockRDD:
def __init__(self, df):
self.df = df
def __iter__(self):
for index, row in self.df.iterrows():
yield row
class MockAccumulator:
def __init__(self):
self.cnt = 0
def add(self, x):
self.cnt += x |
# Copyright (c) 2015, the Dartino project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE.md file.
{
'targets': [
{
'target_name': 'dartino-vm',
'type': 'none',
'dependencies':... |
class EngineBase:
def begin(self):
return self.engine.begin()
|
def get_deepest(courses, num=20, faculty='', existing=False):
if faculty == '':
choice = [x for x in courses.values()]
else:
choice = [x for x in courses.values() if x.faculty == faculty]
if existing:
choice = [x for x in choice if x.is_given == True]
deepest = sorted(choice... |
class Mammals : #super class
def walk(self):
print("!!!!!!!!!!Can WAlk!!!!!!!!!!!!!!!")
class Dog (Mammals) : #sub class of Mammals
def Bark(self):
print("!!!!!!!!!!!!Can Bark!!!!!!!!!!!!!!")
def walk(self):
print("Dog can Walk")
class Cat (Mammals) : #sub class of Mammals
... |
#!python
def linear_search(array, item):
"""return the first index of item in array or None if item is not found"""
# implement linear_search_iterative and linear_search_recursive below, then
# change this to call your implementation to verify it passes all tests
return linear_search_recursive(array, ... |
def media(valores):
return sum(valores) / len(valores)
def gerar_registro(linha):
registro = linha.split(';')
return {"nome": registro[0],
"cidade": registro[1],
"idade": int(registro[2]),
"renda": float(registro[3])}
if __name__ == '__main__':
assert med... |
#https://www.hackerrank.com/challenges/caesar-cipher-1/problem
n_s=input()
s=input()
n=int(input())
s1=''
for i in s:
if 65<=ord(i)<=90:
s1+=chr((ord(i)-65)+n%26+65)
elif 97<=ord(i)<=122:
s1+=chr((ord(i)-97+n)%26+97)
else:
s1+=i
print(s1) |
#se define una lista
lista = [25, 12, 15, 23, 24, 39, 13, 31, 19, 16]
#se ordenan los elementos de menor a mayor
lista.sort()
#definimos una funcion que calcule la media de los elementos de la lista
#es el numero medio de la lista de datos recorridos
def mediana(lista):
mediana_calc = (lista[4] +lista[5])/2
return ... |
class Solution:
def maxDepth(self, s: str) -> int:
"""String.
Running time: O(n) where n == len(s).
"""
res = 0
n = 0
for i in s:
if i == '(':
n += 1
res = max(res, n)
elif i == ')':
n -= 1
... |
#
# PySNMP MIB module CYCLADES-ACS-PM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CYCLADES-ACS-PM-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:34:21 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.