content stringlengths 7 1.05M |
|---|
"""
import pytest
import torch
import pytorch_lightning as pl
from torchphysics.solver import PINNModule
from torchphysics.setting import Setting
from torchphysics.models.fcn import SimpleFCN
from torchphysics.utils.plot import Plotter
from torchphysics.problem.condition import DirichletCondition
from torchphysics.pro... |
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
t = -1
for i in range(len(tokens)):
if tokens[i] == '+':
tokens[t - 1] += tokens[t]
t -= 1
elif tokens[i] == '-':
tokens[t - 1] -= tokens[t]
t... |
def rotate(A, B, C):
return (B[0] - A[0]) * (C[1] - B[1]) - (B[1] - A[1]) * (C[0] - B[0])
def jarvismarch(A):
points_count = len(A)
processing_indexes = range(points_count)
# start point
for i in range(1, points_count):
if A[processing_indexes[i]][0] < A[processing_indexes[0]][0]:
... |
class NodoAST:
def __init__(self, contenido):
self._contenido = contenido
self._hijos = []
def getContenido(self):
return self._contenido
def getHijos(self):
return self._hijos
def setHijo(self, hijo):
self._hijos.append(hijo) |
#This program displays a date in the form
#(Month day, Year like March 12, 2014
#ALGORITHM in pseudocode
#1. get a date string in the form mm/dd/yyyy from the user
#2. use the split method to remove the seperator('/')
# and assign the results to a variable.
#3. determine the month the user entered
# if month is 0... |
# coding=utf-8
"""
Package used to unify the different constant values used in entire project
"""
class Consts(object):
"""
Class used to unify the different constant values used in entire project
"""
# BPMN 2.0 element attribute names
id = "id"
name = "name"
# Flow nodes cannot use "name" ... |
"""
All exceptions that can be raised during handling of a weatherapi request.
"""
# Functions that make a request to weatherapi.com have the possibility
# of raising one of these errors depending on the response.
# We use these custom error classes to make the error code more readable
# and easier to handle.
__all__... |
frase = str(input('Digite uma frase: ')).strip().lower()
print('A letra "a" aparecere {} vezes'.format(frase.count('a')))
print('Ela aparece a primeira vez na posicao {}'.format(frase.find('a')+1))
print('Ela aparece pela última vez na posição {}'.format(frase.rfind('a')+1))
|
n1 = float(input('Valor do produto (R$): '))
n2 = float(input('Desconto em porcentagem (%): '))
d = n2/100
d1 = n1*d
nv = n1-d1
print('Novo valor do produto com {}% de desconto: R${:.2f}'.format(n2,nv))
|
mem_key_cache = 'cache'
mem_key_metadata = 'meta'
mem_key_sponsor = 'sponsor'
mem_key_total_open_source_spaces = 'oss'
mem_key_creeps_by_role = 'roles_alive'
mem_key_work_parts_by_role = 'roles_work'
mem_key_carry_parts_by_role = 'roles_carry'
mem_key_creeps_by_role_and_replacement_time = 'rt_map'
mem_key_prepping_defe... |
# -*- coding: utf-8 -*-
# Scrapy settings for watches project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://doc.scrapy.org/en/latest/topics/settings.html
# https://doc.scrapy.org/en/latest/topic... |
#!/usr/bin/env python
#######################################
# Installation module for eyewitness
#######################################
# AUTHOR OF MODULE NAME
AUTHOR="Kirk Hayes (l0gan)"
# DESCRIPTION OF THE MODULE
DESCRIPTION="This module will install/update EyeWitness."
# INSTALL TYPE GIT, SVN, FILE DOWNLOAD
#... |
users = {'email1': 'password1'}
links = [ # fake array of posts
{
'author': 'users',
'date' : "04-08-2017",
'description': 'cool information site',
'link': 'https://www.wikipedia.org',
'tags': None
},
{
'author': 'user',
'date' : "06-08-2017",
... |
# OAuth app keys
DROPBOX_BUSINESS_FILEACCESS_KEY = None
DROPBOX_BUSINESS_FILEACCESS_SECRET = None
DROPBOX_BUSINESS_MANAGEMENT_KEY = None
DROPBOX_BUSINESS_MANAGEMENT_SECRET = None
DROPBOX_BUSINESS_AUTH_CSRF_TOKEN = 'dropboxbusiness-auth-csrf-token'
TEAM_FOLDER_NAME_FORMAT = '{title}_GRDM_{guid}' # available: {title} ... |
colors = {
'default': (0, 'WHITE', 'BLACK', 'NORMAL'),
'title': (1, 'YELLOW', 'BLUE', 'BOLD'),
'status': (2, 'YELLOW', 'BLUE', 'BOLD'),
'error': (3, 'RED', 'BLACK', 'BOLD'),
'highlight': (4, 'YELLOW', 'MAGENTA', 'BOLD'),
}
|
#-----------------problem parameters-----------------------
depot = []
capacity = 120
time_dist_factor = 10 # time per job converted to distance
num_salesmen = 5
# ---------------------------------------------------------
population = 50
nodes = []
node_num = 0
gnd_truth_tsp = []
gnd_truth_dist_list... |
class MeuObjeto:
def __init__(self, id, nome, sobrenome):
self.id = id
self.nome = nome
self.sobrenome = sobrenome
|
def retry_until(condition):
def retry(request):
try:
return request()
except Exception as exception:
if condition(exception):
return retry(request)
else:
raise exception
return retry
def retry(max_retries):
retries = [0]
... |
def list__data_pt():
length = input("\nEnter the Number of Data Point(s) :\t")
try:
if not length.isnumeric() or int(length) <= 0:
raise Exception
except Exception:
print()
print(length)
print("ERROR !!!")
print("Enter a Natural Number Greater t... |
'''
Escreva um programa que receba um número inteiro na entrada e verifique se o número recebido possui ao menos um dígito com um dígito adjacente igual a ele. Caso exista, imprima "sim"; se não existir, imprima "não".
'''
numero = input('Digite um numero: ')
len = len(numero)
x = 10
y = 1
valor = 0
valor_anterior = -... |
fig, ax = plt.subplots()
ax.hist(my_dataset.Zr, bins='auto', density=True, histtype='step', linewidth=2, cumulative=1, color='tab:blue')
ax.set_xlabel('Zr [ppm]')
ax.set_ylabel('Likelihood of occurrence')
|
# Found in https://leetcode.com/problems/two-sum/
#
# Time Complexity: O(n)
# Space Complexity: O(n)
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
haveSeenIt = {}
for idx, val... |
heights = [161, 164, 156, 144, 158, 170, 163, 163, 157]
can_ride_coaster = [can for can in heights if can > 161]
print(can_ride_coaster)
|
"""Common node-related functions
"""
def set_text_on_node(graph, current_node, errorstring, highlight_color, resize):
"""Sets an error string on the current_node in graph.
Also changes the color to red to highlight it.
The parameter current_node should come from the graph that was parsed from file,
... |
def dobro(valor=0, formato=False):
res = valor + valor
return res if formato is False else moeda(res)
def metade(valor=0, formato=False):
res = valor / 2
return res if formato is False else moeda(res)
def aumento(valor = 0, t = 0, formato=False):
res = valor + (valor * t/100)
return res if fo... |
i = 1
while (i<=10):
print(i, end=" ")
i += 1
print()
|
# -*- coding: utf-8 -*-
DESC = "tts-2019-08-23"
INFO = {
"TextToVoice": {
"params": [
{
"name": "Text",
"desc": "合成语音的源文本,按UTF-8编码统一计算。\n中文最大支持100个汉字(全角标点符号算一个汉字);英文最大支持400个字母(半角标点符号算一个字母)。包含空格等字符时需要url encode再传输。"
},
{
"name": "SessionId",
"desc": "一次请求对应一个Sessio... |
def my_function(*args, **kwargs):
for arg in args:
print('arg:', arg)
for key in kwargs.keys():
print('key:', key, 'has value: ', kwargs[key])
my_function('John', 'Denise', daughter='Phoebe', son='Adam')
print('-' * 50)
my_function('Paul', 'Fiona', son_number_one='Andrew', son_number_two='Jame... |
class A:
def __init__(self):
print("A")
super().__init__()
class B1(A):
def __init__(self):
print("B1")
super().__init__()
class B2(A):
def __init__(self):
print("B2")
super().__init__()
class C(B1, A):
def __init__(self):
print("C")
sup... |
props.bf_Shank_Dia = 10.0
#props.bf_Pitch = 1.5 # Coarse
props.bf_Pitch = 1.25 # Fine
props.bf_Crest_Percent = 10
props.bf_Root_Percent = 10
props.bf_Major_Dia = 10.0
props.bf_Minor_Dia = props.bf_Major_Dia - (1.082532 * props.bf_Pitch)
props.bf_Hex_Head_Flat_Distance = 17.0
props.bf_Hex_Head_Height = 6.4
props.bf_Cap... |
#Key:Value
carros={
"Fabricante":"Honda",
"Modelo":"HRV",
"Ano":"2021"
}
carros["Cambio"]="Autmático"
carros.pop("Cambio")
fab=carros.get("Fabricante")
mod=carros["Modelo"]
print(fab)
print(mod)
print(carros["Ano"])
print("-="*35)
for x in carros:
print(x+": "+carros[x])
print("-="*35)
print(f"Tam... |
def dividedtimes(x):
if not isinstance(x, int):
raise TypeError('x must be integer.')
elif x <= 2:
raise ValueError('x must be greater than 2.')
counter = 0
while x >= 2:
x = x / 2
counter += 1
return counter
|
def bubbleSort(list):
for i in range(0,len(list)-1):
for j in range(0,len(list)-i-1):
if list[j] > list[j+1]:
print("\n%d > %d"%(list[j],list[j+1]))
(list[j], list[j+1]) = (list[j+1], list[j])
print("\nNext Pass\n")
print("\nThe elements are now sorted in ascending order:\n")
for i i... |
# pylint: disable=missing-docstring,redefined-builtin,unsubscriptable-object
# pylint: disable=invalid-name,too-few-public-methods,attribute-defined-outside-init
class Repository:
def _transfer(self, bytes=-1):
self._bytesTransfered = 0
bufff = True
while bufff and (bytes < 0 or self._bytesT... |
# Copyright 2016 Check Point Software Technologies LTD
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... |
g=[]
for a in range (1000):
if a%3==0 or a%5==0:
g.append(a)
print(sum(g))
|
#Strinping Names:
Person_name = " Chandler Bing "
print("Person Name with tab space :\t"+Person_name)
print("Person Name in new line :\n"+Person_name)
print("Person Name with space removed from left side :"+Person_name.lstrip())
print("Person Name with space removed from right side :"+Person_name.rstrip())
print("Pe... |
def divisibleSumPairs(n, k, ar):
count = 0
for i in range(len(ar)-1):
for j in range(i+1, len(ar)):
if (ar[i]+ar[j])%k == 0:
count += 1
return count
|
# Python3 Binary Tree to Doubly Linked List
# 10
# / \
# 12 15 ---> head ---> 25<->12<->30<->10<->36<->15
# / \ /
# 25 30 36
#
def tree2DLL(root, head):
if not root:
return
prev = None
tree2DLL(root.left)
if not prev:
head = prev
else:
root.left = prev
pr... |
class Synapse:
def __init__(self, label, input, weight, next_neurons):
self.label = label
self.input = input
self.weight = weight
self.next_neurons = next_neurons
|
'''
Created on 2020-09-10
@author: wf
'''
class Labels(object):
'''
NLTK labels
'''
default=['GPE','PERSON','ORGANIZATION']
geo=['GPE'] |
'''
Substring Concatenation
Asked in: Facebook
https://www.interviewbit.com/problems/substring-concatenation/
You are given a string, S, and a list of words, L, that are all of the same length.
Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any inter... |
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dic = {}
for i in range(len(nums)):
if nums[i] in dic:
return [dic[nums[i]], i]
dic[target - nums[... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 9 14:37:46 2021
@author: alef
"""
# Exemplo quebra de linha
# Uma linha quebrada por contra-barra
a = 7 * 3 + \
5 / 2
# uma lista quebrada por vírgula
b = ['a','b','c',
'd','e']
# uma chama de função quebrada por vírgula
c = list(range(1,
... |
def trunk_1(arr_1, size_1):
result_1 = []
while arr:
pop_data = [arr_1.pop(0) for _ in range(size_1)]
result_1.append(pop_data)
return result_1
def trunk_2(arr_2, size_2):
arrs = []
while len(arr_2) > size_2:
pice = arr_2[:size_2]
arrs.append(pice)
arr_2 = ... |
#!/usr/bin/env python
if __name__ == "__main__":
print("Hello world from copied executable")
|
def entra_numero_inteiro(msg):
num_ok = False
while (not num_ok):
try:
num = int(input(msg))
num_ok = True
except:
print(" NÚMERO INVÁLIDO")
return num
def entra_numero_real(msg):
num_ok = False
while (not num_ok):
try:
... |
data = open("day3.txt", "r").read().splitlines()
openSquare = data[0][0]
tree = data[0][6]
def howManyTrees(right, down):
position = right
iterator = down
trees = 0
openSquares = 0
for rowIterator in range(0, int((len(data))/down) - 1):
row = data[iterator]
res_row = row * 100
obstacle = res_... |
n = int(input())
d = [[0,0,0] for i in range(n + 1)]
for i in range(1, n + 1):
(r, g, b) = [int(i) for i in input().split()]
d[i][0] = r + min(d[i - 1][1], d[i - 1][2])
d[i][1] = g + min(d[i - 1][0], d[i - 1][2])
d[i][2] = b + min(d[i - 1][0], d[i - 1][1])
print(min(d[n])) |
x = [1,2,3]
def weird(num, default_ls=None):
default_ls = default_ls or []
default_ls.append(num)
print(default_ls)
return default_ls
weird(1)
weird(2)
weird(3)
ls = list()
ls = weird(99, ls) # [99]
print(ls)
weird(1000001, ls) # [99, 100001] [10000001]
"""
MacBook-Pro:random_python_stuff demous... |
# Test passwords are randomly hashed
def test_passwords_hashed_randomly(test_app, test_database, add_user):
user_one = add_user(
"test_user_one", "test_user_one@mail.com", "test_password"
)
user_two = add_user(
"test_user_two", "test_user_two@mail.com", "test_password"
)
assert user... |
def karatsuba(x: int, y: int) -> int:
"""Multiply two numbers using the Karatsuba algorithm
Args:
x (int): the first integer to be multiplied
y (int): the second integer to be multiplied
Returns:
int: the result of the multiplication
"""
# Break the recursion written below... |
# Defination for mathematical operation
def math(token_ip_stream,toko):
if token_ip_stream[0][0] == 'INOUT' and token_ip_stream[1][0] == 'IDENTIFIRE' and token_ip_stream[2][1] == "=" and token_ip_stream[3][1] == toko[0][0] and token_ip_stream[5][1] == toko[1][0] and token_ip_stream[6][0] == "STATEMENT_END" :
... |
# Given an array of integers, write a function that returns true if there is a triplet (a, b, c) that satisfies a2 + b2 = c2.
# First way is brute force
def is_triplet(array):
# Base case, if array is under 3 elements, not possible
if len(array) < 3:
return False
# Iterate through first element... |
#!/usr/bin/python3
"""
Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:
2^2=4, 2^3=8, 2^4=16, 2^5=32
3^2=9, 3^3=27, 3^4=81, 3^5=243
4^2=16, 4^3=64, 4^4=256, 4^5=1024
5^2=25, 5^3=125, 5^4=625, 5^5=3125
If they are then placed in numerical order, with any repeats removed, we get ... |
climacell_yr_map = {
"6201": "48", # heavy freezing rain
"6001": "12", # freezing rain
"6200": "47", # light freezing rain
"6000": "47", # freeing drizzle
"7101": "48", # heavy ice pellets
"7000": "12", # ice pellets
"7102": "47", # light ice pellets
"5101": "50", # heavy snow
"5000... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 22 14:49:25 2018
@author: User
"""
class Airlines():
def __init__(self, code, date, fare):
self.code = code
self.date = date
self.fare = int(fare)
def getDates(self):
print( self.date)
def getFares(self):
... |
# read answer, context, question
# generate vocabulary file for elmo batcher
pre = ['dev', 'train']
fs = ['answer', 'context', 'question']
result = set()
for p in pre:
for f in fs:
print ('Processing ' + p + '.' +f)
with open('../../data/' + p + '.' + f) as ff:
content = ff.readlines()
... |
'''
Insert 5 numbers in the right position without using .sort()
Then show the list orderned
'''
my_list = []
for c in range(0, 5):
num = int(input('Type a number: '))
if c == 0 or num > my_list[-1]:
my_list.append(num)
print('Add this number at the end.')
else:
pos = 0
while... |
# Wi-Fi Diagnostic Tree
print(' Please reboot your computer and try to connect.')
answer = input('Did that fix the problem? ')
if answer != 'yes':
print('Reboot your computer and try to connect.')
answer = input('Did that fix the problem? ')
if answer != 'yes':
print('Make sure the cables between t... |
class Dictionary:
def __init__(self):
self.words = set()
def check(self, word):
return word.lower() in self.words
def load(self, dictionary):
file = open(dictionary, 'r')
for line in file:
self.words.add(line.rstrip('\n'))
file.close()
return True
def size(self):
return len(self.words)
def un... |
class Map:
def __init__(self, x, y):
self.wall = False
self.small_dot = False
self.big_dot = False
self.eaten = False
self.x = x
self.y = y
#--- drawing on map ---#
def draw_dot(self):
if self.small_dot:
if not self.eaten:
... |
# 入力
N, K = map(int, input().split())
# 出力
ans = N - K + 1
print(ans) |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
### CONTROLS (non-tunable) ###
# general
TYPE_OF_RUN = train # train, test, test_episodes, render
LOAD_MODEL_FROM = None
SAVE_MODELS_TO = models/debugging_wmg_dynamic_state_Collins2018_train10_test15.pth
# worker.py
ENV = Collins2018_Env
EN... |
"""
# Startup script
Python script to set certain states at HA start and notify.
This unifies various automations and HA scripts in a simpler one.
"""
SWITCH_EXPERT_MODE = 'input_boolean.show_expert_mode'
# 'expert mode' for filtering groups and visibility control for ESP modules
last_state = hass.states.get(SWITCH... |
class B:
pass
class A:
pass |
# ###############################
# Truthiness of an element:
# ###############################
def print_truthiness(msg, exp):
print(("TRUE" if exp else "FALSE") + " <-- " + msg)
print_truthiness("Testing True", True)
print_truthiness("Testing False", False)
# for sequences
seq = []
print_truthiness("Empty li... |
class Solution:
def maxScore(self, cards, k):
pre = [0]
for card in cards:
pre.append(pre[-1] + card)
ans = 0
n = len(pre)
for i in range(k + 1):
ans = max(pre[i] + pre[-1] - pre[n - 1 - k + i], ans)
return ans
|
número = int(input('\033[35mDigite um número inteiro:\033[m '))
print('Escolha uma das bases para conversão: ')
print('\033[33;1m[1]\033[m converter para \033[33;4;1mBINÁRIO\033[m')
print('\033[36;1m[2]\033[m converter para \033[36;4;1mOCTAL\033[m')
print('\033[34;1m[3]\033[m converter para \033[34;4;1mHEXADECIMAL\033[... |
'''fazer com if dentro do print
fazer com recebe multiplicação *= ou x = x * y'''
num = int(input('Digite um valor p/ ver seu fatorial: '))
c = num - 1
d = num
f = num + 1
while c > 0:
num *= c
f -= 1
print('{} x '.format(f) if f > 2 else '2 x 1 = {}'.format(num),end='')
c -= 1
print('\nFatorial de {}! ... |
def fitness(L, books, D, B_scores, L_signuptimes, L_shipperday):
#assert len(books) == len(L)
score = 0.
d = 0
for l in L:
d += L_signuptimes[l]
number_of_books = (D - d) * L_shipperday[l]
score += sum(books[l][:number_of_books])
return score
|
MESSAGE_PRIORITY = (
(-2, 'Stumm'),
(-1, 'Ruhig'),
(0, 'Normal'),
(1, 'Wichtig'),
(2, 'Emergency'),
) |
class AsyncClass:
async def do_coroutine(self):
"""A documented coroutine function"""
attr_coro_result = await _other_coro_func() # NOQA
async def _other_coro_func():
return "run"
|
class ProcessError(Exception):
"""Exception raised when a process exits with a non-zero exit code."""
def __init__(self, message):
self.message = message
|
# Copyright 2016 Savoir-faire Linux
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
{
"name": "Web No Bubble",
"version": "14.0.1.0.0",
"author": "Savoir-faire Linux, " "Odoo Community Association (OCA)",
"website": "https://github.com/OCA/web",
"license": "AGPL-3",
"category": ... |
# https://adventofcode.com/2019/day/5
#
# --- Day 2: 1202 Program Alarm ---
#
# --- Day 5: Sunny with a Chance of Asteroids ---
#
def loadintCode(fname='input'):
with open(fname, 'r') as f:
l = list(f.read().split(','))
p = [int(x) for x in l]
return p
def printIndexValue(L, pos=0):
... |
class Phone(object):
def __init__(self, phone_number):
phone_number = [char for char in phone_number if char.isdigit()]
if phone_number[:1] == ['1']:
phone_number = phone_number[1:]
if len(phone_number) != 10:
raise ValueError("Insufficient Digits")
if (int(ph... |
# -*- coding: utf-8 -*-
__title__ = u'django-flexisettings'
# semantic versioning, check http://semver.org/
__version__ = u'0.3.1'
__author__ = u'Stefan Berder <stefan.berder@ledapei.com>'
__copyright__ = u'Copyright 2012-2013, Heatwave fashion Ltd., ' \
u'all rights reserved'
|
def solution(p):
answer = p + 1
while(not isBeautifulYear(answer)):
answer += 1
return answer
def isBeautifulYear(year):
years = list(map(int, str(year)))
return len(set([x for x in years])) == len(years)
print(solution(1987)) |
def split_and_add(numbers, n):
temp=[]
count=0
while count<n:
for i in range(0,len(numbers)//2):
temp.append(numbers[0])
numbers.pop(0)
if not temp:
return numbers
if len(temp)<len(numbers):
for i in range(0,len(temp)):
... |
DN = int(input('Qual o seu ano de nascimento?'))
idade = 2022 - DN
if DN >= 2013:
print('A categoria para quem tem {} anos na Confederação Nacional de Natação é: MIRIM'.format(idade))
elif DN >= 2008:
print('A categoria para quem tem {} anos na Confederação Nacional de Natação é: INFANTIL'.format(idade))
elif D... |
if __name__ == "__main__":
with open("file.txt", "r", encoding="utf-8") as f:
a = f.readlines()
for i in a:
if "," in i:
print(i)
|
description='HRPT Graphit Filter via SPS-S5'
devices = dict(
graphit=device('nicos_sinq.amor.devices.sps_switch.SpsSwitch',
description='Graphit filter controlled by SPS',
epicstimeout=3.0,
readpv='SQ:HRPT:SPS1:DigitalInput',
... |
"""
Notes:
This is more "find maximum profit" rather than finding best times to buy and sell stock.
"""
class Solution:
def max_profit(self, prices: [int]) -> int:
profit = 0
for stock in range(len(prices)-1):
if prices[stock+1] > prices[stock]:
profit += prices[stock+1... |
# Copyright 2019 The SQLNet Company GmbH
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, ... |
########
# autora: danielle8farias@gmail.com
# repositório: https://github.com/danielle8farias
# Descrição: Função que recebe dois números e retorna a soma entre eles.
########
def somar(n1, n2):
return n1 + n2
#testes
def test_soma():
assert somar(1,2) == 3
def test_soma1():
assert somar(5,5) == 10
d... |
score=int(input("请输入分数: "))
if 90<score<=100:
print("优秀")
elif 60<=score<=90:
print("及格")
elif 0<=score<60:
print("不及格")
else:
print("不合法分数输入")
string1="qwertyuiopasdfghjklzxcvbnm"
print(string1[:3])
print(string1[1:-1])
print(string1[::2])
a=10; b=20
a,b=b,a
print(a,b)
a=10; b=20
c=a+b
a=c-a
b=c-b
prin... |
# BUILD FILE SYNTAX: SKYLARK
SE_VERSION = '3.11.0'
|
def main(filepath):
rows = []
#file load
with open(filepath) as file:
for line in file:
rows.append(line)
counter = 0
counter2 = 0
for entry in rows:
entry = entry.split(" ")
letter = entry[1][0]
entry[0] = entry[0].split("-")
low =... |
class Solution:
def maxSumSubmatrix(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
if not any(matrix):
return 0
m, n = len(matrix), len(matrix[0])
res = float('-inf')
for left in range(n):
... |
#!/local/usr/bin/python3
"""
better case: O(N)
medium case: O(Nˆ2)
worst case: O(Nˆ2)
"""
def solution(arr, N):
if not N:
return arr
for i in range(N-1):
if arr[i] > arr[i+1]:
swap = arr[i]
arr[i] = arr[i+1]
arr[i+1] = swap
solution(arr, N-1)
arr = [3,4,2,20,3,5,9,8,12]
solution(arr, len(arr))
|
# coding: utf-8
"""*****************************************************************************
* Copyright (C) 2018 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* re... |
x = range(1, 5, 9)
for n in x:
print(n)
|
class StudySeries(object):
def __init__(self, study_object, study_data=None):
'''
Takes study object
'''
assert hasattr(study_object, "__call__"), "invalid study object"
self.study = study_object
if study_data:
self.update(study... |
TRPOconfig = {
'cg_damping': 1e-3,
'GAE_lambda': 0.,
'reward_decay': 0.98,
'max_kl_divergence': 2e-5,
'hidden_layers': [256, 256, 256],
'hidden_layers_v': [256, 256, 256],
'max_grad_norm': None,
'value_lr': 5e-4,
'train_v_iters': 20,
'lr_pi': 5e-4,
'steps_per_iter'... |
default_window_width = -1
default_window_height = -1
default_window_title = 'FC-POS'
default_nest_window_margin = 0
min_window_width = 800
min_window_height = 800 * 0.618
language_locale = {
'25': {
'name': 'Chinese',
'locale': 'zh_CN'
},
'59': {
'name': 'Japanese',
'locale':... |
"""
Crie um programa onde o usuário digite uma expressão quaquer que use parenteses
o aplicativo tem de analisar se a expressao esta com parenteses abertos e fechados na ordem correta
"""
chave = []
expressao = input('Digite a expressão: ')
for v in expressao:
if v == '(':
chave.append('(')
elif v == ')... |
transverse_run5 = [
6165044,
6165046,
6165047,
6165055,
6165058,
6165059,
6165063,
6166051,
6166052,
6166054,
6166055,
6166056,
6166057,
6166059,
6166060,
6166061,
6166070,
6166071,
6166073,
6166074,
6166075,
6166076,
6166090,
6166091,
#6166101, ## no relative luminosities
6167079,
6167083,
6167088
]
## transverse run... |
class Details:
def __init__(self, details):
self.details = details
def __getattr__(self, attr):
if attr in self.details:
return self.details[attr]
else:
raise AttributeError('{attr} is not a valid attribute of Details'.format(attr))
@property
def all(se... |
# Aula 18 - Listas (Parte 2)
teste = list()
teste.append('Marieliton')
teste.append(33)
galera = list()
#galera.append(teste) # fazer isso cria uma dependencia entre as listas
galera.append(teste[:]) # isso faz a copia da lista sem criar dependencia
print(galera)
teste[0] = 'Maria'
teste[1] = 22
print(teste)
galera.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.