content stringlengths 7 1.05M |
|---|
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... |
"""VmTool.
"""
__version__ = '1.0'
|
if __name__ == '__main__':
students = []
scores = set()
for _ in range(int(input())):
name = input()
score = float(input())
scores.add(score)
students.append([name,score])
students.sort()
scores = list(scores)
scores.sort()
second = scores[1]
for student i... |
"""
Opcodes dictionary for assembly and disassembly
"""
lookup = {
"0x0": [1, "NOP", 0],
"0x1": [3, "LXI\tB,#$", 1],
"0x2": [1, "STAX\tB", 0],
"0x3": [1, "INX\tB", 0],
"0x4": [1, "INR\tB", 0],
"0x5": [1, "DCR\tB", 0],
"0x6": [2, "MVI\tB,#$", 1],
"0x7": [1, "RLC", 0],
"0x8": [1, "08"... |
#!/usr/bin/python
#Configuration file for run_experiments.py
istc_uname = 'rhardin'
# ISTC Machines ranked by clock skew
istc_machines=[
#GOOD
"istc1",
"istc3",
#"istc4",
"istc6",
"istc8",
#OK
"istc7",
"istc9",
"istc10",
"istc13",
#BAD
"istc11",
"istc12",
"istc2",
"istc5",
]
vcloud_uname = 'centos'
#identity... |
"""Top-level package for Covid Vision."""
__author__ = """Edson Cavalcanti Neto"""
__email__ = 'profedsoncavalcanti@gmail.com'
__version__ = '0.1.0'
|
#!/usr/bin/env python
#-*- coding: utf-8 -*-
#This software is distributed under the Creative Commons license (CC0) version 1.0. A copy of this license should have been distributed with this software.
#The license can also be read online: <https://creativecommons.org/publicdomain/zero/1.0/>. If this online license dif... |
class Solution:
def maxScore(self, cardPoints: List[int], k: int) -> int:
max_sum = sum(cardPoints[:k])
cur_sum = max_sum
for i in range(k):
cur_sum = cur_sum - cardPoints[k-1-i] + cardPoints[-1*i-1]
max_sum = max(max_sum, cur_sum)
return... |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 5 14:51:57 2021
@author: caear
"""
class inSet(object):
"""An inSet is a set of integers
The value is represented by a list of ints, self.vals.
Each int in the set occurs in self.vals exactly once."""
def __init__(self):
"""Create an empty s... |
NON_MODIFIER_SCOPES = {
'variable': 'variable.other.lsp',
'parameter': 'variable.parameter.lsp',
'function': 'variable.function.lsp',
'method': 'variable.function.lsp',
'property': 'variable.other.member.lsp',
'class': 'supp... |
#Calcula a Hipotenusa de um triangulo
cateto_oposto = float(input('Digite o valor do Cateto Oposto: '))
cateto_adjacente = float(input('Digite o valor do Cateto Adjacente: '))
h = ((cateto_adjacente ** 2) + (cateto_oposto ** 2)) ** (1/2)
print('O valor da hipotenusa de um triangulo com Catetos {} e {} é {:.2f}!'.format... |
#Exercício Python 73: Crie uma tupla preenchida com os 20 primeiros colocados da Tabela do Campeonato Brasileiro de Futebol, na ordem de colocação. Depois mostre:
# a) Os 5 primeiros times.
# b) Os últimos 4 colocados.
# c) Times em ordem alfabética.
# d) Em que posição está o time da Chapecoense.
tabela_brasileirao ... |
# 6из45 + Результаты тиража + предыдущий тираж к примеру 9000
def test_6x45_results_draw_previous_draw(app):
app.ResultAndPrizes.open_page_results_and_prizes()
app.ResultAndPrizes.click_game_6x45()
app.ResultAndPrizes.click_the_results_of_the_draw()
app.ResultAndPrizes.select_draw_9000_in_draw_number... |
class Crypt:
def __init__(self, primesAlgorithm):
self.primes = primesAlgorithm
def isPrime(self, n):
return self.primes.isPrime(n);
def previousPrime(self, n):
while (n > 1):
n -= 1
if self.primes.isPrime(n):
return n
def nextPrime(self... |
# Python - 3.6.0
Test.it('Basic tests')
Test.assert_equals(odd_ball(['even', 4, 'even', 7, 'even', 55, 'even', 6, 'even', 10, 'odd', 3, 'even']), True)
Test.assert_equals(odd_ball(['even', 4, 'even', 7, 'even', 55, 'even', 6, 'even', 9, 'odd', 3, 'even']), False)
Test.assert_equals(odd_ball(['even', 10, 'odd', 2, 'eve... |
class Solution:
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
# return s[::-1]
result = ""
if not s:
return result
n = len(s)
for i in range(n-1, -1, -1):
result = result + (s[i])
return result |
#crate lists with motorcycle brands to learn how to create, change and append
#create a list
motorcycles = ['honda','kawasaki','ducati','yamaha','suzuki','norton']
motorcycles_orig = motorcycles
print(motorcycles)
#change an item
motorcycles[5] = 'harley davidson'
print(motorcycles)
#add an item
motorcycles.append('nor... |
"""Photos bundle entities module."""
class Photo:
"""Photo entity."""
|
# -*- coding: utf-8 -*-
# ファイル入出力
# open("ファイルパス", "モード")
f = open("sample.txt", "r") # ファイルを開く
text = f.read() # ファイル読み込み
print(text)
f.close() # ファイルを閉じる
f = open("sample2.txt", "w")
f.write("sample text 2")
f.close()
# ファイルの読み書き
f = open("sample.txt", "r+")
text = f.read(... |
def merge_adjacent_text_locations(text_locations):
if len(text_locations) == 0:
return []
current_low = text_locations[0][0]
current_high = text_locations[0][1]
output = []
for low, high in text_locations[1:]:
if low <= current_high + 1:
current_high = high
else... |
"""
Package for skvalidate commands.
All modules in this folder are automatically loaded as commands available through `skvalidate`.
"""
|
# Copyright 2012 ThoughtWorks, Inc.
#
# 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 agreed to in writin... |
# https://open.kattis.com/problems/boundingrobots
def walk_think(x, y, c, v):
if c == 'u':
return x, y + v
if c == 'r':
return x + v, y
if c == 'd':
return x, y - v
return x - v, y
def walk_actual(w, l, x, y, c, v):
x, y = walk_think(x, y, c, v)
return min(max(0, x), ... |
# test yield
class Solution:
def fibo(self, N):
if N == 1 or N == 2:
return 1
first = self.fibo(N-1)
second = self.fibo(N-2)
yield first + second
test = Solution().fibo(3)
next(test)
|
def solution(A):
# write your code in Python 3.6
length = len(A)
next_high, next_low = [0] * length, [0] * length
stack = []
first = [(number, i) for i, number in enumerate(A)]
first.sort(key=lambda x: x[0])
print(first)
for (number, i) in first:
while stack and stack[-1] < i and... |
# Your old mobile phone gets broken and so you want to purchase a new smartphone and decide to go through all the online websites to find out which dealer has the best offer for a particular model. You document the prices of N dealers. Dealer ids start from 0 and go up to N. Find out which dealer has the best price fo... |
class Make(object):
KEY = 'make'
@staticmethod
def addParserItems(subparsers):
parser = subparsers.add_parser(Make.KEY, help='Process a makefile to carry out accel builds.')
parser.add_argument('-j', '--cores', type=int, default=1, help='Number of cores allowed.')
@staticmethod
def f... |
class MockFP16DeepSpeedZeroOptimizer:
def __init__(self, optimizer):
self.optimizer = optimizer
def step(self, closure=None):
self.optimizer.step()
def _get_param_groups(self):
return self.optimizer.param_groups
def _set_param_groups(self, value):
self.optimizer.param_... |
# The file contains example SPARQL queries that populate SPARQL query editor
example_query_1 = """# The query searches for all datasets that are licensed under the CC BY-NC-SA license.
PREFIX sdo: <https://schema.org/>
SELECT DISTINCT ?title ?license_name WHERE {
?dataset a sdo:Dataset;
sdo:name ?title;
sdo:licen... |
#!/usr/bin/env python3
N = [int(_) for _ in input().split()]
x = N[0]
y = N[1]
if x % y == 0:
print(-1)
else:
for i in range(2, 1000000000):
# for i in range(2, 1000):
a = x * i
# print(a, x, i)
if a % y == 0:
continue
print(a)
break
|
'''
UFCG
PROGRAMAÇÃO 1
JOSE ARTHUR NEVES DE BRITO - 119210204
NOVO CPF
'''
p1 = int(input())
p2 = int(input())
p3 = int(input())
soma = 0
for x in str(p3):
soma = int(x) + soma
print('{:03}.{:03}.{:03}-{:02}'.format(p1,p2,p3,soma))
|
# 조세퍼스 문제
# https://www.acmicpc.net/problem/1158
input = __import__('sys').stdin.readline
def cycle(pointer, seq, diff):
nxt = pointer + diff - 1
size = len(seq)
return nxt % size
if __name__ == '__main__':
N, M = map(int,input().split())
sequence = list(range(1,N+1))
res = list()
poi... |
DEPS = [
'recipe_engine/json',
'recipe_engine/python',
'recipe_engine/raw_io',
'recipe_engine/step',
'depot_tools/tryserver',
]
|
"""Settings for the ``admin_tools`` app."""
ADMIN_TOOLS_MENU = 'multilingual_project_blog.admin_menu.CustomMenu'
ADMIN_TOOLS_INDEX_DASHBOARD = 'multilingual_project_blog.admin_dashboard.CustomIndexDashboard' # NOPEP8
ADMIN_TOOLS_APP_INDEX_DASHBOARD = 'multilingual_project_blog.admin_dashboard.CustomAppIndexDashboard'... |
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
####################################################################
# Animus AI Developed by Kuldeep Paul Dated 13th March 2018 #
####################################################################
#EchoSkill.py
def echo(Message):
return Message
##########... |
"""ex088 - Boletim com listas compostas
Crie um programa que leia nome e duas notas de varios alunos e guarde tudo em uma lista
composta. No final, mostre um boletim contendo a media de cada um e permita que o usuario
possa mostar as notas de cada aluno individualmente"""
ficha = []
while True:
nome = str(input("... |
'''Crie um programa que leia vários números inteiros pelo teclado.
O programa só vai parar quando o usuário digitar o valor 999, que é a condição de parada.
no final, mostre quantos números foram digitados e qual foi a soma entre eles.
(desconsiderando o caracter flag [999]).'''
n = cont = soma = 0
while n != 999:
... |
def test():
assert "nlp.begin_training()" in __solution__, "¿Llamaste a nlp.begin_training?"
assert (
"range(10)" in __solution__
), "¿Estás entrenando por el número correcto de iteraciones?"
assert (
"spacy.util.minibatch(TRAINING_DATA" in __solution__
), "¿Estás usando la herramien... |
"""
Faça um programa que preencha um vetor com 10 números reais, calcule e mostre a quantidade de
números negativos e a soma dos números positivos desse vetor:
"""
vetor = []
vetor_negativo = []
vetor_positivo = []
for i in range(10):
vetor.append(float(input('Digite um valor positivo ou negativo: \n')))
for i i... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @author : microfat
# @time : 01/26/21 20:40:02
# @File : production_design.py
def blueprint(cache, material):
return "",{} |
''' This component inverses pixel colours in a channel'''
class Component():
def __init__(self):
self._components = []
self.name = "inverse"
def components(self):
# Components are tuples with the data (id, title, init, min, max, type, is_headsup)
self._components.append( (1, "... |
class aluno:
def __init__(self,matricula,nome,notas):
self.matricula = matricula
self.nome = nome
self.notas = notas
def imprimir(self):
print(f"\nmatricula: {self.matricula}")
print(f"nome: {self.nome}")
print(f"notas: {self.notas}\n")
class turma:
def __in... |
def qs(arr):
if len(arr) <= 1:
return arr
smaller = []
larger = []
pivot = 0
pivot_element = arr[pivot]
for i in range(1, len(arr)):
if arr[i] > pivot_element:
larger.append(arr[i])
else:
smaller.append(arr[i])
sorted_smaller = qs(smaller)
sorted_larger = qs(larger)
... |
def rename(names, input_div, output_div):
return [name.replace(inputdiv,output_div) for name in names]
def c_rename(names):
newnames = []
for name in names:
name = name.split("_")
newname = [name[0]]
newname.extend(name[1].split("-"))
newnames.append("_".join(ne... |
# Actually generated with an internal hamming distance of 3, isolation of 2
HAMMING_WEIGHT = 1
DEFAULT_HEADER_CODE = (0, 41)
DEFAULT_MESSAGE_CODE = (54, 31)
class Code(object):
def __init__(self, code, hamming_weight):
# Naively assume that all codes are binary
assert len(code) == 2, "Non binary ... |
with open('input.txt') as f:
chunks = list(map(lambda line: line.strip(), f.readlines()))
mapper = {
'(': ')',
'[': ']',
'{': '}',
'<': '>'
}
error_score = {
')': 3,
']': 57,
'}': 1197,
'>': 25137
}
def validate(line):
stack = []
for ch in line:
if ch in ['(', '[', '{', '<']:
stack.append(ch)
elif ... |
def Dict(a):
b={}
for x in a:
b[x]=len(x)
return b
a=[]
for x in range(int(input("Enter Limit:"))):
a.append(input("Enter String:"))
print (Dict(a))
|
PLUS, MINUS, NUM, EOF = "plus", "minus", "num", "eof"
class Token:
def __init__(self, token_type, value):
self.token_type = token_type
self.value = value
def __str__(self):
return "(type:{},value:{})".format(self.token_type, self.value)
class Interpreter:
def __init__(self, text):
self.tex... |
class SPARQL:
def __init__(self, raw_query, parser):
self.raw_query = raw_query
self.query, self.supported, self.uris = parser(raw_query)
self.where_clause, self.where_clause_template = self.__extrat_where()
def __extrat_where(self):
WHERE = "WHERE"
sparql_query = self.q... |
grades_list = [87, 80, 90] #list
grades_tuple = (89, 93, 95) #immutable
grades_set = {70, 71, 74} #unique & unordered
## Set Operation
my_numbers = {1,2,3,4,5}
winning_numbers = {1,3,5,7,9,11}
#print( my_numbers.intersection(winning_numbers))
#print(my_numbers.union(winning_numbers))
print(my_numbers.di... |
fin = open("input_10_test.txt")
numbers = [int(line) for line in fin]
numbers.append(0)
numbers.append(max(numbers)+3)
fin.close()
numbers.sort()
count1 = 0
count3 = 0
for i,number in enumerate(numbers[:-1]):
diff = numbers[i+1]-number
if diff == 3:
count3 += 1
elif diff == 1:
count1 +... |
A = list(map(int, input().split()))
B = list(map(int, input().split()))
C = list(map(int, input().split()))
t = (A[3]*3600+A[4]*60+A[5])-(A[0]*3600+A[1]*60+A[2])
h, t = divmod(t, 3600)
m, s = divmod(t, 60)
print(h, m, s)
t = (B[3]*3600+B[4]*60+B[5])-(B[0]*3600+B[1]*60+B[2])
h, t = divmod(t, 3600)
m, s = divmod(t, 60)... |
WIDTH = 800
HEIGHT = 600
TITLE = "O.K. Team"
SPEED = 50
ANIMATION_SPEED = 5
BACKGROUND = (253, 246, 227)
WALK_IMAGES = ("walk0", "walk1", "walk1")
HAPPY_IMAGES = ("happy0", "happy1")
FLOWER_IMAGES = ("flower0", "flower1", "flower2")
|
# Модуль запускается только импортируясь.
if __name__ == "__main__": # выход если не внутри программы.
exit()
# Пустая основная функция:
def main_m(args): # Запускаемая часть модуля:
# your code goes here
pass
# Пустая аварийная функция:
def error_m(args): # если main_m дала сбой, запускаем ее:
# your cod... |
class SentenceProcessor(object):
r""" 实现了句子的word2index,index2word和pad """
def __init__(self, vocab, pad_id, start_id, end_id, unk_id):
self.vocab = vocab # index to vocab的词汇表
self.pad_id = pad_id
self.start_id = start_id
self.end_id = end_id
self.unk_id = unk_id
... |
'''
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
'''
n = 100
sqos = pow(sum([x for x in range(1, n+1)]), 2)
sosq = sum([x*x for x in range(1, n+1)])
print(sqos-sosq) |
GENOMES_DIR = '/home/cmb-panasas2/skchoudh/genomes'
OUT_DIR = '/staging/as/skchoudh/rna/September_2017_Shalgi_et_al_Cell_2013'
SRC_DIR = '/home/cmb-panasas2/skchoudh/github_projects/clip_seq_pipeline/scripts'
RAWDATA_DIR = '/home/cmb-06/as/skchoudh/dna/September_2017_Shalgi_et_al_Cell_2013/sra_single_end_mouse'
GENOME_... |
class JobInterruptedException(Exception):
def __init__(self, *args,**kwargs):
Exception.__init__(self,*args,**kwargs)
class RequestFailedException(Exception):
def __init__(self, error_msg, *args,**kwargs):
Exception.__init__(self,*args,**kwargs)
self.error_msg = error_msg |
def count_symbol_occurrences(text):
occurrences = {}
for symbol in text:
if symbol not in occurrences:
occurrences[symbol] = 0
occurrences[symbol] += 1
return occurrences
def print_result(occurrences):
for symbol, count in sorted(occurrences.items()):
print(f"{sym... |
# -*- coding: utf-8 -*-
class ReStructuredTextStyle:
'''reStructuredText风格
用 ``冒号`` 分隔,
PyCharm默认风格
:arg augend: 被加数
:type augend: int
'''
def __init__(self, augend, name='ReStructuredTextStyle'):
'''初始化'''
self.augend = augend
self.name = name
... |
sum=0
num=int(input("enter "))
while 1:
sum+=num
num-=1
print(sum)
if(num==0):
break
print(sum)
|
n1=float(input('digite a primeira nota'))
n2=float(input('digite a segunda nota'))
n3=float(input('digite a terceira nota'))
m=(n1 + n2 +n3) / 3
print('a nota media do aluno é {:.1f}'.format(m)) |
# -*- coding:utf-8 -*-
# Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
#
#
# For example:
# Given binary tree [3,9,20,null,null,15,7],
#
# 3
# / \
# 9 20
# / \
# 15 7
#
#
#
# return its bottom-up le... |
# -*- coding: utf-8 -*-
母到清濁 = {
'幫': '全清',
'端': '全清', '知': '全清',
'精': '全清', '心': '全清', '莊': '全清', '生': '全清', '章': '全清', '書': '全清',
'見': '全清', '影': '全清', '曉': '全清',
'滂': '次清',
'透': '次清', '徹': '次清',
'清': '次清', '初': '次清', '昌': '次清',
'溪': '次清',
'並': '全濁',
'定': '全濁', '澄': '全濁',
... |
# -*- coding: utf-8 -*-
# algorithm_diagnosis/diagnose.py
"""
Created on Thu Jan 25 16:10:00 2018
@author: jercas
"""
|
# -*- coding: utf-8 -*-
# invoice2py: an invoice web interface app for web2py
#
# Project page: http://code.google.com/p/ivoice2py
#
# Copyright (C) 2013 Alan Etkin <spametki@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Publ... |
def get_res(regular_alu,regular_nalurp,regular_nrp,hyper,output):
falu=open(regular_alu)
fnalurp=open(regular_nalurp)
fnrp=open(regular_nrp)
fhyper=open(hyper)
fo_AI=open(output+'_A_to_I_regular.res','w')
fo_hAI=open(output+'_A_to_I_hyper.res','w')
fo_CU=open(output+'_C_to_U.res','w')
... |
n=6
x=1
for i in range(1,n+1):
for j in range(1,i+1):
ch=chr(ord('A')+j-1)
print(ch,end="")
x=x+1
print()
|
valor=float(input("Digite o valor a pagar:"))#esta pedindo um valor do usuario
cédulas=0
atual=100.0
apagar=valor
while True:
#110 é menor ou igual valor queo usuario digitou
if atual<=apagar:
apagar-=atual#vale 100
cédulas+=1
else:
if apagar == 0:
break
if atual... |
#!/usr/bin/env python3
REPLACE_MASK = "@MASK"
BLANK_SPACE = " "
FILE_EXTENSION_SEPARATOR = "."
TAB_SPACE = 4 * BLANK_SPACE
WRITE_MODE = "w"
READ_MODE = "r"
EOL = "\n"
XML_HEADER = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + 2 * EOL
XML_FILE_EXTENSION = FILE_EXTENSION_SEPARATOR + "xml"
SOLR_XML_ADD_OPEN_TAG = "<add>... |
# Generators are functions that create an iterable. They use the special yield syntax.
def gen():
n = 0
while n < 10:
# yielding a value is similiar to returning it
yield n
# The code continues to the next line on the next call to next()
n += 1
for i in gen():
print(i)
|
class Restaurant:
def __init__(self, restaurant_name, cuisine_type):
self.name = restaurant_name
self.cuisine = cuisine_type
self.number_served = 0
def describe_restaurant(self):
print(f"The restaurant's name is {self.name}, its cuisine type is {self.cuisine}")
def open_re... |
asset_types = {
'file': {'name': 'file', 'contents':{'suff_list':['']}},
'lastdb': {'name': 'lastdb',
'contents': {
'suff_patt': '[0-9]*\.(prj|suf|bck|ssp|tis|sds|des)$',
}
},
'taxdump': {'name': 'taxdump',
'contents': {
... |
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
ans = []
def preorder(root: Optional[TreeNode]) -> None:
if not root:
return
ans.append(root.val)
preorder(root.left)
preorder(root.right)
preorder(root)
return ans
|
abc = 'abcdefghijklmnopqrstuvwxyz'
xyz = input()
frs = input()
for i in frs:
print(abc[xyz.find(i)], end='')
print()
|
# 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 postorderTraversal(self, root: TreeNode) -> List[int]:
# '''
# recursion solution
# ... |
class ParticleSystem(object):
"""Holds the position and name of ptf file for a particle system in a level"""
def __init__(self, ptfFile, particlePos):
self.ptfFile = ptfFile
self.particlePos = particlePos
def __repr__(self):
return "Particle System '" + self.ptfFile + "' at... |
# 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 levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if not root:
return [... |
i = 0
while i <= 2:
if i == 1.0:
i = 1
elif i == 2.0:
i = 2
for j in range(1,4):
print("I={0} J={1}".format(i, j + i))
i += 0.2
i = round(i,1)
|
'''
小米兔跳格子
米兔爸爸为了让小米兔好好锻炼身体,便给小米兔设置了一个挑战——跳格子。
要吃到自己心爱的胡萝卜,小米兔需要跳过面前一些格子。
现有 N个格子,每个格子内都写上了一个非负数,表示当前最多可以往前跳多少格,胡萝卜就放在最后一个格子上。
米兔开始站在第 1 个格子,试判断米兔能不能跳到最后一个格子吃到胡萝卜呢?
输入:输入为 N 个数字 (N <10),用空格隔开,第 i 个数字 s_i( 0 <= s_i <10)
表示米兔站在第 i 个格子上时,最多能往前跳的格数。
输出:若米兔能跳到最后一个格子上吃到胡萝卜,输出 “true“,否则输出 “false“
输入样例
2 0 1 0 0 3 4
输出样例
fals... |
#-*- coding: utf-8 -*-
'''
Exceptions for steamwatch.
'''
class ConfigurationError(Exception):
pass
# not used in the template - delete if not required.
class ApplicationError(Exception):
'''Base class for errors in the application logic.'''
pass
class GameNotFoundError(ApplicationError):
pass
|
class Person:
def __init__(self, id: id, name: str, emails: str, categories: str) -> None:
self.id = id
self.name = name
self.emails = self.__no_duplicates(emails)
self.categories = self.__no_duplicates(categories)
def linked_emails(self) -> str:
return ", ".join([f"__{email}__" for email in self.emails.sp... |
# Finding HCF (GCD) and LCM using Recursive Function
# Defining function
def hcf(a,b):
if b==0:
return a
else:
return hcf(b, a%b) # this is recursion as hcf() calls itself
# Reading numbers from user
first = int(input('Enter first number: '))
second = int(input('Enter second number: '))
# Fu... |
SKILLS = [30010166, 30011167, 30011168, 30011169, 30011170]
ARKARIUM = 2159309
sm.completeQuestNoRewards(parentID)
sm.deleteQuest(parentID)
for i in range(5):
if sm.hasSkill(SKILLS[i]):
sm.removeSkill(SKILLS[i]) # remove the skill
sm.removeNpc(ARKARIUM)
sm.warpInstanceIn(927000070, 0)
|
key = int(input())
lanes = int(input())
message = []
for symbol in range(lanes):
letter = input()
decrypt_letter = ord(letter) + key
message.append(chr(decrypt_letter))
print(f"{''.join(message)}")
|
# -*- coding: utf-8 -*-
# created: 2021-07-12
# creator: liguopeng@liguopeng.net
def split(list_obj, count):
return list_obj[:count], list_obj[count:]
|
# complex() returns a complex number with the value real + imag * 1j or
# converts a string or number to a complex number.
# If the first parameter is a string, it will be interpreted as a complex
# number and the function must be called without a second parameter.
# The second parameter can never be a string.
# Each ... |
""" API 1.
Name: ShortenURLAPIView
URL: localhost:8000/r/short-url
Method: POST
Description: Add new long url to make it short
Header : {Authorization: Token [Token Returned from login]}
Request json example:
"""
Json_1 = {
"long_url": "https://google.com",
"suggested_path": "google" # Optional... |
def CompareLists(headA, headB):
currentA=headA
currentB=headB
while currentA!=None or currentB!=None:
if currentA==None:
return 0
elif currentB==None:
return 0
if currentA.data!=currentB.data:
return 0
currentA=currentA.next
current... |
for _ in range(int(input())):
n,k=map(int,input().split())
x,y=n-(k-1),n-2*(k-1)
if x%2!=0 and x>0:
print("YES")
print('1 '*(k-1)+str(x))
elif y%2==0 and y>0:
print("YES")
print('2 '*(k-1)+str(y))
else:
print("NO") |
class Script:
@staticmethod
def main():
superhero_ranks = dict()
superhero_ranks["Aquaman"] = 1
superhero_ranks["Superman"] = 2
print(str(superhero_ranks))
Script.main() |
def test_breadcrumbs(env, similar, template, expected):
template = env.from_string(template)
assert similar(template.render(), expected)
def test_breadcrumbs_with_one_level(env, similar, template, expected):
template = env.from_string(template)
assert similar(template.render(), expected)
def test_br... |
class MaxHeap(object):
def __init__(self,max_size,fn):
"""MaxHeap class.
Arguments:
max_size {int} -- The maximum size of MaxHeap instance.
fn {function} -- Function to caculate the values of items
when comparing items.
A... |
counts = dict()
print('Enter a line of text:')
line = input('')
words = line.split()
print('Words:', words)
print('Counting...')
for word in words:
counts[word] = counts.get(word, 0) + 1
print('Counts', counts)
|
def unique_list(l):
"""Returns a list of unique values from given list l."""
x = []
#iterate over provided list
for a in l:
#check if number is in new list
if a not in x:
#add it to new list
x.append(a)
return x
print(unique_list([1,2, 3, 3, 3, 3, 3, 4, 5]... |
# MIT License
# (C) Copyright 2021 Hewlett Packard Enterprise Development LP.
#
# applianceRebootHistory : returns all Appliances reboot history
def get_appliance_reboot_history(
self,
action: str = None,
) -> list:
"""Get all appliance reboot history, optionally send reboot reports
to Cloud Portal
... |
##########################################################################################
# Author: Jared L. Ostmeyer
# Date Started: 2016-05-02
# Environment: Python3
# License: See LICENSE
# Purpose: Tools for describing an amino acid sequence as a sequence of Atchley factors.
#################################... |
qa_calcs_all = {
'H': (
{'state': 'chrg0.mult2', 'try_easier_state_if_fail': 'None', 'qc_method': 'HF', 'basis_set': basis_set, 'lambda_limits': '(0, 2)', 'dimer_sep_range': 'None', 'dimer_sep_step': 'None', 'broken_symmetry': 'False', 'force_unrestrict_spin': 'False', 'specific_atom_lambda': 'None', 'ma... |
# coding=utf-8
"""Top-level package for NKI-AI Boilerplate."""
__author__ = """NKI AI for Oncology Lab"""
__email__ = "j.teuwen@nki.nl"
__version__ = "0.0.1"
|
def balsa_example_error_callback(log_record):
try:
# in case formatting is not yet set
asc_time = log_record.asctime
except AttributeError:
asc_time = None
if asc_time is None:
print(f'{log_record.levelname} : "{log_record.msg}"')
else:
print(f"{log_record.level... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.