content stringlengths 7 1.05M |
|---|
test = { 'name': 'q3_2_2',
'points': 1,
'suites': [ { 'cases': [ { 'code': '>>> from collections import Counter;\n'
">>> g = train_movies.column('Genre');\n"
">>> r = np.where(test_movies['Title'] == 'tron')[... |
# -*- coding: utf-8 -*-
"""
FlowrouteMessagingLib.APIException
Copyright Flowroute, Inc. 2016
"""
class APIException(Exception):
"""
Class that handles HTTP Exceptions when fetching API Endpoints.
Attributes:
reason (string): The reason (or error message) for the Exception ... |
#Given 2 ints, a and b, return True if one if them is 10 or if their sum is 10.
#makes10(9, 10) → True
#makes10(9, 9) → False
#makes10(1, 9) → True
def makes10(a,b):
if a+b ==10 or a == 10 or b == 10:
return True
else:
return False |
menu='MENU DE INTERAÇÃO'
print('=-'*30)
print(menu.center(55))
print('=-'*30)
print('[1] Cadastro de Produtos')
print('[2] Cadastro de Usuário')
print('[3] Cadastro de Mercados')
print('[4] Comparar preços de produtos')
print('[5] Comparar preços por cesta básica')
print('=-'*30)
RespostaUsuario=int(input('Resposta: ... |
x=10
y=50
z=30
a=3.9
b="roman regions"
c="brock leasner suplex city"
|
"""NICOS GUI default configuration."""
main_window = tabbed(
('Instrument', docked(
vsplit(
panel('nicos.clients.gui.panels.status.ScriptStatusPanel'),
# panel('nicos.clients.gui.panels.watch.WatchPanel'),
panel('nicos.clients.gui.panels.console.ConsolePanel',
... |
# 914000500
ATHENA = 1209007
sm.setSpeakerID(ATHENA)
if sm.sendAskYesNo("You made it back safely! What about the child?! Did you bring the child with you?!"):
sm.completeQuest(parentID)
sm.consumeItem(4001271)
sm.flipSpeaker()
sm.sendNext("Oh, what a relief. I'm so glad...")
sm.setPlayerAsSpeaker... |
# 계산기 내부 프로그램
class Calc_program():
def __init__(self, input_data_R): # 인스턴스 메소드
self.input_data = input_data_R # 외부에서 들어온 수식
self.int_data = [] # 숫자 리스트
self.int_refined_data = [] # 정제된 숫자 리스트
self.str_data = [] # 문자 리스트
self.int1 =0 # 더해진 값
self.str_add = '' ... |
"""
P/L -- profit/loss
Calls (break_even and P/L)
Puts (break_even and P/L)
Options are made up of:
- Intrinsic Value
- Extrinsic Value
Add the shebang (first line):
!/usr/bin/env python3
Make it executable:
chmod +x options.py
Run it with:
./options.py
Variables:
S - current price
K - strike price
cprice... |
##Clock in pt2thon##
t1 = input("Init schedule : ") # first schedule
HH1 = int(t1[0]+t1[1])
MM1 = int(t1[3]+t1[4])
SS1 = int(t1[6]+t1[7])
t2 = input("Final schedule : ") # second schedule
HH2 = int(t2[0]+t2[1])
MM2 = int(t2[3]+t2[4])
SS2 = int(t2[6]+t2[7])
tt1 = (HH1*3600)+(MM1*60)+SS1 # total schedule 1
tt2 = (HH2*... |
class PostmarkerException(Exception):
"""Base class for all exceptions in Postmarker."""
class ClientError(PostmarkerException):
"""Indicates client's error."""
def __init__(self, *args, **kwargs):
self.error_code = kwargs.pop("error_code")
super().__init__(*args, **kwargs)
class SpamAs... |
input = """
x | y.
:- x.
a :- x.
a :- not y.
a :- b.
b :- a.
t :- not a, not b, not x.
"""
output = """
x | y.
:- x.
a :- x.
a :- not y.
a :- b.
b :- a.
t :- not a, not b, not x.
"""
|
#!/bin/python3
# https://www.urionlinejudge.com.br/judge/en/problems/view/1005
def main():
A, B = float(input()), float(input())
wA = 3.5
wB = 7.5
MEDIA = ((A * wA) + (B * wB)) / (wA + wB)
print("MEDIA =", format(MEDIA, '.5f'))
# Start the execution if it's the main script
if __name__ == "__m... |
# Aula 04 - Desafio 2
#
dia = input('Qual o dia do seu nascimento? ')
mes = input('Qual o mês do seu nascimento? ')
ano = input('Qual o ano do seu nascimento? ')
print('\n', 'Você nasceu no dia', dia, 'do mês', mes, 'do ano de', ano + '.', 'Correto?')
|
def test_geo_zones(app):
app.wd.find_element_by_xpath("//a//span[text()='Geo Zones']").click()
counties = app.wd.find_elements_by_xpath("//tr[@class='row']//a[not(@title)]")
for i in range(len(counties)):
app.wd.find_element_by_xpath("(//tr[@class='row']//a[not(@title)])[%s+1]" % i).click()
... |
def maior_elemento(lista):
comparador = -9999
for item in lista:
if item > comparador:
comparador = item
return comparador
|
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT license.
# Target word length. Currently set to match the word length of Arduino (2 bytes)
wordLength = 16
# Range of max scale factor used for exploration
maxScaleRange = 0, -wordLength
# tanh approximation limit
tanhLimit = 1.0
#... |
class Solution:
def findMin(self, nums: 'List[int]') -> 'int':
left, right = 0, len(nums)
if right == 0:
return -1
result = nums[0]
while left + 1 < right:
mid = (left + right) >> 1
result = min(result, nums[mid])
if nums[mid] < nums[le... |
def dependencies(name, dependencies, prefix = "deb", parent_bzl_file = ""):
extra_deps_tools = []
parent_bzl_file_location = ""
if parent_bzl_file:
extra_deps_tools = [parent_bzl_file]
parent_bzl_file_location = "$(location " + parent_bzl_file + ")"
substitute_dependencies_target = target_path("substit... |
# Exercise 5: Bottle Deposits
# (Solved—15 Lines)
# In many jurisdictions a small deposit is added to drink containers to encourage people
# to recycle them. In one particular jurisdiction, drink containers holding one liter or
# less have a $0.10 deposit, and drink containers holding more than one liter have a
# ... |
def bipartido(matriz):
result = ""
Bipartido = True
u =[]
v =[]
def adjacentes(y):
if len(v) > 1:
for i in range(len(v)):
for j in range(len(v)):
z = v[i]
k = v[j]
if matriz[z][k] != 0:
... |
class SyncScheduler(object):
def call(self, fn):
try:
fn()
except:
pass
|
"""
:Authors: - Wilker Aziz
"""
|
格式字符串 = "待办清单: {}"
待办清单 = '''
\t* 吃饭
\t* 睡觉
\t* 打豆豆
'''
print(格式字符串.format(待办清单)) |
innereye_ssl_checkpoint = "hsharma_panda_explore:hsharma_panda_explore_1638437076_357167ae"
innereye_ssl_checkpoint_binary = "hsharma_panda_tiles_ssl:hsharma_panda_tiles_ssl_1639766433_161e03b9"
innereye_ssl_checkpoint_crck_4ws = "ModifyOldSSLCheckpoint:a9259fdb-3964-4c5b-8962-4660e0b79d44"
innereye_ssl_checkpoint_crck... |
'''
Created on 21.05.2019
@author: LH
'''
class TMCM_6212():
def __init__(self, connection):
self.__connection = connection
self.GPs = _GPs
self.APs = _APs
self.MOTORS = 6
def showChipInfo(self):
("TMCM-6212 is a six axes controller/driver module for 2-phase bipolar ... |
#!/usr/bin/env python
##############################################################################
# Written by: Brian G. Merrell <bgmerrell@novell.com>
# Date: May 23 2008
# Description: A description of the remote test machines
#
#
###############################################... |
BLACK = u'\33[40m'
# Default dark background colors
RED = u'\33[41m'
GREEN = u'\33[42m'
YELLOW = u'\33[43m'
BLUE = u'\33[44m'
MAGENTA = u'\33[45m'
CYAN = u'\33[46m'
WHITE = u'\33[47m'
GREY = u'\33[100m'
# Light background colors
LRED = u'\33[101m'
LGREEN = u'\33[102m'
LYELLOW = u'\33[103m'
LBLUE = u'\33[104m'
LMAGEN... |
'''
Given n processes, each process has a unique PID (process id) and its PPID (parent process id).
Each process only has one parent process, but may have one or more children processes. This is just like a tree structure. Only one process has PPID that is 0, which means this process has no parent process. All the PID... |
class Profile:
def __init__(self):
self.id = 0
self.name = ''
self.ranked_pp = 0
self.unranked_pp = 0
self.total_pp = 0
self.rank = 0
class Beatmap:
def __init__(self):
self.id = 0
self.creator = ''
self.approach_rate = 0
self.is_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
pipes = "0 <-> 122, 874, 1940\n1 <-> 1099\n2 <-> 743\n3 <-> 594, 1258\n4 <-> 4, 1473\n5 <-> 109, 628, 1133, 1605\n6 <-> 470, 561, 600, 1272, 1634\n7 <-> 7, 1058, 1074, 1136\n8 <-> 879\n9 <-> 9\n10 <-> 10, 1736\n11 <-> 148, 1826\n12 <-> 774, 1394, 1495\n13 <-> 178, 410\n14 ... |
"""EntryPointCalculator
Entry/Buy: price > btm + atr/2
Exit/Sell: price < top - atr/2
"""
BUY = 1
SELL = 2
class EntryPointCalculator(object):
def __init__(self, trade_type=BUY, atr_factor=1.0):
self.trade_type = trade_type
self.atr_factor = atr_factor
self.pivot = None
self.wait... |
class Edge:
"""Lightweight edge structure for a graph."""
__slots__ = "_origin","_destination","_element"
def __init__(self, u, v, x):
"""Do not call constructor directly. Use Graph's insert_edge(u,v,x)."""
self._origin = u
self._destination = v
self._element = x
def endpoints(self):
"""Return (u,v) tup... |
class InvalidHeader(Exception):
"""
- **API Code** : 1000
- **API Message** : Invalid header
"""
def __init__(*args, **kwargs):
Exception.__init__(*args, **kwargs)
class InvalidRequest(Exception):
"""
- **API Code** : 1001
- **API Message** : Bad request. Error code-1001
"""... |
def generate_group_key(name: str):
return {
'PK': f'GROUP#{name.upper()}',
'SK': f'GROUP#{name.upper()}'
}
|
power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate... |
N = int(input())
ans = 0
def sum(n):
return n * (n + 1) // 2
for i in range(N):
A, B = map(int, input().split())
ans += sum(B) - sum(A-1)
print(ans) |
"""
Helper functions that parse desired information from Trello cards (aka books).
"""
def get_created_action(card):
"""
Return the date when a card was created.
"""
if not card.actions:
return
for action in card.actions:
if action['type'] == 'createCard':
return action... |
class Colors:
def __init__(self, mode):
if(not mode):
self.block_E = (205,193,181)
self.scoreboard = (187,173,160)
self.block_2 = (238, 228, 218)
self.block_4 = (237, 224, 200)
self.block_8 = (242, 177, 121)
self.block_16 = (245, 149, ... |
class Solution:
def wallsAndGates(self, rooms: List[List[int]]) -> None:
"""
Do not return anything, modify rooms in-place instead.
"""
INF = 2147483647
queue = [(i, j) for i, row in enumerate(rooms) for j, val in enumerate(row) if not val]
for i, j in queue:
... |
"""CHAPPS Tests
In designing an application like CHAPPS and learning how to test in Python at
the same time, it has been hard to follow a strictly test-driven strategy.
Nevertheless, I have striven to ensure that all features are covered with
tests.
Right now the main deficiency in testing is testing of the install p... |
class Solution:
def freqAlphabets(self, s: str) -> str:
map_table = {}
for c in 'abcdefghi':
map_table[str(ord(c) - ord('a') + 1)] = c
for c in 'jklmnopqrstuvwxyz':
map_table[str(ord(c) - ord('j') + 10) + '#'] = c
res = []
p = 0
while p < len(s... |
"""
20. As Organizações Tabajara resolveram dar um abono aos seus colaboradores em reconhecimento ao bom resultado alcançado durante o ano que passou. Para isto contratou você para desenvolver a aplicação que servirá como uma projeção de quanto será gasto com o pagamento deste abono.
Após reuniões envolvendo a ... |
def sort012( a, arr_size):
lo = 0
hi = arr_size - 1
mid = 0
while mid <= hi:
if a[mid] == 0:
a[lo], a[mid] = a[mid], a[lo]
lo = lo + 1
mid = mid + 1
elif a[mid] == 1:
mid = mid + 1
else:
a[mid], a[hi] = a[hi]... |
'''
Jean-Luc Jackson & Connor Lester
CEE cinco zero cinco HW #4
11/07/16
'''
class Path(object):
'''
Class Hosts a Path Object.
Contained Attributes - Path ID, Length, and Node/Line Histories.
'''
def __init__(self, nodeHistory=[], lineHistory=[], length=0.0):
'''
CHANGE SO THAT pa... |
[
[float("NaN"), float("NaN"), 99.67229382, 40.73319756],
[float("NaN"), float("NaN"), 84.22728964, 73.36769715],
[float("NaN"), float("NaN"), 99.73572432, 78.98000129],
[float("NaN"), float("NaN"), 99.04333678, 67.27961222],
[float("NaN"), float("NaN"), 97.11394797, 73.68663514],
[float("NaN"),... |
#
# PySNMP MIB module IPFILTER (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IPFILTER
# Produced by pysmi-0.3.4 at Wed May 1 13:55:54 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:1... |
bunker = {category: [] for category in input().split(", ")}
n = int(input())
bunker['all_items_count'] = 0
bunker['all_quality'] = 0
for _ in range(n):
category, item_name, item_params = input().split(" - ")
item_quantity = int(item_params.split(";")[0].split(":")[1])
item_quality = int(item_params.split("... |
"""
Problem 8
-----------
The four adjacent digits in the 1000-digit number
that have the greatest product are 9 × 9 × 8 × 9 = 5832.
[moved to data/008.txt]
Find the thirteen adjacent digits in the 1000-digit number
that have the greatest product. What is the value of this product?
"""
with open('data/008.txt', 'rt... |
#
# PySNMP MIB module CPQCMC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CPQCMC-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:11:28 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:... |
nome = str(input('Digite seu nome: ')).strip().capitalize()
if nome.upper() == 'GUSTAVO':
print(f'Bom dia {nome}, que nome horrivel você tem!')
else:
print(f'Bom dia {nome}, que nome lindo você tem!') |
'''Faça um programa que leia o ano de nascimento de um jovem e informe, de acordo com a sua idade,
se ele ainda vai se alistar ao serviço militar, se é a hora exata de se alistar ou
se já passou do tempo do alistamento. Seu programa também deverá mostrar o tempo que falta ou que passou do prazo.'''
idade=int(input('Em... |
terminal_colors = {
"green": "\033[32m",
"red": "\033[91m",
"reset": "\033[0m",
"yellow": "\033[93m"
}
class SignalsError(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return colorize_string("red", "ERROR: {}".format(self.msg))
def colorize_string(co... |
def ts_test(test_file=None, more_data=[]):
native.sh_test(
name = test_file + "_test",
size = "small",
srcs = ["//util:run_tests.sh"],
# deps = [""],
data = [
test_file,
"@nodejs//:bin/node",
"//:node_modules/mocha/bin/mocha",
"... |
class Solution:
def dominantIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
maxnum = -1
secondmaxnum = -1
maxindex = 0
for i, num in enumerate(nums):
if num > maxnum:
secondmaxnum = maxnum
maxnu... |
cfg_sdd = {
'img_size': 608,
'conf_thres': 0.5,
'nms_thres': 0.3,
}
|
"""
keyed_urls 포맷은 검색엔진에서 키워드를 주고 얻은 이미지 링크 리스트를 저장 한다.
파이썬 구조는 { key: [], ... } 이다.
텍스트 파일 구조는 아래와 같다.
---검색키워드
url
url
.
.
.
---검색키워드
url
url
url
.
.
.
"""
def write_image_urls_as_file(keyed_urls, filename):
"""지정한 filename에 keyed_urls을 저장한다.
"""
with open(filename, 'w') as f:
for key, value in ... |
def fibonacci_seq(num):
i = 0
j = 0
k = 0
for i in range(num):
if i==0:
print(j)
elif i==1:
j = 1
print(j)
else:
temp = j
j = j+k
k = temp
print(j)
fibonacci_seq(10)
|
def set_parameters():
parameters = {
"model":{
"weight":{
"color":"weights/metric_color_weight.pth",
"type":"weights/metric_id_weight.pth"
}
},
"sys":{
"use_feature":["type"],#使用する特徴量"color" or "type"
"... |
class Base:
# Base Class
command = ''
def __init__(self,command):
self.command = command
|
def series1():
num=int(input('enter number: '))
stop=int(input('n0. of elements in series: '))
sum1=0
for i in range (stop):
sum1+=num**i
print('SUM IS',sum1)
series1()
|
addresses = [3, 225, 1, 225, 6, 6, 1100, 1, 238, 225, 104, 0, 1101, 32, 43, 225, 101, 68, 192, 224, 1001, 224, -160, 224, 4, 224, 102, 8, 223, 223, 1001, 224, 2, 224, 1, 223, 224, 223, 1001, 118, 77, 224, 1001, 224, -87, 224, 4, 224, 102, 8, 223, 223, 1001, 224, 6, 224, 1, 223, 224, 223, 1102, 5, 19, 225, 1102, 74, 50,... |
DATASET = 'forest-2'
CLASSES = 2
FEATURES = 54
NN_SIZE = 256
DIFFICULTY = 10000
class Override():
def __init__(self):
self.HPC_FILE = '../data/' + DATASET + '-hpc-fake'
override = Override() |
def includeme(config):
config.add_static_view('static', 'static', cache_max_age=3600)
config.add_route('home', '/')
config.add_route('persons', '/services/persons')
config.add_route('person', '/services/person/{code}')
config.add_route('photo', '/services/person/{code}/photo')
|
class Solution:
def solve(self, nums):
k = Counter(nums).most_common(1)[0][1]
locs = defaultdict(list)
for i in range(len(nums)):
locs[nums[i]].append(i)
return min(locs[num][i+k-1]-locs[num][i]+1 for num in locs for i in range(len(locs[num])-k+1))
|
# Copyright 2016 Google Inc. All Rights Reserved.
#
# 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 applicable law or ag... |
#!/usr/bin/env python
# encoding: utf-8
def run(whatweb, pluginname):
whatweb.recog_from_file(pluginname, "includes/js/tree.js", "PHPDISK")
|
cur.execute('select * from examplefunc(?,?,?)',{'in1':1,'in2':1.1,'in3':'hello'})
out1=cur.fetchone()[0]
out2=cur.fetchone()[1]
out3=cur.fetchone()[2]
|
'''Refaça o desafio 51, lendo o primeiro termo e a razão da PA, mostrando os 10
primeiros termos da progressão usando while.'''
print('10 TERMOS DE UMA PA')
num = int(input('Digite o primeiro termo: '))
razão = int(input('Digite a razão da PA: '))
décimo = num + (10 - 1) * razão
cont = 0
while cont < 10:
cont += 1
... |
# Copyright (c) Microsoft Corporation
# Licensed under the MIT License.
name = 'raiutils'
_major = '0'
_minor = '0'
_patch = '1'
version = '{}.{}.{}'.format(_major, _minor, _patch)
|
class submarine:
def __init__(self):
self.hpos = 0 # Horizontal Position
self.depth = 0 # Depth
def _forward(self, dist):
self.hpos = self.hpos + dist
def _down(self, dist):
# print(f"moving depth from {self.depth} by {dist}")
self.depth = self.depth + dist
... |
"""
练习1:
将两个列表,合并为一个字典
姓名列表["张无忌","赵敏","周芷若"]
房间列表[101,102,103]
{101: '张无忌', 102: '赵敏', 103: '周芷若'}
练习2:
颠倒练习1字典键值
{'张无忌': 101, '赵敏': 102, '周芷若': 103}
"""
list_name = ["张无忌", "赵敏", "周芷若"]
list_room = [101, 102, 103]
# result = {}
# for i in range(len(list_name)):
# ke... |
class no_setters(object):
def __init__(self):
pass
def __getattribute__(self, name):
varname = f"_{name}" if not name.startswith('_') else name
try:
attr_tag = super(no_setters, self).__getattribute__("__attr_descriptor__")
except AttributeError:
attr_tag... |
#
# PySNMP MIB module CISCO-LIVEDATA-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-LIVEDATA-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:04:40 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... |
__version__ = '0.2.14'
__package__ = 'django-politico-slackchat-renderer'
default_app_config = 'chatrender.apps.ChatrenderConfig'
|
# Fantasy Game Inventory
# Chapter 5 - Dictionaries and Data Structures
def display_inventory(inv, name=None):
if name is None:
print("Inventory:")
else:
print("Inventory of " + name + ":")
item_total = 0
for key, val in inv.items():
print(val, end=' ')
print(key)
... |
def cadastrar(*args):
try:
telaProduto = args[0]
telaErro = args[1]
cursor = args[2]
banco10 = args[3]
QtWidgets = args[4]
sabor = telaProduto.produto_cadastro.text()
valor = telaProduto.valor_cadastro.text()
ingredientes = telaProduto.ingredientes.te... |
# task websocket message types
TASK_LOG = 'task/log'
TASK_INIT = 'task/init'
TASK_FAIL = 'task/fail'
TASK_STATUS = 'task/status'
TASK_RETURN = 'task/return'
TASK_STATS = 'task/stats'
|
# The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
# Given an integer n, return all distinct solutions to the n-queens puzzle.
# Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a q... |
logo = """
____ ___ _____ _____ _____ _____ __ __ _ _ _______ ____
/ ___/ _ \| ___| ___| ____| ____| | \/ | / \ | |/ / ____| _ \
| | | | | | |_ | |_ | _| | _| | |\/| | / _ \ | ' /| _| | |_) |
| |__| |_| | _| | _| | |___| |___ | | | |/ ___ \| . \| |___| _ <
\____\___/|_| ... |
def foo(bar):
return bar + 2
class Foo:
baz = staticmethod(foo)
f = Foo()
print(f.baz(10))
|
def FirstFactorial(num: int):
fact = num
while num != 1:
print(1, fact)
num = num - 1
print(2, num)
fact = fact * num
return fact
# keep this function call here
print(3, FirstFactorial(int(input()))) |
def area(l, c):
a = l * c
print(f'A área de um terreno de {l}x{c} é: {a}m²')
print('Controle de terrenos')
larg = float(input('Largura (m): '))
comp = float(input('Comprimento (m): '))
area(larg, comp)
|
""" Convert DNA sequences to RNA """
def rna(seq):
seq = seq.upper()
return seq.replace('T','U')
|
def basic_metrics(tally):
tp, tn, fp, fn, _ = tally
return {
"TPR": tp / (tp + fn),
"TNR": tn / (tn + fp),
"PPV": tp / (tp + fp),
"NPV": tn / (tn + fn),
"FPR": fp / (fp + tn),
"FNR": fn / (fn + tp)
}
|
# list all remote credentials
res = client.get_object_store_remote_credentials()
print(res)
if type(res) == pypureclient.responses.ValidResponse:
print(list(res.items))
# list first five remote credentials using default sort
res = client.get_object_store_remote_credentials(limit=5)
print(res)
if type(res) == pypure... |
PREFIXES = [
"Who is",
"What is",
"History of"
]
TOPIC_QUESTION = "Define a topic "
PREFIX_QUESTION = "Define a prefix"
def _generate_prefixes_option_string(prefixes):
prefixes_string = ""
for key, prefix_string in enumerate(prefixes, start=1):
prefixes_string = "{} {} {} \n".format(prefi... |
class A():
def disp(self):
print("A disp()")
class B(A):
pass
obj = B()
obj.disp() |
"""Add one to a number."""
def add_one(a):
return a+1
def add_thousand(a):
return a+1000
def best_group():
return 'Sparks group obviously'
def do_literally_nothing_to_my_input(a):
return a
def Ramsey_made_it(x_1):
return x_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 minCameraCover(self, root: TreeNode) -> int:
self.result, covered = 0, {None}
def dfs(no... |
# For PyInstaller/lib/ define the version here, since there is no
# package-resource.
__version__ = '0.12.1'
# updated from leycec-modulegraph-1e8f74ef92a5'
|
# @Title: 搜索旋转排序数组 (Search in Rotated Sorted Array)
# @Author: 18015528893
# @Date: 2021-02-18 14:03:16
# @Runtime: 44 ms
# @Memory: 15.1 MB
class Solution:
def search(self, nums: List[int], target: int) -> int:
l = 0
r = len(nums)-1
while l < r:
mid = l + (r - l + 1) // 2
... |
'''
Exercicios propostos
'''
numero = input('informe um numero ')
try:
numero = int(numero)
if numero % 2 == 0:
print('O numero digitado e par')
else:
print('O numero digitado nao e par')
except:
print('ERRO')
'''
if not numero.isdigit():
print(f'{numero} não é um número inteir... |
# Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string. Return a list of all possible strings we could create.
#
#
# Examples:
# Input: S = "a1b2"
# Output: ["a1b2", "a1B2", "A1b2", "A1B2"]
#
# Input: S = "3z4"
# Output: ["3z4", "3Z4"]
#
# Input: S = ... |
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# * RUNTIME SHENG TRANSLATOR - SPANISH TRACK *
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# * Welcome to Runtime Sheng translator. v1.0.0 *
# * MIT License, Copyright(c) 2018, Antony Muga *
# * All Rights... |
"""
ASSIGNMENT OPERATORS
"""
__author__ = 'Sol Amour - amoursol@gmail.com'
__twitter__ = '@solamour'
__version__ = '1.0.0'
# Default values
num01 = 10
num02 = 5
plusEquals = num01 + num02 # Simple addition (10 + 5)
plusEquals += num01 # The positive assignment operator will take the right operand
# (num... |
print('Analizando nomes!!!')
nome = str(input('Nome Completo: '))
print(f'Nome maiuscúlo: {nome.upper()}')
print(f'Nome minúsculo: {nome.lower()}')
print(f'Numero de letras: {len(nome) - nome.count(" ")}')
n = nome.split()
print(f'N de letras primeiro nome: {len(n[0])}')
|
n, a, b = map(int, input().split())
c = a + b
cnt = n // c
ans = a * cnt + min(n % c, a)
print(ans)
|
"""
参考: https://www.runoob.com/w3cnote/shell-sort.html
希尔排序 - 递减增量排序算法
非稳定排序算法
希尔排序是基于直接插入排序的以下两点性质而提出的改进方法:
1, 插入排序在对几乎已经排好序的数据操作时, 效率高, 即可以达到线性排序的效率;
2, 插入排序一般来说是低效的, 因为插入排序每次只能将数据移动一位.
先将整个待排序的记录序列分割成为若干子序列分别进行直接插入排序, 待整个序列中的记录"基本有序"时, 再对全体记录进行依次直接插入排序.
好的增量序列的共同特征:
1, 最后一个增量必须为1;
2, 应该尽量避免序列中的值(尤其是相邻的值)互为倍数的情况... |
l = [1, 4, 6, 8]
l.reverse()
print(l)
s = "строка символов" # последовательность
l = [1, 4, 8, 3]
l.sort()
print(l)
l.reverse()
print(l) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.