content stringlengths 7 1.05M |
|---|
t = int(input())
while t:
N = int(input())
A = list(map(int, input().split()))
l = []
for i in range(N):
for j in range(i+1, N):
l.append(A[i]+A[j])
c = l.count(max(l))
print(c/len(l))
t = t-1 |
#
# 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 writing, software
# ... |
def remove_reads_in_other_fastq(input_fastq, remove_fastq, out_file_name):
out = open(out_file_name, "w")
# Get seq ids to remove
remove_ids = set()
i = 0
for line in open(remove_fastq):
if i % 500000 == 0:
print(i)
i += 1
if line.startswith("@"):
rem... |
magic_number = 3
#Your code here...
while True:
guess = int(input("Enter a guess: "))
if guess == magic_number:
print("You got it!")
break
elif guess > magic_number:
print("Too high!")
else:
print("Too low!")
|
# -*- coding: utf-8 -*-
"""Chart.js script."""
JS_SCRIPT = r'''
/*!
* Chart.js
* http://chartjs.org/
* Version: 2.7.1
*
* Copyright 2017 Nick Downie
* Released under the MIT license
* https://github.com/chartjs/Chart.js/blob/master/LICENSE.md
*/
!function(t){if("object"==typeof exports&&"undefined"!=typeof modu... |
## Shorty
## Copyright 2009 Joshua Roesslein
## See LICENSE
## @url burnurl.com
class Burnurl(Service):
def _test(self):
# all we can test is shrink
turl = self.shrink('http://test.com')
if turl.startswith('http://burnurl.com'):
return True
else:
return Fals... |
def pairs(digits):
for i in range(len(digits) - 1):
yield digits[i], digits[i+1]
yield digits[-1], digits[0]
def halfway(digits):
half = len(digits) // 2
for i in range(half):
yield digits[i], digits[half+i]
for i in range(half, len(digits)):
yield digits[i], digits[i-hal... |
"""Define objects for CTFlex"""
# def eligible(team):
# """Determine eligibility of team
#
# This function is used by CTFlex.
# """
# return (team.standing == team.GOOD_STANDING
# and team.country == team.US_COUNTRY
# and team.background == team.SCHOOL_BACKGROUND)
|
error_map = {
"abecoando": "abencoando",
"abigos": "amigos",
"abilidade": "habilidade",
"abilidades": "habilidades",
"abisurdo": "absurdo",
"abitual": "habitual",
"abrcs": "abracos",
"abrou": "abriu",
"abss": "abracos",
"abussda": "abusada",
"abussdo": "abusado",
"accept": "aceito",
"account":... |
def test_barcamp_add_without_login(client):
"""test adding a barcamp"""
resp = client.post('/b/add', data=dict(
name = "Barcamp 1",
description = "this is barcamp 1",
slug = "barcamp1",
size = "10",
start_date = "17.8.2012",
end_date = "17.9.2012",
loca... |
"""
Entradas
Salario bruto-->float-->salario
Salidas
Salario nuevo-->float-->sueldo
"""
#Entrada
salario=float(input("Digite el salario bruto: "))
#Caja negra
sueldo=0
if(salario<900000):
sueldo=salario*0.15+salario#float
else:
sueldo=salario*0.12+salario#float
#Salida
print("Su nuevo salario es de:",sueldo) |
# Developed by Sunghyun Cho on Feb 25, 2019.
class HangulDecomposer():
초성들 = ["ㄱ", "ㄲ", "ㄴ", "ㄷ", "ㄸ", "ㄹ", "ㅁ", "ㅂ", "ㅃ",
"ㅅ", "ㅆ", "ㅇ", "ㅈ", "ㅉ", "ㅊ", "ㅋ", "ㅌ", "ㅍ", "ㅎ"]
중성들 = ["ㅏ", "ㅐ", "ㅑ", "ㅒ", "ㅓ", "ㅔ", "ㅕ", "ㅖ", "ㅗ", "ㅘ",
"ㅙ", "ㅚ", "ㅛ", "ㅜ", "ㅝ", "ㅞ", "ㅟ", "ㅠ", "ㅡ", "ㅢ", "ㅣ"]
... |
'''
There is an undirected star graph consisting of n nodes
labeled from 1 to n. A star graph is a graph where there
is one center node and exactly n - 1 edges that connect
the center node with every other node.
You are given a 2D integer array edges where each
edges[i] = [ui, vi] indicates... |
class Cell:
"""
| (-1, -1) | (0, -1) | (1, -1) |
| (-1, 0) | x | (1, 0) |
| (-1, 1) | (0, 1) | (1, 1) |
"""
__positions = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]
"""
| | (0, -1) | |
| (-1, 0) | x | (1, 0) |
| ... |
def Agente_corredor_ex_9():
def __init__(self):
self.cur = 1
def invoca(self):
pos = 0
if pos == 0:
if(self.cur == 0):
return "fica parado"
if(self.cur > pos and self.cur > 1):
self.cur = self.cur - 1
return "andar-"
if... |
[
{
"created_at": "Mon Feb 12 03:41:30 +0000 2018",
"id": 962894403256901632,
"text": "RT @JonAcuff: Dear Olympics commentators, at the beginning of each figure skating couple please let us know if the couple loves each other\u2026",
"user.screen_name": "h0llaJess"
},
{
... |
"""
Module: 'micropython' on esp32 1.9.4
"""
# MCU: (sysname='esp32', nodename='esp32', release='1.9.4', version='v1.9.4 on 2018-05-11', machine='ESP32 module with ESP32')
# Stubber: 1.2.0
def alloc_emergency_exception_buf():
pass
def const():
pass
def heap_lock():
pass
def heap_unlock():
pass
def k... |
class BaseMetric(object):
name = None
def get_name(self):
return self.name
class ValueMetric(BaseMetric):
value = None
def get_value(self):
return self.value
class LineChartMetric(BaseMetric):
x = []
y = []
xlabel = 'X Label'
ylabel = 'Y Label'
def get_values(... |
nouns = ['account', 'achiever', 'acoustics', 'act', 'action', 'activity', 'actor', 'addition', 'adjustment',
'advertisement', 'advice', 'aftermath', 'afternoon', 'afterthought', 'agreement', 'air', 'airplane', 'airport',
'alarm', 'amount', 'amusement', 'anger', 'angle', 'animal', 'answer', 'ant', 'ant... |
__author__ = 'shukkkur'
'''
https://codeforces.com/problemset/problem/580/A
'''
n = int(input())
values = list(map(int, input().split()))
records = []
count = 1
for i in range(len(values)-1):
if values[i] <= values[i+1]:
count += 1
else:
records.append(count)
... |
# coding=utf-8
global DEBUG_ON # Turn debug ON/OF (True/False)
DEBUG_ON = False
global LEVEL_SYSTEM # Settings for leveling system
LEVEL_SYSTEM = {
'1': {'cap': 0, 'multiplier': 1},
'2': {'cap': 10, 'multiplier': 1},
'3': {'cap': 100, 'multiplier': 2},
'4': {'cap': 500, 'multiplier': 2},
'5': {'cap': 1000, 'mul... |
def find_loop_size(target):
loop_size = 0
c = 1
while True:
loop_size += 1
c *= 7
c = c % 20201227
if c == target:
return loop_size
def transform_loop(public, loop_size):
c = 1
for _ in range(loop_size):
c *= public
c = c % 20201227
re... |
# Fiona Nealon, 2018-04-07
# A function called factorial() which takes a single input and returns it's factorial
def factorial(upto):
# Create a variable that will become the answer
multupto = 1
# Loop through numbers i from 1 to upto
for i in range(1, upto + 1):
# Multiply ans by i, changing ans to that... |
"""
Target Commands
"""
def retrieve(args):
pass
def create(args):
pass
def start(args):
pass
def stop(args):
pass
def delete(args):
pass
|
'''
348. Design Tic-Tac-Toe
Medium
271
21
Design a Tic-tac-toe game that is played between two players on a n x n grid.
You may assume the following rules:
A move is guaranteed to be valid and is placed on an empty block.
Once a winning condition is reached, no more moves is allowed.
A player who succeeds in placin... |
EXPECTED = {'Foo': {'extensibility-implied': False,
'imports': {},
'object-classes': {},
'object-sets': {},
'tags': 'AUTOMATIC',
'types': {'A': {'restricted-to': [('min', 'max')],
'type': 'Constants'},
'B': {'restricted-to': ['unkn... |
valores = []
while True:
n = (int(input('Digite um valor: ')))
if n not in valores:
valores.append(n)
print('Valor computado com sucesso.')
else:
print('Valor já digitado anteriormente.')
continuar = str(input('Quer continuar? [S/N]: ')).upper().strip()[0]
while continuar no... |
# Code on Python 3.7.4
# Working @ Dec, 2020
# david-boo.github.io
# Define both number and length (13). Then, just check every substring of length 13 and store and print maximum.
num = "73167176531330624919225119674426574742355349194934969835203127745063262395783180169848018694788518438586156078911294949545... |
class cesarToTxtClass:
def __init__(self, cesar, offset=None):
self.cesar = cesar.decode("utf-8").upper()
self.alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".decode("utf-8")
if offset != None:
self.offset = offset
def processCesarWithOffset(self):
decrypted = ""
fo... |
# Topic - Functions: Examples and Exercises
# CST1101-OLXX Spr-2021 WK07CL12 Review
# by Professor Patrick PaSlattery@CityTech.CUNY.edu
### VOID FUNCTION
print("Example of a void function for its side effects")
# a simple function which prints whatever argument it receives
def print_void(argument):
"""T... |
class queue:
def __init__(self):
self.main = []
self.max_c = 10
def deque(self):
del self.main[-1]
def enque(self,val):
if len(self.main) == self.max_c:
self.deque()
self.main.insert(0,val)
else:
self.main.insert(0,val)
def show(self):
return self.main
def __getitem__(self,index):
retu... |
__author__ = 'Edwin Cowart, Kevin McDonough'
# The URL that the Test Cases are received from as HTML
TEST_CASES_URL = "http://www.ccs.neu.edu/home/tonyg/cs4500/6.html"
GEN_TEST_STR = 'test_*.py'
# JSON Directory Names
JSON_STREAM_DIR = "json_streams"
JSON_SITUATION_DIR = "json_situations"
JSON_FEEDING_6_DIR = "json... |
# Copyright (c) 2021 Qianyun, Inc. All rights reserved.
INSTANCE_STATUSES = {
"LAUNCHING": "starting,POWERED_ON",
"RUNNING": "started,POWERED_ON",
"RESTARTING": "starting,POWERED_ON",
"REBOOTING": "starting,POWERED_ON",
"SHUTTINGDOWN": "stopping,POWERED_ON",
"SHUTDOWN": "stopped,POWERED_OFF",
... |
def calcular(a, b):
if (a > b):
total = a * b
elif (a == b):
total = a * (b + 2)
else:
total = a
print(total)
calcular(10, 10)
|
def write_moment1_hybrid(
cube, rms=None, channel_correlation=None,
outfile=None, errorfile=None,
overwrite=True, unit=None,
return_products=True,
strict_vfield=None,
broad_vfield=None,
broad_signal=None,
vfield_prior=None,
vfield_prior_res=None,
... |
class Ray:
def __init__(self, origin, direction):
self.origin = origin
self.direction = direction.normalize()
|
board = [[7,8,0,4,0,0,1,2,0],
[6,0,0,0,7,5,0,0,9],
[0,0,0,6,0,1,0,7,8],
[0,0,7,0,4,0,2,6,0],
[0,0,1,0,5,0,9,3,0],
[9,0,4,0,6,0,0,0,5],
[0,7,0,3,0,0,0,1,2],
[1,2,0,0,0,7,4,0,0],
[0,4,9,2,0,6,0,0,7]]
def solve():
if (checkBoar... |
def main() -> None:
N = int(input())
assert 2 <= N <= 100
graph = [[] for _ in range(N)]
for _ in range(N - 1):
u, v = map(int, input().split())
assert 1 <= u <= N
assert 1 <= v <= N
assert u != v
u -= 1
v -= 1
graph[u].append(v)
graph... |
#!/usr/bin/env python3
"""
This script is used for course notes.
Author: Erick Marin
Date: 12/19/2020
"""
data = input("This will come from STDIN: ")
print("Now we write it to STDOUT: " + data)
# Generating a standard error (type) by concatenating a string with an integer
print("Now we generate an error to STDERR: "... |
class FontSizeConverter(TypeConverter):
"""
Converts font size values to and from other type representations.
FontSizeConverter()
"""
def CanConvertFrom(self,*__args):
"""
CanConvertFrom(self: FontSizeConverter,context: ITypeDescriptorContext,sourceType: Type) -> bool
Determines if conver... |
"""
Statistical models
- standard `regression` models
- `GLS` (generalized least squares regression)
- `OLS` (ordinary least square regression)
- `WLS` (weighted least square regression)
- `GLASAR` (GLS with autoregressive errors model)
- `GLM` (generalized linear models)
- robust statistical models
- ... |
# Merge Sort
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result += left[i:]
def mergeSort(arr):
if len... |
# -*- coding: utf-8 -*-
"""Top-level package for pfr_api."""
__author__ = """Alex Adamson"""
__email__ = 'alex.b.adamson@gmail.com'
__version__ = '0.1.0'
|
# Chess Dictionary Validator Practice Project
# Chapter 5 - Dictionary and Structuing Data (Automate the Boring Stuff with Python)
# Developer: Valeriy B.
def chess_dictionary_validator(inp):
# Creating a blank chess dictionary
chess_dictionary = dict()
# Creating a chess board
chess_board = list... |
km = float(input('Qual vai ser a distância da viagem: '))
if km <= 200:
print('O valor a ser pago é de: R${:.2f}'.format(km * 0.50))
else:
print('O valor a ser pago é de: R${:.2f}'.format(km * 0.45)) |
"""
숫자형 종류
- 정수형
- 실수형
- 복소수형 1 + 2j, 3i ( 많이 사용안함 )
- 8진수 0o25
- 16진수 0x25
"""
# 파이션의 모든 자료형은 객체로 취급한다
# 실행 : ctrl + shift + F10
""" [ 기초 연산자 ]
+ : 더하기
- : 빼기
* : 곱하기
/ : 나누기(실수값 결과)
// : 나누기(정수값 결과)
... |
begin_unit
comment|'# Copyright (c) 2011 Citrix Systems, Inc.'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may'
nl|'\n'
comment|'# not use this file except in compliance with the License. You may obtain'
nl|'\n'
comment|'# a copy of the License at'... |
def show_user(user):
print('имя:', user[0])
print('фамилия:', user[2])
print('возраст:', user[3])
user_1 = ['Иван', 'Иванович', 'Иванов', 21, 'г.Курган']
# 0 1 2 3 4
user_2 = ['Петр', 'Петрович', 'Петров', 19, 'г.Далматово']
user_3 = ['Сидорова', 'Валерьевна', 'Оксан... |
# https://leetcode.com/problems/arithmetic-slices/
class Solution:
def numberOfArithmeticSlices(self, nums: list[int]) -> int:
arithmetic_slices = 0
if len(nums) <= 2:
return arithmetic_slices
last_diff = nums[1] - nums[0]
last_increment = 0
for idx in range(2, l... |
n,m=map(int,input().split());r=0
while n>0:
r+=n;n//=m
print(r)
|
def main(ws, clients):
print("The number of clients is: {}".format(len(clients)))
count = 0
while not ws.closed and count < 5:
message = ws.receive()
ws.send(message)
count += 1
ws.close() |
#!/usr/bin/env python
def getpi(listb):
lista=[]
listcc=[]
for i in listb:
temp=i/180*3.14
lista.append((temp,i))
listcc.append(temp)
return lista
def getangle(listb):
lista=[]
for i in listb:
temp=i/3.14*180
lista.append((i,temp))
return lista
def get... |
class EthJsonRpcError(Exception):
pass
class ConnectionError(EthJsonRpcError):
pass
class BadStatusCodeError(EthJsonRpcError):
pass
class BadJsonError(EthJsonRpcError):
pass
class BadResponseError(EthJsonRpcError):
pass
|
class ActionEnum(enumerate):
"""
Enum for action space
"""
BUY = 1
SELL = -1
HOLD = 0
EXIT = 3
def form_action(action):
"""
Form action from action space
"""
r = 0.0
if action <= -0.5:
r =-(action + 0.5) * 2
return ActionEnum.SELL, r, "SELL"
elif acti... |
doc="""
#Enrich Quality
baseq-SNV qc_enrich ./bam ./bedfile ./out
#Alignment
baseq-SNV run_bwa -1 Read1M.P457.1.fq.gz -2 Read1M.P457.2.fq.gz -g hg38 -n Test -o Test.bam -t 10
#MarkDuplicate
baseq-SNV run_markdup -b Test.bam -m Test.marked.bam
#bqsr
baseq-SNV run_bqsr -m Test.marked.bam -g hg38 -q Test.marked.bqsr.ba... |
def leiaint(num):
while True:
numero = str(input(num))
if numero.isnumeric() == False:
while numero.isnumeric() == False:
print('\033[1;31mERRO! Digite um número inteiro válido.\033[m')
numero = str(input(num))
return numero
print(15*'--')
n = le... |
# http://norvig.com/mayzner.html
character_frequencies = {
'a': 8.04,
'c': 3.34,
'b': 1.48,
'e': 12.49,
'd': 3.82,
'g': 1.87,
'f': 2.40,
'i': 7.57,
'h': 5.05,
'k': 0.54,
'j': 0.16,
'm': 2.51,
'l': 4.07,
'o': 7.64,
'n': 7.23,
'q': 0.12,
'p': 2.14,
... |
# type this to run tests
# 'python -m nose FILENAME -v'
# 'nosetests FILENAME -v'
def test_case01():
assert 'aaa'.upper() == 'AAA'
|
"""
Metroclima database CLI tool
Project information
"""
__title__ = 'metroclima'
__description__ = 'A simple Python tool to retrieve information from ' \
'the Porto Alegre city\'s Metroclima database.'
__url__ = 'https://github.com/jonathadv/metroclima-dump'
__version__ = '1.0.0'
__author__ = 'Jona... |
# https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
#
# algorithms
# Easy (48.15%)
# Total Accepted: 222,749
# Total Submissions: 462,569
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# se... |
_ = 1 < 3
_ = 1 <= 3
_ = 1 < input() and input() > 3
_ = 1 < input() and input() >= 3
_ = 1 < input() and 1 <= input() and input() >= 3
|
def get_input(filename):
data = []
with open(filename, 'r') as i:
for x in i.readlines():
data.append(int(x))
return data
def count_increases(measurements):
previous = measurements[0]
increases = 0
for measurement in measurements[1:]:
if measurement > previous:
... |
def stockmax(p):
ind_max = p.index(max(p)) #find the max price
inv = sum(p[:ind_max]) #split the array before and after max price
pf = len(p[:ind_max])*p[ind_max] - inv #buy all stocks before max price
if len(p[ind_max+1:]) > 0:
pf += stockmax(p[ind_max+1:]) #then sell them at max price
ret... |
"""
Move Zeroes
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
"""
cl... |
def multiply(m, n):
if n > m:
m, n = n, m
if n == 0:
return 0
return m + multiply(m, n - 1)
# print(multiply(3, 5))
def rec(x, y): # x ^ y
if y > 0:
return x * rec(x, y - 1)
return 1
# print(rec(3, 5))
def hailstone(n):
# n is even: n = n / 2
# n is odd: n =... |
"""
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
// 4 -> 5 -> 6
//prev cur nextTemp
// 4 -> 5 -> 6
// prev cur nextTemp
"""
class Solution206:
pass
|
# Utility functions
def mk_param_summary(hyperparams):
return '__'.join([hpname + '_' + val for hpname, val in hyperparams.items()])
def insert_param_summary(filename, param_summary):
basename, extn = filename.rsplit('.', 1)
return basename + '__' + param_summary + '.' + extn
def combinations(ll):
... |
side = 1080
thickness = side*0.4
frames = 84
def skPts():
points = []
for i in range(360):
x = cos(radians(i))
y = sin(radians(i))
points.append((x, y))
return points
def shape(step, var):
speed = var/step
fill(1, 1, 1, 0.05)
stroke(None)
shape = BezierPath()
... |
key_mapping = ['C', 'C#/D♭', 'D', 'D#/E♭', 'E', 'F', 'F#/G♭', 'G', 'G#/A♭', 'A', 'A#/B♭', 'B']
def get_dict_list(l):
return [e.to_dict() for e in l]
def get_english_list(l):
length = len(l)
if length == 0:
return "none"
elif length == 1:
return l[0]
elif length == 2:
ret... |
#EJERCICIO PRACTICO NUMERO 5
print("===========================")
print("EJERCICIO PRACTICO NUMERO 5")
print("===========================\n")
print("=====================")
print("SUCESION DE FIBONACC1")
print("=====================\n")
x, y= 0, 1
while y <= 1597:
print(x, y, end = " ")
x = x + y
y = x ... |
"""Helps manage notes stored as plain files in the filesystem.
If you installed via ``pip``, run ``notesdir -h` to get help.
Or, run ``python3 -m notesdir -h``.
To use the Python API, look at :class:`notesdir.api.Notesdir`
"""
|
class MaxBoxGen():
def findMaxRect(data):
"""http://stackoverflow.com/a/30418912/5008845"""
nrows, ncols = data.shape
w = np.zeros(dtype=int, shape=data.shape)
h = np.zeros(dtype=int, shape=data.shape)
skip = 1
area_max = (0, [])
for r in range(nrows):
... |
'''
need to be very calm to solve this kind of problem
should never confuse yourself, keep clear mind
there is only 2 cases:
1. there is idle: using Counter to solve this case
2. there is no idle: len(tasks)
'''
class Solution:
def leastInterval(self, tasks: List[str], n: int) -> int:
if not task... |
print ("Hello \
world")
# Backslash(\) is a special character that creates whitespace
|
"""Test the TcEx Utils Module."""
# pylint: disable=no-self-use
class TestBool:
"""Test the TcEx Utils Module."""
def test_utils_encrypt(self, tcex):
"""Test writing a temp file to disk.
Args:
tcex (TcEx, fixture): An instantiated instance of TcEx object.
"""
key ... |
#条件について
if int(input("整数を入力してください")): #整数が入力されれば条件がTrue
print("整数が入力されました")
else: #整数が入力されなかったら?
print("整数が入力されませんでした")
#残念ながら整数以外を入力するとエラーが起きてしまいました。
#どうすれば良かったのでしょうか...(error_1.pyに続く…)
|
s = 'nothyp_onan@'
l = [1,2,3,4,5,6,7,8,9]
print(s[::-1])
print(l[::-1])
print(reversed(l))
l1 = l.reverse
print(l1) |
class BaseContest(object):
'''BaseContest is an abstract class for contest-specific modifications to
Marathoner.
'''
def __init__(self, project):
self.project = project
self.maximize = project.maximize
def extract_score(self, visualizer_stdout, solution_stderr):
'''Extract r... |
def slices(series: str, length: int) -> list[str]:
size = len(series)
if length > size or length < 1:
raise ValueError("Invalid Input")
return [series[i:i + length] for i in range(size - length + 1)]
|
#!/usr/bin/env python3
input = '52554437147555553177771524418267843219182859995942215316362429449983637161192948458385799435625432472399695557917723926815678834498379821192395363253412635244153971238243584678919637629487233277745457158515424298321191791399144715235153322473174417191845568913621792673683254866423766856... |
#Time Complexity: O(n)
#Space Complexity: O(1)
#Speed: 84.65%
#Memory: 84.34%
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for token in tokens:
if token.isdigit() or token[1:].isdigit():
stack.append(int(token))
else:
... |
def área( l, c):
ar = l * c
print(f'A área do seu terreno é {ar} m²')
#Programa Principal
print('--' * 30)
print(f'{"Controle de terreno":^60}')
a = float(input('Comprimento do terreno [m]? '))
b = float(input('Largura do terreno [m]? '))
área(a, b)
|
#
# PySNMP MIB module SNA-SDLC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SNA-SDLC-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 16:52:15 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,... |
"""
## Questions: MEDIUM
### 1845. [Seat Reservation Manager](https://leetcode.com/problems/seat-reservation-manager/)
Design a system that manages the reservation state of n seats that are numbered from 1 to n.
Implement the SeatManager class:
SeatManager(int n) Initializes a SeatManager object that will manage n s... |
class MyWorkflow(object):
def __init__(self):
pass
def step3(self, session_time = None):
print("Step3 of session {0}".format(session_time))
|
n = int(input('сколько чисел вы хотите ввести? '))
array = []
printArray = []
for i in range(0, n):
array.append(int(input('Введите число: ')))
if (array[i] % 2 != 0):
printArray.append(array[i])
print(* printArray)
|
#Criando o teste de convergencia 2 (Criterio de Sessenfeld):
def convergencia_2(matriz, num):
print('\n\nCriterio de Sessenfeld:')
beta = list()
for i in range(0, num):
beta.append(1)
for l in range(0, num):
soma = 0;
for c in range(0, dimensao):
if c != l:
soma = soma + (math.fabs(mat... |
#dia, mês, ano = input ('Qual é a data do seu nascimento (no formato dd/mm/aaaa)? ').split('/')
#meses = '''janeiro fevereiro março abril maio junho julho
# agosto setembro outubro novembro dezembro'''.split()
#print (dia, 'de', meses [int (mês) -1], 'de', ano)
for letra in 'aeiou':
print (let... |
def flatten(myList):
newList = []
for item in myList:
if type(item) == list:
newList.extend(flatten(item))
else:
newList.append(item)
return newList
def main():
myList1 = [1,2,3,[1,2],5,[3,4,5,6,7]]
print(flatten(myList1))
myList2 = [1,[2,[3,[4,[5,[6,[7,[... |
#
# This file is part of the profilerTools suite (see
# https://github.com/mssm-labmmol/profiler).
#
# Copyright (c) 2020 mssm-labmmol
#
# 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 withou... |
class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
x=[]
for i,j in enumerate(mat):
x.append(j[i])
x.append(j[len(mat)-(i+1)])
if len(mat)%2==0:
return sum(x)
else:
y=mat[len(mat)//2]
z=y[len(mat)//2]
... |
# The MIT License (MIT)
#
# Copyright (c) 2018 Niklas Rosenstein
#
# 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,... |
class Node:
def __init__(self, data) -> None:
self.data = data
self.right = self.down = None
class LinkedList:
def __init__(self) -> None:
self.head = self.rear = None
def insert(self, item, location):
temp = Node(item)
if self.rear == None:
... |
#continue dan break bisa digunakan di For-Loop dan While-Loop
#Belajar Continue --> Men-skip proses looping sehingga melanjutkan looping selanjutnya
#definisi menurut aris --> digunakan utk menolak data range
for i in range(1,10):
if (i) % 2 == 1: #artinya ganjil
continue #statment TRUE di atas a... |
# define a function that finds the truth by shifting the letter by the specified amount
def lassoLetter( letter, shiftAmount ):
# invoke the ord function to translate the letter to its ASCII code
# and save it to the variable called letterCode
letterCode = ord(letter.lower())
# the ASCII number re... |
t=int(input())
if t>=1:
print("bigger than 1")
else:
print("smaller than 1") |
# Copyright 2015 Jason T Clark
#
# 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 writing... |
for i in range(1,101):
if(i%3==0 and i%5==0):
print("FizzBuzz")
if(i%3==0):
print("Fizz")
if(i%5==0):
print("Buzz")
else:
print(i) |
if __name__ == '__main__':
x = int(input())
y = int(input())
z = int(input())
n = int(input())
l = []
for i in range(x+1):
for j in range(y+1):
for k in range(z+1):
elem = []
elem.append(i)
elem.append(j)
elem.... |
# Created by MechAviv
# Kinesis Introduction
# Map ID :: 101020400
# East Forest :: Magician Association
KINESIS = 1531000
NERO = 1531003
THREE_MOON = 1531004
sm.setNpcOverrideBoxChat(NERO)
sm.sendNext("#face1#Good job! See, you're getting faster every time.")
sm.completeQuest(parentID)
sm.giveExp(11500)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.