content stringlengths 7 1.05M |
|---|
# MQTT certificates
CA_CERT = "./../keys/ca/ca.crt"
CLIENT_CERT = "./../keys/client/client.crt"
CLIENT_KEY = "./../keys/client/client.key"
TLS_VERSION = 2
# MQTT broker options
TOPIC_NAME = "sensors/Temp"
HOSTNAME = "mqtt.sandyuraz.com"
PORT = 8883
# MQTT user options
CLIENT_ID = "sandissa-secret-me"
USERNAME = "kit... |
class AccessStruct(object):
_size_to_width = [None, 0, 1, None, 2]
def __init__(self, mem, struct_def, struct_addr):
self.mem = mem
self.struct = struct_def(mem, struct_addr)
self.trace_mgr = getattr(self.mem, "trace_mgr", None)
def w_s(self, name, val):
struct, field = se... |
#crie um programa que leia varios numeros e coloque em uma lista.
#Depois disso crie 2 listas extras que vao conter apenas os valores pares e eu outra lista os valores impares
#Ao final mostre o conteudo das 3 listas geradas
#minha resposta
lista = []
par = []
impar = []
while True:
lista.append(int(input('Digite ... |
x,y = input().split()
a = int(x)
b = int(y)
if a < b and (b-a) == 1:
print("Dr. Chaz will have " + str(b-a) + " piece of chicken left over!")
elif a < b:
print("Dr. Chaz will have " + str(b - a) + " pieces of chicken left over!")
elif a > b and (a-b) == 1:
print("Dr. Chaz needs " + str(a - b) + " ... |
n=int(input())
sh=5
li=0
cum=0
for i in range(n):
li = sh // 2
sh=(li*3)
cum+=li
print(cum) |
def damage(skill1,skill2):
damage1 = skill1 * 3
damage2 = skill2 * 2 + 10
return damage1,damage2
damages = damage(3,6)
print(damages[0],damages[1])
print(type(damages)) # 元组 tuple
skill1_damage,skill2_damage = damage(3,6)
print(skill1_damage,skill2_damage)
|
n=1
s=0
while(n<50):
cn=n
mdx=0
mposfl=0
pos=0
nod=0
while(cn>0):
ld=cn%10
nod=nod+1
if(ld>mdx):
mdx=ld
mposfl=pos
cn=cn/10
pos=pos+1
apos=nod-mposfl
i=0
sr=0
while(n>0):
if(i==apos):
contin... |
class Solution:
def romanToInt(self, s: str) -> int:
num = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
val, pre = 0, 0
for key in s:
n = num[key] if key in num else 0
val += -pre if n > pre else pre
pre = n
val += pre
... |
'''
给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。
返回删除后的链表的头节点。
注意:此题对比原题有改动
示例 1:
输入: head = [4,5,1,9], val = 5
输出: [4,1,9]
解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.
示例 2:
输入: head = [4,5,1,9], val = 1
输出: [4,5,9]
解释: 给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9.
说明:
- 题目保证链表中节点的值互不相同
- 若使用 C 或 C++ 语言,你不需要 f... |
lb = {
"loadBalancer": {
"name": "mani-test-lb",
"port": 80,
"protocol": "HTTP",
"virtualIps": [
{
"type": "PUBLIC"
}
]
}
}
nodes = {
"nodes": [
{
... |
def includeme(config):
config.add_static_view('js', 'static/js', cache_max_age=3600)
config.add_static_view('css', 'static/css', cache_max_age=3600)
config.add_static_view('static', 'static', cache_max_age=3600)
config.add_static_view('dz', 'static/dropzone', cache_max_age=3600)
config.add_route('ad... |
def last_minute_enhancements(nodes):
count = 0
current_node = 0
for node in nodes:
if node > current_node:
count += 1
current_node = node
elif node == current_node:
count += 1
current_node = node + 1
return count
if __name__ == "__main__"... |
# Opencast server address and credentials for api user
OPENCAST_URL = 'OPENCAST_URL'
OPENCAST_USER = 'OPENCAST_API_USER'
OPENCAST_PASSWD = 'OPENCAST_PASSWORD_USER'
# Timezone for the messages and from the XML file
MESSAGES_TIMEZONE = 'Europe/Berlin'
# Capture agent Klips dictionary
#
# Here you have to put the dic... |
#
# PySNMP MIB module NHRP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NHRP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:51:40 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:1... |
env_name = 'BreakoutDeterministic-v4'
input_shape = [84, 84, 4]
output_size = 4
'''
env_name = 'SeaquestDeterministic-v4'
input_shape = [84, 84, 4]
output_size = 18
'''
'''
env_name = 'PongDeterministic-v4
input_shape = [84, 84, 4]
output_size = 6
''' |
""" Geometry settings """
"""Stack Settings"""
# number of cells in the stack
cell_number = 1
""""Cell Geometry """
# length of the cell, a side of the active area [m]
cell_length = 0.5
# height of the cell, b side of the active area [m]
cell_width = 0.1
# thickness of the bipolar plate [m]
cathode_bipolar_plate_thic... |
def metade(valor=0, formato=False):
res = valor/2
return res if formato is False else moeda(res)
def dobro(valor=0, formato=False):
res = valor*2
return res if formato is False else moeda(res)
def aumentar(valor=0, porcentagem=0, formato=False):
res = valor+(valor * porcentagem/100)
return r... |
# Leetcode 200. Number of Islands
#
# Link: https://leetcode.com/problems/number-of-islands/
# Difficulty: Medium
# Solution using BFS and visited set.
# Complexity:
# O(M*N) time | where M and N represent the rows and cols of the input matrix
# O(M*N) space | where M and N represent the rows and cols of the input... |
BUNDLES = [
#! if api:
'flask_unchained.bundles.api',
#! endif
#! if mail:
'flask_unchained.bundles.mail',
#! endif
#! if celery:
'flask_unchained.bundles.celery', # move before mail to send emails synchronously
#! endif
#! if oauth:
'flask_unchained.bundles.oauth',
#! e... |
class RequestFailedError(Exception):
pass
class DOIFormatIncorrect(Exception):
pass
|
# By submitting this assignment, I agree to the following:
# “Aggies do not lie, cheat, or steal, or tolerate those who do”
# “I have not given or received any unauthorized aid on this assignment”
#
# Name: Jonathan Samuel
# Section: 510
# Assignment: Quiz2
# Date: 9 20 2018
# Get Time from User Input and c... |
N, M, P, Q = map(int, input().split())
result = (N // (M * (12 + Q))) * 12
N %= M * (12 + Q)
if N <= M * (P - 1):
result += (N + (M - 1)) // M
else:
result += P - 1
N -= M * (P - 1)
if N <= 2 * M * Q:
result += (N + (2 * M - 1)) // (2 * M)
else:
result += Q
N -= 2 * M * Q
... |
# This is a line comment
'''
This is a block comment
'''
def main():
print("Hello world!\n");
main()
|
# global progViewWidth
ProgEntryFieldW=10
ProgButX=160
progViewWidth=60
stopProgButX=200
comportlabelx=270
comPortEntryFieldX=390
comPortEntryFieldw=12
comPortButx=495
calibration_entryjoinx=520
calibration_entrydhx=745
calibration_joinx=600
calibration_alphax=800
calibrate_buttoncol2x=210
tab1_instructionbuttonw=16
... |
#########################################################################
# #
# C R A N F I E L D U N I V E R S I T Y #
# 2 0 1 9 / 2 0 2 0 #
# ... |
N_FEATURES = 5
def filter_on_geolocation(df_in, ne_lat, ne_lng, sw_lat, sw_lng):
return df_in.loc[lambda df: (df["lat"] >= sw_lat) & (df["lat"] < ne_lat)].loc[
lambda df: (df["lng"] >= sw_lng) & (df["lng"] < ne_lng)
]
def select_top_features(place_id, df_in, top_x=N_FEATURES):
"""
Selects to... |
# Strings with apostrophes and new lines
# If you want to include apostrophes in your string,
# it's easiest to wrap it in double quotes.
niceday = "It's a nice day!"
print(niceday)
|
#encoding:utf-8
subreddit = 'chessmemes'
t_channel = '@chessmemesenglish'
def send_post(submission, r2t):
return r2t.send_simple(submission)
|
# On the first line, you will be given a positive number, which will serve as a divisor.
# On the second line, you will receive a positive number that will be the boundary.
# You should find the largest integer N, that is:
# • divisible by the given divisor
# • less than or equal to the given bound
# • greater th... |
# Faça um programa que leia um número Inteiro qualquer e mostre na tela a sua tabuada.
t = int(input('Digite um número para visualizar a tabuada: '))
cont = 1
while cont <= 10:
print(f'{t} X {cont} = {t*cont}')
cont += 1
|
def decodeRules(string):
rules = []
# Remove comments
while string.find('%') != -1:
subStringBeforeComment = string[:string.find('%')]
subStringAfterComment = string[string.find('%'):]
if subStringAfterComment.find('\n') != -1:
string = subStringBeforeComment + subString... |
lists = ['dwq', 'bql', 'xx', 'txo']
inquier = {'bql': 'java', 'xx': 'xx', 'dwq': 'java'}
for ren in lists :
for name in inquier.keys():
if ren == str(name):
print ("thank you " + ren)
break
else:
print ("you hava a inquire " + ren)
break
#注意循环的中断的位置,怪... |
APPLICATION_ID = "vvMc0yrmqU1kbU2nOieYTQGV0QzzfVQg4kHhQWWL"
REST_API_KEY = "waZK2MtE4TMszpU0mYSbkB9VmgLdLxfYf8XCuN7D"
MASTER_KEY = "YPyRj37OFlUjHmmpE8YY3pfbZs7FqnBngxX4tezk"
TWILIO_SID = "AC5e947e28bfef48a9859c33fec7278ee8"
TWILIO_AUTH_TOKEN = "02c707399042a867303928beb261e990" |
#Assume hot dogs come in packages of 10, and hot dog buns come in packages of 8.
hotdogs_perpack = 10
hotdogs_bunsperpack = 8
#program should ask the user for the number of people attending the cookout and the number of hot dogs each person will be given.
ppl_attending = int(input('Enter the number of people atte... |
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'solo-tests.db',
}
}
INSTALLED_APPS = (
'solo',
'solo.tests',
)
SECRET_KEY = 'any-key'
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': '127.0.... |
#Author : 5hifaT
#Github : https://github.com/jspw
#Gists : https://gist.github.com/jspw
#linkedin : https://www.linkedin.com/in/mehedi-hasan-shifat-2b10a4172/
#Stackoverflow : https://stackoverflow.com/story/jspw
#Dev community : https://dev.to/mhshifat
def binary_search(ar, value):
s... |
###exercicio 76
produtos = ('lapis', 1.5, 'borracha', 2.00, 'caderno', 15.00, 'livro', 50.00, 'mochila', 75.00)
print ('='*60)
print ('{:^60}'.format('Lista de produtos'))
print ('='*60)
for c in range (0, len(produtos), 2):
print ('{:<50}R$ {:>7}'.format(produtos[c], produtos[c+1]))
print ('-'*60) |
# Programacion orientada a objetos (POO o OOP)
# Definir una clase (molde para crear mas objetos de ese tipo)
# (Coche) con caracteristicas similares
class Coche:
# Atributos o propiedades (variables)
# caracteristicas del coche
color = "Rojo"
marca = "Ferrari"
modelo = "Aventador"
velocidad... |
class Solution:
def calculate(self, s: str) -> int:
stacks = [[0, 1]]
val = ""
sign = 1
for i, ch in enumerate(s):
if ch == ' ':
continue
if ch == '(':
stacks[-1][-1] = sign
stacks.append([0, 1])
... |
class Solution(object):
def frequencySort(self, s):
"""
:type s: str
:rtype: str
"""
freq = dict()
for char in s:
if char in freq:
freq[char] += 1
else:
freq[char] = 1
... |
# -*- coding: utf-8 -*-
urls = (
"/", "Home",
)
|
#!/usr/bin/env python3
BUS = 'http://m.bus.go.kr/mBus/bus/'
SUBWAY = 'http://m.bus.go.kr/mBus/subway/'
PATH = 'http://m.bus.go.kr/mBus/path/'
all_bus_routes = BUS + 'getBusRouteList.bms'
bus_route_search = all_bus_routes + '?strSrch={0}'
bus_route_by_id = BUS + 'getRouteInfo.bms?busRouteId={0}'
all_low_bus_routes = B... |
def config_record_on_account(request,account_id):
pass
def config_record_on_channel(request, channel_id):
pass
|
def gen_primes():
current_number = 2
primes = []
while True:
is_prime = True
for prime in primes:
if prime*prime > current_number: ## This is saying it's a prime if prime * prime > current_testing_number
# print("Caught here")
break # I'd love to s... |
# coding=utf-8
"""
Filename: introduction
Author: Tanyee
Date: 2020/3/25
Original: https://docs.python.org/3.7/tutorial/index.html
Description: A brief introduction to the main content of this getting started tutorial.
"""
"""
Python is an easy to learn, powerful programming language.
It has efficient ... |
def isPrime(x):
for i in range(2,x):
if x%i == 0:
return False
return True
def findPrime(beginning, finish):
for j in range(beginning,finish):
if isPrime(j):
return j
def encrypt():
print("Provide two integers")
x = int(input())
y = int(input())
prime1 = findPrime(x,y)
print("Provi... |
'''import math
n = float(input('Digite um nº: '))
print('O valor digitado foi {}, tendo sua parte inteira {}, e decimal {:.3f}'.format(n,math.trunc(n), n - math.trunc(n)))'''
'''from math import trunc
n = float(input('Digite um nº: '))
print('O valor digitado foi {}, tendo sua parte inteira {}, e decimal {:.3f}'.for... |
# Gegeven zijn twee lijsten: lijst1 en lijst2
# Zoek alle elementen die beide lijsten gemeenschappelijk hebben
# Stop deze elementen in een nieuwe lijst
# Print de lijst met gemeenschappelijke elementen
lijst1 = [1, 45, 65, 24, 87, 45, 23, 24, 56]
lijst2 = [10, 76, 34, 1, 56, 22, 33, 77, 1]
|
class iterator:
def __init__(self,data):
self.data=data
self.index=-2
def __iter__(self):
return self
def __next__(self):
if self.index>=len(self.data):
raise StopIteration
self.index+=2
return self.data[self.index]
liczby=iterator([0,1,... |
vezes = int(input('quantos números vc quer digitar?: '))
todos_os_numeros = []
pares = []
impares = []
for c in range(vezes):
valor = int(input('digite {}° número: '.format(c + 1)))
todos_os_numeros.append(valor)
print(f'valor é {valor}')
if valor % 2 == 0:
pares.append(valor)
el... |
class RemovedInWagtail21Warning(DeprecationWarning):
pass
removed_in_next_version_warning = RemovedInWagtail21Warning
class RemovedInWagtail22Warning(PendingDeprecationWarning):
pass
|
class ListNode(object):
"""
Definition fro singly-linked list.
"""
def __init__(self, val=0, next=None) -> None:
self.val = val
self.next = next |
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def postorder(self, root: 'Node') -> List[int]:
if root == None:
return []
res = []
for index in range(len(root.ch... |
arr = list(map(int, input().split()))
n = int(input())
for i in range(len(arr)):
one = arr[i]
for j in range(i+1,len(arr)):
two = arr[j]
s = one + two
if s == n:
print(f'{one} {two}') |
"""
# 以下方法都可以从网页中提取出'你好,蜘蛛侠!'这段文字
find_element_by_tag_name:通过元素的名称选择
# 如<h1>你好,蜘蛛侠!</h1>
# 可以使用find_element_by_tag_name('h1')
find_element_by_class_name:通过元素的class属性选择
# 如<h1 class="title">你好,蜘蛛侠!</h1>
# 可以使用find_element_by_class_name('title')
find_element_by_id:通过元素的id选择
# 如<h1 id="title">你好,蜘蛛侠!</h1>
# 可以使用find_el... |
"""
Error Message for REST API
"""
CUSTOM_VISION_ACCESS_ERROR = \
('Training key or Endpoint is invalid. Please change the settings')
CUSTOM_VISION_MISSING_FIELD = \
('Either Namespace or Key is missing or incorrect. Please check again')
|
def format(string):
''' Formats the docstring. '''
# reStructuredText formatting?
# Remove all \n and replace all spaces with a single space
string = ' '.join(list(filter(None, string.replace('\n', ' ').split(' '))))
return string
class DocString:
def __init__(self, strin... |
class Solution:
def longestCommonPrefix(self, strs):
if strs == []:
return ""
ans = ""
for i, ch in enumerate(strs[0]): # iterate over the characters of first word
for j, s in enumerate(strs): # iterate over the list of words
if i >= len(strs[j]) or ch != s[i]: # IF the first word is longer
re... |
# ---------------- User Configuration Settings for speed-cam.py ---------------------------------
# Ver 8.4 speed-cam.py webcam720 Stream Variable Configuration Settings
#######################################
# speed-cam.py plugin settings
#######################################
# Calibration Settings
# =... |
def busca(lista, elemento):
for i in range(len(lista)):
if lista[i] == elemento:
return i
return False
o = busca([0,7,8,5,10], 10)
print(o) |
gem3 = (
(79, ("ING")),
)
gem2 = (
(5, ("TH")),
(41, ("EO")),
(79, ("NG")),
(83, ("OE")),
(101, ("AE")),
(107, ("IA", "IO")),
(109, ("EA")),
)
gem = (
(2, ("F")),
(3, ("U", "V")),
(7, ("O")),
(11, ("R")),
(13, ("C", "K")),
(17, ("G")),
(19, ("W")),
(23, ("H")),
(29, ("N")),
(... |
def part_1(data):
blah = {'n': (0, 1), 'ne': (1, 0), 'se': (1, -1),
's': (0, -1), 'sw': (-1, 0), 'nw': (-1, 1)}
x, y = 0, 0
for step in data.split(","):
x, y = x + blah[step][0], y + blah[step][1]
distance = (abs(x) + abs(y) + abs(-x-y)) // 2
return distance
def part_2(... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 18 12:00:00 2020
@author: divyanshvinayak
"""
for _ in range(int(input())):
N, K = map(int, input().split())
A = list(map(int, input().split()))
print(sum(A) % K) |
'''Escreva um progrma que leia um n inteiro qualquer e mostra na tela os n primeiros elementos de uma sequencia de Fibonacci.
Ex: 0 1 1 2 3 5 8'''
n = int(input('Informe um número: '))
t1 = 0
t2 = 1
print('{} > {}'.format(t1, t2), end=' ')
cont = 3
while cont <= n:
t3 = t1 + t2
print(' > {}'.format(t3), end='... |
# -*- coding: utf-8 -*-
"""
Global tables and re-usable fields
"""
# =============================================================================
# Representations for Auth Users & Groups
def shn_user_represent(id):
table = db.auth_user
user = db(table.id == id).select(table.email, limitby=(0, 1), cache=(ca... |
#!/bin/zsh
class Person:
def __init__(self, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc() |
class SmRestartEnum(basestring):
"""
always|never|default
Possible values:
<ul>
<li> "always" ,
<li> "never" ,
<li> "default"
</ul>
"""
@staticmethod
def get_api_name():
return "sm-restart-enum"
|
def TrimmedMean(UpCoverage):
nonzero_count = 0
for i in range(1,50):
if (UpCoverage[-i]>0):
nonzero_count += 1
total = 0
count=0
for cov in UpCoverage:
if(cov>0):
total += cov
count += 1
trimMean = 0
if nonzero_count > 0 and count >20:
#if count >20:
trimMean = total/count;
return trimMean
|
N = int(input())
gradeReal = list(map(int, input().split()))
M = max(gradeReal)
gradeNew = 0
for i in gradeReal:
gradeNew += (i / M * 100)
print(gradeNew / N) |
# -*- coding: utf-8 -*-
"""Entry point for the Nessie Airflow provider.
Contains important descriptions for registering to Airflow
"""
__version__ = "0.1.2"
def get_provider_info() -> dict:
"""Hook for Airflow."""
return {
"package-name": "airflow-provider-nessie",
"name": "Nessie Airflow Pr... |
var = 's'
while var != 'n':
temperatura = float(input('Informe a temperatura em °C: '))
far = 9/5*temperatura+32
print('A temperatura de {:.1f}°C corresponde a {:.1f}°F'.format(temperatura, far))
var = input('Deseja continunar (s/n)? ')
|
universalSet={23,32,12,45,56,67,7,89,80,96}
subSetList=[{23,32,12,45},{32,12,45,56},{56,67,7,89},{80,96},{12,45,56,67,7,89},{7,89,80,96},{89,80,96}]
def getMinSubSetList(universalSet,subSetList):
SetDs=[[i,len(i)] for i in subSetList]
tempSet=set()
setList=[]
while(len(universalSet)!=0):
print("... |
class RMCError(Exception):
def __init__(self, message):
Exception.__init__(self, message)
self.__line_number=None
def set_line_number(self, new_line_number):
self.__line_number=new_line_number
def get_line_number(self):
return self.__line_number
... |
TO_BIN = {'0': '0000', '1': '0001', '2': '0010', '3': '0011',
'4': '0100', '5': '0101', '6': '0110', '7': '0111',
'8': '1000', '9': '1001', 'a': '1010', 'b': '1011',
'c': '1100', 'd': '1101', 'e': '1110', 'f': '1111'}
TO_HEX = {v: k for k, v in TO_BIN.iteritems()}
def hex_to_bin(hex_stri... |
def table(positionsList):
print("\n\t Tic-Tac-Toe")
print("\t~~~~~~~~~~~~~~~~~")
print("\t|| {} || {} || {} ||".format(positionsList[0], positionsList[1], positionsList[2]))
print("\t|| {} || {} || {} ||".format(positionsList[3], positionsList[4], positionsList[5]))
print("\t|| {} || {} || {} ||".... |
def Spline(*points):
assert len(points) >= 2
return _SplineEval(points, _SplineNormal(points))
def Spline1(points, s0, sn):
assert len(points) >= 2
points = tuple(points)
s0 = float(s0)
sn = float(sn)
return _SplineEval(points, _SplineFirstDeriv(points, s0, sn))
def _IPolyMult(prod, poly):
if not pr... |
def find_missing_number(c):
b = max(c)
d = min(c + [0]) if min(c) == 1 else min(c)
v = set(range(d, b)) - set(c)
return list(v)[0] if v != set() else None
print(find_missing_number([1, 3, 2, 4]))
print(find_missing_number([0, 2, 3, 4, 5]))
print(find_missing_number([9, 7, 5, 8]))
|
load("@bazel_skylib//lib:dicts.bzl", "dicts")
# load("//ocaml:providers.bzl", "CcDepsProvider")
load("//ocaml/_functions:module_naming.bzl", "file_to_lib_name")
## see: https://github.com/bazelbuild/bazel/blob/master/src/main/starlark/builtins_bzl/common/cc/cc_import.bzl
## does this still apply?
# "Library outputs ... |
'''
Python中Exception的处理
例子:输入一个数字并进行除法运算
异常1:不是数字
异常2:不能除0
其他异常:结束
finally:必须执行
'''
while True:
try:
number =int(input("what's your fav number hoss?\n"))
print(10/number)
break
except ValueError:
print("Make sure and enter a number.")
except ZeroDivisionError:
print(... |
'''
Created on Jan 22, 2013
@author: sesuskic
'''
__all__ = ["ch_flt"]
def ch_flt(filter_k):
chflt_coe_list = {
1 : [-3, -4, 1, 15, 30, 27, -4, -55, -87, -49, 81, 271, 442, 511], # 305k BW (decim-8*3) original PRO2
# 1: [13 17 -8 -15 14 20 -27 -23... |
N = int(input())
A = [0] + [int(a) for a in input().split()]
B = [0] + [int(a) for a in input().split()]
C = [0] + [int(a) for a in input().split()]
previous = -1
satisfaction = 0
for a in A[1:]:
satisfaction += B[a]
if previous == a-1:
satisfaction += C[a-1]
previous = a
print(satisfaction)
|
#!/usr/bin/python
# Filename: ex_for_before.py
print('Hello')
print('Hello')
print('Hello')
print('Hello')
print('Hello')
|
class InvalidDataDirectory(Exception):
"""
Error raised when the chosen intput directory for the dataset is not valid.
"""
|
#Este programa tem a função de mostrar a mensagem "alo mundo na tela".
"""
Assim se faz um comentário em várias linhas.
Pode-se usar aspas simples ou duplas!
"""
print("Alô mundo na tela");
|
"""
0340. Longest Substring with At Most K Distinct Characters
Medium
Given a string s and an integer k, return the length of the longest substring of s that contains at most k distinct characters.
Example 1:
Input: s = "eceba", k = 2
Output: 3
Explanation: The substring is "ece" with length 3.
Example 2:
Input... |
print('-' * 20)
print(' LOJA SUPER BARATÃO')
print('-' * 20)
totpreço = prod1000 = menor = cont = 0
barato = ''
while True:
produto = str(input('Nome do produto: '))
preço = float(input('Preço: R$ '))
cont += 1
totpreço += preço
if preço > 1000:
prod1000 += 1
if cont == 1 or preço < meno... |
# Exercício Python 093:
# Crie um programa que gerencie o aproveitamento de um jogador de futebol.
# O programa vai ler o nome do jogador e quantas partidas ele jogou.
# Depois vai ler a quantidade de gols feitos em cada partida.
# No final, tudo isso será guardado em um dicionário, incluindo o total de gols feitos dur... |
"""from kivy.app import App
from kivy.uix.scrollview import ScrollView
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
class Tarefas(ScrollView):
def __init__(self, tarefas, **kwargs):
super().__init__(**kwargs)
for tarefa in tarefas:
self.ids.box.add_wid... |
class Solution:
def smallestRange(self, nums: List[List[int]]) -> List[int]:
lo, hi = -100000, 100000
pq = [(lst[0], i, 1) for i, lst in enumerate(nums)]
heapq.heapify(pq)
right = max(lst[0] for lst in nums)
while len(pq) == len(nums):
mn, idx, nxt = heapq.heappop... |
def snail(arr):
""" Inspired by a solution on Codewars by MMMAAANNN """
matrix = list(arr)
result = []
while matrix:
result.extend(matrix.pop(0))
matrix = zip(*matrix)
matrix.reverse()
return result
|
# Copyright (C) 2021 Anthony Harrison
# SPDX-License-Identifier: MIT
VERSION: str = "0.1"
|
'''
File: structures.py
Description: Defines the structures used by socket handler
Date: 26/09/2017
Author: Saurabh Badhwar <sbadhwar@redhat.com>
'''
class ClientList(object):
"""ClientList structure. Used for holding the connected clients list
The general structure looks like:
client_list: {'topic': [cli... |
# coding: utf-8
"""
Created on 30.07.2018
:author: Polianok Bogdan
"""
class Item:
"""
Class represented Item object in skyskanner website response
"""
def __init__(self, jsonItem):
self.agent_id = jsonItem['agent_id']
self.url = jsonItem['url']
self.transfer_protection = js... |
NEGATIVE_CONSTRUCTS = set([
"ain't",
"can't",
"cannot"
"don't"
"isn't"
"mustn't",
"needn't",
"neither",
"never",
"no",
"nobody",
"none",
"nothing",
"nowhere"
"shan't",
"shouldn't",
"wasn't"
"weren't",
"won't"
])
URLS = r'(https?:\/\/(?:www\.|(... |
class Configuration:
port = 5672
security_mechanisms = 'PLAIN'
version_major = 0
version_minor = 9
amqp_version = (0, 0, 9, 1)
secure_response = ''
client_properties = {'client': 'amqpsfw:0.1'}
server_properties = {'server': 'amqpsfw:0.1'}
secure_challenge = 'tratata'
|
#Faça um programa que leia nome e peso de várias pessoas, guardando tudo em uma lista.
# No final, mostre:
#A) Quantas pessoas foram cadastradas.
#B) Uma listagem com as pessoas mais pesadas.
#C) Uma listagem com as pessoas mais leves.
lista = []
pessoas = []
maior = menor = 0
opc = ''
while True:
pessoas.append(s... |
class TrieNode:
def __init__(self):
self.flag = False
self.children = {}
class Trie(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def insert(self, word):
"""
Inserts a word into the trie.... |
class Solution(object):
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
pascal_triangle = [None] * 2
for i in range(rowIndex + 1):
row = [0] * (i + 1)
row[0] = 1
row[-1] = 1
for j in range(1, ... |
# -*- coding: utf-8 -*-
class MissingSender(Exception):
pass
class WrongSenderSecret(Exception):
pass
class NotAllowed(Exception):
pass
class MissingProject(Exception):
pass
class MissingAction(Exception):
pass
|
# O(j +d) Time and space
def topologicalSort(jobs, deps):
# We will use a class to define the graph:
jobGraph = createJobGraph(jobs, deps)
# Helper function:
return getOrderedJobs(jobGraph)
def getOrderedJobs(jobGraph):
orderedJobs = []
# In this case, we need to take the nodes with NO prereqs
nodesWithNoP... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.