content
stringlengths 7
1.05M
|
---|
dicionario_sites = {"Diego": "diegomariano.com"}
print(dicionario_sites['Diego'])
dicionario_sites = {"Diego": "diegomariano.com", "Google": "google.com", "Udemy": "udemy.com", "Luiz Carlin" : "luizcarlin.com.br"}
print ("-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=")
for chave in dicionario_sites:
print (chave + " -:- " +dicionario_sites[chave])
print(dicionario_sites[chave])
print ("-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=")
for i in dicionario_sites.items():
print(i)
print ("-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=")
for i in dicionario_sites.values():
print(i)
print ("-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=")
for i in dicionario_sites.keys():
print(i) |
# -*- coding: utf-8 -*-
# Author: Tonio Teran <[email protected]>
# Copyright: Stateoftheart AI PBC 2021.
'''RLlib's library wrapper.'''
SOURCE_METADATA = {
'name': 'rllib',
'original_name': 'RLlib',
'url': 'https://docs.ray.io/en/master/rllib.html'
}
MODELS = {
'discrete': [
'A2C', 'A3C', 'ARS', 'BC', 'ES', 'DQN', 'Rainbow', 'APEX-DQN', 'IMPALA',
'MARWIL', 'PG', 'PPO', 'APPO', 'R2D2', 'SAC', 'SlateQ', 'LinUCB',
'LinTS', 'AlphaZero', 'QMIX', 'MADDPG', 'Curiosity'
],
'continuous': [
'A2C',
'A3C',
'ARS',
'BC',
'CQL',
'ES',
# 'DDPG',
'TD3',
'APEX-DDPG',
'Dreamer',
'IMPALA',
'MAML',
'MARWIL',
'MBMPO',
'PG',
'PPO',
'APPO',
'SAC',
'MADDPG'
],
'multi-agent': [
'A2C',
'A3C',
'BC',
# 'DDPG',
'TD3',
'APEX-DDPG',
'DQN',
'Rainbow',
'APEX-DQN',
'IMPALA',
'MARWIL',
'PG',
'PPO',
'APPO',
'R2D2',
'SAC',
'LinUCB',
'LinTS',
'QMIX',
'MADDPG',
'Curiosity'
],
'unknown': [
'ParameterSharing', 'FullyIndependentLearning', 'SharedCriticMethods'
],
}
def load_model(name: str) -> dict:
return {'name': name, 'source': 'rllib'}
|
# Recursive, O(2^n)
def LCS(X, Y, m, n):
if m == 0 or n == 0:
return 0
elif X[m - 1] == Y[n - 1]:
return 1 + LCS(X, Y, m - 1, n - 1)
else:
return max(LCS(X, Y, m - 1, n), LCS(X, Y, m, n - 1))
X = "AGGTAB"
Y = "GXTXAYB"
print("Length of LCS is ", LCS(X, Y, len(X), len(Y)))
# Overlapping Substructure, Tabulation, O(mn)
def LCS(X, Y):
m = len(X)
n = len(Y)
L = [[None] * (n + 1) for i in range(m + 1)]
# build L[m+1][n+1] bottom up
# L[i][j] contains length of LCS of X[0..i-1]
# and Y[0..j-1]
for i in range(m + 1):
for j in range(n + 1):
if i == 0 or j == 0:
L[i][j] = 0
elif X[i - 1] == Y[j - 1]:
L[i][j] = L[i - 1][j - 1] + 1
else:
L[i][j] = max(L[i - 1][j], L[i][j - 1])
# L[m][n] contains LCS of X[0..m-1] & Y[0..n-1]
return L[m][n]
X = "ABCDGH"
Y = "AEDFHR"
print("Length of LCS is ", LCS(X, Y))
X = "AGGTAB"
Y = "GXTXAYB"
print("Length of LCS is ", LCS(X, Y))
|
class CalculoZ():
def calcular_z(self, n1, n2, x, y, ux, uy, ox, oy):
arriba = (x-y)-(ux-uy)
abajo = (((ox)**2/(n1))+((oy)**2/(n2)))**0.5
z = arriba/abajo
return z |
"""
입력으로 주어지는 리스트의 첫 원소와 마지막 원소의 합을 리턴
"""
def solution(x):
assert isinstance(x, list) and x and all(isinstance(i, int) for i in x), 'Value error!!!'
first_element = x[0]
last_element = x[-1]
return first_element + last_element
res = solution([i for i in range(11)])
print(f'해는 {res}')
|
class Solution:
def intToRoman(self, num: int) -> str:
res = ""
s = ['I', 'V', 'X', 'L', 'C', 'D', 'M']
index = 0
while num > 0:
x = num % 10
if x < 5:
if x == 4:
temp = s[index] + s[index + 1]
else:
temp = ""
while x > 0:
temp += s[index]
x -= 1
else:
if x == 9:
temp = s[index] + s[index + 2]
else:
temp = s[index + 1]
while x > 5:
temp += s[index]
x -= 1
index += 2
res = temp + res
num = num // 10
return res
if __name__ == '__main__':
print(
Solution().intToRoman(3), "III",
Solution().intToRoman(4), "IV",
Solution().intToRoman(9), "IX",
Solution().intToRoman(58), "LVIII",
Solution().intToRoman(1994), "MCMXCIV",
)
|
class BasicScript(object):
def __init__(self, parser):
"""
Initialize the class
:param parser: ArgumentParser
"""
super(BasicScript, self).__init__()
self._parser = parser
def get_arguments(self):
"""
Get the arguments to configure current script, should be implementd in children classes
:return: list
"""
raise StandardError('Implement get_arguments method')
def run(self, args, injector):
raise StandardError('Implement run method')
def configure(self):
"""
Configure the component before running it
:rtype: Class instance
"""
self.__set_arguments()
return self
def __set_arguments(self):
parser = self._parser.add_parser(self.__class__.__name__.lower(), help=self.__class__.__doc__,
conflict_handler='resolve')
arguments = self.get_arguments()
for argument in arguments:
short = argument['short']
long = argument['long']
del argument['short']
del argument['long']
parser.add_argument(short, long, **argument)
def get_wf_configuration(self, args, injector):
object_configuration = injector.get('object_configuration')
if 1 >= len(object_configuration):
configuration_file = args.configuration_file if 'configuration_file' in args and None != args.configuration_file else injector.get(
'interactive_configuration_file').get(args.wf_dir)
configuration = injector.get('wf_configuration').get_workflow_configuration(configuration_file)
configuration['config_paths'] = configuration_file
for key in configuration:
object_configuration[key] = configuration[key]
return object_configuration
|
def test():
# Here we can either check objects created in the solution code, or the
# string value of the solution, available as __solution__. A helper for
# printing formatted messages is available as __msg__. See the testTemplate
# in the meta.json for details.
# If an assertion fails, the message will be displayed
assert "L(range(12))" in __solution__, "range를 이용해 초기 L을 생성하였나요?"
assert "t *= 2" in __solution__, "*= 연산자를 사용하였나요?"
assert "t[0, 12]" in __solution__, "튜플 방식으로 찾아서 반환하였나요?"
assert "t[mask]" in __solution__, "마스킹 방식으로 찾아서 반환하였나요?"
__msg__.good("잘 하셨습니다!")
|
class ApiError(Exception):
"""
Exception raised when user does not have appropriate credentials
Used for 301 & 401 HTTP Status codes
"""
def __init__(self, response):
if 'error_description' in response:
self.message = response['error_description']
else:
self.message = response['error']
|
"""
Ejercicio: hacer un juego "Guess The number"
PARTE 1: Pedir al usuario que introduzca un número entre 0 y 100
PARTE 2: Adivinar el número por parte del usuario
Usar una función para capitalizar el código común
"""
MIN = 0
MAX = 99
def solicitar_introducir_numero(invite):
# Completar la entrada:
invite += " entre " + str(MIN) + " y " + str(MAX) + " incluídos: "
while True:
# Entramos en un bucle infinito
# Pedimos introducir un número
datoIntroducido = input(invite)
try:
datoIntroducido = int(datoIntroducido)
except:
pass
else:
# Hacer la comparación
if MIN <= datoIntroducido <= MAX:
# Tenemos lo que queremos, salimos del bucle
break
return datoIntroducido
# PARTE 1
numero = solicitar_introducir_numero("Introduzca el número a adivinar")
# PARTE 2
while True:
# Entramos en un bucle infinito
# que permite jugar varios turnos
intento = solicitar_introducir_numero("Adivine el número")
# Se prueba si el intento es correcto o no
if intento < numero:
print("Demasiado pequeño")
elif intento > numero:
print("Demasiado grande")
else:
print("Victoria!")
break
|
N, X, T = map(int, input().split())
time = N // X
if(N%X == 0):
print(time * T)
else:
print((time+1) * T) |
class Token:
__slots__ = ('start', 'end')
def __init__(self, start: int=None, end: int=None):
self.start = start
self.end = end
@property
def type(self):
"Type of current token"
return self.__class__.__name__
def to_json(self):
return dict([(k, self.__getattribute__(k)) for k in dir(self) if not k.startswith('__') and k != 'to_json'])
class Chars:
Hash = '#'
Dollar = '$'
Dash = '-'
Dot = '.'
Colon = ':'
Comma = ','
Excl = '!'
At = '@'
Percent = '%'
Underscore = '_'
RoundBracketOpen = '('
RoundBracketClose = ')'
CurlyBracketOpen = '{'
CurlyBracketClose = '}'
Sibling = '+'
SingleQuote = "'"
DoubleQuote = '"'
Transparent = 't'
class OperatorType:
Sibling = '+'
Important = '!'
ArgumentDelimiter = ','
ValueDelimiter = '-'
PropertyDelimiter = ':'
class Operator(Token):
__slots__ = ('operator',)
def __init__(self, operator: OperatorType, *args):
super(Operator, self).__init__(*args)
self.operator = operator
class Bracket(Token):
__slots__ = ('open',)
def __init__(self, is_open: bool, *args):
super(Bracket, self).__init__(*args)
self.open = is_open
class Literal(Token):
__slots__ = ('value',)
def __init__(self, value: str, *args):
super(Literal, self).__init__(*args)
self.value = value
class NumberValue(Token):
__slots__ = ('value', 'raw_value', 'unit')
def __init__(self, value: int, raw_value: str, unit='', *args):
super(NumberValue, self).__init__(*args)
self.value = value
self.raw_value = raw_value
self.unit = unit
class ColorValue(Token):
__slots__ = ('r', 'g', 'b', 'a', 'raw')
def __init__(self, r=0, g=0, b=0, a=None, raw='', *args):
super(ColorValue, self).__init__(*args)
self.r = r
self.g = g
self.b = b
self.a = a if a is not None else 1
self.raw = raw
class StringValue(Token):
__slots__ = ('value', 'quote')
def __init__(self, value: str, quote='', *args):
super(StringValue, self).__init__(*args)
self.value = value
self.quote = quote
class Field(Token):
__slots__ = ('name', 'index')
def __init__(self, name: str, index: int=None, *args):
super(Field, self).__init__(*args)
self.index = index
self.name = name
class WhiteSpace(Token): pass
|
literals = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ,.?/:;{[]}-=_+~!@#$%^&*()"
#obfuscated
literals = "tJ;EM mKrFzQ_SOT?]B[U@$yqec~fhd{=is&alxPIbnuRkC%Z(jDw#G:/)L,*.V!pov+HNYA^g-}WX"
key = 7
def shuffle(plaintext):
shuffled = ""
# shuffle plaintext
for i in range(int(len(plaintext) / 3)):
block = plaintext[i*3] + plaintext[i*3 + 1] + plaintext[i*3 + 2]
old0 = block[0]
old1 = block[1]
old2 = block[2]
block = old2 + old0 + old1
shuffled += block
shuffled += plaintext[len(plaintext) - (len(plaintext) % 3):len(plaintext)]
return shuffled
def unshuffle(ciphertext):
unshuffled = ""
# unshuffle plaintext
for i in range(int(len(ciphertext) / 3)):
block = ciphertext[i*3] + ciphertext[i*3 + 1] + ciphertext[i*3 + 2]
old0 = block[0]
old1 = block[1]
old2 = block[2]
block = old1 + old2 + old0
unshuffled += block
unshuffled += ciphertext[len(ciphertext) - (len(ciphertext) % 3):len(ciphertext)]
return unshuffled
def shift(plaintext):
shifted = ""
# Cipher shift
tmp = []
for i in range(len(plaintext)):
pos = literals.find(plaintext[i])
if pos >= 0:
if pos + key > len(literals):
pos = (pos + key) - len(literals)
res = literals[pos + key]
else:
res = plaintext[i]
tmp.append(res)
# reconstruct ciphertext
for i in range(len(tmp)):
shifted += tmp[i]
return shifted
def unshift(ciphertext):
unshifted = ""
tmp = []
for i in range(len(ciphertext)):
pos = literals.find(ciphertext[i])
if pos >= 0:
if pos - key < 0:
pos = (pos - key) + len(literals)
res = literals[pos - key]
else:
res = ciphertext[i]
tmp.append(res)
#reconstruct ciphertext
for i in range(len(tmp)):
unshifted += tmp[i]
return unshifted
def encrypt(msg):
msg = shuffle(msg)
msg = shift(msg)
return msg
def decrypt(msg):
#msg = unshuffle(msg)
msg = unshift(msg)
msg = unshuffle(msg)
return msg
def test():
test = "This is my plaintext"
test = "\nThis is a long paragraph with lots of exciting things\nI could go on and on about all of this stuff.\nLove, Zach!"
test = "abcdefghijklmnopqrstuvwxyz-ABCDEFGHIJKLMNOPQRSTUVWXYZ_!@#$%^&*()"
print ("Testing: " + test)
print ("Shuffle: " + shuffle(test))
print ("Shift: " + shift(shuffle(test)))
print ("Unshift: " + unshift(shift(shuffle(test))))
print ("Unshuffle: " + unshuffle(unshift(shift(shuffle(test)))))
print ("")
print ("Encrypt: " + encrypt(test))
print ("Decrypt: " + decrypt(encrypt(test)))
if __name__ == "__main__":
test()
|
# apis_v1/documentation_source/organization_suggestion_tasks_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def organization_suggestion_tasks_doc_template_values(url_root):
"""
Show documentation about organizationSuggestionTask
"""
required_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
{
'name': 'kind_of_suggestion_task',
'value': 'string', # boolean, integer, long, string
'description': 'Default is UPDATE_SUGGESTIONS_FROM_TWITTER_IDS_I_FOLLOW. '
'Other options include UPDATE_SUGGESTIONS_FROM_WHAT_FRIENDS_FOLLOW, '
'UPDATE_SUGGESTIONS_FROM_WHAT_FRIENDS_FOLLOW_ON_TWITTER, '
'UPDATE_SUGGESTIONS_FROM_WHAT_FRIEND_FOLLOWS, '
'UPDATE_SUGGESTIONS_FROM_WHAT_FRIEND_FOLLOWS_ON_TWITTER or UPDATE_SUGGESTIONS_ALL',
},
]
optional_query_parameter_list = [
{
'name': 'kind_of_follow_task',
'value': 'string', # boolean, integer, long, string
'description': 'Default is FOLLOW_SUGGESTIONS_FROM_TWITTER_IDS_I_FOLLOW. '
'Other options include FOLLOW_SUGGESTIONS_FROM_FRIENDS, '
'or FOLLOW_SUGGESTIONS_FROM_FRIENDS_ON_TWITTER, ',
},
]
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'Cannot proceed. A valid voter_device_id parameter was not included.',
},
{
'code': 'VALID_VOTER_ID_MISSING',
'description': 'Cannot proceed. A valid voter_id was not found.',
},
]
try_now_link_variables_dict = {
# 'organization_we_vote_id': 'wv85org1',
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "voter_device_id": string (88 characters long),\n' \
'}'
template_values = {
'api_name': 'organizationSuggestionTasks',
'api_slug': 'organizationSuggestionTasks',
'api_introduction':
"This will provide list of suggested endorsers to follow. "
"These suggestions are generated from twitter ids i follow, or organization of my friends follow",
'try_now_link': 'apis_v1:organizationSuggestionTasksView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
|
peso = float(input('Qual é seu peso? '))
altura = float(input('Qual é sua altura? '))
imc = peso / (altura * altura)
if imc < 18.5:
print(f'IMC {imc:.1f} Abaixo do Peso')
elif imc < 25:
print(f'IMC {imc:.1f} Peso Ideal')
elif imc < 30:
print(f'IMC {imc:.1f} Sobrepeso')
elif imc < 40:
print(f'IMC {imc:.1f} Obesidade')
else:
print(f'IMC {imc:.1f} Obesidade Morbida')
|
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class ConstraintSyntaxError(SyntaxError):
"""A generic error indicating an improperly defined constraint."""
pass
class ConstraintValueError(ValueError):
"""A generic error indicating a value violates a constraint."""
pass
|
curupira = int(input())
boitata = int(input())
boto = int(input())
mapinguari = int(input())
lara = int(input())
total = 225 + (curupira * 300) + (boitata *1500) + (boto * 600) + (mapinguari * 1000)+(lara*150)
print(total) |
class Sibling:
pass
|
if True:
foo = 42
else:
foo = None
|
#!/usr/bin/python3
print("Sum of even-valued terms less than four million in the Fibonacci sequence:")
a, b, sum = 1, 1, 0
while b < 4000000:
sum += b if b % 2 == 0 else 0
a, b = b, a + b
print(sum)
|
class Solution:
def numFactoredBinaryTrees(self, A):
"""
:type A: List[int]
:rtype: int
"""
A.sort()
nums, res, trees, factors = set(A), 0, {}, collections.defaultdict(set)
for i, num in enumerate(A):
for n in A[:i]:
if num % n == 0 and num // n in nums: factors[num].add(n)
for root in A:
trees[root] = 1
for fac in factors[root]: trees[root] += trees[fac] * trees[root // fac]
return sum(trees.values()) % ((10 ** 9) + 7) |
#LeetCode problem 200: Number of Islands
class Solution:
def check(self,grid,nodesVisited,row,col,m,n):
return (row>=0 and row<m and col>=0 and col<n and grid[row][col]=="1" and nodesVisited[row][col]==0)
def dfs(self,grid,nodesVisited,row,col,m,n):
a=[-1,1,0,0]
b=[0,0,1,-1]
nodesVisited[row][col]=1
for k in range(4):
if self.check(grid,nodesVisited,row+a[k],col+b[k],m,n):
self.dfs(grid,nodesVisited,row+a[k],col+b[k],m,n)
def numIslands(self, grid: List[List[str]]) -> int:
nodesVisited=[[0 for i in range(len(grid[0]))] for i in range(len(grid))]
count=0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j]=="0":
continue
elif grid[i][j]=="1" and nodesVisited[i][j]==0:
count+=1
self.dfs(grid,nodesVisited,i,j,len(grid),len(grid[0]))
return count |
# -*- coding: utf-8 -*-
"""
En este paquete se situarán distintas clases de utilidad para el
resto del proyecto.
"""
__author__ = "T. Teijeiro"
__date__ = "$30-nov-2011 17:50:53$"
|
'''
################
# 55. Jump Game
################
class Solution:
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if not nums or (nums[0]==0 and len(nums)>1):
return False
if len(nums)==1:
return True
l = len(nums)
max_ = 0
for i in range (l-1):
if nums[i]+i>max_:
max_ = nums[i] + i
if max_>=l-1:
return True
if max_==i and nums[i]==0:
return False
return False
# nums = [2,3,1,1,4]
nums = [1,2,0,3,0]
solu = Solution()
print (solu.canJump(nums))
'''
########################
# 56. Merge Intervals
########################
# Definition for an interval.
class Interval:
def __init__(self, s=0, e=0):
self.start = s
self.end = e
class Solution:
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
if not intervals:
return intervals
out = []
for interval in sorted(intervals, key=lambda i: i.start):
if out and interval.start<=out[-1].end:
out[-1].end = max(interval.end, out[-1].end)
else:
out.append(interval)
return out
intervals = [Interval(2,3), Interval(8,10),Interval(1,6),Interval(15,18)]
# intervals = [[2,3],[8,10],[1,6],[15,18]]
solu = Solution()
t = solu.merge(intervals)
print (t[1].end)
# print (sorted(intervals, key=lambda i: i.start))
|
'''
Create exceptions based on your inputs. Please follow the tasks below.
- Capture and handle system exceptions
- Create custom user-based exceptions
'''
class CustomInputError(Exception):
def __init__(self, *args, **kwargs):
print("Going through my own CustomInputError")
# Exception.__init__(self, *args, **kwargs)
class MyZeroDivisionException(ZeroDivisionError):
def __init__(self):
print("The data is not valid")
class DataNotValidException(TypeError):
def __init__(self):
print("The data contains Strings. Only numbers are expected in the input data")
|
"""
This folder contains help-functions to Bokeh visualizations
in Python.
There are functions that align 2nd-ary y-axis to primary
y-axis as well as functions that align 3 y-axes.
"""
__credits__ = "ICOS Carbon Portal"
__license__ = "GPL-3.0"
__version__ = "0.1.0"
__maintainer__ = "ICOS Carbon Portal, elaborated products team"
__email__ = ['[email protected]', '[email protected]']
__date__ = "2020-10-15" |
def computador_escolhe_jogada(n, m):
pc_remove = 1
while pc_remove != m:
if (n - pc_remove) % (m+1) == 0:
return pc_remove
else:
pc_remove += 1
return pc_remove
def usuario_escolhe_jogada(n, m):
while True:
usuario_removeu = int(input('Quantas peças você vai tirar? '))
if usuario_removeu > m or usuario_removeu <= 0:
print('Oops! Jogada inválida! Tente de novo.')
else:
break
return usuario_removeu
def campeonato():
for i in range(0, 3):
print()
print(f'**** Rodada {i+1} ****')
print()
partida()
print()
print('**** Final do campeonato! ****')
print()
print('Placar: Você 0 X 3 Computador')
def partida():
n = int(input('Quantas peças? '))
m = int(input('Limite de peças por jogada? '))
while n < m:
print('As peças tem que conter um valor maior que as jogadas. Tente de novo!')
n = int(input('Quantas peças? '))
m = int(input('Limite de peças por jogada? '))
print()
usuario = False
if n % (m+1) == 0:
print('Você começa')
usuario = True
else:
print('Computador começa')
while n > 0:
if usuario:
escolha_do_usuario = usuario_escolhe_jogada(n, m)
print()
if escolha_do_usuario == 1:
print('Você tirou uma peça.')
else:
print(f'Voce tirou {escolha_do_usuario} peças.')
if n == 1:
print('Agora resta apenas uma peça no tabuleiro.')
elif n != 0:
print(
f'Agora resta {n - escolha_do_usuario} peça no tabuleiro.')
n -= escolha_do_usuario
usuario = False
else:
escolha_do_pc = computador_escolhe_jogada(n, m)
print()
if escolha_do_pc == 1:
print('O computador tirou uma peça.')
else:
print(f'O computador tirou {escolha_do_pc} peças.')
if n == 1:
print('Agora resta apenas uma peça no tabuleiro.')
elif n != 0:
print(f'Agora resta {n - escolha_do_pc} peça no tabuleiro.')
print()
n -= escolha_do_pc
usuario = True
print('Fim do jogo! O computador ganhou!')
# Programa Principal!!
print()
print('Bem-vindo ao jogo do NIM! Escolha:')
print()
while True:
print('1 - para jogar uma partida isolada')
partida_ou_campeonato = int(input('2 - para jogar um campeonato '))
if partida_ou_campeonato == 2:
print()
print('Voce escolheu um campeonato!')
print()
campeonato()
break
elif partida_ou_campeonato == 1:
print()
print('Voce escolheu partida isolada')
print()
partida()
break
else:
print('Numero invalido tente de novo! ')
|
"""Collection of all documented ADS constants. Only a small subset of these
are used by code in this library.
Source: http://infosys.beckhoff.com/english.php?content=../content/1033/tcplclibsystem/html/tcplclibsys_constants.htm&id= # nopep8
"""
"""Port numbers"""
# Port number of the standard loggers.
AMSPORT_LOGGER = 100
# Port number of the TwinCAT Eventloggers.
AMSPORT_EVENTLOG = 110
# Port number of the TwinCAT Realtime Servers.
AMSPORT_R0_RTIME = 200
# Port number of the TwinCAT I/O Servers.
AMSPORT_R0_IO = 300
# Port number of the TwinCAT NC Servers.
AMSPORT_R0_NC = 500
# Port number of the TwinCAT NC Servers (Task SAF).
AMSPORT_R0_NCSAF = 501
# Port number of the TwinCAT NC Servers (Task SVB).
AMSPORT_R0_NCSVB = 511
# internal
AMSPORT_R0_ISG = 550
# Port number of the TwinCAT NC I Servers.
AMSPORT_R0_CNC = 600
# internal
AMSPORT_R0_LINE = 700
# Port number of the TwinCAT PLC Servers (only at the Buscontroller).
AMSPORT_R0_PLC = 800
# Port number of the TwinCAT PLC Servers in the runtime 1.
AMSPORT_R0_PLC_RTS1 = 801
# Port number of the TwinCAT PLC Servers in the runtime 2.
AMSPORT_R0_PLC_RTS2 = 811
# Port number of the TwinCAT PLC Servers in the runtime 3.
AMSPORT_R0_PLC_RTS3 = 821
# Port number of the TwinCAT PLC Servers in the runtime 4.
AMSPORT_R0_PLC_RTS4 = 831
# Port number of the TwinCAT CAM Server.
AMSPORT_R0_CAM = 900
# Port number of the TwinCAT CAMTOOL Server.
AMSPORT_R0_CAMTOOL = 950
# Port number of the TwinCAT System Service.
AMSPORT_R3_SYSSERV = 10000
# Port number of the TwinCAT Scope Servers (since Lib. V2.0.12)
AMSPORT_R3_SCOPESERVER = 27110
"""ADS States"""
ADSSTATE_INVALID = 0 # ADS Status: invalid
ADSSTATE_IDLE = 1 # ADS Status: idle
ADSSTATE_RESET = 2 # ADS Status: reset.
ADSSTATE_INIT = 3 # ADS Status: init
ADSSTATE_START = 4 # ADS Status: start
ADSSTATE_RUN = 5 # ADS Status: run
ADSSTATE_STOP = 6 # ADS Status: stop
ADSSTATE_SAVECFG = 7 # ADS Status: save configuration
ADSSTATE_LOADCFG = 8 # ADS Status: load configuration
ADSSTATE_POWERFAILURE = 9 # ADS Status: Power failure
ADSSTATE_POWERGOOD = 10 # ADS Status: Power good
ADSSTATE_ERROR = 11 # ADS Status: Error
ADSSTATE_SHUTDOWN = 12 # ADS Status: Shutdown
ADSSTATE_SUSPEND = 13 # ADS Status: Suspend
ADSSTATE_RESUME = 14 # ADS Status: Resume
ADSSTATE_CONFIG = 15 # ADS Status: Configuration
ADSSTATE_RECONFIG = 16 # ADS Status: Reconfiguration
ADSSTATE_MAXSTATES = 17
"""Reserved Index Groups"""
ADSIGRP_SYMTAB = 0xF000
ADSIGRP_SYMNAME = 0xF001
ADSIGRP_SYMVAL = 0xF002
ADSIGRP_SYM_HNDBYNAME = 0xF003
ADSIGRP_SYM_VALBYNAME = 0xF004
ADSIGRP_SYM_VALBYHND = 0xF005
ADSIGRP_SYM_RELEASEHND = 0xF006
ADSIGRP_SYM_INFOBYNAME = 0xF007
ADSIGRP_SYM_VERSION = 0xF008
ADSIGRP_SYM_INFOBYNAMEEX = 0xF009
ADSIGRP_SYM_DOWNLOAD = 0xF00A
ADSIGRP_SYM_UPLOAD = 0xF00B
ADSIGRP_SYM_UPLOADINFO = 0xF00C
ADSIGRP_SYM_SUMREAD = 0xF080
ADSIGRP_SYM_SUMWRITE = 0xF081
ADSIGRP_SYM_SUMREADWRITE = 0xF082
ADSIGRP_SYMNOTE = 0xF010
ADSIGRP_IOIMAGE_RWIB = 0xF020
ADSIGRP_IOIMAGE_RWIX = 0xF021
ADSIGRP_IOIMAGE_RISIZE = 0xF025
ADSIGRP_IOIMAGE_RWOB = 0xF030
ADSIGRP_IOIMAGE_RWOX = 0xF031
ADSIGRP_IOIMAGE_RWOSIZE = 0xF035
ADSIGRP_IOIMAGE_CLEARI = 0xF040
ADSIGRP_IOIMAGE_CLEARO = 0xF050
ADSIGRP_IOIMAGE_RWIOB = 0xF060
ADSIGRP_DEVICE_DATA = 0xF100
ADSIOFFS_DEVDATA_ADSSTATE = 0x0000
ADSIOFFS_DEVDATA_DEVSTATE = 0x0002
"""System Service Index Groups"""
SYSTEMSERVICE_OPENCREATE = 100
SYSTEMSERVICE_OPENREAD = 101
SYSTEMSERVICE_OPENWRITE = 102
SYSTEMSERVICE_CREATEFILE = 110
SYSTEMSERVICE_CLOSEHANDLE = 111
SYSTEMSERVICE_FOPEN = 120
SYSTEMSERVICE_FCLOSE = 121
SYSTEMSERVICE_FREAD = 122
SYSTEMSERVICE_FWRITE = 123
SYSTEMSERVICE_FSEEK = 124
SYSTEMSERVICE_FTELL = 125
SYSTEMSERVICE_FGETS = 126
SYSTEMSERVICE_FPUTS = 127
SYSTEMSERVICE_FSCANF = 128
SYSTEMSERVICE_FPRINTF = 129
SYSTEMSERVICE_FEOF = 130
SYSTEMSERVICE_FDELETE = 131
SYSTEMSERVICE_FRENAME = 132
SYSTEMSERVICE_REG_HKEYLOCALMACHINE = 200
SYSTEMSERVICE_SENDEMAIL = 300
SYSTEMSERVICE_TIMESERVICES = 400
SYSTEMSERVICE_STARTPROCESS = 500
SYSTEMSERVICE_CHANGENETID = 600
"""System Service Index Offsets (Timeservices)"""
TIMESERVICE_DATEANDTIME = 1
TIMESERVICE_SYSTEMTIMES = 2
TIMESERVICE_RTCTIMEDIFF = 3
TIMESERVICE_ADJUSTTIMETORTC = 4
"""Masks for Log output"""
ADSLOG_MSGTYPE_HINT = 0x01
ADSLOG_MSGTYPE_WARN = 0x02
ADSLOG_MSGTYPE_ERROR = 0x04
ADSLOG_MSGTYPE_LOG = 0x10
ADSLOG_MSGTYPE_MSGBOX = 0x20
ADSLOG_MSGTYPE_RESOURCE = 0x40
ADSLOG_MSGTYPE_STRING = 0x80
"""Masks for Bootdata-Flagsx"""
BOOTDATAFLAGS_RETAIN_LOADED = 0x01
BOOTDATAFLAGS_RETAIN_INVALID = 0x02
BOOTDATAFLAGS_RETAIN_REQUESTED = 0x04
BOOTDATAFLAGS_PERSISTENT_LOADED = 0x10
BOOTDATAFLAGS_PERSISTENT_INVALID = 0x20
"""Masks for BSOD-Flags"""
SYSTEMSTATEFLAGS_BSOD = 0x01 # BSOD: Blue Screen of Death
SYSTEMSTATEFLAGS_RTVIOLATION = 0x02 # Realtime violation, latency time overrun
"""Masks for File output"""
# 'r': Opens file for reading
FOPEN_MODEREAD = 0x0001
# 'w': Opens file for writing, (possible) existing files were overwritten.
FOPEN_MODEWRITE = 0x0002
# 'a': Opens file for writing, is attached to (possible) exisiting files. If no
# file exists, it will be created.
FOPEN_MODEAPPEND = 0x0004
# '+': Opens a file for reading and writing.
FOPEN_MODEPLUS = 0x0008
# 'b': Opens a file for binary reading and writing.
FOPEN_MODEBINARY = 0x0010
# 't': Opens a file for textual reading and writing.
FOPEN_MODETEXT = 0x0020
"""Masks for Eventlogger Flags"""
# Class and priority are defined by the formatter.
TCEVENTFLAG_PRIOCLASS = 0x0010
# The formatting information comes with the event
TCEVENTFLAG_FMTSELF = 0x0020
# Logg.
TCEVENTFLAG_LOG = 0x0040
# Show message box .
TCEVENTFLAG_MSGBOX = 0x0080
# Use Source-Id instead of Source name.
TCEVENTFLAG_SRCID = 0x0100
"""TwinCAT Eventlogger Status messages"""
# Not valid, occurs also if the event was not reported.
TCEVENTSTATE_INVALID = 0x0000
# Event is reported, but neither signed off nor acknowledged.
TCEVENTSTATE_SIGNALED = 0x0001
# Event is signed off ('gone').
TCEVENTSTATE_RESET = 0x0002
# Event is acknowledged.
TCEVENTSTATE_CONFIRMED = 0x0010
# Event is signed off and acknowledged.
TCEVENTSTATE_RESETCON = 0x0012
"""TwinCAT Eventlogger Status messages"""
TCEVENT_SRCNAMESIZE = 15 # Max. Length for the Source name.
TCEVENT_FMTPRGSIZE = 31 # Max. Length for the name of the formatters.
"""Other"""
PI = 3.1415926535897932384626433832795 # Pi number
DEFAULT_ADS_TIMEOUT = 5 # (seconds) Default ADS timeout
MAX_STRING_LENGTH = 255 # The max. string length of T_MaxString data type
|
# https://www.acmicpc.net/problem/8393
a = int(input())
result = 0
for i in range(a + 1):
result = result + i
print(result) |
# conf.py/Open GoPro, Version 1.0 (C) Copyright 2021 GoPro, Inc. (http://gopro.com/OpenGoPro).
# This copyright was auto-generated on Tue May 18 22:08:50 UTC 2021
project = "Open GoPro Python SDK"
copyright = "2020, GoPro Inc."
author = "Tim Camise"
version = "0.5.8"
release = "0.5.8"
templates_path = ["_templates"]
source_suffix = ".rst"
master_doc = "index"
pygments_style = "sphinx"
html_static_path = ["_static"]
extensions = [
"sphinx.ext.autodoc",
"sphinxcontrib.napoleon",
"sphinx_rtd_theme",
"sphinx.ext.autosectionlabel",
]
html_theme = "sphinx_rtd_theme"
html_context = {
"display_github": True,
} |
# Link --> https://www.hackerrank.com/challenges/maximum-element/problem
# Code:
def getMax(operations):
maximum = 0
temp = []
answer = []
for i in operations:
if i != '2' and i != '3':
numbers = i.split()
number = int(numbers[1])
temp.append(number)
if number > maximum:
maximum = number
elif i == '2':
temp.pop()
if len(temp) != 0:
maximum = max(temp)
else:
maximum = 0
else:
answer.append(maximum)
return answer
|
# 양방향 연결 리스트 노드 삽입 (insertBefore() 구현)
class Node:
def __init__(self, item):
self.data = item
self.prev = None
self.next = None
class DoublyLinkedList:
def __init__(self):
self.nodeCount = 0
self.head = Node(None)
self.tail = Node(None)
self.head.prev = None
self.head.next = self.tail
self.tail.prev = self.head
self.tail.next = None
def traverse(self):
result = []
curr = self.head
while curr.next.next:
curr = curr.next
result.append(curr.data)
return result
def insertBefore(self, next, newNode):
prev = next.prev
prev.next = newNode
next.prev = newNode
newNode.prev = prev
newNode.next = next
self.nodeCount += 1
return True
def solution(x):
return 0
|
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 30 15:49:24 2021
@author: alann
"""
arr = [[1,1,0,1,0],
[0,1,1,1,0],
[1,1,1,1,0],
[0,1,1,1,1]]
def largestSquare(arr ) -> int:
if len(arr) < 1 or len(arr[0]) < 1:
return 0
largest = 0
cache = [[0 for i in range(len(arr[0]))] for j in range(len(arr))]
for i, iVal in enumerate(arr):
for j, jVal in enumerate(iVal):
if jVal:
if not i or not j:
cache[i][j] = jVal
else:
currentMin = None
currentMin = min(currentMin, cache[i-1][j]) if currentMin != None else cache[i-1][j]
currentMin = min(currentMin, cache[i-1][j-1]) if currentMin != None else cache[i-1][j-1]
currentMin = min(currentMin, cache[i][j-1]) if currentMin != None else cache[i][j-1]
cache[i][j] = currentMin + 1
largest = max(largest, cache[i][j])
return largest
largest = largestSquare(arr)
print(largest)
"""
if we are allowed to modify original array we can do it in constant space
"""
arr = [[1,1,0,1,0],
[0,1,1,1,0],
[1,1,1,1,0],
[0,1,1,1,1]]
def largestSquare(arr ) -> int:
if len(arr) < 1 or len(arr[0]) < 1:
return 0
largest = 0
for i, iVal in enumerate(arr):
for j, jVal in enumerate(iVal):
if jVal:
if not i or not j:
arr[i][j] = jVal
else:
arr[i][j] = 1 + min(arr[i-1][j], arr[i-1][j-1],arr[i][j-1])
largest = max(largest, arr[i][j])
return largest
largest = largestSquare(arr)
print(largest) |
s = 0
for i in range(1, 500+1, 2):
m = i + 3
s += m
print(s)
# imprime 63250 na tela
'''
soma = 0
for c in range(1, 501, 2)
if c%3 == 0:
soma = soma + c
print('A soma de todos os valores solicitados é {}'.format(soma)
''' |
# -*- coding: utf-8 -*-
"""
Created on Sun May 12 19:10:03 2019
@author: DiPu
"""
shopping_list=[]
print("enter items to add in list and type quit when you arew done")
while True:
ip=input("enter list")
if ip=="QUIT":
break
elif ip.upper()=="SHOW":
print(shopping_list)
elif ip.upper()=="HELP":
print("help1:if input is show then items in list will be displayed")
print("help2:if input is QUIT then total items in list will be printed and user will not be able to add more items")
else:
shopping_list.append(ip)
for count,item in enumerate(shopping_list,1):
print(count,item)
ip=input("enter add to ADDITION/REMOVE of item at some index:")
if ip=="ADDITION":
ip1=int(input("enter index:"))
item=input("enter item:")
shopping_list[ip1-1]=item
elif ip=="REMOVE":
ip1=int(input("enter index:"))
shopping_list.pop(ip1-1)
with open("shopping_list_miniprojectpy.py",'rt') as f1:
with open("shopping.txt",'wt') as f:
for lines in f1:
f.write(lines)
ip=open("shopping.txt")
content=ip.readlines()
print(content)
|
#!/usr/bin/env python3
if __name__ == "__main__":
N = int(input().strip())
stamps = set()
for _ in range(N):
stamp = input().strip()
stamps.add(stamp)
print(len(stamps)) |
"""Provide a class for yWriter chapter representation.
Copyright (c) 2021 Peter Triesberger
For further information see https://github.com/peter88213/PyWriter
Published under the MIT License (https://opensource.org/licenses/mit-license.php)
"""
class Chapter():
"""yWriter chapter representation.
# xml: <CHAPTERS><CHAPTER>
"""
chapterTitlePrefix = "Chapter "
# str
# Can be changed at runtime for non-English projects.
def __init__(self):
self.title = None
# str
# xml: <Title>
self.desc = None
# str
# xml: <Desc>
self.chLevel = None
# int
# xml: <SectionStart>
# 0 = chapter level
# 1 = section level ("this chapter begins a section")
self.oldType = None
# int
# xml: <Type>
# 0 = chapter type (marked "Chapter")
# 1 = other type (marked "Other")
self.chType = None
# int
# xml: <ChapterType>
# 0 = Normal
# 1 = Notes
# 2 = Todo
self.isUnused = None
# bool
# xml: <Unused> -1
self.suppressChapterTitle = None
# bool
# xml: <Fields><Field_SuppressChapterTitle> 1
# True: Chapter heading not to be displayed in written document.
# False: Chapter heading to be displayed in written document.
self.isTrash = None
# bool
# xml: <Fields><Field_IsTrash> 1
# True: This chapter is the yw7 project's "trash bin".
# False: This chapter is not a "trash bin".
self.suppressChapterBreak = None
# bool
# xml: <Fields><Field_SuppressChapterBreak> 0
self.srtScenes = []
# list of str
# xml: <Scenes><ScID>
# The chapter's scene IDs. The order of its elements
# corresponds to the chapter's order of the scenes.
def get_title(self):
"""Fix auto-chapter titles if necessary
"""
text = self.title
if text:
text = text.replace('Chapter ', self.chapterTitlePrefix)
return text
|
"""
"""
# TODO: make this list complete [exclude stuffs ending with 's']
conditionals = [
"cmp",
"cmn",
"tst",
"teq"
]
class CMP(object):
def __init__(self, line_no, text):
self.line_no = line_no
self.text = text
class Branch(object):
def __init__(self, line_no, text, label=None):
text = text.strip()
self.line_no = line_no
self.text = text
# dealing with space
self.label_text = getArgs(text)[0]
self.label = label
class Label(object):
def __init__(self, line_no, text):
self.line_no = line_no
self.text = text.replace(":", "")
class Loop(object):
def __init__(self, label, branch, cmp):
self.label = label
self.branch = branch
self.cmp = cmp
self.enterNode = label.line_no
self.exitNode = branch.line_no
def getStart(self):
return self.enterNode
def getEnd(self):
return self.exitNode
def contains(self, i, j):
if i > self.enterNode and j < self.exitNode:
return True
return False
class If(object):
def __init__(self, cmp, branch_to_end, end_label):
self.cmp = cmp
self.cmp_branch = branch_to_end
self.branch_to_end = branch_to_end
self.end_label = end_label
self.block1_start_line = branch_to_end.line_no + 1
self.block1_end_line = end_label.line_no - 1
def contains(self, i, j):
if i > self.block1_start_line and j <= self.block1_end_line:
return True
return False
def getStart(self):
return self.block1_start_line
def getEnd(self):
return self.block1_end_line
class IfElse(object):
def __init__(self, cmp, branch_to_2nd_block, branch_to_end, block2_label, end_label):
self.cmp = cmp
self.cmp_branch = branch_to_2nd_block
self.branch_to_2nd_Block = branch_to_2nd_block
self.block1_start_line = branch_to_2nd_block.line_no + 1
assert branch_to_end.line_no - 1 == block2_label.line_no - 2
self.block1_end_line = branch_to_end.line_no - 1
self.block2_start_line = block2_label.line_no + 1
self.block2_end_line = end_label.line_no - 1
self.block2_start_label = block2_label
self.block2_label = block2_label
self.block2_end_label = end_label
self.end_label = end_label
def isLabel(text):
if text.strip().endswith(":"):
return True
def isConditional(text):
text = getOpcode(text)
# if text.endswith("s"):
# return True
# print(text)
if text in conditionals:
return True
return False
# TODO: make this more robust
def isBranching(text):
if text.startswith("b"):
return True
return False
def removeSpaces(text):
text = text.replace("\t"," ")
text = text.strip(" ")
text = text.strip("\n")
i = 0
while(i != len(text)-1):
if text[i] == " " and text[i+1] == " ":
text = text[:i+1]+text[i+2:]
continue
i += 1
return text
def getOpcode(text):
text = removeSpaces(text)
op = text.split(" ")[0]
return op
def getArgs(text):
text = removeSpaces(text)
op = ''.join(text.split(" ")[1:])
args = op.split(",")
for i in range(len(args)):
args[i].strip(" ")
if args[i][0] == "#":
args[i] = args[i][1:]
return args
def getComparison(cmp, branch):
vars = getArgs(cmp)
var1 = vars[0]
var2 = vars[1]
cond = getOpcode(branch)[1:]
ans = ""
if cond == "eq":
ans = (str(var1) + " == " + str(var2))
elif cond == "lt":
ans = (str(var1) + " < " + str(var2))
elif cond == "gt":
ans = (str(var1) + " > " + str(var2))
elif cond == "ge":
ans = (str(var1) + " >= " + str(var2))
elif cond == "le":
ans = (str(var1) + " <= " + str(var2))
elif cond == "ne":
ans = (str(var1) + " != " + str(var2))
return ans
'''
def getOpDesc(text):
text = text.upper()
args = getArgs(text)
opcode = getOpcode(text)
if opcode == "add" or opcode == "vadd.f32" or opcode == "vadd.f64":
print(str(args[0]) + " = " + str(args[1]) + " + " + str(args[2]))
elif opcode == "sub":
print(str(args[0]) + " = " + str(args[1]) + " - " + str(args[2]))
elif opcode == "rsb":
print(str(args[0]) + " = " + str(args[2]) + " - " + str(args[1]))
elif opcode == "and":
print(str(args[0]) + " = " + str(args[1]) + " && " + str(args[2]))
elif opcode == "orr":
print(str(args[0]) + " = " + str(args[1]) + " || " + str(args[2]))
elif opcode == "mov" or opcode == "vmov.f32":
print(str(args[0]) + " = " + str(args[1]))
elif opcode == "str":
print(str(args[1]) + " = " + str(args[0]))
elif opcode == "ldr":
print("int " + str(args[0]) + " = " + str(args[1]))
elif opcode == "vldr.32":
print("float " + str(args[0]) + " = " + str(args[1]))
elif opcode == "vldr.64":
print("double " + str(args[0]) + " = " + str(args[1]))
elif opcode == "ldrb":
print("char " + str(args[0]) + " = " + str(args[1]))
''' |
# coding: utf-8
"""
Union-Find (Disjoint Set)
https://en.wikipedia.org/wiki/Disjoint-set_data_structure
"""
class QuickFindUnionFind:
def __init__(self, union_pairs=()):
self.num_groups = 0
self.auto_increment_id = 1
self.element_groups = {
# element: group_id,
}
for p, q in union_pairs:
self.union(p, q)
def __len__(self):
return self.num_groups
# O(1)
def make_group(self, element):
# Initially, every element is in its own group which contains only itself.
group_id = self.element_groups.get(element)
if group_id is None:
# Group id could be arbitrary as long as each group has an unique one.
group_id = self.auto_increment_id
self.element_groups[element] = group_id
self.num_groups += 1
self.auto_increment_id += 1
return group_id
# O(1)
def find(self, p):
try:
return self.element_groups[p]
except KeyError:
# We implicitly create a new group for the new element `p`.
return self.make_group(p)
# O(n)
def union(self, p, q):
p_group_id = self.find(p)
q_group_id = self.find(q)
if p_group_id != q_group_id:
for element, group_id in self.element_groups.items():
# Merge p into q.
if group_id == p_group_id:
self.element_groups[element] = q_group_id
self.num_groups -= 1
# O(1)
def is_connected(self, p, q):
return self.find(p) == self.find(q)
|
class Solution(object):
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
if not nums: return None
i = len(nums)-1
j = -1 # j is set to -1 for case `4321`, so need to reverse all in following step
while i > 0:
if nums[i-1] < nums[i]: # first one violates the trend
j = i-1
break
i-=1
for i in xrange(len(nums)-1, -1, -1):
if nums[i] > nums[j]: #
nums[i], nums[j] = nums[j], nums[i] # swap position
nums[j+1:] = sorted(nums[j+1:]) # sort rest
return |
def sort_data_by_cumulus(data):
"""
Sort data by submitted_by field, which holds
the cumulus number (or id),
Parameters:
data (list): A list containing the report
data.
Returns:
(dict): A dict containg the data sorted by the
cumulus id.
"""
sorted_data = {}
for d in data:
if d["user"] not in sorted_data:
sorted_data[d["user"]] = []
sorted_data[d["user"]].append(d)
else:
sorted_data[d["user"]].append(d)
return sorted_data
|
# -*- coding: utf-8 -*-
# Copyright (C) 2017 Intel Corporation. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
class Group(object):
def __init__(self, name):
self.name = name
self.__attributes = {}
def equals(self, obj):
return self.name == obj.get_name()
def get_attribute(self, key):
return self._attributes[key]
def get_device_members(self):
devices = []
all_devices = IAgentManager.getInstance().get_all_devices()
for device in all_devices:
if self.name in device.get_groups():
devices.append(device)
return devices
def get_name(self):
return self.name
def get_resource_members(self):
resources = []
all_devices = IAgentManager.getInstance().get_all_devices()
for device in all_devices:
resources_device = device.get_resources()
for resource in resource_device:
if self.name in resource.get_groups:
resources.append(resource)
return resources
def hash_code(self):
return hash(self.name)
|
"""
Configuration file
"""
class Config:
"""
Base Configuration
"""
DEBUG = True
SECRET_KEY = r'f\x13\xd9fM\xdc\x82\x01b\xdb\x03'
SQLALCHEMY_POOL_SIZE = 5
SQLALCHEMY_POOL_TIMEOUT = 120
SQLALCHEMY_POOL_RECYCLE = 280
MAIL_SERVER = 'smtp.gmail.com'
MAIL_PORT = 465
MAIL_USERNAME = r'[email protected]'
MAIL_PASSWORD = r'Reset@123'
MAIL_USE_TLS = False
MAIL_USE_SSL = True
FTP_SERVER = 'aigbusiness.in'
FTP_USER = '[email protected]'
FTP_PASSWORD = 'policy123'
class DevelopmentConfig(Config):
"""
Local Development
"""
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'mysql://[email protected]/aig_docs'
class ProductionConfig(Config):
"""
Production configurations
"""
DEBUG = False
SQLALCHEMY_DATABASE_URI = 'mysql://root:maria@[email protected]/aig_docs'
app_config = {
'development': DevelopmentConfig,
'production': ProductionConfig
}
|
# -*- coding:utf-8 -*-
# https://leetcode.com/problems/permutation-sequence/description/
class Solution(object):
def getPermutation(self, n, k):
"""
:type n: int
:type k: int
:rtype: str
"""
factorial = [1]
for i in range(1, n):
factorial.append(i * factorial[-1])
num = [i for i in range(1, n + 1)]
ret = []
for i in range(n - 1, -1, -1):
m = factorial[i]
ret.append(num.pop((k - 1) / m))
k = ((k - 1) % m) + 1
return ''.join(map(str, ret)) |
datasetDir = '../dataset/'
model = '../model/lenet'
modelDir = '../model/'
epochs = 20
batchSize = 128
rate = 0.001
mu = 0
sigma = 0.1
|
"""A board is a list of list of str. For example, the board
ANTT
XSOB
is represented as the list
[['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']]
A word list is a list of str. For example, the list of words
ANT
BOX
SOB
TO
is represented as the list
['ANT', 'BOX', 'SOB', 'TO']
"""
def is_valid_word(wordlist, word):
""" (list of str, str) -> bool
Return True if and only if word is an element of wordlist.
>>> is_valid_word(['ANT', 'BOX', 'SOB', 'TO'], 'TO')
True
"""
return word in wordlist
def make_str_from_row(board, row_index):
""" (list of list of str, int) -> str
Return the characters from the row of the board with index row_index
as a single string.
>>> make_str_from_row([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 0)
'ANTT'
"""
str_row = ''
i=0
for i in range(len(board[row_index])):
str_row = str_row+board[row_index[i]]
i = i+1
return str_row
def make_str_from_column(board, column_index):
""" (list of list of str, int) -> str
Return the characters from the column of the board with index column_index
as a single string.
>>> make_str_from_column([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 1)
'NS'
"""
str_col=''
for strList in board:
str_col += strList[column_index]
return str_col
def board_contains_word_in_row(board, word):
""" (list of list of str, str) -> bool
Return True if and only if one or more of the rows of the board contains
word.
Precondition: board has at least one row and one column, and word is a
valid word.
>>> board_contains_word_in_row([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 'SOB')
True
"""
for row_index in range(len(board)):
if word in make_str_from_row(board, row_index):
return True
return False
def board_contains_word_in_column(board, word):
""" (list of list of str, str) -> bool
Return True if and only if one or more of the columns of the board
contains word.
Precondition: board has at least one row and one column, and word is a
valid word.
>>> board_contains_word_in_column([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 'NO')
False
"""
for index in range(len(board)):
myStr = make_str_from_column(board, index)
if word in myStr:
return True
else:
return False
def board_contains_word(board, word):
""" (list of list of str, str) -> bool
Return True if and only if word appears in board.
Precondition: board has at least one row and one column.
>>> board_contains_word([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 'ANT')
True
"""
return (board_contains_word_in_row(board, word) or board_contains_word_in_column(board, word))
def word_score(word):
""" (str) -> int
Return the point value the word earns.
Word length: < 3: 0 points
3-6: 1 point per character for all characters in word
7-9: 2 points per character for all characters in word
10+: 3 points per character for all characters in word
>>> word_score('DRUDGERY')
16
"""
if len(word) < 3:
return 0
elif len(word) <7:
return 1
elif len(word) < 10:
return 2
else:
return 3
def update_score(player_info, word):
""" ([str, int] list, str) -> NoneType
player_info is a list with the player's name and score. Update player_info
by adding the point value word earns to the player's score.
>>> update_score(['Jonathan', 4], 'ANT')
"""
player_info[1] += word_score(word)
def num_words_on_board(board, words):
""" (list of list of str, list of str) -> int
Return how many words appear on board.
>>> num_words_on_board([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], ['ANT', 'BOX', 'SOB', 'TO'])
3
"""
count=0
for word in words:
if board_contains_word(board, word):
count +=1
return count
def read_words(words_file):
""" (file open for reading) -> list of str
Return a list of all words (with newlines removed) from open file
words_file.
Precondition: Each line of the file contains a word in uppercase characters
from the standard English alphabet.
"""
f = open(words_file)
myList = []
for line in f.readlines():
myList.append(line[0:len(line)-1])
f.close()
return myList
def read_board(board_file):
""" (file open for reading) -> list of list of str
Return a board read from open file board_file. The board file will contain
one row of the board per line. Newlines are not included in the board.
"""
f = open(board_file)
myList = []
for word in f.readlines():
word = word[0:len(word) - 1]
tempList = []
for letter in word:
tempList.append(letter)
myList.append(tempList)
f.close()
return myList
|
# flake8: noqa
_JULIA_V1 = {
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "PythonRuntimeMetadata v1.0",
"description": "PythonRuntimeMetadata runtime/metadata.json schema.",
"type": "object",
"properties": {
"metadata_version": {
"description": "The metadata version.",
"type": "string"
},
"implementation": {
"description": "The implementation (e.g. cpython)",
"type": "string"
},
"version": {
"description": "The implementation version, e.g. pypy 2.6.1 would report 2.6.1 as the 'upstream' part.",
"type": "string"
},
"abi": {
"description": "The runtime's ABI, e.g. 'msvc2008' or 'gnu'.",
"type": "string"
},
"language_version": {
"description": "This is the 'language' version, e.g. pypy 2.6.1 would report 2.7.10 here.",
"type": "string"
},
"platform": {
"description": ("The platform string (as can be parsed by"
"EPDPlatform.from_epd_string"),
"type": "string"
},
"build_revision": {
"description": "Build revision (internal only).",
"type": "string",
},
"executable": {
"description": "The full path to the actual runtime executable.",
"type": "string",
},
"paths": {
"description": "The list of path to have access to this runtime.",
"type": "array",
"items": {"type": "string"},
},
"post_install": {
"description": ("The command (as a list) to execute after "
"installation."),
"type": "array",
"items": {"type": "string"},
},
},
"required": [
"metadata_version",
"implementation",
"version",
"abi",
"language_version",
"platform",
"build_revision",
"executable",
"paths",
"post_install",
]
}
_PYTHON_V1 = {
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "PythonRuntimeMetadata v1.0",
"description": "PythonRuntimeMetadata runtime/metadata.json schema.",
"type": "object",
"properties": {
"metadata_version": {
"description": "The metadata version.",
"type": "string"
},
"implementation": {
"description": "The implementation (e.g. cpython)",
"type": "string"
},
"version": {
"description": "The implementation version, e.g. pypy 2.6.1 would report 2.6.1 as the 'upstream' part.",
"type": "string"
},
"abi": {
"description": "The runtime's ABI, e.g. 'msvc2008' or 'gnu'.",
"type": "string"
},
"language_version": {
"description": "This is the 'language' version, e.g. pypy 2.6.1 would report 2.7.10 here.",
"type": "string"
},
"platform": {
"description": ("The platform string (as can be parsed by"
"EPDPlatform.from_epd_string"),
"type": "string"
},
"build_revision": {
"description": "Build revision (internal only).",
"type": "string",
},
"executable": {
"description": "The full path to the actual runtime executable.",
"type": "string",
},
"paths": {
"description": "The list of path to have access to this runtime.",
"type": "array",
"items": {"type": "string"},
},
"post_install": {
"description": ("The command (as a list) to execute after "
"installation."),
"type": "array",
"items": {"type": "string"},
},
"scriptsdir": {
"description": "Full path to scripts directory.",
"type": "string",
},
"site_packages": {
"description": "The full path to the python site packages.",
"type": "string",
},
"python_tag": {
"description": "The python tag, as defined in PEP 425.",
"type": "string",
},
},
"required": [
"metadata_version",
"implementation",
"version",
"abi",
"language_version",
"platform",
"build_revision",
"executable",
"paths",
"post_install",
"scriptsdir",
"site_packages",
"python_tag",
]
}
|
# Copyright 2009 Moyshe BenRabi
#
# 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
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This is always generated file. Do not edit directyly.
# Instead edit messagegen.pl and descr.txt
class ProgramFragment(object):
def __init__(self):
self.max_program_name = 25
self.program_name = ''
self.program_major_version = 0
self.program_minor_version = 0
self.protocol_major_version = 0
self.protocol_minor_version = 0
self.protocol_source_revision = 0
def clear(self):
self.program_name = ''
self.program_major_version = 0
self.program_minor_version = 0
self.protocol_major_version = 0
self.protocol_minor_version = 0
self.protocol_source_revision = 0
super(ProgramFragment,self).clear()
def frame_data_size(self, frame_index):
result = 0
result += 1
result += 1
result += 1
result += 1
result += 4
return result
def serialize(self, writer):
writer.writeRange(self.program_name,self.max_program_name,'chr')
writer.write(self.program_major_version,'byte')
writer.write(self.program_minor_version,'byte')
writer.write(self.protocol_major_version,'byte')
writer.write(self.protocol_minor_version,'byte')
writer.write(self.protocol_source_revision,'uint')
def deserialize(self, reader):
(self.program_name, c) = reader.readRange(self.max_program_name,'chr',1)
(self.program_major_version, c) = reader.read('byte')
(self.program_minor_version, c) = reader.read('byte')
(self.protocol_major_version, c) = reader.read('byte')
(self.protocol_minor_version, c) = reader.read('byte')
(self.protocol_source_revision, c) = reader.read('uint')
def __str__(self):
return 'ProgramFragment('+self.program_name \
+ str(self.program_major_version) \
+ str(self.program_minor_version) \
+ str(self.protocol_major_version) \
+ str(self.protocol_minor_version) \
+ str(self.protocol_source_revision)+')'
def __eq__(self,other):
return True and \
(self.program_name == other.program_name) and \
self.program_major_version == other.program_major_version and \
self.program_minor_version == other.program_minor_version and \
self.protocol_major_version == other.protocol_major_version and \
self.protocol_minor_version == other.protocol_minor_version and \
self.protocol_source_revision == other.protocol_source_revision
def __ne__(self,other):
return True or \
(self.program_name != other.program_name) or \
self.program_major_version != other.program_major_version or \
self.program_minor_version != other.program_minor_version or \
self.protocol_major_version != other.protocol_major_version or \
self.protocol_minor_version != other.protocol_minor_version or \
self.protocol_source_revision != other.protocol_source_revision
|
class Singleton:
__instance = None
@classmethod
def __get_instance(cls):
return cls.__instance
@classmethod
def instance(cls, *args, **kargs):
cls.__instance = cls(*args, **kargs)
cls.instance = cls.__get_instance
return cls.__instance
"""""
class MyClass(BaseClass, Singleton):
pass
c = MyClass.instance()
""""" |
dadosd = dict()
jogadores = list()
gols = list()
while True:
dadosd['nome'] = str(input('Nome: '))
total = int(input('Quantas partidas {} jogou? '.format(dadosd['nome'])))
for c in range(0, total):
gols.append(int(input('Quantos gols no {}º jogo? '.format(c+1))))
dadosd['gols'] = gols[:]
gols.clear()
jogadores.append(dadosd.copy())
dadosd.clear()
sn = str(input('Quer continuar? S/N '))
while sn not in 'SsNn':
sn = str(input('Quer continuar? S ou N'))
if sn in 'Nn':
break
print('Nº | Nome | Gols | Total')
for i, p in enumerate(jogadores):
print('{} {} {} {}'.format(i, p['nome'], p['gols'], sum(p['gols'])))
print('=-'*30)
while True:
num = int(input('Ler dados de qual jogador? (999 para sair) '))
if num == 999:
break
if num >= len(jogadores):
print('Erro!!! numero não está na lista')
if num <= len(jogadores)-1:
print('Levantamento do jogador {}'.format(jogadores[num]['nome']))
for i, v in enumerate(jogadores[num]['gols']):
print('=> No {}º jogo fez {} '.format(i+1, v))
|
test_cases = int(input())
for t in range(1, test_cases + 1):
nums = list(map(int, input().strip().split()))
result = []
for i in range(0, 5):
for j in range(i + 1, 6):
for k in range(j + 1, 7):
result.append(nums[i] + nums[j] + nums[k])
result = sorted(list(set(result)), reverse=True)
print('#{} {}'.format(t, result[4]))
|
# atomic level
def get_idx(list, key):
for idx in range(len(list)):
if key == list[idx][0]:
return idx
def ins(list, key, val):
list.append([key, val])
return list
def ret(list, key):
idx = get_idx(list, key)
return list[idx][1]
def upd(list, key, val):
new_item = [key.lower(), val]
idx = get_idx(list, key)
list[idx] = new_item
return list
def delete(list, key):
idx = get_idx(list, key)
list.remove(idx)
return list
# table level
def ins_tab(db, table_name):
return ins(db, table_name, [])
def ret_tab(db, table_name):
return ret(db, table_name)
def upd_tab(db, table_name, table):
return upd(db, table_name, table)
def del_tab(db, table_name):
return delete(db, table_name)
# record level
def is_member(record, kv, check_value):
if len(kv) == 0:
return True
else:
for item in record:
if item[0] == kv[0]:
if check_value:
if item[1] == kv[1]:
return True
else:
return True
return False
def kvs_in_rec(record, kv_list):
# all kv's of kv_list_search are members of record
for kv in kv_list:
if not is_member(record, kv, True):
return False
return True
def ins_rec(db, table_name, kv_list):
table = ret(db, table_name)
table.append(kv_list)
return upd(db, table_name, table)
def ret_recs(db, table_name, kv_list):
list = []
table = ret(db, table_name)
for record in table:
if kvs_in_rec(record, kv_list):
list.append(record)
return list
def ret_rec_idx(db, table_name, record_idx):
table = ret(db, table_name)
if len(table) >= record_idx:
return table[record_idx]
else:
return None
def upd_recs(db, table_name, kv_list_search, kv_list_upd):
# updates all records identified by kv_list_search
new_table = []
old_table = ret_tab(db, table_name)
for old_rec in old_table:
if kvs_in_rec(old_rec, kv_list_search):
# matching record
new_rec = old_rec
for kv in kv_list_upd:
# if kv is member of record, update value of kv,
# otherwise insert entire kv
key = kv[0]
val = kv[1]
if is_member(new_rec, kv, False):
new_rec = upd(new_rec, key, val)
else:
new_rec = ins(new_rec, key, val)
new_table.append(new_rec)
else:
new_table.append(old_rec)
return upd(db, table_name, new_table)
def del_recs(db, table_name, kv_list):
new_table = []
old_table = ret_tab(db, table_name)
for record in old_table:
if not kvs_in_rec(record, kv_list):
new_table.append(record)
return upd(db, table_name, new_table)
def del_all(db, table_name):
table = []
return upd(db, table_name, table)
# value level
def ret_val(db, table_name, record_id_key, record_id_value, data_key):
# assumes [record_id_key, record_id_value] identifies a single record
records = ret_recs(db, table_name, [[record_id_key, record_id_value]])
if len(records) == 0:
return None
else:
return ret(records[0], data_key)
def ret_val_idx(db, table_name, record_idx, data_key):
record = ret_rec_idx(db, table_name, record_idx)
if record:
return ret(record, data_key)
else:
return None
def upd_val(db, table_name, record_id_key, record_id_val, data_key, data_val):
# updates all records identified by [record_id_key, record_id_value]
return upd_recs(db,
table_name,
[[record_id_key, record_id_val]],
[[data_key, data_val]])
# summary
def rec_cnt(db, table_name, kv_list):
records = ret_recs(db, table_name, kv_list)
return len(records)
def rec_list(db, table_name, key):
list = []
table = ret_tab(db, table_name)
for record in table:
for item in record:
if item[0].lower() == key.lower():
if not item[1] in list:
list.append(item[1])
return list
|
class Example:
def __init__(self):
self.name = ""
pass
def greet(self, name):
self.name = name
print("hello " + name)
|
class Carrinho_de_compras:
def __init__(self):
self.produtos = []
def inserir_produto(self, produto):
self.produtos.append(produto)
def listar_produtos(self):
for produto in self.produtos:
print(produto.nome, produto.valor)
def soma_total(self):
total = 0
for x in self.produtos:
total = total + x.valor
return total
'''
Eu não consigo desempacotar uma lista dentro de duas variaveis num for aqui nas classes
eu tenho que chamar pra dentro de uma só, e depois, qd for tratar ela, eu especifico com qual método eu quero lidar
'''
class Produto:
def __init__(self, nome, valor):
self.nome = nome
self.valor = valor
|
class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
i = 0
maxlen = 0
self.longest = {}
while i < len(s):
if s[i] == ")":
i = i + 1
continue
else:
l = self.find_longest(i, s)
if l - i + 1 > maxlen:
maxlen = l - i + 1
i = l + 1
return maxlen
def find_longest(self, i, s):
if i in self.longest:
return self.longest[i]
start = balance = i
left = 0
right = 0
while True:
if i >= len(s):
self.longest[start] = balance
return balance
if s[i] == "(":
left += 1
else:
right += 1
if left < right:
self.longest[start] = balance
return balance
if left == right:
balance = i
i = i + 1
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module represent logic of detection and conversion of cheats.
"""
# py_ver : [3.5.2]
# date : [02.11.2016]
# author : [Aleksey Yakovlev]
# email : [[email protected]]
class AntiCheater(object):
""" Help to detect and convert text cheats.
:method check_word: convert word if needed and indicate cheating
"""
def __init__(self):
super().__init__()
self.LRUS = set('АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя')
self.LENG = set('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz')
self.TR_URUS = list('АВЕКМНОРСТУХЬ')
self.TR_UENG = list('ABEKMHOPCTYXb')
self.TR_LRUS = list('аеикорсухь')
self.TR_LENG = list('aeukopcyxb')
def check_word(self, word):
""" Check word for creats - changing russian letters by similar english and vice versa.
Detect cheats and converts cheat-letters to source language.
:param word: a word to check
:return: a tuple like (result_word, is_cheat)
is_cheat = 0 - there is no cheats or 'word' is not alphabetic
result_word = source word
is_cheat = 1 - cheat found
result_word = source word with cheat correction
is_cheat = -1 - cheats maybe found, all letters can be both of rus and eng
if number of RUS unique letters less than ENG, then
result_word = source word with translate to ENG
else
result_word = source word with translate to RUS
is_cheat = -2 - there is bot of rus and eng letters, but it can convert to another lang
result_word = source word
"""
is_cheat = 0
result_word = word
if not word.isalpha():
return result_word, is_cheat
# get set of letters by language
rus_parts = {x for x in word if (x in self.LRUS)}
eng_parts = {x for x in word if (x in self.LENG)}
if not rus_parts or not eng_parts:
# if only one language detected - there is no cheats
return result_word, is_cheat
# check letters can be converted to another language
check_rus = rus_parts.issubset(set(self.TR_LRUS + self.TR_URUS))
check_eng = eng_parts.issubset(set(self.TR_LENG + self.TR_UENG))
if not check_rus and not check_eng:
# strange word, but..
is_cheat = -2
elif check_rus and not check_eng:
# translate to english
is_cheat = 1
result_word = word.translate(str.maketrans(''.join(self.TR_LRUS + self.TR_URUS),
''.join(self.TR_LENG + self.TR_UENG)))
elif not check_rus and check_eng:
# translate to russian
is_cheat = 1
result_word = word.translate(str.maketrans(''.join(self.TR_LENG + self.TR_UENG),
''.join(self.TR_LRUS + self.TR_URUS)))
else:
is_cheat = -1
if len(rus_parts) >= len(eng_parts):
# translate to russian
result_word = word.translate(str.maketrans(''.join(self.TR_LENG + self.TR_UENG),
''.join(self.TR_LRUS + self.TR_URUS)))
else:
# translate to english
result_word = word.translate(str.maketrans(''.join(self.TR_LRUS + self.TR_URUS),
''.join(self.TR_LENG + self.TR_UENG)))
return result_word, is_cheat
def _main():
police = AntiCheater()
print(police.check_word('мoлoкo'))
print(police.check_word('milk'))
print(police.check_word('ёжuк'))
print(police.check_word('cмecb'))
print(police.check_word('вecтник'))
print(police.check_word('КНИГА'))
print(police.check_word('кyкушка'))
print(police.check_word('kykaреку'))
print(police.check_word('АВТOMOБИЛb'))
print(police.check_word('superДОМ'))
if __name__ == '__main__':
_main()
|
#!/usr/bin/env python3
visited = set()
visited.add((0, 0))
turn = 0 # Santa = 0, Robo-Santa = 1
locations = [[0, 0], [0, 0]]
with open('input.txt', 'r') as f:
for line in f:
for ch in line:
pos = locations[turn]
turn = (turn + 1) % 2
if ch == '^':
pos[0] += 1
elif ch == 'v':
pos[0] -= 1
elif ch == '<':
pos[1] -= 1
elif ch == '>':
pos[1] += 1
visited.add(tuple(pos))
print("Total houses", len(visited))
|
# import pytest
class TestBaseReplacerMixin:
def test_target(self): # synced
assert True
def test_write(self): # synced
assert True
def test_flush(self): # synced
assert True
def test_close(self): # synced
assert True
class TestStdOutReplacerMixin:
def test_target(self): # synced
assert True
class TestStdErrReplacerMixin:
def test_target(self): # synced
assert True
class TestStdOutFileRedirector:
def test___str__(self): # synced
assert True
def test_write(self): # synced
assert True
class TestBaseStreamRedirector:
def test___str__(self): # synced
assert True
def test_write(self): # synced
assert True
def test_flush(self): # synced
assert True
def test_close(self): # synced
assert True
class TestStdOutStreamRedirector:
pass
class TestStdErrStreamRedirector:
pass
class TestSupressor:
def test_write(self): # synced
assert True
|
# coding: utf8
db.define_table('post',
Field('Email',requires=IS_EMAIL()),
Field('filen','upload'),
auth.signature)
|
class Solution:
def dfs(self,row_cnt:int, col_cnt:int, i:int, j:int, obs_arr:list, solve_dict:dict):
if (i, j) in solve_dict:
return solve_dict[(i,j)]
right_cnt = 0
down_cnt = 0
#right
if i + 1 < row_cnt and not obs_arr[i + 1][j]:
if (i + 1, j) in solve_dict:
right_cnt = solve_dict[(i + 1, j)]
else:
right_cnt = self.dfs(row_cnt, col_cnt,i + 1, j,obs_arr,solve_dict)
#left
if j + 1 < col_cnt and not obs_arr[i][j + 1]:
if (i, j + 1) in solve_dict:
down_cnt = solve_dict[(i, j + 1)]
else:
down_cnt = self.dfs(row_cnt, col_cnt, i, j + 1,obs_arr, solve_dict)
res = right_cnt + down_cnt
solve_dict[(i, j)] = res
return res
def uniquePathsWithObstacles(self, obstacleGrid: list) -> int:
row = len(obstacleGrid)
if not row:
return 0
col = len(obstacleGrid[0])
if not col:
return 0
if obstacleGrid[row - 1][col - 1]:
return 0
if obstacleGrid[0][0]:
return 0
res = self.dfs(row,col,0,0,obstacleGrid, {(row-1, col - 1):1})
return res
t1 = [
[0,0,0],
[0,1,0],
[0,0,0]
]
sl = Solution()
res = sl.uniquePathsWithObstacles(t1)
print(res) |
class MkDocsTyperException(Exception):
"""
Generic exception class for mkdocs-typer errors.
"""
|
dataset_type = 'ShipRSImageNet_Level2'
# data_root = 'data/Ship_ImageNet/'
data_root = './data/ShipRSImageNet/'
CLASSES = ('Other Ship', 'Other Warship', 'Submarine', 'Aircraft Carrier', 'Cruiser', 'Destroyer',
'Frigate', 'Patrol', 'Landing', 'Commander', 'Auxiliary Ships', 'Other Merchant',
'Container Ship', 'RoRo', 'Cargo', 'Barge', 'Tugboat', 'Ferry', 'Yacht',
'Sailboat', 'Fishing Vessel', 'Oil Tanker', 'Hovercraft', 'Motorboat', 'Dock',)
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations', with_bbox=True),
dict(type='Resize', img_scale=(1333, 800), keep_ratio=True),
dict(type='RandomFlip', flip_ratio=0.5),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size_divisor=32),
dict(type='DefaultFormatBundle'),
dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']),
]
test_pipeline = [
dict(type='LoadImageFromFile'),
dict(
type='MultiScaleFlipAug',
img_scale=(1333, 800),
flip=False,
transforms=[
dict(type='Resize', keep_ratio=True),
dict(type='RandomFlip'),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size_divisor=32),
dict(type='ImageToTensor', keys=['img']),
dict(type='Collect', keys=['img']),
])
]
data = dict(
samples_per_gpu=8,
workers_per_gpu=2,
train=dict(
type=dataset_type,
classes=CLASSES,
ann_file=data_root + 'COCO_Format/ShipRSImageNet_bbox_train_level_2.json',
img_prefix=data_root + 'VOC_Format/JPEGImages/',
pipeline=train_pipeline),
val=dict(
type=dataset_type,
classes=CLASSES,
ann_file=data_root + 'COCO_Format/ShipRSImageNet_bbox_val_level_2.json',
img_prefix=data_root + 'VOC_Format/JPEGImages/',
pipeline=test_pipeline),
test=dict(
type=dataset_type,
classes=CLASSES,
ann_file=data_root + 'COCO_Format/ShipRSImageNet_bbox_val_level_2.json',
img_prefix=data_root + 'VOC_Format/JPEGImages/',
pipeline=test_pipeline))
evaluation = dict(interval=10, metric='bbox')
|
class Solution:
def minFlips(self, mat: List[List[int]]) -> int:
# 放到 flip 函数外面可以减少计算
mapper = {"0": "1", "1": "0"}
def flip(state: List[str], i: int) -> None:
state[i] = mapper[state[i]]
if i % n != 0:
state[i - 1] = mapper[state[i - 1]]
if i % n < n - 1:
state[i + 1] = mapper[state[i + 1]]
if i >= n:
state[i - n] = mapper[state[i - n]]
if i < (m - 1) * n:
state[i + n] = mapper[state[i + n]]
m = len(mat)
n = len(mat[0])
target = "0" * (m * n)
cur = "".join(str(cell) for row in mat for cell in row)
queue = [cur]
visited = set()
steps = 0
while len(queue) > 0:
for _ in range(len(queue)):
cur = queue.pop(0)
if cur == target:
return steps
if cur in visited:
continue
visited.add(cur)
for i in range(len(cur)):
s = list(cur)
flip(s, i)
queue.append("".join(s))
steps += 1
return -1
|
#https://programmers.co.kr/learn/courses/30/lessons/64061
# 크레인 인형뽑기
def solution(board, moves):
answer = 0
size = len(board[0])
a = []
for m in moves:
for i in range(size):
if board[i][m-1] != 0:
a.append(board[i][m-1])
board[i][m-1] = 0
break
if len(a) == 1 or len(a) == 0:
continue
else:
if a[-1] == a[-2]:
a.pop()
a.pop()
answer+=2
print(a)
return answer |
def dbapi_subscription(dbsession, action, input_dict, action_filter={}, caller_area={}):
_api_name = "dbapi_subscription"
_api_entity = 'SUBSCRIPTION'
_api_action = action
_api_msgID = set_msgID(_api_name, _api_action, _api_entity)
_process_identity_kwargs = {'type': 'api', 'module': module_id, 'name': _api_name, 'action': _api_action, 'entity': _api_entity, 'msgID': _api_msgID,}
_process_adapters_kwargs = {'dbsession': dbsession}
_process_log_kwargs = {'indent_method': 'AUTO', 'indent_level':None}
_process_debug_level = get_debug_level(caller_area.get('debug_level'), **_process_identity_kwargs, **_process_adapters_kwargs)
_process_debug_files = get_debug_files(_process_debug_level, **_process_identity_kwargs, **_process_adapters_kwargs)
_process_debug_kwargs={'debug_level':_process_debug_level,'debug_files':_process_debug_files}
_process_signature = build_process_signature(**_process_identity_kwargs, **_process_adapters_kwargs, **_process_debug_kwargs, **_process_log_kwargs)
_process_call_area = build_process_call_area(_process_signature, caller_area)
log_process_start(_api_msgID,**_process_call_area)
log_process_input('', 'input_dict', input_dict,**_process_call_area)
log_process_input('', 'action_filter', action_filter,**_process_call_area)
log_process_input('', 'caller_area', caller_area,**_process_call_area)
input_dict.update({'client_type': 'subscriber'})
if action.upper() in ('REGISTER','ADD','REFRESH'):
action='REFRESH'
action_result = dbsession.table_action(dbmodel.CLIENT, action, input_dict, action_filter, auto_commit=True, caller_area=_process_call_area)
api_result = action_result
thismsg=action_result.get('api_message')
api_result.update({'api_action': _api_action, 'api_name': _api_name})
if not api_result.get('api_status') == 'success':
# msg = f"subscription not registered"
# api_result.update({'api_message':msg})
log_process_finish(_api_msgID, api_result, **_process_call_area)
return api_result
client = api_result.get('api_data')
client_id = client.get('client_id')
input_dict.update({'client_id': client_id})
elif action.upper() in ('CONFIRM', 'ACTIVATE', 'DEACTIVATE', 'DELETE'):
subscription_dict = dbsession.get(dbmodel.SUBSCRIPTION, input_dict, 'DICT', caller_area=_process_call_area)
if not subscription_dict:
msg = f'subscription not found'
action_status='error'
api_result = {'api_status': action_status, 'api_message': msg, 'api_data': input_dict, 'api_action': _api_action.upper(), 'api_name': _api_name}
log_process_finish(_api_msgID, api_result, **_process_call_area)
return api_result
client_dict=dbsession.get(dbmodel.CLIENT, subscription_dict,'DICT', caller_area=_process_call_area)
if not client_dict:
msg = f'client not found'
action_status='error'
api_result = {'api_status': action_status, 'api_message': msg, 'api_data': subscription_dict, 'api_action': _api_action.upper(), 'api_name': _api_name}
log_process_finish(_api_msgID, api_result, **_process_call_area)
return api_result
#action='CONFIRM'
action_result = dbsession.table_action(dbmodel.CLIENT, action, input_dict, action_filter, auto_commit=True, caller_area=_process_call_area)
api_result = action_result
api_result.update({'api_action': _api_action, 'api_name': _api_name})
thismsg=action_result.get('api_message')
if not api_result.get('api_status') == 'success':
# msg = f'client confirmation failed'
# api_result.update({'api_message':msg})
log_process_finish(_api_msgID, api_result, **_process_call_area)
return api_result
subscription_dict = dbsession.get(dbmodel.SUBSCRIPTION, subscription_dict, 'DICT', caller_area=_process_call_area)
status=subscription_dict.get('status')
client_id=subscription_dict.get('client_id')
# if not subscription_dict.get('status') == 'Active':
# msg = f"service provider not confirmed. status={status}"
# action_status='error'
# api_result = {'api_status': action_status, 'api_message': msg, 'api_data': subscription_dict, 'messages': messages, 'rows_added': rows_added, 'rows_updated': rows_updated, 'api_action': _api_action.upper(), 'api_name': _api_name}
# log_process_finish(_api_msgID, api_result, **_process_call_area)
# return api_result
input_dict.update({'status': status})
input_dict.update({'client_id': client_id})
action_result = dbsession.table_action(dbmodel.SUBSCRIPTION, action, input_dict, action_filter, auto_commit=True, caller_area=_process_call_area)
api_result = action_result
thismsg=thismsg.replace('CLIENT',_api_entity)
api_result.update({'api_action': _api_action, 'api_name': _api_name,'api_message':thismsg})
log_process_finish(_api_msgID, api_result, **_process_call_area)
return api_result
|
def recursiveCalc(n, counter=0, steps=''):
if n<10:
steps += 'Total Steps: ' + str(counter) + '.'
return steps, counter
counter+=1
result = calc(n)
steps += str(result)+', '
return recursiveCalc(result, counter, steps)
def calc(n):
result = 1
while (n>0):
mod = n % 10
result *= mod
n -= mod
n /= 10
return result
def printNumber(n, steps):
print (str(n) + ': ' + steps)
max = -1
bestNumbers = []
for i in range(1000000):
result = recursiveCalc(i)
if(result[1] > max):
max = result[1]
printNumber(i, result[0])
bestNumbers.append(i)
print (bestNumbers)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Question:
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]:
3
/ \
9 20
/ \
15 7
Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]:
1
/ \
2 2
/ \
3 3
/ \
4 4
Return false.
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def check(root):
if root is None:
return 0
left = check(root.left) #左子树的深度
right = check(root.right) #右子树的深度
if left == -1 or right == -1 or abs(left - right) > 1:
return -1 #如果左子树严重倾斜,left == -1可以大大节省递归时间
return 1 + max(left, right)
return check(root) != -1 |
def ifPossible(a):
while a%2==0:
a/=2
return a
test=int(input())
while test:
a,b = input().split()
a=int(a)
b=int(b)
if a>b:
n=b
b=a
a=n
num=ifPossible(b)
ans=0
if num!=ifPossible(a):
print("-1")
else:
b/=a
while b>=8:
b/=8
ans+=1
if b>1:
ans+=1
print(ans)
test-=1
|
#!/usr/bin/python3
class Student():
"""Student class with name and age"""
def __init__(self, first_name, last_name, age):
"""initializes new instance of Student"""
self.first_name = first_name
self.last_name = last_name
self.age = age
def to_json(self, attrs=None):
"""returns dict attributes of Student"""
if attrs is None:
obj_dict = self.__dict__
return obj_dict
else:
o_D = self.__dict__
D = dict(([k, v] for k, v in o_D.items() if k in attrs))
return D
def reload_from_json(self, json):
"""reloads Student instance from input dictionary"""
for k, v in json.items():
setattr(self, k, v)
|
def bubble_sort(arr):
swapped = True
while swapped:
swapped = False
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
arr[i], arr[i + 1] = arr[i + 1], arr[i]
swapped = True
def selection_sort(arr):
for i in range(len(arr)):
minpos = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[minpos]:
minpos = j
arr[i], arr[minpos] = arr[minpos], arr[i]
def insertion_sort(arr):
for i in range(1, len(arr)):
current = arr[i]
j = i - 1
while j >= 0 and arr[j] > current:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = current
def merge_sort(array):
def _merge(left_arr, right_arr):
_summary = [0] * (len(left_arr) + len(right_arr))
li = ri = n = 0
while li < len(left_arr) and ri < len(right_arr):
if left_arr[li] <= right_arr[ri]:
_summary[n] = left_arr[li]
li += 1
n += 1
else:
_summary[n] = right_arr[ri]
ri += 1
n += 1
while li < len(left_arr):
_summary[n] = left_arr[li]
li += 1
n += 1
while ri < len(right_arr):
_summary[n] = right_arr[ri]
ri += 1
n += 1
return _summary
if len(array) <= 1: return
middle = len(array) // 2
left_array = [array[i] for i in range(0, middle)]
right_array = [array[i] for i in range(middle, len(array))]
merge_sort(left_array)
merge_sort(right_array)
summary = _merge(left_array, right_array)
for i in range(len(array)):
array[i] = summary[i]
def quick_sort(array):
if len(array) <= 1:
return
pivot = array[0]
left_array = []
right_array = []
middle_array = []
for x in array:
if x < pivot:
left_array.append(x)
elif x > pivot:
right_array.append(x)
else:
middle_array.append(x)
quick_sort(left_array)
quick_sort(right_array)
index = 0
for x in left_array + middle_array + right_array:
array[index] = x
index += 1
|
class Project():
def __init__(self, client, project_id=None):
self.client = client
self.project_id = project_id
def get_details(self, project_id=None):
"""
Get information about a specific project
http://developer.dribbble.com/v1/projects/#get-a-project
"""
project_id = project_id if project_id is not None else self.project_id
project_details = self.client.GET("/projects/{}".format(project_id))
return project_details.json()
def get_shots(self, project_id=None):
"""
Retrieves a list of all shots that are part of this project
http://developer.dribbble.com/v1/projects/shots/#list-shots-for-a-project
"""
project_id = project_id if project_id is not None else self.project_id
shots = self.client.GET("/projects/{}/shots".format(project_id))
return shots.json()
|
class AllennlpReaderToDict:
def __init__(self, **kwargs):
self.kwargs = kwargs
def __call__(self, *args_ignore, **kwargs_ignore):
kwargs = self.kwargs
reader = kwargs.get("reader")
file_path = kwargs.get("file_path")
n_samples = kwargs.get("n_samples")
instances = reader._read(file_path)
n_samples = n_samples or len(instances)
d = dict()
i = 0
for instance in instances:
if n_samples and i >= n_samples:
break
d[i] = instance.fields
i += 1
return d
|
def one_hot_encode(_df, _col):
_values = set(_df[_col].values)
for v in _values:
_df[_col + str(v)] = _df[_col].apply(lambda x : float(x == v) )
return _df |
class Solution(object):
def sumOddLengthSubarrays(self, arr):
"""
:type arr: List[int]
:rtype: int
"""
# Runtime: 32 ms
# Memory: 13.4 MB
prefix_sum = []
last_sum = 0
for item in arr:
last_sum += item
prefix_sum.append(last_sum)
total = sum(arr) # Lengths of subarrays with length = 1
for subarr_size in range(3, len(arr) + 1, 2):
for ptr in range(len(arr) - subarr_size + 1):
total += prefix_sum[ptr + subarr_size - 1]
if ptr != 0:
total -= prefix_sum[ptr - 1]
return total
|
"""
This code was written by JonECope
Using Python 3035 in Processing 3.3.7
"""
color_choice = color(0, 0, 0)
circ = True
instructions = "Press Mouse to draw, Right-click to erase, Q to exit, R, O, Y, G, B, V for colors. Press S for square brush or C for circle brush. Press Enter to save."
def setup():
#size(800, 800)
fullScreen()
background(255)
textSize(30)
fill(0)
text(instructions, 10, 100, width-20, 200)
circ = True
def draw():
global color_choice
if mousePressed:
if mouseButton == LEFT:
fill(color_choice)
stroke(color_choice)
elif mouseButton == RIGHT:
fill(255, 255, 255)
stroke(255, 255, 255)
else:
fill(0, 0, 0, 0)
stroke(0, 0, 0, 0)
global circ
if keyPressed:
if key == "s" or key == "S":
circ = False
elif key == "c" or key == "C":
circ = True
if key == "q" or key == "Q":
exit()
elif key == ENTER:
save("MyDrawing.png")
background(255)
fill(255, 0, 0)
text("Your creation has been saved to the application's folder!", 10, 100, width-20, 200)
elif keyCode == LEFT:
color_choice = color(0)
elif key == "r" or key == "R":
color_choice = color(255, 0, 0)
elif key == "o" or key == "O":
color_choice = color(255, 156, 0)
elif key == "y" or key == "Q":
color_choice = color(255, 255, 0)
elif key == "g" or key == "Q":
color_choice = color(0, 255, 0)
elif key == "b" or key == "Q":
color_choice = color(0, 0, 255)
elif key == "v" or key == "Q":
color_choice = color(169, 0, 255)
if circ:
ellipse(mouseX, mouseY, 30, 30)
else:
rect(mouseX, mouseY, 30, 30)
|
def differ(string_1, string_2):
new_string = ""
for i in range(len(string_1)):
if string_1[i] == string_2[i]:
new_string += string_1[i]
return new_string
def main():
f = [line.rstrip("\n") for line in open("Data.txt")]
for i in range(len(f)):
for j in range(i + 1, len(f)):
if len(differ(f[i], f[j])) == len(f[i]) - 1:
print(differ(f[i], f[j]))
if __name__ == "__main__":
main()
|
"""
字符串字面值
"""
# 1. 各种写法
# 双引号
name01 = "悟空"
# 单引号
name02 = '悟空'
# 三引号: 可见即所得
name03 = '''
孙
悟
空'''
print(name03)
name03 = """悟空"""
# 2. 引号冲突
message = '我是"孙悟空"同学.'
message = "我是'孙悟空'同学."
message = """我是'孙'悟"空"同学."""
# 3. 转义字符:能够改变含义的特殊字符
# \" \' \\ 换行\n
message = "我是\"孙悟空\"同\n学."
print(message)
url = "C:\\antel\\bxtremeGraphics\\cUI\\desource"
# 原始字符
url = r"C:\antel\bxtremeGraphics\cUI\desource"
print(url) |
class UpgradeInfo():
def __init__(self):
self.baseCost_mineral = 100
self.baseCost_gas = 100
self.baseCost_time = 266
self.upgradeFactor_mineral = 50
self.upgradeFactor_gas = 50
self.upgradeFactor_time = 32
def GetInfo(self):
res = f'초기비용 : {self.baseCost_mineral}M / {self.baseCost_gas}G / {self.baseCost_time}T\n'
res += f'1단계당 추가비용 : {self.upgradeFactor_mineral}M / {self.upgradeFactor_gas}G / {self.upgradeFactor_time}T\n'
return res
def GetUpgradeCost(self, n):
return self.baseCost_mineral + (n-1)*self.upgradeFactor_mineral, self.baseCost_gas + (n-1)*self.upgradeFactor_gas, self.baseCost_time + (n-1)*self.upgradeFactor_time
def calcN2N(self, startUpgrade, endUpgrade):
all_mineral = 0
all_gas = 0
all_time = 0
while startUpgrade <= endUpgrade:
mineral, gas, time = self.GetUpgradeCost(startUpgrade)
all_mineral += mineral
all_gas += gas
all_time += time
startUpgrade += 1
return all_mineral,all_gas,all_time
|
class Car(object):
# setting some default values
num_of_doors = 4
num_of_wheels = 4
def __init__(self, name='General', model='GM', car_type='saloon', speed=0):
self.name = name
self.model = model
self.car_type = car_type
self.speed = speed
if self.name is 'Porshe' or self.name is 'Koenigsegg':
self.num_of_doors = 2
elif self.car_type is 'trailer':
self.num_of_wheels = 8
else:
self
def is_saloon(self):
'''
Determine between saloon and trailer
'''
if self.car_type is not 'trailer':
return True
return False
def drive(self, speed):
'''
Check the car type and return appropriate speed
'''
if self.car_type is 'trailer':
self.speed = speed * 11
else:
self.speed = 10 ** speed
return self |
class Tree:
def __init__(self,data):
self.tree = [data, [],[]]
def left_subtree(self,branch):
left_list = self.tree.pop(1)
if len(left_list) > 1:
branch.tree[1]=left_list
self.tree.insert(1,branch.tree)
else:
self.tree.insert(1,branch.tree)
def right_subtree(self,branch):
right_list = self.tree.pop(2)
if len(right_list) > 1:
branch.tree[2]=right_list
self.tree.insert(2,branch.tree)
else:
self.tree.insert(2,branch.tree)
#EXECUTION
print("Create Root Node")
root = Tree("Root_node")
print("Value of Root = ",root.tree)
print("Create Left Tree")
tree_left = Tree("Tree_Left")
root.left_subtree(tree_left)
print("Value of Tree_Left = ",root.tree)
print("Create Right Tree")
tree_right = Tree("Tree_Right")
root.right_subtree(tree_right)
print("Value of Tree_Right = ",root.tree)
print("Create Left Inbetween")
tree_inbtw = Tree("Tree left in between")
root.left_subtree(tree_inbtw)
print("Value of Tree_Left = ",root.tree)
print("Create TreeLL")
treell = Tree("TreeLL")
tree_left.left_subtree(treell)
print("Value of TREE = ",root.tree)
|
peso = float(input("digite aqui o seu peso(kg): "))
altura = float(input("digite sua altura: "))
imc = peso/altura**2
print("seu imc é {:3.2f}".format(imc))
if imc < 18.5:
print("você está abaixo do peso")
elif 18.5 <= imc < 25:
print("parabéns, você está no peso ideal!")
elif 25 <= imc < 30:
print("sobrepeso")
elif 30 <= imc < 40:
print("você está obeso")
elif imc >= 40:
print("obesidade morbida!") |
def get_input():
EF1 = float(input("введите значения жесткостей элементов: " + "\n" + "EF1 = "))
EF2 = float(input("EF2 = "))
F = float(input("введите значение усилия:" + "\n" + "F = "))
return EF1, EF2, F |
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"[{self.x},{self.y}]"
class X(Point):
def __init__(self, x, y):
super().__init__(x, y)
def __str__(self):
return "X" + super().__str__()
class O(Point):
def __init__(self, x, y):
super().__init__(x, y)
def __str__(self):
return "O" + super().__str__()
class Board:
def __init__(self):
self._board = [
[" ", " ", " "],
[" ", " ", " "],
[" ", " ", " "],
]
@property
def board(self):
return self._board
@board.setter
def board(self, val):
x = int(val[1]) - 1
y = int(val[2]) - 1
self._board[x][y] = val[0]
def __str__(self):
"""
| X | O | |
| O | | |
| | X | |
"""
board_str = ""
for line in self._board:
board_str += "| " + " | ".join(line) + " |\n"
return board_str
# if __name__ == "__main__":
# board = Board()
# print(board)
#
# x = X(x=1, y=1)
# print(X.__name__)
|
print('=' * 12 + 'Desafio 73' + '=' * 12)
tabelabrasileirao = (
"Flamengo", "Santos", "Palmeiras", "Grêmio", "Athletico-PR", "São Paulo", "Internacional", "Corinthians",
"Fortaleza", "Goiás", "Bahia", "Vasco", "Atlético-MG", "Fluminense", "Botafogo", "Ceará", "Cruzeiro", "CSA",
"Chapecoense", "Avaí")
print(f'Os 5 primeiros colocados são: {tabelabrasileirao[:5]}')
print(f'Os 4 últimos colocados são: {tabelabrasileirao[16:]}')
print(f"""A ordem alfabética dos times é:
{sorted(tabelabrasileirao)}""")
print(f'A Chapecoense está na {tabelabrasileirao.index("Chapecoense")+1}ª posição.')
|
def input_dimension():
while True:
dimension = input("Enter your board dimensions: ").split()
len_x1 = 0
len_y1 = 0
if len(dimension) != 2:
print("Invalid dimensions!")
continue
try:
len_x1 = int(dimension[0])
len_y1 = int(dimension[1])
except ValueError:
print("Invalid dimensions!")
continue
if len_x1 <= 0 or len_y1 <= 0:
print("Invalid dimensions!")
else:
break
return len_x1, len_y1
def input_starting():
while True:
position = input("Enter the knight's starting position: ").split()
x1, y1 = 0, 0
if len(position) != 2:
print("Invalid dimensions!")
continue
try:
x1 = int(position[0])
y1 = int(position[1])
except ValueError:
print("Invalid dimensions!")
continue
if not 1 <= x1 <= len_x or not 1 <= y1 <= len_y:
print("Invalid dimensions!")
else:
break
return x1, y1
def create_board():
for _i in range(len_x):
current_row = []
for _j in range(len_y):
current_row.append("_")
board.append(current_row)
def print_board(board1):
max_len = len(str(len_x * len_y))
print(" " + "-" * (len_x * (max_len + 1) + 3))
for i in range(len_y, 0, -1):
s = ""
for j in range(1, len_x + 1):
if board1[j - 1][i - 1] != '_':
s += " " + " " * (max_len - len(board1[j - 1][i - 1])) + board1[j - 1][i - 1]
elif count(board1, j, i, 'X') != 0:
next_count = str(count(board1, j, i, '_'))
s += " " + " " * (max_len - len(next_count)) + next_count
else:
s += " " + "_" * max_len
print(f"{i}|{s} |")
print(" " + "-" * (len_x * (max_len + 1) + 3))
s = ''
for i in range(len_x):
s += " " * max_len + str(i + 1)
print(" " + s + " ")
print()
def count(board1, x1, y1, symbol):
value = 0
if x1 + 1 <= len_x and y1 + 2 <= len_y and board1[x1][y1 + 1] == symbol:
value += 1
if x1 + 1 <= len_x and y1 - 2 > 0 and board1[x1][y1 - 3] == symbol:
value += 1
if x1 - 1 > 0 and y1 + 2 <= len_y and board1[x1 - 2][y1 + 1] == symbol:
value += 1
if x1 - 1 > 0 and y1 - 2 > 0 and board1[x1 - 2][y1 - 3] == symbol:
value += 1
if x1 + 2 <= len_x and y1 + 1 <= len_y and board1[x1 + 1][y1] == symbol:
value += 1
if x1 + 2 <= len_x and y1 - 1 > 0 and board1[x1 + 1][y1 - 2] == symbol:
value += 1
if x1 - 2 > 0 and y1 + 1 <= len_y and board1[x1 - 3][y1] == symbol:
value += 1
if x1 - 2 > 0 and y1 - 1 > 0 and board1[x1 - 3][y1 - 2] == symbol:
value += 1
return value
def move(board1, new_x1, new_y1):
board2 = []
for i in range(len_x):
current_row = []
for j in range(len_y):
if board1[i][j] == 'X':
current_row.append('*')
else:
current_row.append(board1[i][j])
board2.append(current_row)
board2[new_x1 - 1][new_y1 - 1] = "X"
return board2
def next_step(board1, new_x1, new_y1, index):
board2 = []
for i in range(len_x):
current_row = []
for j in range(len_y):
current_row.append(board1[i][j])
board2.append(current_row)
board2[new_x1 - 1][new_y1 - 1] = str(index)
return board2
def check_solution(board1):
total = 0
for i in range(len_x):
for j in range(len_y):
if board1[i][j] == '_' and count(board1, i + 1, j + 1, 'X') != 0:
board2 = move(board1, i + 1, j + 1)
if check_solution(board2):
return True
elif board1[i][j] in '*X':
total += 1
return total == len_x * len_y
def play_game(board1):
print_board(board1)
invalid = False
count_squares = 1
while True:
movie = input("Invalid move! Enter your next move: " if invalid else 'Enter your next move: ').split()
new_x = int(movie[0])
new_y = int(movie[1])
if board1[new_x - 1][new_y - 1] != '_' or count(board1, new_x, new_y, 'X') == 0:
invalid = True
else:
invalid = False
board1 = move(board1, new_x, new_y)
count_squares += 1
if count(board1, new_x, new_y, '_') == 0:
if len_x * len_y == count_squares:
print('What a great tour! Congratulations!')
else:
print('No more possible moves!')
print(f'Your knight visited {count_squares} squares!')
break
print_board(board1)
def print_solution(board1):
board2 = fill_board(board1, 1)
print_board(board2)
def fill_board(board1, index):
for i in range(len_x):
for j in range(len_y):
if board1[i][j] == '_' and count(board1, i + 1, j + 1, str(index)) != 0:
board2 = next_step(board1, i + 1, j + 1, index + 1)
if index + 1 == len_x * len_y:
return board2
board3 = fill_board(board2, index + 1)
if board3 is not None:
return board3
return None
board = []
len_x, len_y = input_dimension()
create_board()
x, y = input_starting()
board[x - 1][y - 1] = "X"
while True:
try_puzzle = input('Do you want to try the puzzle? (y/n): ')
if try_puzzle == 'y':
if not check_solution(list(board)):
print('No solution exists!')
exit()
play_game(board)
break
elif try_puzzle == 'n':
if not check_solution(list(board)):
print('No solution exists!')
exit()
board[x - 1][y - 1] = "1"
print("Here's the solution!")
print_solution(board)
break
else:
print('Invalid dimensions!')
|
# coding: utf-8
# # Using Python to investigate data
# 
# 
# # MANY important non-standard packages
# 
# 
# ## Which Python distribution?
# * Currently best supported is Anaconda by Continuum.io
# * Works on the major three operating systems
# * Comes with the most important science packages pre-installed.
# ## Getting started
# The following launches the Python interpreter in `interactive` mode:
# ```bash
# $ python
# Python 3.5.1 |Continuum Analytics, Inc.| (default, Dec 7 2015, 11:24:55)
# [GCC 4.2.1 (Apple Inc. build 5577)] on darwin
# Type "help", "copyright", "credits" or "license" for more information.
# >>> print('hello world!')
# hello world!
# ```
# ## To leave Python:
# ```bash
# >>> <Ctrl-D>
# $
# ```
# ## Run an existing script file with Python code
# This is running Python code `non-interactive`:
# ```bash
# $ python script_name.py
# [...output...]
# ```
# * Python itself can be run interactively, but not many features.
# * -> Fernando Pérez, then at CU Boulder, invents IPython, a more powerful interactive environment for Python.
# ## Launching IPython
# Launching works the same way:
# ```bash
# $ ipython
# Python 3.5.1 |Continuum Analytics, Inc.| (default, Dec 7 2015, 11:24:55)
# Type "copyright", "credits" or "license" for more information.
#
# IPython 4.2.0 -- An enhanced Interactive Python.
# ? -> Introduction and overview of IPython's features.
# %quickref -> Quick reference.
# help -> Python's own help system.
# object? -> Details about 'object', use 'object??' for extra details.
# Automatic calling is: Smart
#
# In [1]:
# ```
# # Most important IPython features
# * Tab completion for Python modules
# * Tab completion for object's attributes ("introspection")
# * automatic reload possible of things you are working on.
# # Latest technology jump: IPython notebook (Now Jupyter)
#
# * Cell-based interactivity
# * Combining codes with output including plot display **AND** documentation (like this!)
# * Very successful. Received twice Sloan foundation funding (here to stay!)
# * Became recently language agnostic: JU_lia, PYT_hon, R (and many many more)
# # My recommendation
# * Work with IPython for quick things that don't need plots or on slow remote connection
# * Work with Jupyter notebook for interactive data analysis and to develop working code blocks
# * Put working code blocks together into script files for science production and run "non-interactive"
# # Launching Jupyter notebook
# ```bash
# $ jupyter notebook
# [I 16:27:34.880 NotebookApp] Serving notebooks from local directory: /Users/klay6683/src/RISE
# [I 16:27:34.880 NotebookApp] 0 active kernels
# [I 16:27:34.880 NotebookApp] The Jupyter Notebook is running at: http://localhost:8889/
# [I 16:27:34.881 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
# ```
# * Will launch what is called a "notebook server" and open web browser with dash-board
# * This server pipes web browser cells to the underlying Python interpreter.
# 
# # And here we are!
# ## Now let's do some Python!
# First, let's look at variables
# In[ ]:
a = 5
s = 'mystring' # both single and double quotes are okay.
# new comment
# Python is `dynamically typed`, meaning I can change the type of any variable at any time:
# In[ ]:
a = 'astring'
print(a) # not the last line, so if I want to see it, I need to use the print() function.
s = 23.1
s # note that if the last line of any Jupyter cell contains a printable object, it will be printed.
# Python is written in C, therefore uses many of the same technicalities.
#
# For examples, one equal sign `=` is used for value assignment, while two `==` are used for equality checking:
# In[ ]:
a = 5
a
# In[ ]:
a == 5
# Storing more than one item is done in `lists`.
#
# A list is only one of Python's `containers`, and it is very flexible, it can store any Python object.
# In[ ]:
mylist = [1, 3.4, 'hello', 3, 6]
mylist
# Each item can be accessed by an 0-based index (like in C):
# In[ ]:
print(mylist[0])
print(mylist[2])
len(mylist)
# One can get slices of lists by providing 2 indices, with the right limit being exclusive, not inclusive
# In[ ]:
i = 2
print(mylist[:i])
print(mylist[i:])
# ### Sensible multiplication
# Most Python objects can be multiplied, in the most logical sense depending on its type:
# In[ ]:
a = 5
s = 'mystring'
mylist = [1,2]
# In[ ]:
print(5*a)
print(2*s)
print(3*mylist)
# ### Conditional branching: if statement
# In[ ]:
temp = 80
if temp > 110:
print("It's too hot.")
elif temp > 95 and temp < 110: # test conditions are combined with `and`
print("It's okay.")
else:
print("Could be warmer.")
# See how I use double quotes here to avoid ambiguity with single quote in the string.
# ### Functions
#
# Functions are called with `()` to contain the arguments for a function.
#
# We already used one: `print()`
#
# Learn about function's abilitys using IPython's help system. It is accessed by adding a question mark to any function name. In Jupyter notebooks, a sub-window will open. When done reading, close it by pressing `q` or clicking the x icon:
# In[ ]:
get_ipython().magic('pinfo print')
# #### Making your own function
#
# This is very easy, with using the keyword `def` for "define":
# In[ ]:
def myfunc(something): # note how I don't care about the type here!
"""Print the length of `something` and print itself."""
print("Length:", len(something)) # all `something` needs to support is to have a length
print("You gave:", something)
# In[ ]:
myfunc('mystring')
# In[ ]:
myfunc(['a', 1, 2])
# In[ ]:
myfunc(5)
# The principle of not defining a required type for a function, but require an `ability` is very important in Python and is called `duck typing`:
#
# > "In other words, don't check whether it IS-a duck: check whether it QUACKS-like-a duck, WALKS-like-a duck, etc, etc, depending on exactly what subset of duck-like behaviour you need to play your language-games with."
# ## Loops
#
# Loops are the kings of programming, because they are the main reason why we do programming:
#
# > Execute tasks repeatedly, stop when conditions are fulfilled.
#
# These conditions could be simply that data are exhausted, or a mathematical condition.
#
# 2 main loops exist: The more basic `while` loop, and the more advanced `for` loop.
#
# ### while loops
#
# `while` loops run until their conditional changes from True to False.
#
# The loop is only entered when the condition is True.
#
# Note how in Python sub blocks of code are defined simply by indentation and the previous line
# ending with a colon `:`.
# In[ ]:
i = 0
while i < 3: # this is the condition that is being checked.
print(i, end=' ')
i = i + 1 # very common statement, read it from right to left!
print('Done')
# In[ ]:
i < 3
# In[ ]:
i
# `while` loops are the most low level loops, they always can be made to work, as you design the interruption criteria yourself.
#
# ### For loops
#
# `for` loops are designed to loop over containers, like lists.
#
# They know how to get each element and know when to stop:
# In[ ]:
mylist = [5, 'hello', 23.1]
for item in mylist:
print(item)
# The "`in`" keyword is a powerful and nicely readable concept in Python.
#
# In most cases, one can check ownership of an element in a container with it:
# In[ ]:
5 in mylist
# ### The `range()` function
#
# `range()` is very useful for creating lists for you that you can loop over and work with.
#
# It has two different call signatures:
#
# * range(n) will create a list from 0 to n-1, with an increment of +1.
# * range(n1, n2, [step]) creates a list from n1 to n2-1, with again a default increment of 1
#
# Negative increments are also okay:
# In[ ]:
for i in range(10):
print(i, end=' ')
# In[ ]:
for i in range(2, 5):
print(i, end=' ')
# In[ ]:
for i in range(0, -5, -1):
print(i, end=' ')
# In[ ]:
get_ipython().magic('pinfo range')
# **IMPORTANT**
#
# Note, that for memory efficiency, `range()` is not automatically creating the full list, but returns an object called a `generator`.
#
# This is basically an abstract object that knows **HOW TO** create the requested list, but didn't do it yet.
# In[ ]:
print(range(10))
# It takes either a loop (as above) or a conversion to a list to see the actual content:
# In[ ]:
print(list(range(10)))
# ### Combine `if` and `for`
#
# Let's combine `for` and `if` to write a mini program.
# The task is to scan a container of 1's and 0's and count how many 1's are there.
# In[ ]:
mylist = [0,1,1,0,0,1,0,1,0,0,1]
mylist
# In[ ]:
one_counter = 0
for value in mylist: # note the colon!
if value == 1: # note the indent for each `block` !
one_counter += 1 # this is the short version of a = a + 1
print("Found", one_counter, "ones.")
# ### Writing and reading files
#
# Need to get data in and out.
# In principle, I recommend to use high level readers from science packages.
#
# But you will need to know the principles of file opening nonetheless.
# In[ ]:
afile = open('testfile', 'w')
# In[ ]:
get_ipython().magic('pinfo afile.name')
# In[ ]:
afile.write('some text \n') # \n is the symbol to create a new line
afile.write('write some more \n')
# The `write` function of the `afile` object returns the length of what just was written.
#
# When done, the file needs to be closed!
#
# Otherwise, the content could not end up in the file, because it was `cached`.
# In[ ]:
afile.close()
# I can call operating system commands with a leading exclamation mark:
# In[ ]:
get_ipython().system('cat testfile')
# #### reading the file
#
# One can also use a so called `context manager` and indented code block to indicate to Python when to automatically close the file:
# In[ ]:
with open('testfile', 'r') as afile:
print(afile.readlines())
# In[ ]:
with open('testfile', 'r') as afile:
print(afile.read())
# ### Tutorial practice
#
# Now you will practice a bit of Python yourself.
#
# I recommend to join forces in groups of two.
#
# This working technique is called "pair programming":
# One person is the "driver", typing in code, while the other person is the "navigator", reviewing everything that is being typed in.
# The roles should be frequently changed (or not, depending on preferences).
#
# This way you can discuss anything that's being worked on.
#
# Next session we will learn how to import all these powerful analysis packages into a Python session, learn about the most import science packages and play with some real data.
|
"""Mirror of release info
TODO: generate this file from GitHub API"""
# The integrity hashes can be computed with
# shasum -b -a 384 [downloaded file] | awk '{ print $1 }' | xxd -r -p | base64
TOOL_VERSIONS = {
"7.0.1-rc1": {
"darwin_arm64": "sha384-PMTl7GMV01JnwQ0yoURCuEVq+xUUlhayLzBFzqId8ebIBQ8g8aWnbiRX0e4xwdY1",
},
}
# shasum -b -a 384 /Users/thesayyn/Downloads/go-containerregistry_Darwin_arm64.tar.gz | awk '{ print $1 }' | xxd -r -p | base64 |
with open("input.txt") as file:
data = file.read()
m = [-1, 0, 1]
def neight(grid, x, y):
for a in m:
for b in m:
if a == b == 0:
continue
xx = x+a
yy = y+b
if 0 <= xx < len(grid) and 0 <= yy < len(grid[xx]):
yield grid[xx][yy]
def neight_on(grid, x, y):
return sum(1 for c in neight(grid, x, y) if c == '#')
def update_corners(grid):
new_grid = []
for x in range(len(grid)):
l = []
for y in range(len(grid[x])):
if x in (0, len(grid)-1) and y in (0, len(grid[x])-1):
l.append('#')
else: # pass
l.append(grid[x][y])
new_grid.append("".join(l))
return new_grid
def update(grid):
new_grid = []
for x in range(len(grid)):
l = []
for y in range(len(grid[x])):
on_count = neight_on(grid,x,y)
if x in (0, len(grid)-1) and y in (0, len(grid[x])-1):
l.append('#')
elif grid[x][y] == '#': # on
l.append('#' if on_count in (2,3) else '.')
else: # pass
l.append('#' if on_count == 3 else '.')
new_grid.append("".join(l))
return new_grid
# TEST
grid = """.#.#.#
...##.
#....#
..#...
#.#..#
####..""".splitlines()
for i in range(4):
grid = update(grid)
print("\n".join(grid) + "\n")
# PART 1
grid = data.splitlines()
for i in range(100):
grid = update(grid)
s = sum(1 for row in grid for c in row if c == '#')
print(s)
# TEST 2
grid = """.#.#.#
...##.
#....#
..#...
#.#..#
####..""".splitlines()
grid = update_corners(grid)
for i in range(5):
grid = update_corners(update(grid))
print("\n".join(grid) + "\n")
# PART 1
grid = data.splitlines()
grid = update_corners(grid)
for i in range(100):
grid = update_corners(update(grid))
s = sum(1 for row in grid for c in row if c == '#')
print(s) |
#
# This file contains the Python code from Program 6.2 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/pgm06_02.txt
#
class StackAsArray(Stack):
def __init__(self, size = 0):
super(StackAsArray, self).__init__()
self._array = Array(size)
def purge(self):
while self._count > 0:
self._array[self._count] = None
self._count -= 1
#...
|
class DefaultConfig(object):
env = 'default' # visdom 环境
model = 'SimpleCGH' # 使用的模型,名字必须与models/__init__.py中的名字一致
train_data_root = './data/training_set/' # 训练集存放路径
# test_data_root = './data/test1' # 测试集存放路径
load_model_path =None# 'checkpoints/model.pth' # 加载预训练的模型的路径,为None代表不加载
batch_size = 10 # batch size
use_gpu = False # use GPU or not
num_workers = 4 # how many workers for loading data
print_freq = 20 # print info every N batch
# debug_file = '/tmp/debug' # if os.path.exists(debug_file): enter ipdb
# result_file = 'result.csv'
max_epoch = 10
lr = 0.1 # initial learning rate
lr_decay = 0.95 # when val_loss increase, lr = lr*lr_decay
weight_decay = 1e-4 # 损失函数
def parse(self, kwargs):
'''
根据字典kwargs 更新 config参数
'''
# 更新配置参数
for k, v in kwargs.items():
if not hasattr(self, k):
# 警告还是报错,取决于你个人的喜好
warnings.warn("Warning: opt has not attribut %s" %k)
setattr(self, k, v)
# 打印配置信息
print('user config:')
for k, v in self.__class__.__dict__.items():
if not k.startswith('__'):
print(k, getattr(self, k)) |
n = input()
split =n.split()
limak = int(split[0])
bob = int(split[-1])
years = 0
while True:
limak*=3
bob*=2
years+=1
if limak>bob:
break
print(years)
|
fizz = 3
buzz = 5
upto = 100
for n in range(1,(upto + 1)):
if n % fizz == 0:
if n % buzz == 0:
print("FizzBuzz")
else:
print("Fizz")
elif n % buzz == 0:
print("Buzz")
else:
print(n)
|
#!/usr/bin/env python3
def count_combos(coins, total):
len_coins = len(coins)
memo = {}
def count(tot, i):
if tot == 0:
return 1
if i == len_coins:
return 0
subproblem = (tot, i)
try:
return memo[subproblem]
except KeyError:
j = i + 1
subtotals = range(0, total + 1, coins[i])
combos = sum(count(tot - subtot, j) for subtot in subtotals)
memo[subproblem] = combos
return combos
return count(total, 0)
def read_record():
return map(int, input().split())
total, _ = read_record() # don't need m
coins = list(read_record())
print(count_combos(coins, total))
|
ans = []
n = int(input())
for i in range(n):
a, b = list(map(int, input().split()))
ans.append(a + b)
for i in range(len(ans)):
print("Case #{}: {}".format(i+1, ans[i])) |
SYSDIGERR = -1
NOPROCESS = -2
NOFUNCS = -3
NOATTACH = -4
CONSTOP = -5
HSTOPS = -6
HLOGLEN = -7
HNOKILL = -8
HNORUN = -9
CACHE = ".cache"
LIBFILENAME = "libs.out"
LANGFILENAME = ".lang.cache"
BINLISTCACHE = ".binlist.cache"
LIBLISTCACHE = ".liblist.cache"
BINTOLIBCACHE = ".bintolib.cache"
TOOLNAME = "CONFINE"
SECCOMPCPROG = "seccomp"
DOCKERENTRYSCRIPT = "docker-entrypoint.sh"
DOCKERENTRYSCRIPTMODIFIED = "docker-entrypoint.wseccomp.sh"
ERRTOMSG = dict()
ERRTOMSG[SYSDIGERR] = "There was an error running sysdig, please make sure it is installed and the script has enough privileges to run it"
ERRTOMSG[NOPROCESS] = "Sysdig was not able to identify any processes. This causes our dynamic analysis to fail and the static analysis cannot analyze anything"
ERRTOMSG[NOFUNCS] = "No imported functions could be extracted from any of the binaries and libraries required by the container"
ERRTOMSG[NOATTACH] = "The container did not run in attached mode"
ERRTOMSG[CONSTOP] = "The container got killed after being launched in attach mode"
ERRTOMSG[HSTOPS] = "The hardened container stops running. Probably due to a problem in generating the SECCOMP profile and prohibiting access to a required system call"
ERRTOMSG[HLOGLEN] = "While the container has been hardened successfully, the log length doesn't match the original log length, which was run without any SECCOMP profile"
ERRTOMSG[HNOKILL] = "The container has been hardened successfully, but we could not kill it afterwards. This usually means that the container has died. If so, the generated profile has a problem"
ERRTOMSG[HNORUN] = "The hardened container does not run at all. The generated SECCOMP profile has a problem"
|
'''
Uma rainha requisitou os serviços de um monge e disse-lhe que pagaria qualquer preço. O monge, necessitando de alimentos, perguntou a rainha se o pagamento poderia ser feito em grãos de trigo dispostos em um tabuleiro de damas, de forma que o primeiro quadrado tivesse apenas um grão, e os quadrados subseqüentes, o dobro do quadrado anterior. A rainha considerou o pagamento barato e pediu que o serviço fosse executado, porém, um dos cavaleiros que estava presente e entendia um pouco de matemática alertou-a que seria impossível executar o pagamento, pois a quantidade de grão seria muito alta. Curiosa, a rainha solicitou então a este cavaleiro que era bom em cálculo, que fizesse um programa que recebesse como entrada o número de quadrados a serem usados em um tabuleiro de damas e apresentasse a quantidade de kg de trigo correspondente, sabendo que cada 12 grãos do cereal correspondem a uma grama. Finalmente, o cálculo da quantidade deverá caber em um valor inteiro de 64 bits sem sinal.
Entrada
A primeira linha de entrada contem um único inteiro N (1 ≤ N ≤ 100), indicando o número de casos de teste. Cada caso de teste contém um único inteiro X (1 ≤ X ≤ 64), indicando o número de casas do tabuleiro que serão utilizadas.
Saída
Para cada caso de teste, imprima a quantidade de kgs de trigo que o monge esperava receber.
'''
N = int(input())
for i in range(N):
graos = []
c = 1
X = int(input())
for i in range(X):
graos.append(c)
c *= 2
qt_cereal = sum(graos)/12
qt_kg = qt_cereal/1000
qt_kg = int(qt_kg)
print(str(qt_kg)+' kg')
|
class ChatObject:
def __init__(self, service, json):
"""Base class for objects emmitted from chat services."""
self.json = json
self.service = service
|
"""
Author : HarperHao
TIME : 2020/10/
FUNCTION:
"""
|
def test_tcp_id(self):
"""
Comprobacion de que el puerto (objeto heredado) coincide con el asociado al Protocolos
Returns:
"""
port = Ports.objects.get(Tag="ssh")
tcp = Tcp.objects.get(id=port)
self.assertEqual(tcp.get_id(), port)
|
class GMHazardError(BaseException):
"""Base GMHazard error"""
def __init__(self, message: str):
self.message = message
class ExceedanceOutOfRangeError(GMHazardError):
"""Raised when the specified exceedance value is out of range when
going from exceedance to IM on the hazard curve"""
def __init__(self, im: str, exceedance: float, message: str):
super().__init__(message)
self.exceedance = exceedance
self.im = im
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.