content stringlengths 7 1.05M |
|---|
"""
registry = {
'NLP_SERVICE_ADDRESS': "ipc:///tmp/nlp-service.sock",
'ANN_SERVICE_ADDRESS': "ipc:///tmp/ann-service.sock",
'RECOMMEND_SERVICE_ADDRESS': "ipc:///tmp/recommend-service.sock",
'DIALOG_SERVICE_ADDRESS': "ipc:///tmp/dialog-service.sock",
'INTENT_SERVICE_ADDRESS': "ipc:///tmp/intent-serv... |
#перша задача
years = int(input("кількість років: "))
terms = years / 4
if terms > 2:
print("Президент не може бути на посту президента більше 2 термінів")
else:
print("президент був на пості президента ",terms," термінів")
#друга задача
president = input("введіть ім'я президента:")
George_Washington = 2
Thomas... |
# Desafio106 o programa imprime o interative Help
#Funcções
def menu_bonito(nome_que_vai_no_menu):
print(f'\033[1:32:40m{"#"* len(nome_que_vai_no_menu)}####\033[m')
print(f' {nome_que_vai_no_menu}')
print(f'\033[1:32:40m{"#"* len(nome_que_vai_no_menu)}####\033[m')
print()
def menu_bonito2(nome_que_... |
def mod_value(mod, value):
def apply_mod(x):
return x % mod
return apply_mod
def mod_add(mod, a, b):
return (a + b) % mod
def mod_multiply(mod, a, b):
return (a * b) % mod
def mod_metabolism(mod, base):
def metabolism(a):
return (base * a) % mod
return metabolism
def f_add(mo... |
__all__ = ["m1m1"]
def m1m1():
pass
def m1m2():
pass |
lista=[]
def teste(n1):
for i in (range(n1+1)):
var=2**i
lista.append(var)
return lista
tt= teste(5)
print(tt)
|
##########################DATA LABEL PROPERTIES###############################
cameraInfo = {"Pelco" : 11.34, "Andor" : 8.1}
qualityParameters = ["Good","Very Good", "Amazing"],[0.1,0.05,0.01],["Bad"]
qualityN = {"N":3}
columnLocations = {"calX":3,"calTime":0,"pullP1X":1,"pullP2X":3,"FWHM":1}
alphabet = ["a","b","c","... |
n = int(input())
c = 0
c += n // 100
n %= 100
c += n // 20
n %= 20
c += n // 10
n %= 10
c += n // 5
n %= 5
c += n // 1
n %= 1
print(c) |
# @Title: N 皇后 (N-Queens)
# @Author: KivenC
# @Date: 2020-09-03 22:09:08
# @Runtime: 68 ms
# @Memory: 14 MB
class Solution:
# def solveNQueens(self, n: int) -> List[List[str]]:
# # 回溯
# # 利用三个集合记录皇后的位置
# self.col = set()
# self.diag_1 = set()
# self.diag_2 = set()
# ... |
# Object Oriented Programmning
# 객체(데이터, 각각의 데이터를 처리하는 방법) <=> 객체: 메세지를 전달
# 함수형 프로그래밍 => Lambda, Lambda Operator, List Comprehension
# Object에 대한 이해
# 허진한 학생
# 학생이 무엇인가?
class Student():
__campus = "패스트캠퍼스"
def __init__(self, name, age):
'''
init => initialize( 초기화하다)
Student() ... |
# --------------------------------------------------------
# Multi-Epitope-Ligand Cartography (MELC) phase-contrast image based segmentation pipeline
#
#
# Written by Filip Mivalt
# --------------------------------------------------------
"""
A package containing fucntions and classes for data handling.
The pa... |
arr = []
arr.append(0)
arr.append(1)
i = 0
while len(arr) != 61:
if i == 0:
arr.append(2)
else:
x = str(arr[i])
x = x[::-1]
y = str(arr[i+1])
y = y[::-1]
arr.append(int(x)+int(y))
i += 1
while True:
try:
x = int(input())
pr... |
BENGALI_FONT = [
[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], # 0x00
[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], # 0x01
[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], # 0x02
[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], # 0x03
[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], ... |
'''
Statement
Given an integer n, create a two-dimensional array of size n×n according to the following rules and print it:
On the main diagonal put 0.
On the diagonals adjacent to the main put 1.
On the next adjacent diagonals put 2, and so forth.
Example input
5
Example output
0 1 2 3 4
1 0 1 2 3
2 1 0 1 2
3 2 1 ... |
# Pybashrc file. Create your command-line accessible python functions here.
def _hidden_print_function(*args):
"""This function will be ignored by pybashrc, and will not be available from the
command line.
However, other functions can still use it.
"""
print(*args)
def test_pybashrc(first_argumen... |
key="find"
with open("mt7_7.txt","r",encoding="utf-8") as tf:
for i,line in enumerate(tf):
if line.find(key) >=0:
a=line.find(key)
print(a)
print(i+1, ":",line)
|
EXAMPLE_ARR = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
def flipRows(arr):
""" left(r) to left
top to bottom
right(r) to right
bottom to top
>>> flipRows(EXAMPLE_ARR)
[[7, 8, 9], [4, 5, 6], [1, 2, 3]]
>>> flipRows(flipRows(EXAMPLE_ARR)) == EXAM... |
d = 1
n = 2
for i in range(2,101):
c = 2*(i//3) if i%3 == 0 else 1
t = d
d = n
n = c*d + t
print(sum([int(i) for i in str(n)])) |
"""
Banging my head against monads again. Attacking it by trying to fully
understand that:
"a monad is a monoid in the category of endofunctors"
A Category has:
* Objects (typically sets, but any mathematical object)
* One or more Morphism (typically associative functions)
* Can think of as a labele... |
"""
Problem Statement
=================
Given the number n, find the nth fibanacci number.
The fibonacci series is 0, 1, 1, 2, 3 ...
And follows the formula Fn = Fn-1 + Fn-2
Complexity
----------
* Recursive Solution: O(2^n)
* Dynamic Programming: O(n)
"""
def fibonacci_recursive(n):
if n == 0 or n == 1:
... |
class Car1:
"""一次模拟器汽车的简单尝试"""
def __init__(self, make, model, year):
"""初始化描述汽车的属性"""
self.make = make
self.model = model
self.year = year
def get_descriptive_name(self):
"""返回整洁的描述性信息"""
long_name = f"{self.year} {self.make} {self.model}"
... |
#!/usr/bin/python
message = '!yadhtriB yppaH'[::-1]
print(message)
#prints Happy Birthday!
|
"""
TLD List defined things.
"""
api = "https://tld-list.com/xaja/dac"
headers = {
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML,"
" like Gecko) Ubuntu Chromium/69.0.3497.81 Chrome/69.0.3497.81 "
"Safari/537.36",
"Origin": "https://tld-list.com",
"Referer": "https://tld-li... |
class fftcomp:
"""
This operation will plot the Fourier transform of given time series.
The time series and FFT are shown interactively so the user can select
a desired time slot and get the FFT from that region.
Parameters
----------
start : str
Starting date to retrieve data fr... |
def add_two_num(a, b):
# a and b are the parameters of add_two_num()
'''This function compute the sum of two numbers(a and b).
'''
return a + b # the result which function will return
print(add_two_num(3, 5)) # 3 and 5 are the arguments of add_two_num()
x = 10
y = 20
print(add_two_num(x, y)) # x and y... |
#Statement:Determine the sum of all elements in the sequence, ending with the number 0.
seq = int(input("enter numbers: "))
sum = seq
while seq > 0:
seq = int(input("enter number: "))
sum+= seq
if seq == 0:
break
print(sum) |
# The next lines will make the Pixel Turtle and its heading invisible
# and will clear the screen for light show
hidePixel()
hideHeading()
clear()
# First we move to the top left corner
moveTo(0, 0)
right(2)
for i in range(0, 8):
for j in range(0, 15):
if j % 2 == 0:
setColor(red)
else... |
# if every sentences has these anotated words then label anotation with 0
# NOT_ANNOTATED = ["not", "no", "normal", "without", "negative for", "stable", "intact", "unchanged", "no evidence", "no acute", "no suspicious", "clear", "free of", "removal", "removed"]
NOT_ANNOTATED = ["not", "negative for", "no evidence", "no... |
""" Unique Paths
A robot is located at the top-left corner of a m x n grid
(marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time.
The robot is trying to reach the bottom-right corner of the grid
(marked 'Finish' in the diagram below).
+-----------+-----+-----+-----... |
__author__ = 'jbowman'
# https://pythonspot.com/poylmorphism/
class Bear(object):
def sound(self):
print("Groarrr")
class Dog(object):
def sound(self):
print("Ruffff")
def makeSound(animalType):
animalType.sound()
bearObj = Bear()
dogObj = Dog()
makeSound(bearObj)
makeSound(dogObj)
cl... |
tanmuLink = '''
<link rel="stylesheet" href="/static/css/bootstrap.min.css"/>
<link rel="stylesheet" href="/static/css/bootstrapValidator.min.css"/>
''' |
'''
Created on 2016年2月23日
@author: Darren
'''
'''
Given an image represented by an NxN matrix,
where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees.
Can you do this in place?
'''
'''
* clockwise rotate
* first reverse up to down, then swap the symmetry
* 1 2 3 7 8 9 ... |
# Exercício Python 040:
# Crie um programa que leia duas notas de um aluno e calcule sua média, mostrando uma mensagem
# no final, de acordo com a média atingida:
# – Média abaixo de 5.0: REPROVADO
# – Média entre 5.0 e 6.9: RECUPERAÇÃO
# – Média 7.0 ou superior: APROVADO
nota1 = float(input("Digite a Primeir... |
# Metadata options:
# ---------------------------------
META_COMMENTS_MAP = 'comments-map'
META_KNITTY_COMMENTS_EXT = 'knitty-comments-ext'
META_KNITTY_LANG = 'knitty-lang'
PANDOC_CODECELL_CLASSES = ('code', 'cell')
|
"""
在终端中录入4个同学年龄,打印最小的年龄。
"""
age01 = int(input("请输入第1个同学年龄:"))
age02 = int(input("请输入第2个同学年龄:"))
age03 = int(input("请输入第3个同学年龄:"))
age04 = int(input("请输入第4个同学年龄:"))
min_age = age01
if min_age > age02:
min_age = age02
if min_age > age03:
min_age = age03
if min_age > age04:
min_age = age04
print("年龄最小值是"... |
sv1 = {0: 1, 1: 1, 2: 3}
sv2 = {0: 4, 1: 5, 2: 6}
def sparse_add(sv1, sv2):
"""dict, dict -> dict
Returns a new dictionary that is the sum of the other two.
>>>sparse_add(sv1, sv2)
{0: 5, 1: 6, 2: 9}
"""
newdict = {}
keys = set(sv1.keys()) | set(sv2.keys())
for key in keys:
x... |
load("//sqlc:def.bzl", _sqlc_package = "sqlc_package")
load("//sqlc:def.bzl", _SQLCRelease = "SQLCRelease")
sqlc_package = _sqlc_package
SQLCRelease = _SQLCRelease
|
def COP(T_c):
return 0.35*((45+273.15)/(45-T_c))
def T_from_COP(COP):
return 45 - ((45+273.15)/(COP/0.35)) |
'''
扁平化嵌套列表迭代器
给你一个嵌套的整型列表。请你设计一个迭代器,使其能够遍历这个整型列表中的所有整数。
列表中的每一项或者为一个整数,或者是另一个列表。其中列表的元素也可能是整数或是其他列表。
'''
class NestedInteger:
def __init__(self, val):
self.val = val
def isInteger(self) -> bool:
return isinstance(self.val, int)
def getInteger(self) -> int:
return self.val
... |
class OpenOptException(BaseException):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
#pass
#def ooassert(cond, msg):
# assert cond, msg
def oowarn(msg):
s = oowarn.s + msg
print(s)
return s
oowarn.s = 'OpenOpt Warning: '
errSet = set()
def ... |
def fatorial(x, show=False):
f = 1
for c in range(x, 0, -1):
if show:
print(c, end='')
if c>1:
print(f' x ', end='')
else:
print(' = ', end='')
f *= c
return f
print(fatorial(5, show=True))
|
##parameters=file='', **kw
##
try:
upload = file.read()
except AttributeError:
return context.setStatus(True)
else:
if upload:
return context.setStatus(True, text=upload)
else:
return context.setStatus(True)
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Created by Roger on 2019/11/13
def pprint_tensor(x, name):
print("tensor %s: %s with %s" % (name, x.size(), type(x)))
print(x)
if __name__ == "__main__":
pass
|
def normalize(name):
name = name.capitalize()
return name
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)
|
# Dabeeruddin Syed # Doubly linked list # Bi-directional linked list
class LinkedNode(object):
# Each node has its value and a pointer that points to next node in the Linked List
def __init__(self, value, next = None, previous = None):
self.value = value;
self.next = next;
self.previous... |
class ModelRepository(object):
def __init__(self, *args, **kwargs):
self.obj = None
def __call__(self, func):
def authorize_and_call(*args, **kwargs):
obj = args[0]
if obj is None or obj._repository is None:
raise Exception(
'This obje... |
src =Split('''
''')
component =aos_component('lib_mico_ble_firmware', src)
BT_CHIP = aos_global_config.get('BT_CHIP')
BT_CHIP_REVISION = aos_global_config.get('BT_CHIP_REVISION')
BT_CHIP_XTAL_FREQUENCY = aos_global_config.get('BT_CHIP_XTAL_FREQUENCY')
if BT_CHIP_XTAL_FREQUENCY == None:
src.add_sources( BT_CHIP+BT... |
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
# if not s:
# return 0
# if len(s) == 1:
# return 1
# count = 0
# s0 = set()
# max_ = 0
# for letter in s:
# if letter not in s0:
# count += 1
... |
# Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.
# For example, given the array [2,3,1,2,4,3] and s = 7,
# the subarray [4,3] has the minimal length under the problem constraint.
# click to sh... |
"""
Problem Description:
The numbers 1,2,3.. are known as Natural numbers. Calculate the sum of all the natural numbers from 1 to N, where N will be the input.
Input:
A positive integer N
Output:
Output will be sum of numbers from 1 to N
Constraints:
1<N<1000
Sample Input:
5
Sample Output:
15
"""
n = int(input())... |
class GatewayError(RuntimeError):
def __init__(self, error_code, error_message):
super().__init__(error_message)
self.error_code = error_code
self.error_message = error_message
|
""" Dunder methods is a fancy name for 'under under method under under' or __method__()
They are built-in functions that add functionality to python code and also unlock new features on objects """
class Garage:
""" Stores cars in a garage object """
def __init__(self):
self.cars = []
def __len_... |
#!/usr/bin/env python3
"""
dictmask masks dictionary data based on mask
"""
def dictmask(data, mask, missing_keep=False):
"""dictmask masks dictionary data based on mask"""
if not isinstance(data, dict):
raise ValueError("First argument with data should be dictionary")
if not isinstance(mask, di... |
filename = "test_file.txt"
fh = open(filename, "r")
print(dir(fh))
for line in fh.readlines():
print(line, end="") |
def max_profit_memo(price_list, count, cache):
# base case
if count in [0, 1]:
return price_list[count]
if count in cache:
return cache[count]
if count < len(price_list):
profit = price_list[count]
else:
profit = 0
# recursive case
for i in ... |
def merge(array, left, right):
i = j = k = 0
while i < len(left) and j < len(right):
if left[i][0] <= right[j][0]:
array[k] = left[i]
k += 1
i += 1
else:
array[k] = right[j]
k += 1
j += 1
if len(left) > i:
arra... |
# rule definitions for a level (ex. level 4 is rule_full)
RULE_FULL,RULE_PASSIVE,RULE_PHASE,RULE_FAULT,RULE_HINT = 0,1,2,3,4
# rule index that make up the above level rules (ex. hints are present)
RULEI_ANY, RULEI_SIDE, RULEI_PHASE, RULEI_FAULT, RULEI_HINTDELAY, RULEI_HINTREWARD = 0,1,2,3,4,5
rules = { # [rule_any,... |
# Normal Lambda Expression
lambda_Func = lambda x, y : x + y
print("Normal Lambda : ",lambda_Func(x = 15, y =20))
# Argumental Lambda Expression
lambda_Args = lambda *args : sum(args)
print("Args Lambda : ",lambda_Args(10,20,30,40,50))
# Key Value Argumental Lambda Expression
lambda_KeyArgs = lambda **args : sum(ar... |
def heapify(arr):
n = len(arr)
for i in reversed(range(n//2)):
shift_down(arr, n, i)
def shift_down(arr, n, k):
while 2 * k + 1 < n:
j = 2 * k + 1
if j + 1 < n and arr[j + 1] < arr[j]:
j += 1
if arr[k] <= arr[j]:
break
arr[k], arr[j] = arr[j]... |
# -*- coding: utf-8 -*-
class LossModelBertottiError(Exception):
"""Raised when there is a Loss error"""
pass
|
number_of_chicken_menu = int(input())
number_of_fish_menu = int(input())
number_of_vege_menu = int(input())
chicken_menu = 10.35
fish_menu = 12.40
vege_menu = 8.15
total_chicken = chicken_menu * number_of_chicken_menu
total_fish = fish_menu * number_of_fish_menu
total_vege = vege_menu * number_of_vege_menu
sum_of_al... |
def brick_sort(arr):
n = len(arr)
is_sorted = 0
while is_sorted == 0:
is_sorted = 1
for i in range(1, n-1, 2):
if arr[i] > arr[i+1]:
arr[i], arr[i+1] = arr[i+1], arr[i]
is_sorted = 0
for i in range(0, n-1, 2):
if arr[i] > arr... |
# -*- coding: utf-8 -*-
# !/usr/bin/env python
# MIT License
#
# Copyright (c) 2017 Maxime Busy
#
# 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 limit... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class WeightedQuickUnion(object):
def __init__(self, data=None):
self.id = data
self.weight = [1] * len(data)
self.count = len(data)
def count(self):
return self.count
def find(self, val):
n = val
while self.i... |
""""
a = int(input()) #Рубли 1го товара
b = int(input()) #Копейки 1го товара
c = int(input()) #Рубли 2го товара
d = int(input()) #Копейки 2го товара
cost1 = a * 100 + b
cost2 = c * 100 + d
totalCost = cost1 + cost2
print(totalCost // 100, totalCost % 100)
"""
n = int(input())
print(n % 256) |
# Exercise 1.4.
# Observe that our model of evaluation allows for combinations whose operators are compound expressions.
# Use this observation to describe the behavior of the following procedure:
# (define (a-plus-abs-b a b)
# ((if (> b 0) + -) a b))
def a_plus_abs_b (a, b):
if b > 0:
return a + b
el... |
# Criptografia de Cézar
Alfabeto=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
chave=3
num=int (input(" 1 <--- Criptografar\n 2 <---Descriptografar\n 0 <--- Sair: \n "))
while (num !=0) :
frase_digitada=input("Digite a frase: ")
fra... |
class Solution:
def invalidTransactions(self, transactions: List[str]) -> List[str]:
lis = [s.split(",") for s in transactions]
l = len(transactions)
ans = []
for i in range(0, l):
if int(lis[i][2]) > 1000:
ans.append(transactions[i])
conti... |
def getLockdownFirewallConfigCommand(root):
for command in root.iter('command'):
if 'name' in command.attrib and \
'/usr/bin/firewall-config' in command.attrib['name']:
return command.attrib['name']
return ''
def getEbtablesTablesInUse(root):
tables = []
for rule in roo... |
x = ' \033[34mDESAFIO 07\033[m '
print('{:=^22}'.format(x))
n1 = float(input('Informe a primeira nota: '))
n2 = float(input('Informe a segunda nota: '))
media = (n1+n2) /2
print('A sua media e \033[36m{:.1f}\033[m'.format(media)) |
p=float(input('qual o preco do produto?'))
des=p*5/100
pf=p-des
print('o preco final com desconto de 5% fica ', pf)
|
class Node:
def __init__(self, element):
self.item = element
self.next_link = None
class CircularLinkedList:
def __init__(self):
self.head = Node(None)
self.tail = Node(None)
self.head.next_link = self.tail
self.tail.next_link = self.head
def is_empty(self)... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class HashTable():
def __init__(self, size):
self.size = size
self.slots = [None] * self.size
self.data = [None] * self.size
def put(self, key, data):
hashvalue = self.hashfunction(key, len(self.slots))
if self.slots[has... |
#%%
def test(s,seq):
if s == '' or seq == []:
return s == '' and seq == [] # if both are empty, True. If only one, False.
r = rules[seq[0]]
if '"' in r:
if s[0] in r:
return test(s[1:], seq[1:]) # strip first character
else:
return False # wrong first cha... |
"""
KAIST 단일인증서비스.
KAIST에서 제공하는 단일인증서비스 v3.0(KAIST Single Auth Service v3.0)을
이용하여 인증 처리를 진행하는 앱입니다. DJANGO4KAIST 프로젝트의 ksso 앱을
수정하여 정보제공 동의절차 등의 기능을 추가된 버전입니다.
"""
default_app_config = 'apps.ksso.apps.KssoConfig'
|
#conversor de medida
m = float(input('Digite sua altura em metros: '))
cm = m*100
mm = m*1000
print('Você tem {} metros. Ou {} centimetros. Ou {} milimetros'.format(m, cm, mm)) |
def magic_index(array, seed = 0):
if len(array) == 0: return None
middle = len(array) // 2
if array[middle] == middle + seed: return middle + seed
if middle == 0: return None
if array[middle] > middle:
return magic_index(array[:middle], seed)
return magic_index(array[(middle + 1):], mid... |
class Message(object):
__slots__ = ['opcode', 'position',
'is_event']
|
def range2region(s):
if ';' in s:
parts = s.split(';')
return range2region(parts[0]) + range2region(parts[1])
parts = s.split('-')
parts = [int(x) for x in parts]
return range(parts[0], parts[1]+1)
|
# Get your keys from https://apps.twitter.com/
consumer_key = '*****'
consumer_secret = '*****'
access_token = '*****'
access_token_secret = '*****'
|
def find_pythagorean_triplet_sum(sum):
c = 1
while(c < sum):
c += 1
b = 1
while(b < c):
a = 1
while(a < b):
if (check_pythagorean_triplet(a, b, c) and (a + b + c) == sum):
return [a, b, c]
a += 1
b +=... |
#!/bin/python3
# Copyright 2020 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
"""
BioThings Explorer.
.. moduleauthor:: Jiwen Xin <kevinxin@scripps.edu>
""" |
#!/usr/bin/python3
def format_number(str):
w = ""
for ch in str:
if (ch>='0' and ch<='9') or (ch>='A' and ch<='Z') or (ch >='a' and ch <= 'z') or (ch == ' '):
w+=ch
if w.startswith("91"):
w = w[2:]
return "'"+w+"'"
def format_msg(msg):
w=""
msg = msg.lower()
fo... |
tempCount = 0 #Contador de temporales para su generación
labelCount = 0 #Contador de etiquetas para su generación
entorno = 0 #Contador de entorno
temporales ={} #Diccionario en el que se almacena [id:temporal]
funciones = []#Diccionario para metadata de las funciones
arregloFunciones = [] #Arreglo en donde se guardar... |
def nti_triangle(n):
return n*(n+1)//2
def dodaj_triangle(sez, n):
return sez + [nti_triangle(n)]
def nta_penta(n):
return n*(3*n - 1)//2
def dodaj_pento(sez, n):
return sez + [nta_penta(n)]
def nta_hexa(n):
return n*(2*n - 1)
def dodaj_hexo(sez, n):
return sez + [nta_hexa(n)]
triangli = [1]
t ... |
class Solution:
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
stack, res = [], 0
for i, c in enumerate(s):
if c == '(':
stack.append(i)
else:
if stack and s[stack[-1]] == '(':
... |
# 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
class Solution:
def counting(self, node) -> int:
if not node:
return 0
else:
return self.c... |
"""
N light bulbs are connected by a wire. Each bulb has a switch associated with it, however due to faulty wiring,
a switch also changes the state of all the bulbs to the right of current bulb. Given an initial state of all bulbs,
find the minimum number of switches you have to press to turn on all the bulbs. You can ... |
ABBREVIATIONS = {
'ALLPURP': 'All Purpose',
'AL': 'Aluminum',
'&': 'And',
'APPL': 'Apple',
'APPLS': 'Apples',
'APPLSAUC': 'Applesauce',
'APPROX': 'Approximately',
'ARM&BLD': 'Arm and Blade',
'ART': 'Artificial',
'VIT C': 'Vitamin C',
'ASPRT': 'Aspartame',
'ASPRT-S... |
"""
FIT1008 Prac 5 Task 2
@purpose binary.py
@author Loh Hao Bin 25461257, Derwinn Ee 25216384
@modified 20140823
@created 20140822
"""
def binary():
"""
@purpose This function accepts a positive integer,
and outputs the binary representation of the integer.
@parameter: None
@complexity:
... |
URL = {
"WS_LATEST_BLOCK": "wss://ws.blockchain.info/inv",
"LATEST_BLOCK": "https://blockchain.info/latestblock",
"RAW_BLOCK": "https://blockchain.info/rawblock/",
}
NEW_BLOCK_WAITING_TIME = 10.0
NUMBER_OF_BLOCKS_ON_A_PAGE = 5
NEED_FIELDS_OF_TRANSACTION = (
"block_index",
"hash",
"... |
"""
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/submissions/
1293. Shortest Path in a Grid with Obstacles Elimination (Hard)
[풀이방법]
BFS 탐색 활용한 풀이법
0,0 부터시작해서 x,y가 오른쪽 맨끝에 도달하면 step수 반환
1. 큐에서 pop
2. 방문안했었던 위치면 진행
2-1. 방문표시
2-2. 현재위치에... |
class ProtobufException(Exception):
SYMBOL = 0
NOT_FOUND = 1
@property
def sym(self):
return self._sym
@property
def code(self):
return self._code
def __init__(self, code, sym=None):
self._code = code
self._sym = sym
if code == ProtobufException.SYM... |
"""
"""
greek_letters_map = {
'Alpha': 'Α',
'Beta': 'Β',
'Chi': 'Χ',
'Delta': 'Δ',
'Epsilon': 'Ε',
'Eta': 'Η',
'Gamma': 'Γ',
'Iota': 'Ι',
'Kappa': 'Κ',
'Lamda': 'Λ',
'Mu': 'Μ',
'Nu': 'Ν',
'Omega': 'Ω',
'Omicron': 'Ο',
'Phi': 'Φ',
'Pi': 'Π',
'Psi': 'Ψ'... |
ies = []
ies.append({ "iei" : "", "value" : "Paging identity", "type" : "Paging identity", "reference" : "9.9.3.25A", "presence" : "M", "format" : "V", "length" : "1"})
ies.append({ "iei" : "60", "value" : "CLI", "type" : "CLI", "reference" : "9.9.3.38", "presence" : "O", "format" : "TLV", "length" : "3-14"})
ies.appen... |
#-*- coding:UTF-8 -*-
#!/usr/bin/env python3
str = input('请输入一个数字')
print('您输入了:',str)
input("\n输入 Enter 退出。")
|
def recovery_factor_drygas_waterdrive(swi, Bgi, sgr, Bga):
"recovery factor of dry gas reservoir with waterdrive"
# gas FVF at abandonment pressure (RB/scf)
# sgr: residual gas saturation
rf = (((1 - swi) / Bgi) - (sgr / Bga)) / ((1 - swi) / Bgi)
return(rf)
def recovery_factor_drygas_volumetric(Bgi, Bga):
... |
# Input = [1, 1, 2, 2, 3, 4, 4] : ordered list
# Output = [1, 2, 3, 4]
def remove_dups(l):
if not l or len(l) == 0:
return
f = None
i = 0
while i < len(l):
if l[i] == f:
del l[i]
else:
f = l[i]
i += 1
|
soma = 0
conta = 0
for c in range (1, 7):
numero = int(input('Digite o {} valor: '.format(c)))
if numero%2 == 0:
conta = conta + 1
soma = soma + numero
print('''A soma entre todos algarismos pares escritos é igual a {}.
Você informou {} algarismos pares!'''.format(soma, conta)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.