content stringlengths 7 1.05M |
|---|
"""
The RequestSupplement object that will get injected on marketplace requests
"""
class RequestSupplement(object):
# adding some duplicate fields keyed to more consistent python naming and
# more understandable naming in some cases. You're free to use whichever
# you want.
EXTRAS = {
'port... |
# import matplotlib.pyplot as plt
# Menge an Werten
zahlen = "1203456708948673516874354531568764645"
# Initialisieren der Histogramm Variable
histogramm = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for index in range(len(zahlen)):
histogramm[int(zahlen[index])] += 1
# plt.hist(histogramm, bins = 9)
# plt.show()
for i in r... |
#!/usr/bin/env pytho
codigo = {
'A': '.-', 'B': '-...', 'C': '-.-.',
'D': '-..', 'E': '.', 'F': '..-.',
'G': '--.', 'H': '....', 'I': '..',
'J': '.---', 'K': '-.-', 'L': '.-..',
'M': '--', 'N': '-.', 'O': '---',
'P': '.--.', 'Q': '--.-', 'R': '.-.',
... |
class Cloth:
def __init__(self, name, shop_url, available, brand_logo, price, img_url):
self.name = name
self.shop_url = shop_url
self.available = available
self.brand_logo = brand_logo
self.price = price
self.img_url = img_url
def __str__(self):
print('N... |
#!/usr/bin/env python3
"""
The marketing team is spending way too much time typing in hashtags.
Let's help them with our own Hashtag Generator!
Here's the deal:
It must start with a hashtag (#).
All words must have their first letter capitalized.
If the final result is longer than 140 chars it must return... |
def pickingNumbers(a):
solution = 0
for num1 in a:
if a.count(num1) + a.count(num1 + 1) > solution:
solution = a.count(num1) + a.count(num1 + 1)
return solution |
# while loops
def nearest_square(limit):
number = 0
while (number+1) ** 2 < limit:
number += 1
return number ** 2
test1 = nearest_square(40)
print("expected result: 36, actual result: {}".format(test1))
# black jack
card_deck = [4, 11, 8, 5, 13, 2, 8, 10]
hand = []
while sum(hand) <= 21:
hand.a... |
A_1,B_1 = input().split(" ")
a = int(A_1)
b = int(B_1)
if a > b:
horas = (24-a) + b
print("O JOGO DUROU %i HORA(S)"%(horas))
elif a == b:
print("O JOGO DUROU 24 HORA(S)")
else:
horas = b - a
print("O JOGO DUROU %i HORA(S)"%(horas))
|
"""Example of comments within the Hello World package
This is a further elaboration of the docstring. Here, you can
define the details and steps appropriate for the situation.
Code tells you how. Comments tell you why.
args:
name (int): a description of the parameter
name (str): a description of the paramete... |
# https://app.codesignal.com/arcade/code-arcade/well-of-integration/QmK8kHTyKqh8xDoZk
def threeSplit(numbers):
# From a list of numbers, cut into three pieces such that each
# piece contains an integer, and the sum of integers in each
# piece is the same.
# We know that the total sum of elements in the arr... |
def comparator(predicate):
"""Makes a comparator function out of a function that reports whether the first
element is less than the second"""
return lambda a, b: predicate(a, b) * -1 + predicate(b, a) * 1
|
# https://stackoverflow.com/questions/14485255/vertical-sum-in-a-given-binary-tree
# https://codereview.stackexchange.com/questions/151208/vertical-sum-in-a-given-binary-tree
d = {}
def traverse(node, hd):
if not node:
return
if not hd in d:
d[hd] = 0
d[hd] = d[hd] + node.value
traverse(node.left, h... |
class BaseError(Exception):
def __init__(self, error_code):
super().__init__(self)
self.error_dic = {
'1001': 'Get params failed. ',
'1002': 'Type of input error. ',
'1003': 'File does not exists. ',
'1004': 'File receiving. ',
'1005': 'P... |
conf_my_cnf_xenial = """[mysqld]
bind-address = 0.0.0.0
default-storage-engine = innodb
innodb_file_per_table
max_connections = 4096
collation-server = utf8_general_ci
character-set-server = utf8
innodb_autoinc_lock_mode=2
innodb_flush_log_at_trx_commit=0
innodb_buffer_pool_size=122M
# MariaDB Galera Cluster in Xenial... |
def elevadorLotado(paradas, capacidade):
energiaGasta = 0
while paradas:
ultimo = paradas[-1]
energiaGasta += 2*ultimo
paradas = paradas[:-capacidade]
return energiaGasta
testes = int(input())
for x in range(testes):
NCM = input().split()
capacidade = int(NCM[1])
destinhos = list(map... |
with open('EN_op_1_57X32A15_31.csv','r') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(row[1])
|
class Blosum62:
"""Score matrix BLOSUM62"""
def __init__(self):
self.blosum62 = {
'A': {'A': 4, 'R':-1, 'N':-2, 'D':-2, 'C': 0, 'Q':-1, 'E':-1, 'G': 0, 'H':-2, 'I':-1, 'L':-1, 'K':-1, 'M':-1, 'F':-2, 'P':-1, 'S': 1, 'T': 0, 'W':-3, 'Y':-2, 'V': 0, 'B':-2, 'Z':-1, 'X': 0, '-':-4},
... |
chars = {
'A': ['010',
'101',
'111',
'101',
'101'],
'B': ['110',
'101',
'111',
'101',
'110'],
'C': ['011',
'100',
'100',
'100',
'011'],
'D': ['110',
'101',
'101',
'101',
'110'],
'E': ['111',
'100',
'111',
... |
SAGA_ENABLED = 1
MIN_DETECTED_FACE_WIDTH = 20
MIN_DETECTED_FACE_HEIGHT = 20
PICKLE_FILES_DIR = "/app/facenet/resources/output"
MODEL_FILES_DIR = "/app/facenet/resources/model"
UPLOAD_DIR = "/app/resources/images/"
# PICKLE_FILES_DIR = '/Users/ashishgupta/git/uPresent/face-recognition/resources/output'
# MODEL_FILES_DIR... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 22 21:48:29 2019
@author: zejiran.
"""
def fecha_a_dias(anio: int, mes: int, dia: int) -> int:
""" Convierte una fecha a días, ingresada comop año, mes y día. Se
supone que todos los meses tienen 30 días.
Parámetros:
anio (int) Año de la ... |
"""
VIS_LR
Visualization tools for learning rate stuff
Stefan Wong 2019
"""
def plot_lr_vs_acc(ax, lr_data, acc_data, **kwargs):
title = kwargs.pop('title', 'Learning Rate vs. Accuracy')
if len(lr_data) != len(acc_data):
plot_len = min([len(lr_data), len(acc_data)])
else:
plot_len = len(... |
class Contact:
def __init__(self, first_name: str, second_name: str, phone_number: str):
self._first_name = first_name
self._second_name = second_name
self._phone_number = phone_number
@property
def first_name(self):
return self._first_name
@property
def second_name... |
'''A fórmula para calcular a área de uma circunferência é: area = π . raio2. Considerando para este problema que π = 3.14159:
- Efetue o cálculo da área, elevando o valor de raio ao quadrado e multiplicando por π.'''
R = float(input())
A = 3.14159 * (R ** 2)
print('A={:.4f}'.format(A))
|
def answer(l):
res = 0
length = len(l)
for x in xrange(length):
left = 0
right = 0
for i in xrange(x):
if not (l[x] % l[i]):
left = left + 1
for i in xrange(x + 1, length):
if not (l[i] % l[x]):
right = right + 1
... |
# NOTE: The sitename and dataname corresponding to the observation are 'y' by default
# Any latents that are not population level
model_constants = {
'arm.anova_radon_nopred': {
'population_effects':{'mu_a', 'sigma_a', 'sigma_y'},
'ylims':(1000, 5000),
'ylims_zoomed':(1000, 1200)
},
... |
def addStrings(num1: str, num2: str) -> str:
i, j = len(num1) - 1, len(num2) - 1
tmp = 0
result = ""
while i >= 0 or j >= 0:
if i >= 0:
tmp += int(num1[i])
i -= 1
if j >= 0:
tmp += int(num2[j])
j -= 1
result = str(tmp % 10) + result... |
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param A: a list of integer
@return: a tree node
"""
def sortedArrayToBST(self, A):
# write your code here
if len(A) == 0... |
intin = int(input())
if intin == 2:
print("NO")
elif intin%2==0:
if intin%4==0:
print("YES")
elif (intin-2)%4==0:
print("YES")
else:
print("NO")
else:
print("NO") |
def rgb(r, g, b):
s=""
if r>255:
r=255
elif g>255:
g=255
elif b>255:
b=255
if r<0:
r=0
elif g<0:
g=0
elif b<0:
b=0
r='{0:x}'.format(r)
g='{0:x}'.format(g)
b='{0:x}'.format(b)
if int(r,16)<=15 and int(r,16)>=0:
r='0'+r
... |
# https://www.reddit.com/r/dailyprogrammer/comments/1ystvb/022414_challenge_149_easy_disemvoweler/
def disem(str):
result = ''
rem_vowels = ''
vowels = 'aeiou'
for c in str:
if c not in vowels and not c.isspace():
result += c
elif not c.isspace():
rem_vowels += c... |
'''
@description 2019/09/22 20:53
'''
|
def setup():
size (500,500)
background (100)
smooth()
noLoop()
strokeWeight(15)
str(100)
def draw ():
fill (250)
rect (100,100, 100,100)
fill (50)
rect (200,200, 50,100)
|
#Write a function that accepts a 2D list of integers and returns the maximum EVEN value for the entire list.
#You can assume that the number of columns in each row is the same.
#Your function should return None if the list is empty or all the numbers in the 2D list are odd.
#Do NOT use python's built in max() functi... |
class PolicyOwner(basestring):
"""
cluster-admin|vserver-admin
Possible values:
<ul>
<li> "cluster_admin" ,
<li> "vserver_admin"
</ul>
"""
@staticmethod
def get_api_name():
return "policy-owner"
|
""" HealthDES - A python library to support discrete event simulation in health and social care """
class ResourceBase:
# TODO: Build out the do and query functions for person, activity and resource objects.
# Need to create dictionary of actions and parameters.
# Subclassing allows dictionary of actions... |
### assuming you have Google Chrome installed...
## remember `pip3 install -r setup.py` before trying any scrapers in this dir
# have a nice day
selenium
chromedriver
requests
|
class Power:
def __init__(self, power_id, name, amount):
self.power_id = power_id
self.power_name = name
self.amount = amount
@classmethod
def from_json(cls, json_object):
return cls(json_object["id"], json_object["name"], json_object["amount"])
def __eq__(self, other)... |
DB_PORT=5432
DB_USERNAME="postgres"
DB_PASSWORD="password"
DB_HOST="127.0.0.1"
DB_DATABASE="eventtriggertest"
|
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 14 20:07:55 2018
@author: vegetto
"""
# Local versus Global
def local():
# m doesn't belong to the scope defined by the local function so Python will keep looking into the next enclosing scope. m is finally found in the global scope
print(m, 'printing from the l... |
class WindowNeighbor:
"""The window class for finding the
neighbor pixels around the center"""
def __init__(self, width, center, image):
# center is a list of [row, col, Y_intensity]
self.center = [center[0], center[1], image[center][0]]
self.width = width
self.neighbors... |
class Solution(object):
def findLengthOfLCIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
start = 0
prev = None
m = 0
for i, n in enumerate(nums):
if prev is not None:
if n <= prev:
start = i
... |
setting = {
'file': './data/crime2010_2018.csv',
'limit': 10000,
'source': [0,1,2,3,7,8,10,11,14,16,23,5,25],
'vars': {
0 : 'num',
1 : 'date_reported',
2:'date_occured',
3:'time_occured',
7:'crime_code',
8:'crime_desc',
10:'victim_age',
11:... |
'''from axju.core.tools import SmartCLI
from axju.worker.git import GitWorker
def main():
cli = SmartCLI(GitWorker)
cli.run()
if __name__ == '__main__':
main()
'''
|
# -*- coding: utf-8 -*-
class PaytabsApiError(Exception):
"""Exception raised when an a RequestHandler indicates the request failed.
Attributes:
code -- the error code returned from the API
msg_english -- explanation of the error
"""
def __init__(self, code, message):
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Michael Eaton <meaton@iforium.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Li... |
"""Top-level package for siphr."""
__author__ = """Shamindra Shrotriya"""
__email__ = "shamindra.shrotriya@gmail.com"
__version__ = "0.1.0"
|
class ActivityBar:
"""
Content settings for the activity bar.
"""
def __init__(self, id: str, title: str, icon: str) -> None:
self.id = id
self.title = title
self.icon = icon
class StaticWebview:
"""
Content settings for a Static Webview.
"""
d... |
load("//webgen:webgen.bzl", "erb_file", "js_file", "scss_file", "website")
def page(name, file, out=None, data=False, math=False, plot=False):
extra_templates = []
if data: extra_templates.append("template/data.html")
if math: extra_templates.append("template/mathjax.html")
if plot: extra_templates.app... |
num1 = int(input('Digite o primeiro número: '))
num2 = int(input('Digite o segundo número: '))
if num1 == num2:
print('Os números {} e {} são equivalentes.'.format(num1, num2))
elif num1 > num2:
print('O número {} é maior que o número {}.'.format(num1, num2))
elif num2 > num1:
print('O número {} é maior qu... |
class Solution:
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
return int(math.factorial(m+n-2)/ (math.factorial(m-1)* math.factorial(n-1)))
|
def two_finger_sort(arr, brr):
"""
The two_finger_sort() is a function that takes two sorted lists as input
parameters and returns a single sorted list.
Its time complexity is O(n), but it also needs extra space to store the new
sorted list.
Explanation : arr = [1, 2, 34, 56], brr = [3, 5]... |
# A return statement in a Python function serves two purposes:
# It immediately terminates the function and passes execution control back to the caller.
# It provides a mechanism by which the function can pass data back to the caller.
def f():
print('foo')
print('bar')
return
f()
# In this example, the re... |
#data kualitatif
a = "the dogis hungry. The cat is bored. the snack is awake."
s = a.split(".")
print(s)
print(s[0])
print(s[1])
print(s[2])
|
'''
Completion sample module
'''
def func_module_level(i, a='foo'):
'some docu'
return i * a
class ModClass:
''' some inner namespace class'''
@classmethod
def class_level_func(cls, boolean=True):
return boolean
class NestedClass:
''' some inner namespace class'''
@c... |
N = int(input())
A = int(input())
for a in range(A+1):
for j in range(21):
if a + 500 * j == N:
print("Yes")
exit()
print("No")
|
# ----------------------------------------------------------------
# Copyright 2016 Cisco Systems
#
# 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/LICENS... |
# Scrapy settings for uefispider project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
#
BOT_NAME = 'uefispider'
SPIDER_MODULES = ['uefispider.spiders']
NEWSPIDER_MODULE = '... |
class Solution:
def baseNeg2(self, N: int) -> str:
if N == 0:
return "0"
nums = []
while N != 0:
r = N % (-2)
N //= (-2)
if r < 0:
r += 2
N += 1
nums.append(r)
return ''.join(map(str, nums[::-... |
# 🚨 Don't change the code below 👇
print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
# 🚨 Don't change the code above 👆
lower_name1 = name1.lower()
lower_name2 = name2.lower()
names_together = lower_name1 + lower_name2
#print(names_together)
True_T... |
# This file contains the different states of the api
class Config(object):
DEBUG = False
SQLALCHEMY_DATABASE_URI = 'sqlite:///database.db'
SQLALCHEMY_TRACK_MODIFICATIONS = False
class Production(Config):
DEBUG = False
class DevelopmentConfig(Config):
DEBUG = True |
class Node(object):
def __init__(self, item):
self.data = item
self.left = None
self.right = None
def BTToDLLUtil(root):
if root is None:
return root
if root.left:
left = BTToDLLUtil(root.left)
while left.right:
left = left.right
... |
#!/usr/bin/env python
print('nihao')
|
def friend_find(line):
check=[i for i,j in enumerate(line) if j=="red"]
total=0
for i in check:
if i>=2 and line[i-1]=="blue" and line[i-2]=="blue":
total+=1
elif (i>=1 and i<=len(line)-2) and line[i-1]=="blue" and line[i+1]=="blue":
total+=1
elif (i<=len(line... |
# _*_ coding: utf-8 _*_
#
# Package: bookstore.src.core.validator
__all__ = ["validators"]
|
sanitizedLines = []
with open("diff.txt") as f:
for line in f:
sanitizedLines.append("https://interclip.app/" + line.strip())
print(str(sanitizedLines))
|
#
# chmod this file securely and be sure to remove the default users
#
users = {
"frodo" : "1ring",
"yossarian" : "catch22",
"ayla" : "jondalar",
}
|
def calcMul(items):
mulTotal = 1
for i in items:
mulTotal *= i
return mulTotal
print("The multiple is: ",calcMul([10,20,30])) |
def validate_contract_create(request, **kwargs):
if request.validated['auction'].status not in ['active.qualification', 'active.awarded']:
request.errors.add('body', 'data',
'Can\'t add contract in current ({}) auction status'.format(request.validated['auction'].status))
... |
# -*- coding: utf-8 -*-
"""
enquanto não maça
passo
pega
"""
"""
while not maça:
passo
pega
while not maça:
if bloco:
passo
if buraco:
pula
if moeda:
pega
pega
"""
'''
for c in range(1,10):
print(c)
print('fIMM')'''
c = 1
while c < 10:
print(c)
... |
# flask-login 用クラス
class FlaskUser(object):
def __init__(self, user_hash, username=None):
self.user_hash = user_hash
if username is not None:
self.username = username
def is_authenticated(self):
return True
def is_active(self):
return True
def is_anonymo... |
"""Constants for Skoda Connect library."""
BASE_SESSION = 'https://msg.volkswagen.de'
BASE_AUTH = 'https://identity.vwgroup.io'
BRAND = 'VW'
COUNTRY = 'DE'
# Data used in communication
CLIENT = {
'Legacy': {
'CLIENT_ID': '9496332b-ea03-4091-a224-8c746b885068%40apps_vw-dilab_com', # client id for VW... |
class User:
def __init__(self, userName, firstName, lastName, passportNumber, address1, address2, zipCode):
self.userName = userName
self.firstName = firstName
self.lastName = lastName
self.passportNumber = passportNumber
self.address1 = address1
self.address2 = addre... |
# pylint: skip-file
# pylint: disable=too-many-instance-attributes
class VMInstance(GCPResource):
'''Object to represent a gcp instance'''
resource_type = "compute.v1.instance"
# pylint: disable=too-many-arguments
def __init__(self,
rname,
project,
z... |
#create veriable........
cr_pass=0##insert veriables
defer=0##insert veriables
fail=0##insert veriables
choice=0#staff choice.
count1=0#$$$counting "Progress"
count2=0#$$$counting "Trailing"
count3=0#$$$counting "Excluded"
count4=0#$$$counting "Retriever"
total=0#@@@@all counting values total
#start th... |
'''
Item : Python 100Dsays
Time : 20200521
變量
'''
# 設變數 a, b 進行計算
a = 123
b = 456
c = "hello world"
d = 1 + 5j
e = True
#-計算 --------------------------------------------
print(a + b) # 579
print(a - b) # -333
print(a * b) # 560888
print(a / b) # 0.269...
# 檢索變量的類型的函數 type -----------------------
print(type(a... |
#
# Variables:
# - Surname: String
# - SurnameLength, NextCodeNumber, CustomerID, i: Integer
# - NextChar: Char
#
Surname = input("Enter your surname: ")
SurnameLength = len(Surname)
CustomerID = 0
for i in range(0, SurnameLength):
NextChar = Surname[i]
NextCodeNumber = ord(NextChar)
CustomerID = C... |
class EmptyType(object):
"""A sentinel value when nothing is returned from the database"""
def __new__(cls):
return Empty
def __reduce__(self):
return EmptyType, ()
def __bool__(self):
return False
def __repr__(self):
return 'Empty'
Empty = object.__new__(EmptyT... |
class classproperty(object):
'''Implements both @property and @classmethod behavior.'''
def __init__(self, getter):
self.getter = getter
def __get__(self, instance, owner):
return self.getter(instance) if instance else self.getter(owner)
|
'''
Exercicio 004
Faça um Programa que peça as 4 notas bimestrais e mostre a média.
'''
n1 = float(input('Digite a nota do primeiro bimestre: '))
n2 = float(input('Digite a nota do segundo bimestre: '))
n3 = float(input('Digite a nota do terceiro bimestre: '))
n4 = float(input('Digite a nota do quarto bimestre: '))
m... |
class Game(object):
def initialize(self, ): pass
def start(self, ): pass
def end(self, ): pass
def play(self):
self.initialize()
self.start() # 开始游戏
self.end() # 结束游戏
class Cricket(Game):
def initialize(self, ):
print("Cricket Game Finished!")
def start(se... |
def is_empty(text):
if text in [None,'']:
return True
return False
|
''' 013 Faça um algoritmo que leia o salário de um funcionário e mostre seu novo salária, com 15% de aumento'''
sal = float(input('Digite o seu salário: R$ '))
print(f'O seu salário com aumento de 15% é {sal + (sal * 15)/100:.2f}')
|
mysql_config = {
'user': 'USER',
'password': 'PASSWORD',
'host': 'HOST',
'port': 3306,
'charset': 'utf8mb4',
'database': 'DATABASE',
'raise_on_warnings': False,
'use_pure': False,
} |
class Preprocess_Data:
"""this class converts the integer date time values to the python datetime string format"""
def __init__(self, data_dict):
self.data_dict = data_dict
def preprocess(self):
from_year = self.data_dict["fromYr"]
from_month = self.data_dict["fromMth"]
to_... |
class Solution:
def XXX(self, root: TreeNode) -> int:
if not root:
return 0
res = 1
q = [root]
while q:
n = len(q)
for i in range(n):
node = q.pop(0)
if node.left and node.right: # 有两个子节点
... |
#CORES
r = str('\33[31m') #red
g = str('\33[32m') #green
y = str('\33[33m') #yellow
b = str('\33[34m') #blue
m = str('\33[35m') #magenta
c = str('\33[36m') #cian
x = str('\33[m') #fechamento
#PROGRAMA
print('=~'*12)
print('Minha casa minha vida')
print('=~'*12)
casa = float(input('Qual o valor da casa que você... |
user_name = "huyankai"
user_age = 24
print(user_name, "今年", str(user_age), sep=">>>>",end="")
print(user_name, "今年", str(user_age), sep=">>>>")
|
#!/usr/bin/env python3
"""Global color definitions.
"""
BLUE_BACKGROUND: int = 20
GREEN_BACKGROUND: int = 30
RED_BACKGROUND: int = 5
WHITE: int = 0
YELLOW_BACKGROUND: int = 186
|
# TIme problem
# 00:00:00 - n:59:59
# 해당 문제는 완전 탐색 유형(Brute Forcing)으로도 풀 수 있다.
# 완전 탐색 알고리즘은 가능한 경우의 수를 모두 검사해보는 탐색 방법이다.
# 시간 복잡도로 인해서 일반적으로 알고리즘 문제를 풀 때 확인(탐색)해야 하는 전체 데이터의 개수가 100만개 이하 일 때 완전 탐색을 사용하면 적절하다.
# 내가 푼 방법은 완전 탐색보다는 시간 복잡도를 O(N)으로 감소하여 처리하는 알고리즘이다. 이는 일정한 데이터 제한 안에서 휴리스틱을 적용했다.
# Heuristic
# 01. 시간에 3이 포... |
movie = {"title": "padmavati", "director": "Bhansali","year": "2018", "rating": "4.5"}
print(movie)
print(movie['year'])
movie['year'] = 2019 #update data.
print(movie['year'])
print('-' * 20)
for x in movie:
print(x) #this print key.
print(movie[x]) #this print value at key.
print('-' *... |
espanhol = {"um": "uno", "dois": "dos"}
ingles = {"um": "one", "dois": "two"}
idioma = input("Escolha o idioma: ")
if (idioma=="espanhol"):
print(idioma+["um"])
elif (idioma=="ingles"):
print(ingles["um"])
else:
print("inválido") |
def comb(m, s):
if m == 1: return [[x] for x in s]
if m == len(s): return [s]
return [s[:1] + a for a in comb(m-1, s[1:])] + comb(m, s[1:])
|
n, x = map(int, input().split())
mark_sheet = []
for _ in range(x):
mark_sheet.append( map(float, input().split()) )
for i in zip(*mark_sheet):
print( sum(i)/len(i) ) |
__name__ = "lbry"
__version__ = "0.42.1"
version = tuple(__version__.split('.'))
|
def main():
# input
N = int(input())
As = [*map(int, input().split())]
# compute
## 1-9の各数字がそれぞれ何回登場するかを数える
counts = [0] * 9
for A in As:
counts[A-1] += 1
## 各数字の登場回数の最大値を求める
target = counts[0]
ans = 0
for i, count in enumerate(counts):
if target < count:
... |
# -*- coding: utf-8 -*-
class Base(RuntimeError):
"""An extendible class for responding to exceptions caused within your application.
Usage:
.. code-block: python
class MyRestError(errors.Base):
pass
# somewhere in your code...
raise MyRestError(c... |
# initialize/define the blockchain list
blockchain = []
open_txs = []
def get_last_blockchain_val():
""" Returns the last element of the blockchain list. """
if len(blockchain) < 1:
return None
return blockchain[-1]
def add_tx(tx_amt, last_tx=[1]):
""" Adds the last transaction amount
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
.. py:currentmodule:: leepstools.file.angle
.. moduleauthor:: Hendrix Demers <hendrix.demers@mail.mcgill.ca>
Read angle distribution result from LEEPS simulation.
"""
###############################################################################
# Copyright 2017 He... |
# coding=utf-8
class AutumnInvokeException(Exception):
pass
class InvocationTargetException(Exception):
pass
if __name__ == '__main__':
pass
|
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
'''
T: O(n log n + n^3)
S: O(1)
'''
n = len(nums)
if n < 4: return []
nums.sort()
results = set()
for x in range(n):
for y in rang... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.