content stringlengths 7 1.05M |
|---|
# 05/04/2017
def bowl_score(sheet):
total = 0
score = lambda x: 10 if x[1] == '/' else 20 if x == 'XX' else sum([int(n) for n in x])
next_ball = lambda x: 10 if x == 'X' else int(x[0])
next_2_balls = lambda x, y: 10 + next_ball(y[0]) if x == 'X' else score(x[0:2])
frames = sheet.replace('-', '0').... |
# -*- coding: utf-8 -*-
"""
pepipost
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
class CreateSubaccount(object):
"""Implementation of the 'Create subaccount' model.
CreateSubaccount modal
Attributes:
username (string): provide a ... |
class AeroDB(object):
def __init__(self, aerodb=None, cal=1, area=None):
if isinstance(aerodb, AeroDB):
self.clone(aerodb)
else:
self.clear()
if cal is None and area is None:
raise ValueError("Provide at least one of caliber and area as dimensiona... |
class Token(object):
def __init__(self, cell, railroad):
self.cell = cell
self.railroad = railroad
class Station(Token):
pass
class PrivateCompanyToken(Token):
@staticmethod
def place(name, cell, railroad, properties):
if railroad.is_removed:
raise ValueError(f"A re... |
# coding: utf-8
# In[ ]:
#Exist Database
database={"log_in":{"User_ID":[100,101,102,103,104,105], "Password":
["@Tanmoy*1234","@Tarpan*1234","@Sagnik*1234","@Nikita*1234"
"@Pritam*1234","@Gautamee*1234"],"Name":["Tanmoy","Tarpan"
,"Sagnik","Nikita","Pr... |
filters = \
('+ c ESI Full ms [300.00-2000.00]',
'+ c ESI Full ms [400.00-2000.00]',
'+ c d Full ms2 400.31@cid45.00 [100.00-815.00]',
'+ c d Full ms2 401.39@cid45.00 [100.00-815.00]',
'+ c d Full ms2 406.73@cid45.00 [100.00-825.00]',
'+ c d Full ms2 408.00@cid45.00 [100.00-830.00]',
'+ c d Full ms2 412.90@cid45.... |
num = 9669
s = str(num)
max = num
x = num
for i in s:
if (i == '6'):
s = s.replace(i, '9', 1)
if (int(s) > max):
max = int(s)
s = str(x)
else:
s = str(x)
elif ( i == '9'):
s =s.replace(i, '6', 1)
if (int(s) > max):
max = i... |
class ImageFormatConverter(TypeConverter):
"""
System.Drawing.ImageFormatConverter is a class that can be used to convert System.Drawing.Imaging.ImageFormat objects from one data type to another. Access this class through the System.ComponentModel.TypeDescriptor object.
ImageFormatConverter()
"""
... |
# coding=utf-8
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# -----------------------------------------------------... |
"""
The structure of Segment Tree is a binary tree which each node has two attributes start and end denote an segment /
interval.
start and end are both integers, they should be assigned in following rules:
The root's start and end is given by build method.
The left child of node A has start=A.left, end=(A.left + A.r... |
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
def mkdir(tmp_path, *parts):
path = tmp_path.joinpath(*parts)
if not path.exists():
path.mkdir(parents=True)
return path
|
expected_output = {
"fpc-information": {
"fpc": {
"pic-detail": {
"pic-slot": "0",
"pic-type": "2X100GE CFP2 OTN",
"pic-version": "1.19",
"port-information": {
"port": [
... |
#!/usr/bin/python3
"""defining read_file function"""
def read_file(filename=""):
"""reads filename with utf-8"""
with open(filename, encoding='utf-8') as f:
print(f.read(), end="")
|
# $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ #
# $$$$$$$$$$ Type Casting - DataType COnversion $$$$$$$$$$ #
# $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ #
# First Method
print('Salary Calculator!')
hour = input('Hour in Week: ')
hour = int(hour)
salary = input('Salary per Hour: ')
salary = i... |
css = [
{"selector": "table, th, td", "props": [("border", "0")]},
{
"selector": "thead th",
"props": [
("padding", "10px 3px"),
("border-bottom", "1px solid black"),
("text-align", "right"),
],
},
{"selector": "td", "props": [("padding", "3px"... |
#
# PySNMP MIB module JNX-MPLS-TE-P2MP-STD-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/JNX-MPLS-TE-P2MP-STD-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:58:39 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... |
#Last Updated: 1/20/17
class CachedTeamData(object):
def __init__(self, teamNumber):
super(CachedTeamData, self).__init__()
self.number = teamNumber
self.completedTIMDs = []
class CachedCompetitionData(object):
def __init__(self):
super(CachedCompetitionData, self).__init__()
self.teamsWithMatchesCompleted... |
def Mailchimp(thoughts, eyes, eye, tongue):
return f"""
{thoughts}
{thoughts}"""+"""
______
/ ___M ]__
C{ ( o o )}
{ ••
\\___
----´
""" |
# -*- coding: utf-8 -*-
"""
@date: 2020/11/21 下午2:37
@file: __init__.py.py
@author: zj
@description:
"""
|
(10 ** 2)[::-5]
(10 ** 2)[5]
(10 ** 2)(5)
(10 ** 2).foo
-(10 ** 2)
+(10 ** 2)
~(10 ** 2)
5 ** 10 ** 2
(10 ** 2) ** 5
5 * 10 ** 2
10 ** 2 * 5
5 / 10 ** 2
10 ** 2 / 5
5 // 10 ** 2
10 ** 2 // 5
5 + 10 ** 2
10 ** 2 + 5
10 ** 2 - 5
5 - 10 ** 2
5 >> 10 ** 2
10 ** 2 << 5
5 & 10 ** 2
10 ** 2 & 5
5 ^ 10 ** 2
10 ** 2 ^... |
# http://www.lintcode.com/en/problem/find-the-missing-number/
class Solution:
# @param nums: a list of integers
# @return: an integer
def findMissing(self, nums):
return sum(range(len(nums)+1)) - sum(nums)
|
"""683. Word Break III
"""
class Solution:
"""
@param s: A string
@param dict: A set of word
@return: the number of possible sentences.
"""
def wordBreak3(self, s, dict):
# Write your code here
## Practice:
lower_dict = set()
for word in dict:
lower_di... |
first_rect = input().split()
for x in range(len(first_rect)):
first_rect[x] = int(first_rect[x])
second_rect = input().split()
for x in range(len(second_rect)):
second_rect[x] = int(second_rect[x])
x_list = [first_rect[0], first_rect[2], second_rect[0], second_rect[2]]
y_list = [first_rect[1], first_... |
def Leiaint(msg):
while True:
try:
n = int(input(msg))
except(ValueError, TypeError):
print(f'\033[0;31mErro: por favor, digite um número inteiro válido.\033[m')
continue
except (KeyboardInterrupt):
print('\033[0;31mO usuário preferiu não digit... |
'''
Contains dicts of links for use in prempy
'''
scorespro = {
"epl": {
"_l_name":"https://www.scorespro.com/soccer/england/premier-league/",
"_l_name_r":"https://www.scorespro.com/soccer/england/premier-league/results/",
"_l_name_f":"https://www.scorespro.com/soccer/england/premier-league/fixtures/",
"_l_na... |
#! Занятие по книге Python Crash Course, chapter 10, "Files and
# Exceptions". Занятие четвёртое.
# Try it yourself 10-6, 10-7.
def addition(x, y):
while x != 'stop' or y != 'stop':
try:
print(int(x) + int(y))
except ValueError:
print("Value Error")
x ... |
# lista de produtos
tupla = ('Sabonete', 2.99, 'Xampu', 5.50, 'Pão de sal', 5, 'Frios', 4.50, 'Café', 4.19)
print('\033[31;40mproduto', '-'*(12), '==', 'Preço\033[m')
for c in range(0, len(tupla), 2):
pos = tupla.index(tupla[c])
print(f'{tupla[c]:.<20} == {tupla[pos+1]}')
|
# Creating a cyclic sort function
def cyclic_sort(a):
i=0
while(i<len(a)):
if(a[i]!=i+1):
index=a[i]-1
x=a[i]
a[i]=a[index];
a[index]=x;
else:
i+=1
return a
list1 = [4,5,6,2,1,7,3]
print("The... |
n = int(input())
contador = 3
c2 = 0
c3 = 1
print(f'{c2}, {c3}', end='')
while n >= contador:
c4 = c2 + c3
print(f',', end=' ')
print(f'{c4}', end='')
c2 = c3
c3 = c4
contador += 1
|
### leitura correta
sexo = str(input('Qual o seu sexo?[M/F]\n')).strip().lower()
while sexo!='f' and sexo!='m':
sexo = str(input('Qual o seu sexo?[M/F]\n'))
print('Está correto!')
|
# A simple calculator - Y1, group D, MEET Project
# Author: Tamar Shabtai
# This function adds two numbers
def add(x, y):
return x + y
# This function subtracts two numbers
def subtract(x, y):
return x - y
# This function multiplies two numbers
def multiply(x, y):
return x * y
# This function divides ... |
#calcular imc
print("Calcule o seu IMC")
nome = str(input("Qual o seu nome? ")).strip()
peso = float(input("Qual o seu peso? "))
altura = float(input("Qual a sua altura? "))
imc = peso / (altura ** 2)
if imc < 16:
print(f"{nome}: seu indice aponta magreza grave e pode causar insuficiência cardíaca, "
... |
num = int(input("Enter the nmber.\n"))
f = 1
print("Factors :")
for i in range(1 , num+1):
if(num%i) == 0:
print(i)
print("Factorial:")
for j in range(1 , num+1):
f = f*j;
print(f)
|
def union (setA = '', setB = ''):
print('union')
pass
def intersection ():
print('intersection')
pass
def difference ():
print('difference')
pass |
# Quest 03
num1 = int(input("Digite o primeiro número: "))
num2 = int(input("Digite o segundo número: "))
num3 = int(input("Digite o terceiro número: "))
num1Ganha = num1 > num2
num2Ganha = num2 >= num3
num3Ganha = num3 >= num1
if(num1Ganha and num2Ganha):
print("O maior número é %i" % num1)
elif(num2Ganha and n... |
# -*- coding: utf-8 -*-
EMPTY_QUESTIONS="""
{
"total": 0,
"page": 1,
"pagesize": 1,
"questions": []
}
"""
EMPTY_ANSWERS="""
{
"total": 0,
"page": 1,
"pagesize": 1,
"answers": []
}
"""
QUESTION="""
{
"total": 1,
"page": 1,
"pagesize": 1,
"questions": [
{
"tags": [
"c#",
... |
L = [
1, 2, 3, 4, 5, 6, 7, 8, 9
]
def split_list(a_list):
half = len(a_list)//2
return a_list[:half], a_list[half:]
B, C = split_list(L)
print (B)
print (C) |
thisdict = {
"brand":"Ford",
"model":"Mustang",
"year":1964
}
del thisdict
print(thisdict) #Error
|
def parse_cls_ind(clsind_path):
with open(clsind_path) as cls_ind:
cls_dic = {}
for line in cls_ind:
label, cls_name = line.split(',')
cls_dic[cls_name.strip()] = int(label)
cls_dic[int(label)] = cls_name.strip()
return cls_dic |
def delKlinkers(woord):
'This returns a given word without vowels'
result = ''
for char in woord: # loop
if char not in 'aeiou':
result = result + char
return result # returns result to variable result
delKlinkers('Achraf')
|
''' Problem Statemenr : Python program to segregate even and odd nodes in a Linked List
Complexity : O(n)'''
head = None # head of list
# Node class
class Node:
# Function to initialise the node object
def __init__(self, data):
self.data = data # Assign data
self.next =None
def segregateEvenOdd():
g... |
"""InnovAnon Inc. Proprietary"""
class Euclid:
# l[h] = l[k] * a + r
# l[h] = l[k] ** a * r
def __init__ (self, quotient, remainder, iszero):
self.quotient = quotient
self.remainder = remainder
self.iszero = iszero
def euclid (self, a, b):
"""https://plus.maths.org/content/music-and-euclids-algorithm... |
"""
Decorators
-> Modify or enhance an existing function in a non-intrusive and maintainable way
-> Implemented as a callable that accepts a callable and returns a callable
-> "A function accepting a function an returning a function"
"""
"""
Summary:
-> Decorators modify existing callables extrinsically
-> Apply decor... |
ies = []
ies.append({ "ie_type" : "Node ID", "ie_value" : "Node ID", "presence" : "M", "instance" : "0", "comment" : "This IE shall contain the unique identifier of the sending Node."})
ies.append({ "ie_type" : "Node Report Type", "ie_value" : "Node Report Type", "presence" : "M", "instance" : "0", "comment" : "This IE... |
'''
Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
Examples:
s = "leetcode"
return 0.
s = "loveleetcode",
return 2.
'''
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
... |
def get_unique_username():
id = 0
base_string = "locust_username_"
while True:
id = id + 1
yield base_string + str(id)
def get_unique_email():
id = 0
base_string = "locust@email_"
while True:
id = id + 1
yield base_string + str(id)
def get_unique_password():
... |
def predict_boxes_connect(heatmap,T,threshold=0.9):
'''
This function takes heatmap and returns the bounding boxes and associated
confidence scores.
'''
'''
BEGIN YOUR CODE
'''
temp_h=int(T.shape[0]//2)
temp_w=int(T.shape[1]//2)
print(temp_h)
origin_map = np.copy(heatmap)
def explore(i,j,cnt):
if hea... |
def remainder(a,b):
if a==0 or b ==0:
if a > b:
if b ==0:
return None
else:
return a % b
elif b > a:
if a ==0:
return None
else:
return b % a
elif a > b:
return a%b
else:
... |
output_fname = raw_input("Enter the output filename: ")
search_text = raw_input("Enter the inclusion text: ")
f = open("features.tsv","r")
included_lines = []
for line in f.readlines():
if search_text in line:
included_lines.append(line)
print("found lines: %d" % len(included_lines))
outf = open(output_fname, "w... |
def parse (input):
decoded_input = input.decode()
decoded_input = decoded_input.split('\n')
destination = decoded_input[-1]
decoded_input = decoded_input[0:len(decoded_input)-1]
time_consider = decoded_input[0].split(',')[2]
visited_nodes = []
for i in decoded_input:
visited_nodes.ap... |
"""
name - jméno string
need - patenty potřebné pro výzkum (patent)
research_time - doba výzkumu integer secunds
research_price - cena výzkumu integer coins
unit_list - seznam j... |
# Attributes on the fly
class User:
pass
user_1 = User()
user_1.username = "Chandra"
user_2 = User()
user_2
# NOTE 1 : You can define "object" attributes on the fly
print(user_1.username)
# AttributeError: 'User' object has no attribute 'username'
# print(user_2.username)
# Class Attributes
class Person:
... |
satz = "Fischers Fritze fischt frische Fische"
# Häufigkeit Buchstabe e
# 1. Ansatz: for-schleife und Zähler
zaehler = 0
for zeichen in satz:
if zeichen == "e":
zaehler += 1
print (zaehler)
# Häufigkeit der Buchstaben im Satz
dic_m03 = {}
for zeichen in satz:
if zeichen in dic_m03:
... |
# -*- coding: utf-8 -*-
#
# pyDFTD3 -- Python implementation of Grimme's D3 dispersion correction.
# Copyright (C) 2020 Rob Paton and contributors.
#
# This file is part of pyDFTD3.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (th... |
class BaseView(object):
def get_table(self):
return {
"headings": self.get_headings(),
"body": self.get_rows(),
}
# Type
def get_column_type(self, column):
return "plain"
def get_row_type(self, row):
return "plain"
# Heading
def get_head... |
##parameters=
##title=Manage filter cookie
##
REQUEST=context.REQUEST
if REQUEST.get('clear_view_filter', 0):
context.clearCookie()
REQUEST.set('folderfilter', '')
REQUEST.set('close_filter_form', '1')
elif REQUEST.get('set_view_filter', 0):
filter=context.encodeFolderFilter(REQUEST)
REQUEST.RESPONS... |
'''Escreva um programa que converta uma temperatura digitada em Cº e converta em ºF.'''
temperatura = float(input('Informe a temperatura: Cº '))
calculo = (temperatura * 1.8) + 32
print(f'A temperatura convertida de Celsius para Fahrenheit é: ºF {calculo:.0f}') |
class User:
def __init__(self,uid,name,surname,email,password,card_number,certificate):
self.uid=uid
self.name=name
self.surname=surname
self.email=email
self.certificate=certificate
self.password=password
self.card_number=card_number
|
"""
helpers
"""
def square(x):
"""square()"""
return x * x
|
class AverageDeviationAnomalyClass:
def __init__(self, conf, confa):
self.confObj = conf
self.confaObj = confa
# init global vars
# init global vars
self.sql = conf.sql
self.cur = conf.db.cursor()
self.gl = conf.Global
# define transactions data... |
# -*- coding: utf-8 -*-
known_chains = {
"BTS": {
"chain_id": "4018d7844c78f6a6c41c6a552b898022310fc5dec06da467ee7905a8dad512c8",
"core_symbol": "BTS",
"prefix": "BTS",
},
"TEST": {
"chain_id": "39f5e2ede1f8bc1a3a54a7914414e3779e33193f1f5693510e73cb7a87617447",
"core_... |
city = input()
sales = float(input())
commision = 0
if city == 'Sofia':
if 0 <= sales <= 500:
commision = 0.05
elif 500 < sales <= 1000:
commision = 0.07
elif 1000 < sales <= 10000:
commision = 0.08
elif sales > 10000:
commision = 0.12
elif city == 'Varna':
if 0 <= s... |
"""
lambda表达式
定义:
匿名函数
语法:
lambda 参数:函数体
lambda能表达的函数,def都能表达.
但是lambda函数体,不支持赋值语句,也只能有一条语句
"""
# 1. 有参数有返回值
# def func01(p1,p2):
# return p1 > p2
func01 = lambda p1, p2: p1 > p2
print(func01(3, 8))
# 2. 有参数无返回值
# def func02(p1):
# print("参数是:",p1)
... |
__metaclass__ = type
class Filter_node:
def __init__(self, struc=None, config=None, save=None, debug=None):
self.myInfo = "Filter Node"
self.struc = str(struc)
self.save = str(save)
self.config = str(config)
self.debug = debug
self.nodeNum = -1
self.nodeList... |
class ThumbnailCacheContext(object):
""" Lazy computation of of images as thumbnails.
DEPRICATED
Just pass a list of uuids corresponding to the images. Then compute images
flagged as dirty and give them back to the context. thumbs_list will be
populated on contex exit
"""
def __init__(s... |
FF = 'ff'
ONGOING = 'normal'
FINISHED = 'finished'
CHEATED = 'cheated'
|
"""
DAY 32 : Multiply two strings.
https://www.geeksforgeeks.org/multiply-large-numbers-represented-as-strings/
QUESTION : Given two numbers as stings s1 and s2. Calculate their Product.
Expected Time Complexity: O(n1* n2)
Expected Auxiliary Space: O(n1 + n2)
where n1 and n2 are sizes of strings s1 and s2 res... |
"""
https://leetcode.com/problems/climbing-stairs/
Difficulty: Easy
"""
class Solution:
@staticmethod
def climb_stairs(n: int) -> int:
paths = {0: 1, 1: 1, 2: 2}
for i in range(3, n + 1):
paths[i] = paths[i - 1] + paths[i - 2]
return paths[n]
|
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def printLinkedList(l: ListNode) -> None:
if l:
print(l.val, end=" ")
nextNode = l.next
while nextNode:
print(nextNode.val, end=" ")
nextNode = nextNode.next
... |
# encoding: utf-8
class _ServiceRegistry(object):
def __init__(self):
self.services = {}
def get(self, name):
"""
Return the handler for the given name. Raises `KeyError` if
the handler does not exist.
"""
return self.services[name]
def register(self, servi... |
class Solution:
def rearrangeBarcodes(self, barcodes: List[int]) -> List[int]:
cnt = collections.Counter(barcodes).most_common()[::-1]
ref = [val for val, t in cnt for _ in range(t)]
for i in range(0, len(barcodes), 2):
barcodes[i] = ref.pop()
for i in range(1, len(barcod... |
'''
Elections are in progress!
Given an array of the numbers of votes given to each of the candidates so far, and an integer k equal to the number of voters who haven't cast their vote yet, find the number of candidates who still have a chance to win the election.
The winner of the election must secure strictly more ... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, node):
if self.head == None:
self.head = node
else:
cur = self.head
# go till end
... |
# continue vs break vs pass
print('for continue function')
# continue is used for skipping outpot
for letter in range(5):
if letter == 3:
continue
print ('hi', letter)
print ('for pass function')
# pass is used to skip variable/print definition
for letter in range(5):
pass
print('for brea... |
n1 = int(input('Digite o primeiro termo de uma PA.'))
raz = int(input('Digite a razão dessa PA.'))
c = 1
termo = n1
mais = 1
total = 10
while mais != 0:
while c <= total:
print(termo+raz)
c += 1
termo = termo + raz
mais = int(input('Deseja mostrar mais quantos termos?'))
total = tota... |
CARDS_FROM_API = [
{
"object": "card",
"id": "3066cc8b-7a5a-4822-a202-dd560a4fda85",
"oracle_id": "ac8cc74d-e43b-4118-bba0-dfa8b9c04d45",
"multiverse_ids": [
479369
],
"tcgplayer_id": 205243,
"cardmarket_id": 426... |
WoqlSelect = {
"jsonObj": {
"@type": "woql:Select",
"woql:variable_list": [
{
"@type": "woql:VariableListElement",
"woql:variable_name": {"@value": "V1", "@type": "xsd:string"},
"woql:index": {"@type": "xsd:nonNegativeInteger", "@value": 0}... |
#author: <Samaiya Howard>
# date: <7/1/21>
# --------------- Section 1 --------------- #
# ---------- Integers and Floats ---------- #
# you may use floats or integers for these operations, it is at your discretion
# addition
# instructions
# 1 - create a print statement that prints the sum of two numbers
# ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
username = 'admin'
password = 'admin'
tenant_name = 'admin'
admin_auth_url = 'http://controller:35357/'
auth_url = 'http://controller:5000/' # discover api version
auth_url_v2 = 'http://controller:5000/v2.0/'
auth_url_v3 = 'http://controller:5000/v3/'
glance_url = 'http:/... |
#누적하기
a = "abc"
for i in range(3):
a += "%d\t" % (i)
print(a)
|
print('Hello, chap3, sec1.')
pub = dict()
pub['author'] = 'John F. Nash'
pub['title'] = 'Equilibrium points in n-person games'
pub['journal'] = 'PNAS'
pub['year'] = '1950' |
def p(a,n):
a.sort()
s=0
for i in range(n):
s+=a[i]
a.append(s)
print(max(a))
t=int(input())
n,m,a=[],[],[]
for i in range(t):
n.append(list(map(int,(input()).strip().split(' '))))
a.append(list(map(int,(input()).strip().split(' ')))[:n[i][0]])
for i in range(t):
... |
class Init:
def __init__(self):
return
def phone(self, phone: int) -> int:
try:
phstr = str(phone)
step = int(phstr[0])
for x in range(len(phstr)):
if not x + 1 == len(phstr):
step = (step ** int(phstr[x + 1]) // int(phstr... |
def min_of_maxes(nums,k):
count = 0
highest = None
lowest = None
for i in nums:
count += 1
if highest == None:
highest = i
if i > highest:
highest = i
if count == k:
if lowest == None:
lowest = highest
if highest < lowest:
lowest = highest
high... |
class AuthenticationError(Exception):
pass
class APICallError(Exception):
pass |
def test_species_del(neuron_instance):
"""Test deleting an uninitialized species does not raise any error or
exceptions.
"""
h, rxd, data, save_path = neuron_instance
soma = h.Section(name="soma")
cyt = rxd.Region([soma])
c = rxd.Species(cyt)
try:
c.__del__()
except:
... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
# Recursive
def isUnivalTree(root: TreeNode) -> bool:
def compare_value(cur_root: TreeNode, previous_root: int) -> bool:
if n... |
class LookAhead():
"""
Look ahead iterator. Look ahead using `.peek`.
"""
_NONE = object()
def __init__(self, iterable):
self._it = iter(iterable)
self._set_peek()
def __iter__(self):
return self
def __next__(self):
ret = self.peek
self._set_peek()
... |
# Compare two version numbers version1 and version2.
# If version1 > version2 return 1; if version1 < version2 return -1;otherwise return 0.
# You may assume that the version strings are non-empty and contain only digits and the . character.
# The . character does not represent a decimal point and is used to separate n... |
## Colm Higgins
## This program will ask the user to input a string and prints
## every second letter in reverse order
# input sentence
x = input("Please type a sentence of your choice: ")
# print input removing every 2nd letter and reversed
# [::2] is every 2nd letter and putting a - before will reverse it.
# Shor... |
'''
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
'''
class Solution:
# @param A, a li... |
# coding: utf-8
google_10000_path = '/home/pj/datum/GraduationProject/dataset/google-10000-english/google-10000-english.txt'
google_1000 = open(google_10000_path, 'r')
def read_google_10000_english(num):
"""
get diff word from google 10000 english database
:params num: word's number wanting to use
"... |
# -*- coding: utf-8 -*-
Error = {
'department': '❌ Не удалось обновить кафедру! Проверь правильность вводимых данных.',
'group': '❌ Не удалось обновить группу! Проверь правильность вводимых данных.',
'info_student': '❌ Не удалось получить данные о тебе! Возможно, их просто еще нет.\nДля добавления информаци... |
"""
2903 : 중앙 이동 알고리즘
URL : https://www.acmicpc.net/problem/2903
Input :
1
Output :
9
"""
MAX_N = 16
cache = [0 for i in range(MAX_N)]
cache[0] = 2
for i in range(1, MAX_N):
cache[i] = cache[i - 1] + (cache[i - 1] - 1)
n = int(input())
print(cache[n] ** 2)
|
# Title : Nato Phonetic Expansion
# Author : Kiran raj R.
# Date : 17:10:2020
persons = {'John': {'Age': '55', 'Gender': 'Male'},
'Toney': {'Age': '23', 'Gender': 'Male'},
'Karin': {'Age': '42', 'Gender': 'Female'},
'Cathie': {'Age': '29', 'Gender': 'Female'},
'Rosalba': ... |
class NoneType(object):
def __new__(self, *args):
return None
def __init__(self, *args):
pass
def __bool__(self):
return False
def __str__(self):
return "None"
___assign("%NoneType", NoneType)
|
# -*- coding: utf-8 -*-
# @Author: 何睿
# @Create Date: 2018-12-21 11:18:38
# @Last Modified by: 何睿
# @Last Modified time: 2018-12-21 14:26:43
class Solution:
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place ... |
# -*- coding: utf-8 -*-
DESC = "cloudaudit-2019-03-19"
INFO = {
"StartLogging": {
"params": [
{
"name": "AuditName",
"desc": "Tracking set name"
}
],
"desc": "This API is used to enable a tracking set."
},
"GetAttributeKey": {
"params": [
{
"name": "Websit... |
# test basic async for execution
# example taken from PEP0492
class AsyncIteratorWrapper:
def __init__(self, obj):
print('init')
self._it = iter(obj)
async def __aiter__(self):
print('aiter')
return self
async def __anext__(self):
print('anext')
try:
... |
# Exercício Python 099:
# Faça um programa que tenha uma função chamada maior(),
# que receba vários parâmetros com valores inteiros.
# Seu programa tem que analisar todos os valores e
# dizer qual deles é o maior.
def l(qtd=30): print('=-'*qtd + '=')
def maior(*numeros):
l()
print(f'foram informados os valo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.