content stringlengths 7 1.05M |
|---|
#!/usr/bin/env python
# AUTHOR OF MODULE NAME
AUTHOR="Mauricio Velazco (@mvelazco)"
# DESCRIPTION OF THE MODULE
DESCRIPTION="This module simulates an adversary leveraging a compromised host to perform password spray attacks."
LONGDESCRIPTION="This scenario can occur if an adversary has obtained control of a domain j... |
"""
for a string with '(' find the count of complete '()' ones, '(()))" does not count, if does not have full brackets, return -1
time & space: O(n), n = length of S
"""
def count_brackets(S):
# initializations
cs,stack,cnt = S[:],[],0
# iterate through char array of S
for c in cs:
# if it is ... |
# 18. Write a language program to get the volume of a sphere with radius 6
radius=6
volume=(4/3)*3.14*(radius**3)
print("Volume of sphere with radius 6= ",volume)
|
# I usually do not hard-code urls here,
# but there is not much need for complex configuration
BASEURL = 'https://simple-chat-asapp.herokuapp.com/'
login_button_text = 'Login'
sign_in_message = 'Sign in to Chat'
who_are_you = 'Who are you?'
who_are_you_talking_to = 'Who are you talking to?'
chatting_text = 'Chatting'... |
# code to run in IPython shell to test whether clustering info in spikes struct array and in
# the neurons dict is consistent:
for nid in sorted(self.sort.neurons):
print(nid, (self.sort.neurons[nid].sids == np.where(self.sort.spikes['nid'] == nid)[0]).all())
|
def sum67(nums):
count = 0
blocked = False
for n in nums:
if n == 6:
blocked = True
continue
if n == 7 and blocked:
blocked = False
continue
if not blocked:
count += n
return count
|
# author : @akash kumar
# problem link:
# https://prepinsta.com/tcs-coding-question-1/
x,y,d,t=0,0,10,1
for n in range(int(input())):
if t==1:
x+=d
t=2
d+=10
elif t==2:
y+=d
t=3
d+=10
elif t==3:
x-=d
t=4
d+=10
elif t==4:
y-=d
t=5... |
#!/usr/bin/env python3
#encoding=utf-8
#--------------------------------------------
# Usage: python3 3-calltracer_descr-for-method.py
# Description: make descriptor class as decorator to decorate class method
#--------------------------------------------
class Tracer: # a decorator + descriptor
def __ini... |
def bytes2int(data: bytes) -> int:
return int.from_bytes(data, byteorder="big", signed=True)
def int2bytes(x: int) -> bytes:
return int.to_bytes(x, length=4, byteorder="big", signed=True)
|
#!/usr/bin/python3.4
tableData = [['apples','oranges','cherries','bananas'],
['Alice','Bob','Carol','David'],
['dogs','cats','moose','goose']]
# Per the hint
colWidth = [0] * len(tableData)
# Who knew you had to transpose this list of lists
def matrixTranspose( matrix ):
if not matrix: ... |
class Niark:
def __init__(self):
self.statements = []
def addStatement(self, statement):
self.statements.insert(0,statement)
def printObject(self, tabs):
for x in range (0, len(self.statements)):
self.statements[x].printObject(tabs)
#####################################... |
#!/usr/bin/env python3
"""
ATTOM API
https://api.developer.attomdata.com
"""
HINSDALE = "HINSDALE, IL"
MADISON_HINSDALE = {}
HOMES = {
"216 S MADISON ST": HINSDALE,
"607 S ADAMS ST": HINSDALE,
"428 MINNEOLA ST": HINSDALE,
"600 S BRUNER ST": HINSDALE,
"637 S BRUNER ST": HINSDALE,
"142 S STOUGH ST": HINSDA... |
folder_nm='end_to_end'
coref_path="/home/raj/"+folder_nm+"/output/coreferent_pairs/output2.txt"
chains_path="/home/raj/"+folder_nm+"/output/chains/chains.txt"
f1=open(chains_path,"w+")
def linear_search(obj, item, start=0):
for l in range(start, len(obj)):
if obj[l] == item:
return l
return... |
SCOUTOATH = '''
On my honor, I will do my best
to do my duty to God and my country
to obey the Scout Law
to help other people at all times
to keep myself physically strong, mentally awake and morally straight.
'''
SCOUTLAW = '''
A scout is:
Trustworthy
Loyal
Helpful
Friendly
Courteous
Kind
... |
# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREY = (140, 140, 140)
CYAN = (0, 255, 255)
DARK_CYAN = (0, 150, 150)
ORANGE = (255, 165, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
|
data = (
'kka', # 0x00
'kk', # 0x01
'nu', # 0x02
'no', # 0x03
'ne', # 0x04
'nee', # 0x05
'ni', # 0x06
'na', # 0x07
'mu', # 0x08
'mo', # 0x09
'me', # 0x0a
'mee', # 0x0b
'mi', # 0x0c
'ma', # 0x0d
'yu', # 0x0e
'yo', # 0x0f
'ye', # 0x10
'yee', # 0x11
'yi', # 0x12
'ya... |
# -*- Python -*-
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Alex Dementsov
# California Institute of Technology
# (C) 2010 All Rights Reserved
#
# {LicenseText}
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... |
def extractSharramycatsTranslations(item):
"""
'Sharramycats Translations'
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol or frag) or 'preview' in item['title'].lower():
return None
tagmap = [
('11 Ways to Forget Your Ex-Boyfriend', '11 Ways to Forget Y... |
class RangeQuery:
def __init__(self, data, func=min):
self.func = func
self._data = _data = [list(data)]
i, n = 1, len(_data[0])
while 2 * i <= n:
prev = _data[-1]
_data.append([func(prev[j], prev[j + i]) for j in range(n - 2 * i + 1)])
i <<= 1
... |
"""
Main python file for the sssdevops example
"""
def mean(num_list):
"""
Calculate the mean of a list of numbers
Parameters
----------
num_list: list of int or float
Returns
-------
float of the mean of the list
Examples
--------
>>> mean([1, 2, 3, 4, 5])
3.0
... |
class SymbolTableItem:
def __init__(self, type, name, customId, value):
self.type = type
self.name = name
self.value = value
# if type == 'int' or type == 'bool':
# self.value = 0
# elif type == 'string':
# self.value = ' '
# else:
# ... |
#Desafio14
#Escreva um programa que converta uma temperatura digitando em
#graus Celsius e converta para graus Fahrenheit
temp=int(input('Digite a temperatura °C: '))
f=9*temp/5+32
print('A temperatura de {}°C corresponde a {}°F!'.format(temp,f))
|
# Define the fileName as a variable
fileToWrite = 'outputFile.txt'
fileHandle = open(fileToWrite, 'w')
i = 0
while i < 10:
fileHandle.write("This is line Number " + str(i) + "\n")
i += 1
fileHandle.close()
|
NOTES = """
(c) 2017 JUSTYN CHAYKOWSKI
PROVIDED UNDER MIT LICENSE
SCHOOLOGY.COM
ACCESS CODE: GNH9N-KZ2C2
RIC 115 <-- OFFICE HOURS:
M 4-6 PM
W 12-6 PM
##########################################
# RICE LAB
#
# TEXT BOOK = ARDX ARDUINO EXPERIMENTER'S KIT - OOMLOUT
#
# CLASS PROJECT --MUST-- BUILD OFF OF WORK ALREADY D... |
a = source()
if True:
b = a + 3 * sanitizer2(y)
else:
b = sanitizer(a)
sink(b) |
#
# This file contains the Python code from Program 10.10 of
# "Data Structures and Algorithms
# with Object-Oriented Design Patterns in Python"
# by Bruno R. Preiss.
#
# Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved.
#
# http://www.brpreiss.com/books/opus7/programs/pgm10_10.txt
#
class AVLTree(Bin... |
# Python program to print Even Numbers in given range
start, end = 4, 19
# iterating each number in list
for num in range(start, end + 1):
# checking condition
if num % 2 == 0:
print(num, end = " ")
|
x = input()
y = input()
z = input()
flag = z % (1 + 1) == 0 and (1 < x and x < 123) or (1 > y and y > x and x > y and y < 123)
def identity(var):
return var
if x ^ y == 1 or (
x % 2 == 0 and (3 > x and x <= 3 and 3 <= y and y > z and z >= 5) or (
identity(-1) + hash('hello') < 10 + 120 and 10 +... |
def main():
class student:
std = []
def __init__(self,name,id,cgpa):
self.name = name
self.id = id
self.cgpa = cgpa
def showId(self):
return self.id
def result(self):
if(self.cgpa > 8.5):
print(... |
def valid(a):
a = str(a)
num = set()
for char in a:
num.add(char)
return len(a) == len(num)
n = int(input())
n += 1
while True:
if valid(n):
print(n)
break
else:
n += 1
|
class QtConnectionError(Exception):
pass
class QtRestApiError(Exception):
""" Problem with authentification"""
pass
class QtFileTypeError(Exception):
"""Invalid type of file"""
pass
class QtArgumentError(Exception):
pass
class QtVocabularyError(Exception):
pass
class QtModelError(E... |
class PeculiarBalance:
"""
Can we save them? Beta Rabbit is trying to break into a lab that contains the only known zombie cure - but there's
an obstacle. The door will only open if a challenge is solved correctly. The future of the zombified rabbit
population is at stake, so Beta reads the challenge: ... |
P, A, B = map(int, input().split())
if P >= A+B:
print(P)
elif B > P:
print(-1)
else:
print(A+B)
|
PASSWORD = "PASSW0RD2019"
TO = ["test@gmail.com",
"test2@gmail.com"]
FROM = "test@gmail.com"
|
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incor... |
class Config(object):
ORG_NAME = 'footprints'
ORG_DOMAIN = 'footprints.devel'
APP_NAME = 'Footprints'
APP_VERSION = '0.4.0'
|
class Solution:
def minSubArrayLen(self, s: int, nums: List[int]) -> int:
left, sum, count = 0, 0, float('inf')
for right in range(len(nums)):
sum += nums[right]
while sum >= s:
count = min(count, right - left + 1)
sum -= ... |
def line(y1, x1, y2, x2):
"""
Yield integer coordinates for a line from (y1, x1) to (y2, x2).
"""
dy = abs(y2 - y1)
dx = abs(x2 - x1)
if dy == 0: # Horizontal
for x in range(x1, x2 + 1):
yield y1, x
elif dx == 0: # Vertical
for y in range(y1, y2 + 1):
... |
"""
TESTS TO WRITE:
* API contract tests for notify/email provider, github, trello
"""
|
def pisano(m):
prev,curr=0,1
for i in range(0,m*m):
prev,curr=curr,(prev+curr)%m
if prev==0 and curr == 1 :
return i+1
def fib(n,m):
seq=pisano(m)
n%=seq
if n<2:
return n
f=[0]*(n+1)
f[1]=1
for i in range(2,n+1):
f[i]=f[i-1]+f[i-2]
... |
### Malha de repetição (loop) - While
'''
O while é bastante parecido com um 'if': ele possui uma expressão,
e é executado caso ela seja verdadeira.
Mas o if é executado apenas uma vez e depois o código segue adiante.
O while não: ao final de sua execução, ele torna a testar a expressão,
e caso ela seja verdadeira, e... |
#
# PySNMP MIB module TRAPEZE-NETWORKS-RF-BLACKLIST-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRAPEZE-NETWORKS-RF-BLACKLIST-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:27:23 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using P... |
T = int(input())
for i in range(T):
try:
a, b = map(str, input().split())
print(int(int(a)//int(b)))
except Exception as e:
print("Error Code:", e)
|
def sortNums(nums):
# constant space solution
i = 0
j = len(nums) - 1
index = 0
while index <= j:
if nums[index] == 1:
nums[index], nums[i] = nums[i], nums[index]
index += 1
i += 1
if nums[index] == 2:
index += 1
if nums[index] ... |
#!/usr/bin/env python
def num_digits(k):
c = 0
while k > 0:
c += 1
k /= 10
return c
def is_kaprekar(k):
k2 = pow(k, 2)
p10ndk = pow(10, num_digits(k))
if k == (k2 // p10ndk) + (k2 % p10ndk):
return True
else:
return False
if __name__ == '__main__':
for ... |
def citerator(data: list, x: int, y: int, layer = False) -> list:
"""Bi-dimensional matrix iterator starting from any point (i, j),
iterating layer by layer around the starting coordinates.
Args:
data (list): Data set to iterate over.
x (int): X starting coordinate.
y (int): Y start... |
def decorating_fun(func):
def wrapping_function():
print("this is wrapping function and get func start")
func()
print("func end")
return wrapping_function
@decorating_fun
def decorated_func():
print("i`m decoraed")
decorated_func() |
class CannotAssignValueFromParentCategory(Exception):
def __init__(self):
super().__init__("422 Cannot assign value from parent category")
|
# read file
f=open("funny.txt","r")
for line in f:
print(line)
f.close()
# readlines()
f=open("funny.txt","r")
lines = f.readlines()
print(lines)
# write file
f=open("love.txt","w")
f.write("I love python")
f.close()
# same file when you write i love javascript the previous line goes away
f=open("love.txt","w")
... |
class NoKeywordsException(Exception):
"""Website does not contains any keywords in <meta> tag"""
pass
class BadURLException(Exception):
"""Website does not exists in a given URL"""
pass
|
# -*- coding: utf-8 -*-
"""
This software is licensed under the License (MIT) located at
https://github.com/ephreal/rollbot/Licence
Please see the license for any restrictions or rights granted to you by the
License.
"""
# A mock guild object for testing
class MockGuild():
def __init__(self, name=None, text_chan... |
"""
Programa que leia duas notas de um aluno e calcule sua média,
mostrando uma mensagem no final, de acordo com a média atingida.
- media abaixo de 5.0:
reprovado
- media entre 5.0 e 6.9:
recuperação
- media 7.0 ou superior:
aprovado
"""
nota1 = float(input('Informe a primeira nota: '))
nota2 = float(input('Inform... |
def get_first_matching_attr(obj, *attrs, default=None):
for attr in attrs:
if hasattr(obj, attr):
return getattr(obj, attr)
return default
def get_error_message(exc) -> str:
if hasattr(exc, 'message_dict'):
return exc.message_dict
error_msg = get_first_matching_attr(exc, '... |
class Batcher(object):
"""
Batcher enables developers to batch multiple retrieval requests.
Example usage #1::
from pycacher import Cacher
cacher = Cacher()
batcher = cacher.create_batcher()
batcher.add('testkey')
batcher.add('testkey1')
batcher.add('test... |
matriz = []
valor = []
somaPar = somaColuna3 = maiorLinha2 = 0
#Gerador de matriz 3x3
for i in range(0, 3):
for j in range(0, 3):
valor.append(int(input(f'Digite um valor para [{i}, {j}]: ')))
matriz.append(valor[:])
valor.clear()
print('-='*30)
for i in range(0, 3):
for j in range(0, 3):
... |
'''
Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST):
BSTIterator(TreeNode root) Initializes an object of the BSTIterator class. The root of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number small... |
c = input().strip()
fr = input().split()
n = 0
for i in fr:
if c in i: n += 1
print('{:.1f}'.format(n*100/len(fr)))
|
#Задача N3. Вариант 8
#Напишите программу, которая выводит имя "Борис Николаевич Бугаев", и
#запрашивает его псевдоним. Программа должна сцеплять две эти строки и
#выводить полученную строку, разделяя имя и псевдоним с помощью тире.
#Будашов Андрей
#03.03.2016
print("Герой нашей сегодняшней программы-Борис Николаевич ... |
# -*- coding: utf-8 -*-
# @Author: TD21forever
# @Date: 2019-05-25 00:18:44
# @Last Modified by: TD21forever
# @Last Modified time: 2019-05-26 11:36:12
'''
保证差距最远的两个磁道的概率最小
'''
def solution(k,alist):
sumRate = sum(alist)
rate = [i/sumRate for i in alist]
rate.sort()
j = 0
k = 0
result = 0
tm... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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 agree... |
raw_data = [
b'\x1cT#01 61.01,\r\nT#03 88.07,90.78,90.17,29.48,14.41\r\n \r\n \xae$\xe2\x02\xe0D\x143P\x02\xe0',
b'T#01 56.92,\r\nT#03 88.10,90.62,90.42,29.68,14.39\r\n \r\n C \xfc',
b'T#01 63.51,\r\nT#03 87.98,90.36,90.15,29.30,14.41\r\n \r\n \x03\x82\x01\x80$\x9f\xd8\xbc\x0f\x08',
b'T#01 56.05,\r\nT#0... |
# -*- coding: utf-8 -*-
#
# Unless explicitly stated otherwise all files in this repository are licensed
# under the Apache 2 License.
#
# This product includes software developed at Datadog
# (https://www.datadoghq.com/).
#
# Copyright 2018 Datadog, Inc.
#
"""crud_service.py
Service-helpers for creating and updatin... |
#
# @lc app=leetcode id=1299 lang=python3
#
# [1299] Replace Elements with Greatest Element on Right Side
#
# @lc code=start
class Solution:
def replaceElements(self, arr: List[int]) -> List[int]:
index = 0
result = []
for i,v in enumerate(arr):
if i+1 == len(arr):
... |
class Solution:
def findNumberOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
dp = [1 for i in range(len(nums))]
c = [1 for i in range(len(nums))]
for i in range(1, len(nums)):
for j in range(... |
# REFAZENDO O DESAFIO 51
# mostra os 10 primeiros termos de uma PA
print('GERADOR DE PA')
a1 = int(input('Digite o primeiro termo da PA: '))
r = int(input('Digite a razão da PA: '))
print('Dez primeiros termos da PA:')
termo = a1
i = 1
while i <= 10:
print('{} '.format(termo), end='')
termo += r
... |
def rotate(cur_direction, rotation_command):
# Assumes there are only R/L 90/180/270
invert_rl = {
"R": "L",
"L": "R",
}
if int(rotation_command[1:]) == 270:
rotation_command = f"{invert_rl[rotation_command[0]]}90"
elif int(rotation_command[1:]) == 180:
flip ... |
#-------------------------------------------------------------------------------
# Name: module2
# Purpose:
#
# Author: user
#
# Created: 28/03/2019
# Copyright: (c) user 2019
# Licence: <your licence>
#-------------------------------------------------------------------------------
pri... |
# https://codeforces.com/problemsets/acmsguru/problem/99999/100
A, B = map(int, input().split())
print(A+B)
|
"""
Check if items are in list
"""
def has_invalid_fields(fields):
for field in fields:
if field not in ['foo', 'bar']:
return True
return False
def has_invalid_fields2(fields):
return bool(set(fields) - set(['foo', 'bar']))
""" set eliminates duplicates """
""" Code is valid but... |
# Hand decompiled day 19 part 2
a,b,c,d,e,f = 1,0,0,0,0,0
c += 2
c *= c
c *= 209
b += 2
b *= 22
b += 7
c += b
if a == 1:
b = 27
b *= 28
b += 29
b *= 30
b *= 14
b *= 32
c += b
a = 0
for d in range(1, c+1):
if c % d == 0:
a += d
print(a) |
'''Faça um programa que tenha uma função chamada área(), que receba as dimensões de um terreno retangular (largura e comprimento) e mostre a área do terreno.'''
def linha():
print('=' * 30)
def area():
resultado = l * c
print('=' * 50)
print(f'A área total do terreno {l}X{c}é {resultado} metros.')
li... |
class test_result():
"""Log the performance on the test set"""
def __init__(self, autonet, X_test, Y_test):
self.autonet = autonet
self.X_test = X_test
self.Y_test = Y_test
def __call__(self, model, epochs):
if self.Y_test is None or self.X_test is None:
retu... |
'''Crow/AAP Alarm IP Module Feedback Class for alarm state'''
class StatusState:
# Zone State
@staticmethod
def get_initial_zone_state(maxZones):
"""Builds the proper zone state collection."""
_zoneState = {}
for i in range (1, maxZones+1):
_zoneState[i] = {'status': {'o... |
def go(o, a, b):
if o == '+':
return a + b
return a * b
def main():
a, o, b = int(input()), input(), int(input())
return go(o, a, b)
if __name__ == '__main__':
print(main())
|
"""Migration for a given Submitty course database."""
def up(config, database, semester, course):
if not database.table_has_column('teams', 'last_viewed_time'):
database.execute('ALTER TABLE teams ADD COLUMN last_viewed_time timestamp with time zone')
def down(config, database, semester, course):
pass... |
def cube(a):
"""Cube the number a.
Args:
a (float): The number to be squared.
"""
return a**3
|
#
# This file contains the Python code from Program 14.14 of
# "Data Structures and Algorithms
# with Object-Oriented Design Patterns in Python"
# by Bruno R. Preiss.
#
# Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved.
#
# http://www.brpreiss.com/books/opus7/programs/pgm14_14.txt
#
class SimpleRV(Ra... |
def test_list(client, seeder, utils):
user_id, admin_unit_id = seeder.setup_base()
seeder.create_event(admin_unit_id)
url = utils.get_url("planing")
utils.get_ok(url)
url = utils.get_url("planing", keyword="name")
utils.get_ok(url)
|
class Solution:
def to_hex(self, num: int) -> str:
if num == 0:
return "0"
prefix, ans = "0123456789abcdef", ""
num = 2 ** 32 + num if num < 0 else num
while num:
item = num & 15 # num % 16
ans = prefix[item] + ans
num >>= 4 # num //=... |
classifiers = """
License :: OSI Approved :: BSD License
Operating System :: POSIX
Intended Audience :: Developers
Intended Audience :: Science/Research
Programming Language :: C
Programming Language :: C++
Programming Language :: Cython
Programming Language :: Python
Programming Language :: Python :: 2
Programming Lan... |
def partTwo(instr: str) -> int:
# This is the parsing section
service_list = instr.strip().split("\n")[-1].split(",")
eqns = []
for i, svc in enumerate(service_list):
if svc == "x":
continue
svc = int(svc)
v = 0
if i != 0:
v = svc - i # This is ... |
'''
Motion Event Provider
=====================
Abstract class for the implemention of a
:class:`~kivy.input.motionevent.MotionEvent`
provider. The implementation must support the
:meth:`~MotionEventProvider.start`, :meth:`~MotionEventProvider.stop` and
:meth:`~MotionEventProvider.update` methods.
'''
__all__ = ('Mot... |
class Model(object):
def __init__(self, xml):
self.raw_data = xml
def __str__(self):
return self.raw_data.toprettyxml( )
def _get_attribute(self, attr):
val = self.raw_data.getAttribute(attr)
if val == '':
return None
return val
def _get_eleme... |
# cook your dish here
a=int(input())
b=int(input())
while(1):
if a%b==0:
print(a)
break
else:
a-=1
|
"""
Operadores relacionais
== Igual
!= Diferente
> Maior
< Menor
>= Maior ou igual
<= Menor ou igual
Operadores Lógicos
Operador Operação
AND → Duas condições sejam verdadeiras
OR → Pelo menos uma condição seja ver... |
# Exercício Python 086:
# Crie um programa que declare uma matriz de dimensão 3x3 e preencha com valores lidos pelo teclado.
# No final, mostre a matriz na tela, com a formatação correta.
matriz = list()
for contador in range(0, 10):
if 1 <= contador <= 3:
valor = int(input(f"Digite o valor da elemento [1,... |
"""
1. **kwargs usage
"""
def test(**kwargs):
# Do not use **kwargs
# Print key serials
print(*kwargs)
_dict = kwargs
for k in _dict.keys():
print("Key=", k)
print("Value=", _dict[k])
print()
test(a=1, b=2, c=3)
"""
1. * -> unpack container type
"""
list1 = [1, 2,... |
# -*- coding: utf-8 -*-
AUCTIONS = {
'simple': 'openprocurement.auction.esco.auctions.simple',
'multilot': 'openprocurement.auction.esco.auctions.multilot',
}
|
# python3
def max_pairwise_product(numbers):
x = sorted(numbers)
n = len(numbers)
return x[n-1] * x[n-2]
if __name__ == '__main__':
input_n = int(input())
input_numbers = [int(x) for x in input().split()]
print(max_pairwise_product(input_numbers))
|
def topological_sort(inc, out):
# ・ノードIDは、0~N-1とする
# ・以下のデータは既に作られているとする
# inc[n] = nに流入するリンク数(int)
# out[n] = nからの流出先のノード集合(list or set)
# N = 7
# inc = [0] * N
# out = [[] for _ in range(N)]
# inc[0] = 3
# inc[1] = 0
# inc[2] = 0
# inc[3] = 0
# inc[4] = 1
# inc... |
#!/usr/bin/env python3
"""
Custom errors for Seisflows
"""
class ParameterError(ValueError):
"""
A new ValueError class which explains the Parameter's that threw the error
"""
def __init__(self, *args):
if len(args) == 0:
msg = "Bad parameter."
super(ParameterError, sel... |
'''
Homework assignment for the 'Python is easy' course by Pirple.
Written by Ed Yablonsky.
It pprints the numbers from 1 to 100.
But for multiples of three print "Fizz" instead of the number and for the
multiples of five print "Buzz".
For numbers which are multiples of both three and five print "FizzBuzz".
It also a... |
"""
1309. Decrypt String from Alphabet to Integer Mapping
Given a string s formed by digits ('0' - '9') and '#' . We want to map s to English lowercase characters as follows:
Characters ('a' to 'i') are represented by ('1' to '9') respectively.
Characters ('j' to 'z') are represented by ('10#' to '26#') respectively. ... |
a=input()
print(a)
print(a)
print(a)
|
load(
"@io_bazel_rules_dotnet//dotnet/private:providers.bzl",
"DotnetLibrary",
)
def collect_transitive_info(deps):
"""Collects transitive information.
Args:
deps: Dependencies that the DotnetLibrary depends on.
Returns:
A depsets of the references, runfiles and deps. References and d... |
# ================================================================================
# Copyright (c) 2017-2019 AT&T Intellectual Property. All rights reserved.
# ================================================================================
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not... |
# Fancy-pants method for getting a where clause that groups adjacent image keys
# using "BETWEEN X AND Y" ... unfortunately this usually takes far more
# characters than using "ImageNumber IN (X,Y,Z...)" since we don't run into
# queries asking for consecutive image numbers very often (except when we do it
# deli... |
# A module for class Restaurant
"""A set of classes that can be used to represent a restaurant."""
class Restaurant():
"""A model of a restaurant."""
def __init__(self, name, cuisine):
"""Initialize name and age attributes."""
self.name = name
self.cuisine = cuisine
def describe... |
g = int(input().strip())
for _ in range(g):
n = int(input().strip())
s = [int(x) for x in input().strip().split(' ')]
x = 0
for i in s:
x ^= i
if len(set(s))==1 and 1 in s:
#here x=0 or 1
if x:#odd no. of ones
print("Second")
else:#even no. of... |
class SerializerNotFound(Exception):
"""
Serializer not found
"""
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.