content stringlengths 7 1.05M |
|---|
# -*- coding: utf-8 -*-
"""
Пример наследования классов
"""
class Figure(object):
def __init__(self, side):
self.side = side
class Square(Figure):
def draw(self):
for i in range(self.side):
print('*' * self.side)
class Triangle(Figure):
def draw(self):
... |
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 13 21:31:02 2021
@author: eliphat
"""
class BaseConstraint:
def cause_vars(self):
raise NotImplementedError()
def effect_vars(self):
raise NotImplementedError()
def fix(self, ts):
raise NotImplementedError()
def is_resolved(self... |
def fun():
a=89
str="adar"
return[a,str];
print(fun())
|
'''
Parâmetros: são os nomes dados aos atributos que uma função pode receber. Definem quais argumentos são aceitos por uma função, podendo ou não ter um valor padrão (default).
Argumentos: são os valores que realmente são passados para uma função.
'''
def calculadora_salario(valor, horas=220):
return horas * valo... |
"""The version number is based on semantic versioning.
References
- https://semver.org/
- https://www.python.org/dev/peps/pep-0440/
This file is autogenerated, do not modify by hand.
"""
__version__ = "0.0.0"
COMMIT = "ed3301fdf82f5608a53a19a4aa0961c14c323421"
MAJOR = 0
MINOR = 0
PATCH = 0
|
# input
N, X, Y = map(int, input().split())
As = [*map(int, input().split())]
Bs = [*map(int, input().split())]
# compute
# output
print(sum(i not in As and i not in Bs for i in range(1, N+1)))
|
fout=open('orth_I.txt','w')
alphabet='ΕΡΤΥΘΙΟΠΑΣΔΦΓΗΞΚΛΖΧΨΩΒΝΜ'
#alphabet='ΧΥ'
#fout.write('0 0 eps eps 0\n')
for i in alphabet:
fout.write('0 0 '+i+' '+i+' 0\n')
fout.write('0')
|
names = ["duanzijie","zhaokeer","lijiaxi","zhuzi","wangwenbo","gongyijun"]
print(names)
print(names[0])
print(names[1])
print(names[2])
print(names[3])
print(names[4])
print(names[5])
hi = "hi" + " " + name[1]
print(hi) |
"""
User defined here are allowed to use privileged bot commands
"""
regulars = [
965146, #Shree
4946380, #Mithrandir
5067311, #Andras Deak
397817, #Stephen Kennedy
6707985, #geisterfurz007
]
|
# -*- coding: utf-8 -*-
"""
Author: @heyao
Created On: 2019/6/26 上午10:07
"""
|
n = int(input())
s = input()
c=0
for i in range(n-1):
if s[i]==s[i+1]:
c +=1
print(c)
|
# Чтобы подготовиться к семинару, Гоше надо прочитать статью по эффективному менеджменту.
# Так как Гоша хочет спланировать день заранее, ему необходимо оценить сложность статьи.
# Он придумал такой метод оценки: берётся случайное предложение из текста
# и в нём ищется самое длинное слово. Его длина и будет условной сл... |
# practice of anna
class TestClass:
def __init__(self, name):
# __init__ is the rule first creator made so every time we have to foloow
self.name = name
if __name__ == '__main__':
obj1 = TestClass()
print(obj1)
obj2 = TestClass()
print(obj2) |
"""
请判断一个链表是否为回文链表
**示例**
输入: 1 -> 2
输出: False
输入: 1 -> 2 -> 2 -> 1
输出: True
**test case**
# Solution
"""
class ListNode:
def __init__(self, value):
self.value = value
self.next = None
def __repr__(self):
return f"List Node Value: {self.value}"
head = ListNode(1)
head.next = L... |
class SpiderpigError(Exception):
pass
class ValidationError(SpiderpigError):
pass
class NotInitialized(SpiderpigError):
pass
class CyclicExecution(SpiderpigError):
pass
class TooManyDependencies(SpiderpigError):
pass
|
## bisenetv2
cfg = dict(
model_type='bisenetv2',
num_aux_heads=4,
lr_start = 5e-2,
weight_decay=5e-4,
warmup_iters = 1000,
max_iter = 150000,
im_root='./datasets/coco',
train_im_anns='./datasets/coco/train.txt',
val_im_anns='./datasets/coco/val.txt',
scales=[0.5, 1.5],
crops... |
# Exercício 015 - Aluguel de Carros
dias = int(input('Quantos dias alugados? '))
km = float(input('Quantos Km rodados? '))
preco_dias = dias * 60
preco_km = km * 0.15
total = preco_dias + preco_km
print(f'O total a pagar é de R${total:.2f}')
|
class PorterStemmer:
def __init__(self):
self.vowels = ('a', 'e', 'i', 'o', 'u')
def is_consonant(self, s: str, i: int):
return not self.is_vowel(s, i)
def is_vowel(self, s: str, i: int):
if s[i].lower() in self.vowels:
return True
elif s[i].lower() == 'y':
... |
def bubble_sort(L):
swap = False
while not swap:
swap = True
for j in range(1, len(L)):
if L[j-1] > L[j]:
swap = False
temp = L[j]
L[j] = L[j-1]
L[j-1] = temp
|
#
# PySNMP MIB module CRESCENDO-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CRESCENDO-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:12:29 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... |
la_liga_goals = 43
champions_league_goals = 10
copa_del_rey_goals = 5
total_goals = la_liga_goals + champions_league_goals + copa_del_rey_goals |
"""
Too Long
Print and remove all elements with length
greater than 4 in a given list of strings.
"""
the_list = ["dragon", "cab", "science", "dove", "lime", "river", "pop"]
to_remove = []
for x in the_list: # iterates through every element in the list
if len(x) > 4: # if the element length is greater than 4
... |
class NoUserIdOrSessionKeyError(Exception):
pass
class NoProductToDelete(Exception):
pass
class NoCart(Exception):
pass
class BadConfigError(Exception):
pass
|
"""WizCoin
By Al Sweigart test@gmail.com
A basic Python project."""
__version__ = '0.1.0'
|
def main():
*t, n = map(int, input().split())
t=list(t)
for i in range(2, n):
t.append(t[i-2] + t[i-1]*t[i-1])
print(t[-1])
if __name__ == '__main__':
main()
|
'''
Created on Oct 2, 2012
@author: vadim
Todo: need to learn string algorithms.
'''
f = open('data/keylog.txt')
mx = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, ... |
""" CSCI 204, Stack lab """
""" Tongyu Yang CSCI204 Lab06 """
class MyStack:
""" Implement this Stack ADT using a Python list to hold elements.
Do NOT use the len() feature of lists.
"""
CAPACITY = 10
def __init__( self ):
""" Initialize an empty stack. """
self._capac... |
#
# Copyright (c) 2019 Opticks Team. All Rights Reserved.
#
# This file is part of Opticks
# (see https://bitbucket.org/simoncblyth/opticks).
#
# 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 a... |
# Swap assign variables
print("Enter 3 no.s:")
a = float(input("a: "))
b = float(input("b: "))
c = float(input("c: "))
a, b = a+b, b+c
print("Variables are: ")
print("a:", a)
print("b:", b)
print("c:", c)
|
class A:
def __setitem__(self, e, f):
print(e + f)
a = A()
a[2] = 8
|
"""
for i in range(1,101,2):
if(i%7==0):
continue
print(i)
"""
c=0
while c<=100:
if(c%2!=0 and c%7!=0):
print(c)
c=c+1 |
cpp_config = [
'query-lib/official/cpp/codeql-suites/cpp-security-and-quality.qls',
'query-lib/official/cpp/codeql-suites/cpp-security-extended.qls',
]
js_config = []
# exported
lang_configs = {
'cpp' : cpp_config,
'javascript' : js_config
}
need_compile = ['cpp', 'java'] |
# Push (temp, idx) in a stack. Pop element when a bigger elem is seen and update arr[idx] with (new_idx-idx).
# class Solution:
# def dailyTemperatures(self, T: List[int]) -> List[int]:
# S = []
# res = [0]*len(T)
# for i in range(len(T)-1, -1, -1):
# while S and T[S[-1... |
class OrderBook:
"""
Implements data structure to append messages one at a time
"""
def __init__(self):
# bids, asks
self.book = (dict(), dict())
def bestBid(self):
if not self.book[0].keys():
return (float('nan'), float('nan'))
price = max(self.book[... |
class BaseType:
def __init__(self, db_type: str, python_type: type):
self.db_type = db_type
self.python_type = python_type
Float = BaseType("REAL", float)
Int = BaseType("INTEGER", int)
String = BaseType("TEXT", str)
TypeMap = {
float: Float,
int: Int,
str: String
}
|
'''
UFCG
PROGRAMAÇÃO 1
JOSE ARTHUR NEVES DE BRITO - 119210204
PRECO DE VENDA
'''
custo = float(input())
desp_indireta = float(input())
lucro_desj = float(input())
impostos = float(input())
comissao = float(input())
desc = float(input())
encargos = float(input())
preco = ((custo + desp_indireta + lucro_desj)*100) / ... |
album_info = {
'Arrival - ABBA': {
'image': 'arrival.jpg',
'spotify_link_a': '1M4anG49aEs4YimBdj96Oy',
},
}
|
print('Hello, world.')
print('Hello, Python!')
print(2 + 3)
print('2' * 3)
print(f'2 + 3 = {2 + 3}')
print('1', '2', '3', sep=' + ', end=' ')
print('=', 1 + 2 + 3, end='')
print('!')
|
"""Escreva um programa que leia um número N inteiro qualquer e mostre na tela os N primeiros elementos
de uma Sequência de Fibonacci. Exemplo:
0 – 1 – 1 – 2 – 3 – 5 – 8 """
print('=*'*26)
print('*'*14, 'SEQUENCIA DE FIBONACCI', '*'*14)
print('=*'*26)
n = int(input('Quantos termos você quer mostrar? '))
t1 = 0
t2 = 1
t... |
class Settings():
'''Uma classe para armazenar todas as configurações do jogo.'''
def __init__(self):
'''Inicializa as configurações do jogo.'''
# Configurações da tela
self.screen_width = 1000
self.screen_height = 600
self.bg_color = (230, 230, 230)
# Configurações da espaçonave
self.ship_speed_facto... |
#!/usr/bin/env python
#coding: utf-8
class Solution:
# @param A, a list of integers
# @return an integer
def firstMissingPositive(self, A):
if not A: return 1
la = len(A)
i = 0
while i < la:
if i + 1 == A[i]:
i += 1
continue
... |
def xor(a, b):
return (a or b) and not (a and b)
def collapse_polymer(polymer):
pos = 0
while pos + 1 < len(polymer):
first = polymer[pos]
second = polymer[pos + 1]
if first.lower() == second.lower() and xor(first.isupper(), second.isupper()):
if pos + 2 >= len(polymer)... |
class Aula:
def __init__(self, id, numero, titulo):
self._id = id
self._numero = numero
self._titulo = titulo
def get_id(self):
return self._id
def get_numero(self):
return self._numero
def get_titulo(self):
return self._titulo |
# -*- coding: utf-8 -*-
# spróbój czegos takiego jak
def index(): return dict()
def kupon():
if not session.ids:
session.ids=[]
else:
session.ids.append(2)
return request.vars.text_value
def testFunction(a):
if not request.vars.a:
request.vars.a=123
session.id=request.vars.... |
class Queue(object):
def __init__(self):
self.q = []
def push(self, value):
self.q.insert(0, value)
def pop(self):
return self.q.pop()
def is_empty(self):
return self.q == []
def size(self):
return len(self.q)
# Example
q = Queue()
q.push(1... |
"""
@Author: huuuuusy
@GitHub: https://github.com/huuuuusy
系统: Ubuntu 18.04
IDE: VS Code 1.37
工具: python == 3.7.3
"""
"""
思路:
动态规划
结果:
执行用时 : 36 ms, 在所有 Python3 提交中击败了98.50%的用户
内存消耗 : 13.7 MB, 在所有 Python3 提交中击败了5.14%的用户
"""
class Solution:
def uniquePaths(self, m, n):
dp = [[1]*n] + [[1]+[0]... |
file = open("day 04/Toon - Python/input", "r")
lines = file.readlines()
numbers = [int(x) for x in lines[0][:-1].split(',')]
boards = [[int(x) for x in line[:-1].split(' ') if x != '' ] for line in lines[2:]]
boards = [boards[i*6:i*6+5] for i in range(100)]
def contains_bingo(board):
return -5 in [sum(line) for li... |
# Faça um programa que leia 5 valores numéricos e guarde-os em uma lista.
# No final, mostre qual foi o maior e o menor valor digitado e as suas respectivas posições na lista.
print('—' * 60)
lista = []
for contador in range(0, 5):
lista.append(int(input(f'Digite um valor para a Posição {contador}: ')))
maior ... |
class Solution:
# s3的最后一个字符是从s1尾巴来的或者s2尾巴来的
# s3的前i个字符是s1的前个字符和s2的前k个字符交错形成的
# 降维, i = j + k, 不用开三维数组, 降到2维
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
m, n = len(s1), len(s2)
if m + n != len(s3):
return False
f = [[False] * (n + 1) for _ in... |
listOriginPath = [
{
"header": "test.example.com",
"httpPort": 80,
"mappingUniqueId": "993419389425697",
"origin": "10.10.10.1",
"originType": "HOST_SERVER",
"path": "/example",
"status": "RUNNING"
},
{
"header": "test.example.com",
"ht... |
# -- coding:utf-8--
my_games = {
"pc":"GTA5",
"mac_os":"final_cut_pro",
"ipad":"皇室战争",
"iphone":"皇权",
}
print(my_games)
#中文编码不支持!
|
@jit(nopython=True)
def pressure_poisson(p, b, l2_target):
J, I = b.shape
iter_diff = l2_target + 1
n = 0
while iter_diff > l2_target and n <= 500:
pn = p.copy()
for i in range(1, I - 1):
for j in range(1, J - 1):
p[j, i] = (.25 * (pn[j, i + 1] +
... |
a = [int(x) for x in input().split()]
time = None
# a[0] initial hour
# a[1] initial min
# a[2] final hour
# a[3] final min
start = 60 * a[0] + a[1]
finish = 60 * a[2] + a[3]
if finish <= start:
finish += 1440 # 24 * 60
time = finish - start
print(f"O JOGO DUROU {int(time / 60)} HORA(S) E {int(time % 60)} MI... |
n = int(input('Digite um número inteiro: '))
n0 = contador = 0
n1 = 1
print('{} {}'.format(n0, n1), end=' ')
while contador < (n - 2):
n2 = n0 + n1
print(n2, end=' ')
n0 = n1
n1 = n2
contador += 1
|
def Compute_kmeans_inertia(resultsDict, FSWRITE = False, gpu_available = False):
# Measure inertia of kmeans model for a variety of values of cluster number n
km_list = list()
data = resultsDict['PCA_fit_transform']
#data = resultsDict['NP_images_STD']
N_clusters = len(resultsDict['imagesFilenameList'])... |
num = 11
while num <= 10:
num += 1
if num == 3:
continue
if num == 4:
print('4')
break
else:
#不满足条件或程序报错
print('wrong')
print() # 等价于print(end = "\n") 自动换行
print(end = "\n") |
n_students = int(input())
skills = list(input().split(" "))
skills = [int(skill) for skill in skills]
skills = sorted(skills)
n_problems = 0
ptr1 = n_students - 1
ptr2 = n_students - 2
while ptr2 >= 0:
if (skills[ptr1] == skills[ptr2]):
ptr1 -= 2
ptr2 -= 2
else:
n_problems += 1
... |
"""
0011. Container With Most Water
Medium
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). Find two lines, which, together with the x-axis forms a container, such that the... |
teste = [0, 2, 3, 4, 5]
print(teste)
teste.insert(0, teste[3])
print(teste)
teste.pop(4)
print(teste) |
# -*- coding: utf-8 -*-
"""Top-level package for ePages Client."""
__author__ = """Pekka Piispanen, Tero Kotti"""
__email__ = 'pekka@vilkas.fi, tero@vilkas.fi'
__version__ = '0.2.0'
|
arr = [1, 2, 3, 4, 4, 4, 5, 6, 6, 7, 8, 9]
arr.sort()
my_dict = {i:arr.count(i) for i in arr}
# sorting the dictionary based on value
my_dict = {k: v for k, v in sorted(my_dict.items(), key=lambda item: item[1])}
print(len(my_dict))
print(my_dict)
list = list(my_dict.keys())
print(list[-1])
|
# Model parameters
model_hidden_size = 768
model_embedding_size = 256
model_num_layers = 1
# Training parameters
n_steps = 2e4
learning_rate_init = 1e-3
speakers_per_batch = 16
utterances_per_speaker = 32
## Tensor-train parameters for last linear layer.
compression = 'tt'
n_cores = 2
rank = 2
# Evaluation and Test... |
"""*******************************************************
This module has functions converting energies
*****************************************************
"""
#print __doc__
def convert_energy(Energy, Input_unit, Output_unit):#converts distance modulus to distance in parsec
"""Description: ocnverts energy from... |
BRIGHTID_NODE = 'http://node.brightid.org/brightid/v5'
VERIFICATIONS_URL = BRIGHTID_NODE + '/verifications/idchain/'
OPERATION_URL = BRIGHTID_NODE + '/operations/'
CONTEXT = 'idchain'
RPC_URL = 'wss://idchain.one/ws/'
RELAYER_ADDRESS = '0x0df7eDDd60D613362ca2b44659F56fEbafFA9bFB'
DISTRIBUTION_ADDRESS = '0x6E39d7540c2a... |
# Time: O(n log n); Space: O(n)
def target_indices(nums, target):
nums.sort()
ans = []
for i, n in enumerate(nums):
if n == target:
ans.append(i)
return ans
# Time: O(n + k); Space(n + k)
def target_indices2(nums, target):
count = [0] * (max(nums) + 1)
for n in nums:
... |
class Browser(object):
def __init__(self):
form = {}
def open(self, url):
pass
def set_handle_robots(self, status):
pass
def set_cookiejar(self, cj):
pass
def forms(self):
forms = [{'session[username_or_email]':'', 'session[password]':''}]
return f... |
class Dataset():
def __init__(self, data,feature=None):
self.len = data.shape[0]
if (feature is not None):
self.data = data[:,:feature]
self.label = data[:,feature:]
else:
feature = data.shape[1]
self.data = data[:,:feature]
self.label = None
def __getitem__(self, index):... |
date = input('Entre com uma data aa/mm/aaaa:')
if '-' in date:
date = date.replace('-', '/')
date = date.split('/')
meses = ('janeiro', 'fevereiro', 'março', 'abril', 'maio', 'junho', 'julho', 'agosto', 'setembro', 'outubro',
'novembro', 'dezembro')
if len(date[2]) <= 2:
if int(date[2]) > 50:
... |
class UnbundledTradeIndicatorEnum:
UNBUNDLED_TRADE_NONE = 0
FIRST_SUB_TRADE_OF_UNBUNDLED_TRADE = 1
LAST_SUB_TRADE_OF_UNBUNDLED_TRADE = 2
|
# -*- coding: UTF-8 -*
def input_data2():
return None
|
def longest_possible_word_length():
return 189819
class iterlines(object):
def __init__(self, filehandle):
self._filehandle = filehandle
def __iter__(self):
self._filehandle.seek(0)
return self
def __next__(self):
line = self._filehandle.readline()
if line == '... |
"""
Two ways for checking model architectures:
1. Use torchsummary.
2. Define your model classes as a BaseModel (instead of a nn.Module),
which specifies a __str__() function.
"""
# from __future__ import print_function
# import torch
# import torchsummary
# device = torch.device("cuda" if torch.cuda.is_availabl... |
class DependencyResolutionError(RuntimeError):
"""Raised when task dependencies cannot be resolved.
This may be raised by :meth:`.Queue.submit` (if it is possible to detect at
that time), or by :meth:`.Task.result` later.
"""
class PatternMissingError(RuntimeError):
"""Raised by :meth:`.Task... |
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def __repr__(self):
if type(self.data) != 'str':
return str(self.data)
return self.data
def _height(root):
if root is None:
return 0
return max(_heig... |
def most_frequent(arr):
ret = None
counter = {}
max_count = -1
for n in arr:
counter.setdefault(n, 0)
counter[n] += 1
if counter[n] > max_count:
max_count = counter[n]
ret = n
return ret
|
# Created by MechAviv
# Kinesis Introduction
# Map ID :: 331003200
# Subway :: Subway Car #3
JAY = 1531001
GIRL = 1531067
sm.spawnNpc(GIRL, 699, 47)
sm.showNpcSpecialActionByTemplateId(GIRL, "summon")
sm.spawnMob(2700303, 250, 57, False)
sm.spawnMob(2700303, 250, 57, False)
sm.spawnMob(2700303, 250, 57, False)
sm.spa... |
# https://www.hackerrank.com/challenges/30-review-loop/
T = int(input())
S = list()
for i in range(T):
S.append(str(input()))
for i in range(len(S)):
print(S[i][0] + S[i][2::2] + ' ' + S[i][1::2])
|
#
# PySNMP MIB module A3COM0420-SWITCH-EXTENSIONS (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM0420-SWITCH-EXTENSIONS
# Produced by pysmi-0.3.4 at Mon Apr 29 16:54:17 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python versio... |
L = int(input())
R = int(input())
xor = L ^ R
max_xor = 1
while xor:
xor >>= 1
max_xor <<= 1
print (max_xor-1)
|
num = int(input('Digite um número inteiro:'))
print('''Escolha uma das bases para conversão:
[1] converter para Binário
[2] converter para Octal
[3] converter para Hexadecimal''')
opção = int(input('Sua opção: '))
if opção == 1:
print('{} convertido para Binário é igual a {}'.format(num, bin(num)[2:]))
elif opção =... |
# microbit-module: shared_config@0.1.0
RADIO_CHANNEL = 17
MSG_DEYLAY = 50
|
# Invert a binary tree.
# Input:
# 4
# / \
# 2 7
# / \ / \
# 1 3 6 9
#
# Output:
# 4
# / \
# 7 2
# / \ / \
# 9 6 3 1
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Solution:
def invertTree... |
def roundUp(number:float)->int:
split = [int(i) for i in str(number).split(".")]
if split[1] >0:
return split[0]+1
return split[0]
## Program Start ##
n, k = [int(i) for i in input().strip().split(" ")][-2:]
scores = sorted([int(i) for i in input().strip().split(" ")])
min_days = roundUp(n/k)
ou... |
'''
Мороженое
'''
k = int(input())
if (k % 5 == 4 and k >= 9):
print('YES')
elif (k % 5 == 3):
print('YES')
elif (k % 5 == 2 and k >= 12):
print('YES')
elif (k % 5 == 1 and k >= 6):
print('YES')
elif (k % 5 == 0):
print('YES')
else:
print('NO')
|
class StackOfPlates(object):
def __init__(self):
self.stack = []
self.capacity = 10
def push(self, item):
if self.stack and self.stack[-1].length() < 10:
self.stack[-1].push(item)
else:
new_stack = Stack()
new_stack.push(item)
sel... |
"""
This module will be transformed... into something far greater.
"""
a = "Hello"
msg = f"{a} World"
msg2 = f"Finally, {a} World"
print(msg)
|
'''
A+B for Input-Output Practice(VIII)
描述
Your task is to calculate the sum of some integers
输入
Input contains an integer N in the first line, and then N lines follow.
Each line starts with a integer M, and then M integers follow in the same line
输出
For each group of input integers you should output their sum in one l... |
class Person:
def __init__(self):
self.name = None
self.age = None
def input(self):
self.name = input("Введіть ім'я:")
self.age = input("Введіть вік:")
def print(self):
print(self.name, self.age)
class Friend(Person):
def __init__(self):... |
def skipVowels(word):
novowels = ''
for ch in word:
if ch.lower() in 'aeiou':
continue
novowels += ch
novowels+=ch
return novowels
print(skipVowels('hello'))
print(skipVowels('awaited'))
|
# -*- coding: utf-8 -*-
"""
----------Phenix Labs----------
Created on Sat Jan 23 22:41:46 2021
@author: Gyan Krishna
Topic: HCF andf LCM of tow numbers
"""
a = int(input("enter first number "))
b = int(input("enter second number "))
hcf = 1
small = min(a,b)
for i in range(1,small+1):
if(a%i == 0 and b%i == 0):... |
class orf(object):
""" Class that represents and Open Reading Frame
Attributes:
start (int): Start codon coordinate of the ORF in the parent sequence
stop (int): Stop codon coordinate of the ORF in the parent sequence
length (int): Number of aminoacids in the ORF
translation (str... |
"""
Test cases for 7.py found in the LeetCode folder.
Answer by @VGZELDA
"""
# function to be tested
def reverse(x):
x=int(x)
if(x>=0):
x=str(x)
x=x[::-1]
x=int(x)
if(x<-1*(2**31))or(x>=2**31):
return 0
else:
ret... |
DosTags = {
# System
33: "SYS_Input",
34: "SYS_Output",
35: "SYS_Asynch",
36: "SYS_UserShell",
37: "SYS_CustomShell",
# CreateNewProc
1001: "NP_SegList",
1002: "NP_FreeSegList",
1003: "NP_Entry",
1004: "NP_Input",
1005: "NP_Output",
1006: "NP_CloseInput",
1007: "N... |
# 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 findBottomLeftValue(self, root: TreeNode) -> int:
current = [root]
while True:
... |
#
# PySNMP MIB module CXMLPPP-IP-NCP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CXMLPPP-IP-NCP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:33:10 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... |
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: The root of binary tree.
@return: Level order in a list of lists of integers
"""
def levelOrder(self, root):
# wr... |
def B():
n = int(input())
a = [int(x) for x in input().split()]
d = {i:[] for i in range(1,n+1)}
d[0]= [0,0]
for i in range(2*n):
d[a[i]].append(i)
ans = 0
for i in range(n):
a , b = d[i] , d[i+1]
ans+= min(abs(b[0]-a[0])+abs(b[1]-a[1]) , abs(b[0]-a[1])+abs(b[1]-a[0])... |
# Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
# To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
# Note:... |
line_items = [{
"invNumber": 100,
"lineNumber": 1,
"partNumber": "TU100",
"description": "TacUmbrella",
"price": 9.99
},
{
"invNumber": 100,
"lineNumber": 2,
"partNumber": "TLB9000",
"description": "TacLunch... |
class ResizeError(Exception):
pass
def codelengths_from_frequencies(freqs):
freqs = sorted(freqs.items(),
key=lambda item: (item[1], -item[0]), reverse=True)
nodes = [Node(char=key, weight=value) for (key, value) in freqs]
while len(nodes) > 1:
right, left = nodes.pop(), nodes.pop()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.