content stringlengths 7 1.05M |
|---|
__all__ = ['global_config']
class _Config(object):
def __repr__(self):
return repr(self.__dict__)
class RobeepConfig(_Config):
pass
_config = _Config()
_config.robeep = dict()
_config.robeep['name'] = 'robeep agent'
_config.robeep['host'] = 'localhost'
_config.robeep['port'] = 8086
_config.robeep[... |
class Solution:
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
s_list = list(s)
t_list = list(t)
s_list.sort()
t_list.sort()
if (s_list == t_list):
return True
else:
... |
#!/usr/bin/env python
#coding=utf-8
_temple_wd = """
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ECharts</title>
<script src='https://cdn.bootcss.com/echarts/3.2.2/echarts.simple.js'></script>
<script type="text/javascript" src="http://data-visual.cn/datav/src/js/echarts/extension/ech... |
#!/usr/bin/env python3
# https://codeforces.com/problemset/problem/651/A
# 数学,DP,贪心?
# 注意边界条件..
a1,a2 = list(map(int,input().split()))
if a1<=1 and a2<=1:
print(0)
else:
print(a1+a2-3 if (a1-a2)%3==0 else a1+a2-2)
|
base_config = {
'agent': '@spinup_bis.algos.tf2.SUNRISE',
'total_steps': 3000000,
'num_test_episodes': 30,
'ac_kwargs': {
'hidden_sizes': [256, 256],
'activation': 'relu',
},
'ac_number': 5,
'autotune_alpha': True,
'beta_bernoulli': 1.,
}
params_grid = {
'task': [
... |
'''
Exercício Python 14:
Escreva um programa que converta uma temperatura digitando em graus Celsius e converta para graus Fahrenheit.
'''
c = float(input('Digite a temperatura em °c: '))
f = (c * 9/5) + 32
print(f'A temperatura {c:.2f}°c é equivalente a {f:.2f}°f.')
|
teststring = "It was the best of times. It was the worst of times."
print(f"Here's a slice: {teststring[0:5]}")
print(f"Here's another: {teststring[7:]}")
print(f"Here's another: {teststring[:9]}")
print(f"The string length is {len(teststring)}")
mystring = input("Please give me a string: ")
newstring = mystring.rep... |
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 26 17:19:00 2014
@author: Kelly
@version 0.1
"""
class CAResult(object):
def __init__(self, value):
self.NAME_OF_THE_ENTITY
self.countrycode
self.A1= None
self.A2= None
self.A3= None
self.A4= None
self.A... |
# Step 1: Annotate `get_name`.
# Step 2: Annotate `greet`.
# Step 3: Identify the bug in `greet`.
# Step 4: Green sticky on!
def num_vowels(s: str) -> int:
result = 0
for letter in s:
if letter in "aeiouAEIOU":
result += 1
return result
def get_name():
return "YOUR NAME HERE"
def ... |
def tree_maximum(self):
atual = self.root
anterior = None
while atual != None:
anterior = atual
atual = atual.dir
return anterior |
# 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13
for i in range(14):
print(i)
# 42, 43, 44, 45, ..., 99
for i in range(42, 100):
print(i)
# odd numbers between 0 to 100
for i in range(1, 100, 2):
print(i) |
def swap(a, b):
# usage : a, b = swap(a, b)
return b, a
def rotation(matrix):
# 외부 코드 사용 : https://stackoverflow.com/questions/8421337/rotating-a-two-dimensional-array-in-python#answer-48950436
wheel = list(zip(*reversed(matrix)))
return [list(i)[::-1] for i in wheel][::-1]
n, t = [int(i) for i in... |
"""Kata: Find the odd int - Find the int that is in the sequence odd amt times.
#1 Best Practices Solution by cerealdinner, ynnake, sfr, netpsychosis,
VadimPopov, user7514902 (plus 291 more warriors)
def find_it(seq):
for i in seq:
if seq.count(i)%2!=0:
return i
... |
def sumd(a1):
c=0
a=a1
while(a!=0):
c+=int(a%10)
a//=10
return c
n=int(input())
ans=0
for i in range(n-97,n+1):
if(i+sumd(i)+sumd(sumd(i))==n):
ans+=1
print(ans) |
VOCAB_FILE = '/content/drive/Shared drives/BioNLP/project/medical_data/embeddings/MIMIC_BERT/vocab.txt'
BERT_CONFIG_FILE = '/content/drive/Shared drives/BioNLP/project/medical_data/embeddings/MIMIC_BERT/config.json'
# BC5CDR_WEIGHT = 'weights/bc5cdr_wt.pt'
# BIONLP13CG_WEIGHT = 'weights/bionlp13cg_wt.pt'
BERT_WEIGHTS =... |
def minkowski(ratings_1, ratings_2, r):
"""Computes the Minkowski distance.
Both ratings_1 and rating_2 are dictionaries of the form
{'The Strokes: 3.0, 'Slightlyt Stoopid: 2.5}
"""
distance = 0
commonRatings = False
for key in ratings_1:
if key in ratings_2:
distance += ... |
# ----
# |C s |
# | @ S|
# |C s>|
# ----
level.description("Your ears become more in tune with the surroundings. "
"Listen to find enemies and captives!")
level.tip("Use warrior.listen to find spaces with other units, "
"and warrior.direction_of to determine what direction they're in.")
l... |
class Struct:
def __init__(self, id, loci):
self.id = id
self.loci = loci
def make_dict(self, num, mydict, pattrn):
mydict[pattrn] = num
|
CUSTOM_TEMPLATES = {
# https://iot.mi.com/new/doc/embedded-development/ble/object-definition#%E7%89%99%E5%88%B7%E4%BA%8B%E4%BB%B6
'ble_toothbrush_events': "{%- set dat = props.get('event.16') | default('{}',true) | from_json %}"
"{%- set tim = dat.timestamp | default(0,true) | times... |
class GenericsPrettyPrinter:
''' Pretty printing of ugeneric_t instances.
'''
def __init__(self, value):
#print(str(value))
self.v = value
def to_string (self):
t = self.v['t']
v = self.v['v']
#print(str(t))
#print(str(v))
if t['type'] >= 11: # m... |
class TinyIntError(Exception):
def __init__(self):
self.message = 'El numero entregado NO es un dato tipo TinyInt'
def __str__(self):
return self.message
|
'''
SciPy Introduction
What is SciPy?
* SciPy is a scientific computation library that uses NumPy underneath.
* SciPy stands for Scientific Python.
* It provides more utility functions for optimization, stats and signal processing.
* Like NumPy, SciPy is open source so we can use it freely.
* SciPy was created by Num... |
def normalize(name):
if name[-4:] == '.pho':
name = name[:-4]
return "{}.pho".format(name)
|
# 单调栈
n=int(input())
s=list(map(int, input().split()))
stk,tt = [0]*n,0
for i in range(n):
# 当tt不等于0并且栈顶元素大于当前元素,栈顶元素出栈
while tt and stk[tt]>=s[i]:
tt-=1
# 如果栈不为空,那么栈顶元素就是小于当前元素左边最近的元素
if tt:
print(stk[tt],end=' ')
else:
print(-1,end=' ')
# 当前元素入栈
tt+=1
stk[tt]=s[... |
# Author: Andrew Jewett (jewett.aij at g mail)
# License: MIT License (See LICENSE.md)
# Copyright (c) 2013
espt_delim_atom_fields = set(["pos", "type", "v", "f",
"bond",
"temp", "gamma",
"q",
"... |
class tree:
def __init__(self, data, left=None, right=None):
self.data = data
self.left: 'tree|None' = left
self.right: 'tree|None' = right
def inorder(self):
if self.left:
yield from self.left.inorder()
yield self.data
if self.right:
yiel... |
"""
Space : O(n)
Time : O(n)
"""
class Solution:
def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
s1, s2 = '', ''
for x in word1:
s1 += x
for y in word2:
s2 += y
return s1 == s2
|
n = 42
f = -7.03
s = 'string cheese'
# 42 -7.030000 string cheese
print('%d %f %s'% (n, f, s) )
# align to the right
# 42 -7.030000 string cheese
print('%10d %10f %10s'%(n, f, s) )
# align to the right with sign
# +42 -7.030000 string cheese
print('%+10d %+10f %+10s'%(n, f, s) )
# align to the left
#... |
#
# Copyright 2021 Red Hat Inc.
# SPDX-License-Identifier: Apache-2.0
#
"""Masu utility methods."""
|
# 유클리드 알고리즘으로 최대공약수 구하기
def GCD_Euclid_Re(a, b):
if b == 0:
return a
else:
return GCD_Euclid_Re(b, a%b)
print(GCD_Euclid_Re(1, 5))
print(GCD_Euclid_Re(3, 6))
print(GCD_Euclid_Re(60, 24))
print(GCD_Euclid_Re(81, 27))
|
def main():
""" Cuerpo principal """
# Entrada
while True:
cad = str(input('Ingrese un texto: '))
if len(cad) == 0:
print('Error, la cadena no puede ser vacia.')
else:
break
# Proceso
cad_copy = cad.lower()
palindromo = lambda cad: cad == cad... |
class Solution:
"""
@param m: An integer m denotes the size of a backpack
@param A: Given n items with size A[i]
@param V: Given n items with value V[i]
@return: The maximum value
"""
def backPackII(self, m=0, A=None, V=None):
if A is None:
A = []
l = len(A)
... |
# Time Complexity: O(nlogn)
def merge(nums1, nums2):
i, j, merged = 0, 0, []
while i < len(nums1) and j < len(nums2):
if nums1[i] < nums2[j]:
merged.append(nums1[i])
i += 1
else:
merged.append(nums2[j])
j += 1
return merged+nums1[i:]+nums2[j:]... |
n_casos = int(input())
'''
# recursão
def fibonacci(number):
if number == 1:
return 1
if number == 0:
return 0
return fibonacci(number - 1) + fibonacci(number - 2)
'''
# sem recursão
def fibonacci(n):
if n == 0:
return 0
resultado, n_1, n_2 = 1, 1, 1
for i in range(2, n)... |
# Kasia Connell, 2019
# Solution to question 6
# The program will take user's input string and output every second word
# References:
# Ian's video tutorials: https://web.microsoftstream.com/video/909896e3-9d9d-45fe-aba0-a1930fe08a7f
# Programiz: https://www.programiz.com/python-programming/methods/string/join
# Stac... |
class IFormattable:
""" Provides functionality to format the value of an object into a string representation. """
def ZZZ(self):
"""hardcoded/mock instance of the class"""
return IFormattable()
instance=ZZZ()
"""hardcoded/returns an instance of the class"""
def ToString(self,format,formatProvider):
"... |
#!/usr/bin/env python3
# coding:utf-8
"""
在一个二维数组中,每一行都按照从左到右递增的顺序排序,
每一列都按照从上到下递增的顺序排序, 请完成一个函数,输入这样的
一个二维数组和一个整数,判断数组中是否含有该整数.
"""
class Solution(object):
def find_number(self, data, rows, columns, number):
if not data:
return False
if len(data) != rows and any(map(lambda x: len(x... |
SIZE = 20 # quadratic size of labyrinth
WIDTH, HEIGHT = SIZE, SIZE # can be set to any wanted non-quadratic size
WALL_SYMBOL = '#'
EMPTY_SYMBOL = '.'
NUM_WORMHOLES = 20
WORMHOLE_LENGTH = WIDTH * HEIGHT / 33
DIRECTION_CHANGE_CHANCE = 25
|
class Student:
def __init__(self, student_record):
self.id = student_record[0]
self.cognome = student_record[1]
self.nome = student_record[2]
self.matricola = student_record[3]
self.cf = student_record[4]
self.desiderata = student_record[5]
self.sesso = stude... |
# Power digit sum
# Problem 16
# 215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
#
# What is the sum of the digits of the number 21000?
# oh well... python
print(sum((int(c) for c in str(2 ** 1000)))) |
def deprecated(reason):
string_types = (type(b''), type(u''))
if isinstance(reason, string_types):
def decorator(func1):
fmt1 = "Call to deprecated function {name} ({reason})."
@functools.wraps(func1)
def new_func1(*args, **kwargs):
warnings.simplefilter('always', DeprecationWarning)
warnings... |
class MacroFiles:
def cfclos(self, **kwargs):
"""Closes the "command" file.
APDL Command: ``*CFCLOS``
Notes
-----
This command is valid in any processor.
"""
command = f"*CFCLOS,"
return self.run(command, **kwargs)
def cfopen(self, fname="", ext... |
class Pelicula:
def __init__(self, nombre):
self.__nombre = nombre
@property
def nombre(self):
return self.__nombre
@nombre.setter
def nombre(self, nombre):
self.__nombre = nombre
def __str__(self):
return "Pelicula: {}".format(self.__nombre)
if __name... |
#!/usr/bin/python
# t.py
# test program for Python line counter.
print("Hello, World!")
print("Hello again.") # Code line with comment, too.
print('''Hello again again.''')
print("""Looks like a block comment but isn't.""")
''' begin block comment with single quotes
inside block comment
'''
""" begin block c... |
# Radar eletrônico
'''Escreva um programa que leia a velocidade de
um carro. Se ela ultrapassar 80 km/h, mostre uma
mensagem dizendo que ele foi multado. A multa vai
custar R$ 7,00 por cada km acima do limite'''
velocidade = float(input('Qual é a velocidade atual do carro? '))
if velocidade > 80:
print('\033[1;31m... |
# Solution to problem 6
# Rebecca Turley, 2019-02-18
# secondstring.py
# The user is asked to enter a sentence, which is then shortened to x in the programme to simplify working with it (rather than having to use the full sentence each time)
x = input ("Please enter a sentence: ")
# enumerate is a function that re... |
def bytes_to_hex(input_bytes: bytes):
"""Takes in a byte string. Outputs that string as hex"""
return input_bytes.hex()
def hex_to_bytes(input_hex: str):
"""Takes in a hex string. Outputs that string as bytes"""
return bytes.fromhex(input_hex)
|
#
# PySNMP MIB module Nortel-Magellan-Passport-IpiVcMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-Magellan-Passport-IpiVcMIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:18:13 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using P... |
"""
Node is defined as
self.left (the left child of the node)
self.right (the right child of the node)
self.info (the value of the node)
"""
def levelOrder(root):
#Write your code here
q = []
q.append(root)
while q:
n = q[0]
print(n.info,end=" ")
if n.left:
... |
#
# PySNMP MIB module CISCO-SWITCH-USAGE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-SWITCH-USAGE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:13:45 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... |
"""
Question 24 :
Python has many build-in functions, and if you do not know
how to use it, you can read document online or books. But Python
has a build-in socument function for every build-in function.
Write a program to print some Python build-in functions
documents, suchas abs(), int(), input()... |
n = input()
j = [int(x) for x in list(str(n))]
count = 0
for i in range(3):
if j[i] == 1:
count = count + 1
print(count) |
(some_really_long_variable_name_you_should_never_use_1,
some_really_long_variable_name_you_should_never_use_2,
some_really_long_variable_name_you_should_never_use_3) = (1, 2, 3)
print(some_really_long_variable_name_you_should_never_use_1,
some_really_long_variable_name_you_should_never_use_2,
some_really_long_variable_... |
non_agent_args = {
'env': {'help': 'gym environment id', 'required': True},
'n-envs': {
'help': 'Number of environments to create',
'default': 1,
'type': int,
'hp_type': 'categorical',
},
'preprocess': {
'help': 'If specified, states will be treated as atari frame... |
# coding: utf-8
class Parser(object):
def __init__(self):
pass |
"""
* Assignment: Operator String Format
* Required: yes
* Complexity: easy
* Lines of code: 8 lines
* Time: 8 min
English:
1. Overload `format()`
2. Has to convert length units: km, cm, m
3. Round result to one decimal place
4. Run doctests - all must succeed
Polish:
1. Przeciąż `format()`
2.... |
aa = [[0 for x in range(42)] for y in range(42)]
a = [[0 for x in range(42)] for y in range(42)]
version = 0
z = 0
sum = 0
def solve1(out):
global version
num1 = 0
num2 = 0
num3 = 0
z = 256
for i in range(34, 37):
for j in range(39, 42):
if a[i][j] != 0:
num... |
def primefactors(arr):
p = []
for i in range(0, len(arr)):
factor = []
if arr[i] > 1:
for j in range(2, arr[i]+1):
if arr[i]%j == 0:
factor.append(j)
for j in range(0, len(factor)):
if factor[j] > 1:
if facto... |
expected_output ={
"lentry_label": {
16: {
"aal": {
"deagg_vrf_id": 0,
"eos0": {"adj_hdl": "0x65000016", "hw_hdl": "0x7ff7910f32b8"},
"eos1": {"adj_hdl": "0x65000016", "hw_hdl": "0x7ff7910f30a8"},
"id": 1174405122,
"... |
#!/usr/bin/env python3
############################################################################################
# #
# Program purpose: Prints letter 'T' to the console. #
# Program ... |
people = {1: 'fred', 0: 'harry', 9: 'andy'}
print(sorted(people.keys()))
print(sorted(people.values()))
print(sorted(people.items()))
print(dict(sorted(people.items()))) # really???
person = people.get(1, None)
assert person == 'fred'
person = people.get(8, None)
assert person is None
|
def replace(s, old, new):
temp = s.split(old)
temp2 = new.join(temp)
return temp2
print(replace("Mississippi", "i", "I"))
|
class Loader:
@classmethod
def load(cls, slide: "Slide"):
raise NotImplementedError
@classmethod
def close(cls, slide: "Slide"):
raise NotImplementedError
|
#
# @lc app=leetcode.cn id=1196 lang=python3
#
# [1196] filling-bookcase-shelves
#
None
# @lc code=end |
# Validador de CPF
# exemplo 2
cpf = '16899535009'
novo_cpf = cpf[:-2]
soma1 = 0
soma2 = 0
for e, r in enumerate(range(10, 1, -1)):
soma1 = soma1 + int(novo_cpf[e]) * int(r)
digito_1 = 11 - (soma1 % 11)
if digito_1 > 9:
digito_1 = 0
novo_cpf += str(digito_1)
for e, r in enumerate(range(11, 1, -1)):
soma... |
class Meld:
cards = list()
canasta = False
mixed = False
wild = False
cardType = str
def __init__(self, cards):
self.cards = cards
if len(cards) > 7:
self.canasta = True
self.wild = True
self.cardType = '2'
for card in self.cards:
if card['code'][0] != '2' or card['code'][0] != 'X':
self.wil... |
class NervenException(Exception):
def __init__(self, msg):
self.msg = msg
def __repr__(self):
return 'NervenException: %s' % self.msg
class OptionDoesNotExist(NervenException):
def __repr__(self):
return 'Config option %s does not exist.' % self.msg
|
def largest_prime(n):
"Output the largest prime factor of a number"
i = 2
while n != 1:
for i in range(2,n+1):
if n%i == 0:
n = int(n/i)
p = i
break
else:
pass
return p
#The following function is unnc... |
'''
@author: Pranshu Aggarwal
@problem: https://hack.codingblocks.com/app/practice/1/484/problem
'''
def pattern_with_zeros(n):
for row in range(1, n + 1):
for col in range(1, row + 1):
if (col == 1) or (col == row): print(row, end = '')
else: print(0, end = '')
... |
def OddLengthSum(arr):
sum = 0
l = len(arr)
for i in range(l):
for j in range(i, l, 2):
for k in range(i, j + 1, 1):
sum += arr[k]
return sum
arr = [ 1, 4, 2, 5, 3 ]
print(OddLengthSum(arr))
|
def get(client: object) -> dict:
"""Get a list of core school user roles.
Documentation:
https://developer.sky.blackbaud.com/docs/services/school/operations/v1rolesget
Args:
client (object): The SKY API client object.
Returns:
Dictionary of results.
"""
url = f'https:/... |
# -*- encoding: utf-8 -*-
"""
License: MIT
Copyright (c) 2019 - present BlueTensor.ai
"""
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Выполнить индивидуальное задание 1 лабораторной работы 4.1, максимально
задействовав имеющиеся в Python средства перегрузки операторов.
Поле first — целое положительное число, числитель; поле second — целое положительное
число, знаменатель. Реализовать метод ipart() ... |
expressao = str(input("Digite a expressão: "))
parenteses = []
for i,c in enumerate(expressao):
if c == '(' or c == ')':
parenteses.append(c)
direita = esquerda = 0
for p in parenteses:
if p == '(': esquerda += 1
elif p == ')': direita += 1
if parenteses[0] == '(' and parenteses[len(parenteses)-1... |
def maxArea(arr):
pass
if __name__ == '__main__':
arr=[]
print(maxArea(arr)) |
# Copyright (c) 2019 Monolix
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
class Function:
def __init__(self, function, description, returns):
self.function = function
self.name = function.__name__
self.example = function.__doc__
self.de... |
class ImageStatus:
New = "NEW"
Done = "DONE"
Skipped = "SKIPPED"
InProgress = "IN PROGRESS"
ToReview = "TO REVIEW"
AutoLabelled = "AUTO-LABELLED"
class ExportFormat:
JSON_v11 = "json_v1.1"
SEMANTIC_PNG = "semantic_png"
JSON_COCO = "json_coco"
IMAGES = "images"
class SemanticF... |
class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
products.sort()
prefix=""
t=[]
for i in searchWord:
prefix+=i
k=[]
for z in products:
if z[:len(prefix)]==prefix:
... |
N=int(input())
L=[]
dR=[0,1,0,-1]
dC=[-1,0,1,0]
for i in range(N):
L.append(list(map(int,input().split())))
d=0
r=N//2
c=N//2
start=sum([sum(L[i]) for i in range(N)])
def cheak(r,c):
if 0<=r<N and 0<=c<N:
return True
else:
return False
#55
def wind(r,c,d):
sand=L[r][c]
#왼쪽
l... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: wxnacy@gmail.com
"""
"""
class ContinueError(Exception):
pass
class BreakError(Exception):
pass
class ExitError(Exception):
pass
class CommnadNotFoundError(Exception):
pass
|
"""
cmd.do('alter ${1:3fa0}, resi=str(int(resi)+${2:100});sort;')
"""
cmd.do('alter 3fa0, resi=str(int(resi)+100);sort;')
# Description: Add or substract a residue number offset.
# Source: https://www.pymolwiki.org/index.php/Sync
|
def check_sum_two_values():
try:
number_checker = int(input("Digite o número a ser checado: "))
scan_result = False
while len(list_any) != 0 and scan_result == False:
index = 0
while index != len(list_any) and scan_result == False:
current_value = list... |
def leiaInt(msg):
while True:
try:
n = int(input(msg))
except (ValueError, TypeError):
print('\033[0;31mERRO! Digite um código valido:\033[m ')
continue
except KeyboardInterrupt:
print('\033[0;31mUsuario preferiu nao digitar o numero!\033[m ')
... |
class DbCache:
__slots__ = "cache", "database", "iteration"
def __init__(self, database):
self.cache = {}
self.database = database
self.iteration = -1
def get(self, *flags, **forced_flags):
required = {flag: True for flag in flags}
required.update(forced_flags)
... |
#Buttons
SW1 = 21
SW2 = 20
SW3 = 16
#in and out
IN1 = 19
IN2 = 26
OUT1 = 5
OUT2 = 6
OUT3 = 13
#servos
SERVO = 27
# GPI for lcd
LCD_RS = 4
LCD_E = 17
LCD_D4 = 18
LCD_D5 = 22
LCD_D6 = 23
LCD_D7 = 24
|
# Programa que leia sete valores numericos e cadastre os em uma lista unica que mantenha separados os valores pares e impares
# mostre os valores pares e impares de forma crescente
lista = [[], []]
num = 0
for n in range(0, 7):
num = int(input(f'Digite o {n+1} valor: '))
if num % 2 == 0:
lista[0].appe... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"prepare_data": "00_core.ipynb",
"train_valid_split": "00_core.ipynb",
"Availability": "00_core.ipynb",
"LinearMNL": "00_core.ipynb",
"DataLoaders": "00_core.ipynb",
... |
class Solution:
def findPairs(self, nums: List[int], k: int) -> int:
ans = 0
numToIndex = {num: i for i, num in enumerate(nums)}
for i, num in enumerate(nums):
target = num + k
if target in numToIndex and numToIndex[target] != i:
ans += 1
del numToIndex[target]
return ans... |
#!/usr/bin/env python3
# Day 29: 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.
# How many possible unique paths ... |
# Helper module for a test_reflect test
1//0
|
DEBUG = True
#SECRET_KEY = 'not a very secret key'
ADMINS = (
)
#ALLOWED_HOSTS = ["*"]
STATIC_ROOT = '/local/aplus/static/'
MEDIA_ROOT = '/local/aplus/media/'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'aplus',
},
}
CACHES = {
'default': {
'BACKE... |
SAMPLE_DATASET = """HumptyDumptysatonawallHumptyDumptyhadagreatfallAlltheKingshorsesandalltheKingsmenCouldntputHumptyDumptyinhisplaceagain.
22 27 97 102"""
SAMPLE_OUTPUT = "Humpty Dumpty"
def solution(dataset):
words = dataset[0]
indices = [int(indice) for indice in dataset[1].split()]
word1 = words[indic... |
# thingsboardwrapper/device.py
class TENANT(object):
def __init__(self):
pass
def getDevicesIds(self,base_url, session):
response = session.get(base_url +'/api/tenant/devices', params = {'limit':'100'})
json_dict = response.json()
deviceIds = []
for i in range(0, len(json_dict['data'])):
deviceIds.appe... |
def get_secret_key(BASE_DIR):
key = ''
with open(f'{BASE_DIR}/passport/private_key.pem') as secret_file:
key = secret_file.read().replace('\n', '').replace(
'-', '').replace('BEGIN RSA PRIVATE KEY', '').replace('END RSA PRIVATE KEY', '')
return key |
"""
https://leetcode.com/problems/permutations/
Given a collection of distinct integers, return all possible permutations.
"""
|
def main():
num_words = int(input())
for _ in range(num_words):
current_word = input()
if len(current_word) > 10:
print(
f"{current_word[0]}{len(current_word) - 2}{current_word[-1]}")
else:
print(current_word)
main()
|
ALPHA = 0.25
PENALIZATION = 0
|
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def print_list(self):
curr_node = self.head
while curr_node:
print(curr_node.data)
curr_node = curr_node.next
... |
class Animal:
def __init__(self, nombre: str):
self.nombre = nombre
def get_nombre(self) -> str:
pass
def hacer_sonido(self):
pass
animales = {
Animal('león'),
Animal('ratón'),
Animal('Vaca')
}
class Leon(Animal):
def hacer_sonido(self):
return 'Roar'
... |
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done":
break
try:
ii = int(num)
except:
print("Invalid input")
try:
if largest < ii:
largest = ii
if smallest > ii:
smallest = ii
except:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.