content stringlengths 7 1.05M |
|---|
print('\033[32;1mDESAFIO 59 - Analise de Dados em uma Tuplas\033[m')
print('\033[32;1mALUNO:\033[m \033[36;1mJoaquim Fernandes\033[m')
print('-' * 80)
num = (int(input('Digite um número: ')),
int(input('Digite outro número: ')),
int(input('Digite mais um número: ')),
int(input('Digite último número: ')))
print(f'Você digitou os Valores: {num}')
print(f'O Valor 9 apareceu {num.count(9)} vezes')
if 3 in num:
print(f'O Valor 3 apareceu na {num.index(3)+1}ª Posição')
else:
print('O Valor 3 não foi Digitado em nenhuma Posição')
print(f'Os Valores Pares digitados foram ', end='')
for n in num:
if n % 2 == 0:
print(n, end=' ')
|
"""Configuration information for an AgPipeline Transformer
"""
class Configuration:
"""Contains configuration information on Transformers
"""
# Silence this error until we have public methods
# pylint: disable=too-few-public-methods
# The version number of the transformer
transformer_version = None
# The transformer description
transformer_description = None
# Short name of the transformer
transformer_name = None
# The sensor associated with the transformer
transformer_sensor = None
# The transformer type (eg: 'rgbmask', 'plotclipper')
transformer_type = None
# The name of the author of the extractor
author_name = None
# The email of the author of the extractor
author_email = None
# Contributors to this transformer
contributors = []
# Repository URI of where the source code lives
repository = None
# Override flag for disabling the metadata file requirement.
# Uncomment and set to False to override default behavior
# metadata_needed = True
|
n1 = float(input('Primeira nota: '))
n2 = float(input('Segunda aula: '))
m = (n1 + n2) / 2
print(f'Sua média foi {m}.')
if m < 5:
print('REPROVADO!')
elif m == 5 or m <= 6.9:
print('RECUPERAÇÃO!')
else:
print('APROVADO!')
|
# Copyright (c) 2017, Matt Layman
class AbortError(Exception):
"""Any fatal errors that would prevent handroll from proceeding should
signal with the ``AbortError`` exception."""
|
"""Strip .HTML extension from URIs."""
def process(app, stream):
for item in stream:
# Most modern HTTP servers implicitly serve one of these files when
# requested URL is pointing to a directory on filesystem. Hence in
# order to provide "pretty" URLs we need to transform destination
# address accordingly.
if item["destination"].name not in ("index.html", "index.htm"):
item["destination"] = item["destination"].parent.joinpath(
item["destination"].stem, "index.html"
)
yield item
|
#
# Font compiler
#
fonts = [ None ] * 64
current = -1
for l in open("font.txt").readlines():
print(l)
if l.strip() != "":
if l[0] == ':':
current = ord(l[1]) & 0x3F
fonts[current] = []
else:
l = l.strip().replace(".","0").replace("X","1")
assert len(l) == 3
fonts[current].append(int(l,2))
for i in range(0,64):
print(i,fonts[i])
assert(len(fonts[i]) == 5)
n = 0
for g in fonts[i]:
n = n * 8 + g
n = n * 2 + 1
fonts[i] = n
open("fonttable.asm","w").write("\n".join([" dw "+str(x) for x in fonts])) |
"""Classes used in warehouse"""
class ItemSet:
"""A set of identical items.
The dimensions is a tuple (x, y, z) of the dimensions of a single item.
The weight is a weight of a single member"""
def __init__(self, dimensions, weight, ref_id, quantity, colour):
self.dimensions = dimensions
self.weight = weight
self.ref_id = ref_id
self.quantity = quantity
self.colour = colour
def __str__(self):
return f"An ItemSet of {self.quantity} individual items of size {self.dimensions}, individual weight {self.weight}, id {self.ref_id}, colour {self.colour}"
class Box:
"""A Box dimensions is a tuple of (x, y, z)"""
def __init__(self, name, dimensions, max_weight):
self.name = name
self.dimensions = dimensions
self.max_weight = max_weight
def __str__(self):
return f'A {self.name} Box of size {self.dimensions} and maximum weight {self.max_weight}'
class Package:
"""A Package corresponds to one Box that contains
items of class ItemSet of quantity 1.
itemsets_and_locations is a list of tuples ordered by the order of packages being put in the box
each tuple contains a ItemSet class and a """
def __init__(self, itemsets_and_locations, box, image):
self.itemsets_and_locations = itemsets_and_locations
self.box = box
self.image = image
def __str__(self):
return f'Package of Box {self.box} containing ItemSets at locations {self.itemsets_and_locations}'
|
# Read a DNA Sequence
def readSequence():
sequence = open(raw_input('Enter sequence filename: '),'r')
sequence.readline()
sequence = sequence.read().replace('\n', '')
return sequence
def match(a, b):
if a == b:
return 1
else:
return -1
# Align two sequences using Smith-Waterman algorithm
def alignSequences(s1, s2):
gap = -2
s1 = '-'+s1
s2 = '-'+s2
mWidth = len(s1)
mHeight = len(s2)
similarity_matrix = [[i for i in xrange(mHeight)] for i in xrange(mWidth)]
for i in range (mWidth):
similarity_matrix[i][0] = 0
for j in range (mHeight):
similarity_matrix[0][j] = 0
for i in range (1,mWidth):
for j in range (1, mHeight):
p0 = 0
p1 = similarity_matrix[i-1][j-1] + match(s1[i], s2[j])
p2 = similarity_matrix[i][j-1] + gap
p3 = similarity_matrix[i-1][j] + gap
similarity_matrix[i][j] = max(p0, p1, p2, p3)
#Find biggest number in the similarity matrix
maxNumber = 0
maxNumberI = 0
maxNumberJ = 0
for i in range(mWidth):
for j in range(mHeight):
if similarity_matrix[i][j] >= maxNumber:
maxNumber = similarity_matrix[i][j]
maxNumberI = i
maxNumberJ = j
i = maxNumberI
j = maxNumberJ
alignmentS1 = ''
alignmentS2 = ''
while similarity_matrix[i][j] > 0:
if similarity_matrix[i][j] == similarity_matrix[i-1][j-1] + match(s1[i], s2[j]):
alignmentS1 = s1[i] + alignmentS1
alignmentS2 = s2[j] + alignmentS2
j-=1
i-=1
elif similarity_matrix[i][j] == similarity_matrix[i-1][j] + gap:
alignmentS1 = s1[i] + alignmentS1
alignmentS2 = '-' + alignmentS2
i-=1
else:
alignmentS1 = '-' + alignmentS1
alignmentS2 = s2[j] + alignmentS2
j-=1
qtdeAlinhamento = 0
for i in range(max(len(alignmentS1), len(alignmentS2))):
if alignmentS1[i] == alignmentS2[i]:
qtdeAlinhamento+=1
print('Tabela final:',similarity_matrix)
print('Melhor alinhamento local para a sequencia 1: ', alignmentS1)
print('Melhor alinhamento local para a sequencia 2: ', alignmentS2)
print('Identidade do alinhamento: ', qtdeAlinhamento)
s1 = readSequence()
s2 = readSequence()
alignSequences(s1, s2) |
distance = int(input('Qual vai ser a distância da sua viagem? '))
if distance <= 200:
print(f'O preço da passagem será R${distance*0.5:.2f}')
else:
print(f'O preço da passagem será R${distance*0.45:.2f}') |
def flip(arr, i):
start = 0
while start < i:
temp = arr[start]
arr[start] = arr[i]
arr[i] = temp
start += 1
i -= 1
def findMax(arr, n):
mi = 0
for i in range(0,n):
if arr[i] > arr[mi]:
mi = i
return mi
def pancakeSort(arr, n):
curr_size = n
while curr_size > 1:
mi = findMax(arr, curr_size)
if mi != curr_size-1:
flip(arr, mi)
flip(arr, curr_size-1)
curr_size -= 1
n = int(input("Enter the size of array : "))
arr = list(map(int, input("Enter the array elements :\n").strip().split()))[:n]
print("Before")
print(arr)
pancakeSort(arr, n);
print ("Sorted Array ")
print(arr)
|
n = int(input())
s = []
while n != 0:
n -= 1
name = input()
s.append(name)
r = input()
for i in range(len(s)):
if r in s[i]:
while r in s[i]:
s[i] = s[i].replace(r, "")
max_seq = ""
for i in range(len(s[0])):
ans = ""
for j in range(i, len(s[0])):
ans += s[0][j]
for k in range(1, len(s)):
if ans in s[k]:
if len(ans) > len(max_seq):
max_seq = ans
print(max_seq) |
class EnvMap(object):
"""EnvMap object used to load and render map from file"""
def __init__(self, map_path):
super(EnvMap, self).__init__()
self.map_path = map_path
self.load_map()
def get_all_treasure_locations(self):
treasure_locations = []
for row in range(len(self.grid)):
for col in range(len(self.grid[row])):
if self.has_treasure(row, col):
treasure_locations.append((row, col))
return treasure_locations
def get_all_wall_locations(self):
wall_locations = []
for row in range(len(self.grid)):
for col in range(len(self.grid[row])):
if self.has_wall(row, col):
wall_locations.append((row, col))
return wall_locations
def get_all_lightning_probability(self):
lightning_probability = []
for row in range(len(self.grid)):
r = []
for col in range(len(self.grid[row])):
r.append(self.get_lightning_probability(row, col))
lightning_probability.append(r)
return lightning_probability
def load_map(self):
self.grid = []
with open(self.map_path) as fp:
line = fp.readline()
while line:
row = list(map(float, line.strip().split()))
self.grid.append(row)
line = fp.readline()
def render(self):
for row in self.grid:
print(row)
def agent_location(self):
for row in range(len(self.grid)):
for col in range(len(self.grid[row])):
if self.is_agent_position(row, col):
return (row, col)
return None
def has_wall(self, row, col):
return self.grid[row][col] == 2
def has_treasure(self, row, col):
return self.grid[row][col] == 3
def is_agent_position(self, row, col):
return self.grid[row][col] == 4
def get_lightning_probability(self, row, col):
if (self.has_wall(row, col)
or self.is_agent_position(row, col)
or self.has_treasure(row, col)):
return 0
return self.grid[row][col]
def shape(self):
return (len(self.grid), len(self.grid[0]))
|
testArray = [1, 2, 3, 4, 5]
testString = 'this is the test string'
newString = testString + str(testArray)
print(newString) |
class Solution:
def alienOrder(self, words: List[str]) -> str:
"""
Approach:
1. Make a graph according to the letters order, comparing to adjacent words
2. Find Topological order based on the graph
Examples:
["ba", "bc", "ac", "cab"]
b: a
a: c
res = bac
["ywx", "wz", "xww", "xz", "zyy", "zwz"]
y: 0
w: 2
z: 2
x: 1
y: w, w
w: x, z
x: z
res = ywxz
"""
n = len(words)
graph = defaultdict(list)
indegree = defaultdict(int)
for word in words:
for character in word:
indegree[character] = 0
for i in range(n-1):
word1, word2 = words[i], words[i+1]
idx1, idx2 = 0, 0
while idx1 < len(word1) and idx2 < len(word2):
char1 = word1[idx1]
char2 = word2[idx2]
if char1 != char2:
graph[char1].append(char2)
indegree[char2] += 1
break
idx1 += 1
idx2 += 1
else:
if len(word2) < len(word1):
return ""
order = []
q = deque([node for node, count in indegree.items() if count == 0])
while q:
source = q.popleft()
order.append(source)
for dest in graph[source]:
indegree[dest] -= 1
if indegree[dest] <= 0:
q.append(dest)
if len(order) != len(indegree):
return ""
return "".join(order) |
"""
https://leetcode.com/problems/find-lucky-integer-in-an-array/
Given an array of integers arr, a lucky integer is an integer which has a frequency in the array equal to its value.
Return a lucky integer in the array. If there are multiple lucky integers return the largest of them. If there is no lucky integer return -1.
Example 1:
Input: arr = [2,2,3,4]
Output: 2
Explanation: The only lucky number in the array is 2 because frequency[2] == 2.
Example 2:
Input: arr = [1,2,2,3,3,3]
Output: 3
Explanation: 1, 2 and 3 are all lucky numbers, return the largest of them.
Example 3:
Input: arr = [2,2,2,3,3]
Output: -1
Explanation: There are no lucky numbers in the array.
Example 4:
Input: arr = [5]
Output: -1
Example 5:
Input: arr = [7,7,7,7,7,7,7]
Output: 7
Constraints:
1 <= arr.length <= 500
1 <= arr[i] <= 500
"""
# time complexity: O(n), space complexity: O(n)
class Solution:
def findLucky(self, arr: List[int]) -> int:
dic = dict()
for num in arr:
dic[num] = dic.get(num, 0) + 1
result = -1
for key, item in dic.items():
if key == item and key > result:
result = key
return result
|
def load_sensitivity_study_file_names(design):
"""
Parameters
----------
design: Name of design
Returns experiment files names of a design
-------
"""
file_names = {}
if design == 'NAE-IAW':
path = '../Files_Results/Sensitivity_Study/NAE-IAW/'
file_names['FILE_MeanDrift_var0.01'] = 'Sensitivity_Study_RandomNumpyRandomNormalUniform_onlyMeanDrift_var0.01_50DR_100Dims_1MinDimBroken_300MinL_2000MaxL_2021-08-10_10.32.pickle_2021-08-24_12.30_10ITERATIONS_fitNewAETrue_fitFalse'
file_names['FILE_MeanDrift_var0.05'] = 'Sensitivity_Study_RandomNumpyRandomNormalUniform_onlyMeanDrift_var0.05_50DR_100Dims_1MinDimBroken_300MinL_2000MaxL_2021-08-06_10.42.pickle_2021-08-24_14.36_10ITERATIONS_fitNewAETrue_fitFalse'
file_names['FILE_MeanDrift_var0.25'] = 'Sensitivity_Study_RandomNumpyRandomNormalUniform_onlyMeanDrift_var0.25_50DR_100Dims_1MinDimBroken_300MinL_2000MaxL_2021-08-06_10.45.pickle_2021-08-24_17.24_10ITERATIONS_fitNewAETrue_fitFalse'
file_names['FILE_VarianceDrift'] = 'Sensitivity_Study_RandomNumpyRandomNormalUniform_onlyVarianceDrift_50DR_100Dims_1MinDimBroken_300MinL_2000MaxL_2021-08-06_11.15.pickle_2021-08-24_20.58_10ITERATIONS_fitNewAETrue_fitFalse'
file_names['FILE_MeanVarianceDrift_all_broken'] = 'Sensitivity_Study_RandomNumpyRandomNormalUniform_50DR_100Dims_100MinDimBroken_300MinL_2000MaxL_2021-08-06_10.54.pickle_2021-08-24_13.34_10ITERATIONS_fitNewAETrue_fitFalse'
file_names['FILE_MeanVarianceDrift'] = 'Sensitivity_Study_RandomNumpyRandomNormalUniform_50DR_100Dims_1MinDimBroken_300MinL_2000MaxL_2021-08-06_10.53.pickle_2021-08-24_16.22_10ITERATIONS_fitNewAETrue_fitFalse'
file_names['FILE_RandomRBF_Generator'] = 'Sensitivity_Study_RandomRandomRBF_50DR_100Dims_50Centroids_1MinDriftCentroids_300MinL_2000MaxL_2021-08-06_10.57.pickle_2021-08-24_13.20_10ITERATIONS_fitNewAETrue_fitFalse'
file_names['FILE_MergedStream'] = 'Sensitivity_Study_Mixed_300MinDistance_DATASET_A_RandomNumpyRandomNormalUniform_DATASET_B_RandomRandomRBF.pickle_2021-08-24_13.08_10ITERATIONS_fitNewAETrue_fitFalse'
file_names['FILE_FashionMNIST'] = 'Sensitivity_Study_RandomMNIST_and_FashionMNIST_SortAllNumbers19DR_2021-08-06_11.07.pickle_2021-08-25_12.07_10ITERATIONS_fitNewAETrue_fitFalse'
if design == 'RAE-IAW':
path = '../Files_Results/Sensitivity_Study/RAE-IAW/'
file_names['FILE_MeanDrift_var0.01'] = 'Sensitivity_Study_RandomNumpyRandomNormalUniform_onlyMeanDrift_var0.01_50DR_100Dims_1MinDimBroken_300MinL_2000MaxL_2021-08-10_10.32.pickle_2021-08-11_19.36_10ITERATIONS_fitNewAEFalse_fitTrue'
file_names['FILE_MeanDrift_var0.05'] = 'Sensitivity_Study_RandomNumpyRandomNormalUniform_onlyMeanDrift_var0.05_50DR_100Dims_1MinDimBroken_300MinL_2000MaxL_2021-08-06_10.42.pickle_2021-08-12_00.04_10ITERATIONS_fitNewAEFalse_fitTrue'
file_names['FILE_MeanDrift_var0.25'] = 'Sensitivity_Study_RandomNumpyRandomNormalUniform_onlyMeanDrift_var0.25_50DR_100Dims_1MinDimBroken_300MinL_2000MaxL_2021-08-06_10.45.pickle_2021-08-12_14.18_10ITERATIONS_fitNewAEFalse_fitTrue'
file_names['FILE_VarianceDrift'] = 'Sensitivity_Study_RandomNumpyRandomNormalUniform_onlyVarianceDrift_50DR_100Dims_1MinDimBroken_300MinL_2000MaxL_2021-08-06_11.15.pickle_2021-08-12_18.04_10ITERATIONS_fitNewAEFalse_fitTrue'
file_names['FILE_MeanVarianceDrift_all_broken'] = 'Sensitivity_Study_RandomNumpyRandomNormalUniform_50DR_100Dims_100MinDimBroken_300MinL_2000MaxL_2021-08-06_10.54.pickle_2021-08-12_20.47_10ITERATIONS_fitNewAEFalse_fitTrue'
file_names['FILE_MeanVarianceDrift'] = 'Sensitivity_Study_RandomNumpyRandomNormalUniform_50DR_100Dims_1MinDimBroken_300MinL_2000MaxL_2021-08-06_10.53.pickle_2021-08-13_00.30_10ITERATIONS_fitNewAEFalse_fitTrue'
file_names['FILE_RandomRBF_Generator'] = 'Sensitivity_Study_RandomRandomRBF_50DR_100Dims_50Centroids_1MinDriftCentroids_300MinL_2000MaxL_2021-08-06_10.57.pickle_2021-08-12_19.37_10ITERATIONS_fitNewAEFalse_fitTrue'
file_names['FILE_MergedStream'] = 'Sensitivity_Study_Mixed_300MinDistance_DATASET_A_RandomNumpyRandomNormalUniform_DATASET_B_RandomRandomRBF.pickle_2021-08-13_03.54_10ITERATIONS_fitNewAEFalse_fitTrue'
file_names['FILE_FashionMNIST'] = 'Sensitivity_Study_RandomMNIST_and_FashionMNIST_SortAllNumbers19DR_2021-08-06_11.07.pickle_2021-08-12_22.40_10ITERATIONS_fitNewAEFalse_fitTrue'
return path, file_names
|
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
class DepthInfo:
# The default depth that we travel before forcing a foreign key attribute
DEFAULT_MAX_DEPTH = 2
# The max depth set if the user specified to not use max depth
MAX_DEPTH_LIMIT = 32
def __init__(self, current_depth, max_depth, max_depth_exceeded):
# The maximum depth that we can resolve entity attributes.
# This value is set in resolution guidance.
self.current_depth = current_depth # type: int
# The current depth that we are resolving at. Each entity attribute that we resolve
# into adds 1 to depth.
self.max_depth = max_depth # type: int
# Indicates if the maxDepth value has been hit when resolving
self.max_depth_exceeded = max_depth_exceeded # type: int
|
class Solution:
def isMatch(self, text, pattern):
if not pattern:
return not text
first_match = bool(text) and pattern[0] in {text[0], '.'}
if len(pattern) >= 2 and pattern[1] == '*':
return (self.isMatch(text, pattern[2:]) or
first_match and self.isMatch(text[1:], pattern))
else:
return first_match and self.isMatch(text[1:], pattern[1:])
class Solution:
def isMatch(self, text, pattern):
memo = {}
def dp(i, j):
if (i, j) not in memo:
if j == len(pattern):
ans = i == len(text)
else:
first_match = i < len(text) and pattern[j] in {text[i], '.'}
if j+1 < len(pattern) and pattern[j+1] == '*':
ans = dp(i, j+2) or first_match and dp(i+1, j)
else:
ans = first_match and dp(i+1, j+1)
memo[i, j] = ans
return memo[i, j]
return dp(0, 0)
class Solution:
def isMatch(self, text, pattern):
dp = [[False] * (len(pattern) + 1) for _ in range(len(text) + 1)]
dp[-1][-1] = True
for i in range(len(text), -1, -1):
for j in range(len(pattern) - 1, -1, -1):
first_match = i < len(text) and pattern[j] in {text[i], '.'}
if j+1 < len(pattern) and pattern[j+1] == '*':
dp[i][j] = dp[i][j+2] or first_match and dp[i+1][j]
else:
dp[i][j] = first_match and dp[i+1][j+1]
return dp[0][0]
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Associations Management',
'version': '0.1',
'category': 'Marketing',
'description': """
This module is to configure modules related to an association.
==============================================================
It installs the profile for associations to manage events, registrations, memberships,
membership products (schemes).
""",
'depends': ['base_setup', 'membership', 'event'],
'data': ['views/association_views.xml'],
'demo': [],
'installable': True,
'auto_install': False,
}
|
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
class SnapKorf(MakefilePackage):
"""SNAP is a general purpose gene finding program suitable for both
eukaryotic and prokaryotic genomes."""
homepage = "http://korflab.ucdavis.edu/software.html"
url = "http://korflab.ucdavis.edu/Software/snap-2013-11-29.tar.gz"
git = "https://github.com/KorfLab/SNAP.git"
version('2021-11-04', commit='62ff3120fceccb03b5eea9d21afec3167dedfa94')
version('2013-11-29', sha256='e2a236392d718376356fa743aa49a987aeacd660c6979cee67121e23aeffc66a')
depends_on('perl', type=('build', 'run'))
def edit(self, spec, prefix):
if spec.satisfies('@2013-11-29%gcc@6:'):
rstr = '\\1 -Wno-tautological-compare -Wno-misleading-indentation'
filter_file('(-Werror)', rstr, 'Zoe/Makefile')
rstr = '\\1 -Wno-error=format-overflow -Wno-misleading-indentation'
filter_file('(-Werror)', rstr, 'Makefile')
filter_file(r'(^const char \* zoeFunction;)', 'extern \\1',
'Zoe/zoeTools.h')
filter_file(r'(^const char \* zoeConstructor;)', 'extern \\1',
'Zoe/zoeTools.h')
filter_file(r'(^const char \* zoeMethod;)', 'extern \\1',
'Zoe/zoeTools.h')
def install(self, spec, prefix):
mkdirp(prefix.bin)
progs = ['snap', 'fathom', 'forge']
if spec.satisfies('@2013-11-29'):
progs = progs + ['depend', 'exonpairs', 'hmm-info']
for p in progs:
install(p, prefix.bin)
install('*.pl', prefix.bin)
install_tree('Zoe', prefix.Zoe)
install_tree('HMM', prefix.HMM)
install_tree('DNA', prefix.DNA)
def setup_run_environment(self, env):
env.set('ZOE', self.prefix)
env.prepend_path('PATH', self.prefix)
|
def format_sql(table, obj: dict) -> str:
cols = ','.join(obj.keys())
values = ','.join(obj.values())
sql = "insert into {table} ({cols}) values ({values})".format(table=table, cols=cols, values=values)
return
def format_sqls(table, objs: list) -> str:
obj = objs.__getitem__(0)
cols = ','.join(obj.keys())
values = get_values_str(objs)
sql = "insert into {table} ({cols}) values {values}".format(table=table, cols=cols, values=values)
return sql
def get_values_str(objs: list):
values = []
for obj in objs:
values.append("({sqlValue})".format(sqlValue=','.join("'%s'" % o for o in obj.values())))
return ",".join(values)
# format_sqls("coin", [{"a": "1", "b": "2"}, {"a": "3", "b": "4"}])
|
# 문제: 238. Product of Array Except Self
# 링크: https://leetcode.com/problems/product-of-array-except-self/
# 시간/공간: 248ms / 22.4MB
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
n = len(nums)
# 앞에서 부터 시작해 누적곱 계산
left = [nums[0]]
for i in range(1, n):
left.append(left[-1] * nums[i])
# 뒤에서 부터 시작해 누적곱 계산
right = [nums[-1]]
for i in range(n - 2, -1, -1):
right.append(right[-1] * nums[i])
right.reverse()
answer = [right[1]]
for i in range(1, n - 1):
# i를 제외한 곱 계산
answer.append(left[i - 1] * right[i + 1])
answer.append(left[n - 2])
return answer
# 시간/공간: 240ms / 21.2MB
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
n = len(nums)
answer = [1] * n # 정답 배열
left = right = 1 # 앞, 뒤 누적곱
for i in range(n):
j = n - left - 1 # 포인터
answer[i] *= left
answer[j] *= right
left *= nums[i]
right *= nums[j]
return answer
|
# Head ends here
def next_move(posr, posc, board):
p = 0
q = 0
dmin = 0
dmax = 0
position = 0
for i in range(5) :
count = 0
for j in range(5) :
if board[i][j] == "d" :
count += 1
if count == 1 :
dmax = dmin = j
elif count > 1 :
dmax = j
if count > 0 :
for l in range(dmin , dmax + 1):
if position < dmin :
for k in range(position , dmin , 1) :
print("RIGHT")
position = k + 1
elif position > dmin :
for k in range(position , dmin , -1) :
if board[i][k] == "d" :
print("CLEAN")
board[i][k] == "-"
print("LEFT")
position = k - 1
elif position == dmin :
print("CLEAN")
board[i][dmin] = "-"
if dmin != dmax :
position += 1
print("RIGHT")
if i != 4 :
print("DOWN")
# Tail starts here
if __name__ == "__main__":
pos = [int(i) for i in input().strip().split()]
board = [[j for j in input().strip()] for i in range(5)]
next_move(pos[0], pos[1], board)
# Slight Changes in the above code
# Head ends here
def next_move(posr, posc, board):
p = 0
q = 0
dmin = 0
dmax = 0
position = 0
for i in range(5) :
count = 0
for j in range(5) :
if board[i][j] == "d" :
count += 1
if count == 1 :
dmax = dmin = j
elif count > 1 :
dmax = j
if count > 0 :
for l in range(dmin , dmax + 1):
if position < dmin :
for k in range(position , dmin , 1) :
print("RIGHT")
position = k + 1
if position > dmin :
for k in range(position , dmin , -1) :
if board[i][k] == "d" :
print("CLEAN")
board[i][k] == "-"
print("LEFT")
position = k - 1
if position == dmin :
print("CLEAN")
board[i][dmin] = "-"
if dmin != dmax :
position += 1
print("RIGHT")
if i != 4 :
print("DOWN")
# Tail starts here
if __name__ == "__main__":
pos = [int(i) for i in input().strip().split()]
board = [[j for j in input().strip()] for i in range(5)]
next_move(pos[0], pos[1], board)
|
class Person:
def __init__(self, name):
self.name = name
# create the method greet here
def greet(self):
print(f"Hello, I am {self.name}!")
in_name = input()
p = Person(in_name)
p.greet()
|
load("@wix_oss_infra//:import_external.bzl", import_external = "safe_wix_scala_maven_import_external")
def dependencies():
import_external(
name = "org_xerial_snappy_snappy_java",
artifact = "org.xerial.snappy:snappy-java:1.1.7.1",
artifact_sha256 = "bb52854753feb1919f13099a53475a2a8eb65dbccd22839a9b9b2e1a2190b951",
srcjar_sha256 = "a01c58c2af4bf16d2b841c74f76d98489bc03b5f9cf63aea33a8cb14ce376258",
)
|
'''from flask import render_template
from flask import Response
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return render_template('streaming2.html')
def generate(camera):
while True:
frame = camera.get_frame()
yield (b'--frame\r\n'
b'Content-Type: image/jpg\r\n\r\n' + frame + b'\r\n\r\n')
@app.route('/video_feed')
def video_feed():
return Response(gen(),
mimetype='multipart/x-mixed-replace;
boundary=frame')''' |
#Função verifica se é par ou impar
numero=int(input('Digite um número: '))
def Ehpar(numero):
if(numero%2==0):
return True
else:
return False
print('Portanto, o número digitado é par? ', Ehpar(numero)) |
class AbBuildUnsuccesful(Exception):
""" Build was not successful """
def __init__(self, msg, output):
self.msg = msg
self.output = output
def __str__(self):
return "%s" % self.msg
|
class StreamQueue:
repeat = False
current = None
streams = []
def next(self):
if self.repeat and self.current is not None:
return self.current
self.current = None
if len(self.streams) > 0:
self.current = self.streams.pop(0)
return self.current
def add(self, url):
self.streams.append(url)
def clear(self):
self.current = None
self.streams.clear()
def __len__(self):
return len(self.streams)
|
# GCD, LCM
"""
T = int(input())
def lcm(x, y):
if x > y:
greater = x
else:
greater = y
while True:
if greater % x == 0 and greater % y == 0:
lcm = greater
break
greater += 1
return lcm
for _ in range(T):
M, N, x, y = map(int(), input().split())
"""
def get_year(m, n, x, y):
while x <= m * n:
if (x-y) % n == 0:
return x
x += m
return -1
T = int(input())
for _ in range(T):
m, n, x, y = map(int, input().split())
print(get_year(m,n,x,y)) |
transformers = [
{
'id': 1,
'category': 'Feature Extractors',
'transformer': 'Dictionary Vectorizer',
'description': 'The class DictVectorizer can be used to convert feature arrays represented as lists of standard Python dict objects to the NumPy/SciPy representation used by scikit-learn estimators.',
'tags': ['transformer'],
'connection': {
'istarget': True,
'issource': True,
'maxtargets': 3,
'maxsources': 3
}
},
{
'id': 2,
'category': 'Feature Extractors',
'transformer': 'Count Vectorizer',
'description': 'Count Vectorizer implements both tokenization and occurrence counting in a single class.',
'tags': ['transformer'],
'connection': {
'istarget': True,
'issource': True,
'maxtargets': 3,
'maxsources': 3
}
},
{
'id': 3,
'category': 'Feature Extractors',
'transformer': 'Tfidf Transformer',
'description': 'Tf means term-frequency while tf–idf means term-frequency times inverse document-frequency.',
'tags': ['transformer'],
'connection': {
'istarget': True,
'issource': True,
'maxtargets': 3,
'maxsources': 3
}
},
{
'id': 4,
'category': 'Feature Extractors',
'transformer': 'Hashing Vectorizer',
'description': 'Convert a collection of text documents to a matrix of token occurrences.',
'tags': ['transformer'],
'connection': {
'istarget': True,
'issource': True,
'maxtargets': 3,
'maxsources': 3
}
},
{
'id': 5,
'category': 'Preprocessing',
'transformer': 'Scale',
'description': 'Standardization of datasets is a common requirement for many machine learning estimators implemented in scikit-learn; they might behave badly if the individual features do not more or less look like standard normally distributed data: Gaussian with zero mean and unit variance.',
'tags': ['transformer'],
'connection': {
'istarget': True,
'issource': True,
'maxtargets': 3,
'maxsources': 3
}
},
{
'id': 6,
'category': 'Preprocessing',
'transformer': 'Standard Scaler',
'description': 'Standardize features by removing the mean and scaling to unit variance.',
'tags': ['transformer'],
'connection': {
'istarget': True,
'issource': True,
'maxtargets': 3,
'maxsources': 3
}
},
{
'id': 7,
'category': 'Preprocessing',
'transformer': 'MinMax Scaler',
'description': 'Transforms features by scaling each feature to a given range.',
'tags': ['transformer'],
'connection': {
'istarget': True,
'issource': True,
'maxtargets': 3,
'maxsources': 3
}
},
{
'id': 8,
'category': 'Preprocessing',
'transformer': 'MinAbs Scaler',
'description': 'Scale each feature by its maximum absolute value.',
'tags': ['transformer'],
'connection': {
'istarget': True,
'issource': True,
'maxtargets': 3,
'maxsources': 3
}
},
{
'id': 9,
'category': 'Preprocessing',
'transformer': 'Robust Scaler',
'description': 'Scale features using statistics that are robust to outliers.',
'tags': ['transformer'],
'connection': {
'istarget': True,
'issource': True,
'maxtargets': 3,
'maxsources': 3
}
},
{
'id': 10,
'category': 'Preprocessing',
'transformer': 'Kernel Centerer',
'description': 'Center a kernel matrix.',
'tags': ['transformer'],
'connection': {
'istarget': True,
'issource': True,
'maxtargets': 3,
'maxsources': 3
}
}
]
|
def Move():
global ArchiveIndex, gameData
playerShip.landedBefore = playerShip.landedOn
playerShip.landedOn = None
for Thing in PlanetContainer:
XDiff = playerShip.X - Thing.X
YDiff = playerShip.Y + Thing.Y
Distance = (XDiff ** 2 + YDiff ** 2) ** 0.5
if Distance > 40000:
ArchiveContainer.append(Thing)
PlanetContainer.remove(Thing)
elif Distance <= Thing.size + 26:
# collision OR landed --> check speed
if playerShip.speed > 2:
playerShip.hull -= playerShip.speed ** 2
if playerShip.hull <= 0:
# crash!
# Play('boom')
if gameData.homePlanet in ArchiveContainer:
PlanetContainer.append(gameData.homePlanet)
ArchiveContainer.remove(gameData.homePlanet)
if gameData.homePlanet.oil > 1592: # 592+1000
playerShip.hull = 592
playerShip.oil = 1000
playerShip.X = 0
playerShip.Y = 25
playerShip.toX = 0
playerShip.toY = 0
playerShip.faceAngle = 180
gameData.homePlanet.oil -= 1592
else:
playerShip.hull = 0
DisplayMessage(
"You crashed and died in the explosion. You lose.")
gameData = None
return "to menu"
else:
# land!
playerShip.landedOn = PlanetContainer.index(Thing)
if not Thing.playerLanded:
if gameData.tutorial and gameData.stage == 1:
checkProgress("player landed")
if (
Thing.baseAt is not None
and (
(
Thing.X
+ Thing.size * cos(radians(Thing.baseAt + 90))
- playerShip.X
)
** 2
+ (
-Thing.Y
- Thing.size * sin(radians(Thing.baseAt + 90))
- playerShip.Y
)
** 2
)
** 0.5
< 60
):
Thing.playerLanded = "base"
else:
Thing.playerLanded = True
playerShip.toX = 0
playerShip.toY = 0
continue
else:
NDistance = (
(playerShip.X + playerShip.toX - Thing.X) ** 2
+ (playerShip.Y + playerShip.toY + Thing.Y) ** 2
) ** 0.5
if NDistance < Distance:
playerShip.toX = Thing.size / 20 / Distance * XDiff / Distance
playerShip.toY = Thing.size / 20 / Distance * YDiff / Distance
playerShip.speed = (
playerShip.toX ** 2 + playerShip.toY ** 2
) ** 0.5
playerShip.angle = degrees(
atan2(-playerShip.toX, playerShip.toY)
)
playerShip.move()
playerShip.toX = 0
playerShip.toY = 0
continue
else:
Thing.playerLanded = False
if gameData.stage > 0 and Thing.enemyAt is not None:
pos = radians(Thing.enemyAt + 90)
X = Thing.X + Thing.size * cos(pos)
Y = Thing.Y + Thing.size * sin(pos)
if ((playerShip.X - X) ** 2 + (playerShip.Y + Y) ** 2) ** 0.5 < 300:
playerShip.hull -= random.randint(1, 3) * random.randint(1, 3)
gameData.shootings = 3
if playerShip.hull <= 0:
# Play('boom')
if gameData.homePlanet in ArchiveContainer:
PlanetContainer.append(gameData.homePlanet)
ArchiveContainer.remove(gameData.homePlanet)
if gameData.homePlanet.oil > 1592: # 592+1000
playerShip.hull = 592
playerShip.oil = 1000
playerShip.X = 0
playerShip.Y = 25
playerShip.toX = 0
playerShip.toY = 0
playerShip.faceAngle = 180
gameData.homePlanet.oil -= 1592
else:
playerShip.hull = 0
DisplayMessage("You where shot and died. You lose.")
gameData = None
return "to menu"
Acceleration = Thing.size / 20 / Distance
playerShip.toX -= Acceleration * XDiff / Distance
playerShip.toY -= Acceleration * YDiff / Distance
playerShip.speed = (playerShip.toX ** 2 + playerShip.toY ** 2) ** 0.5
playerShip.angle = degrees(atan2(-playerShip.toX, playerShip.toY))
for Thing in ShipContainer:
# move ships
Thing.move()
if gameData.stage > 0:
if (
(playerShip.X - Thing.X) ** 2 + (playerShip.Y + Thing.Y) ** 2
) ** 0.5 < 300:
playerShip.hull -= random.randint(1, 3) * random.randint(1, 3)
gameData.shootings = 3
if playerShip.hull <= 0:
Play("boom")
if gameData.homePlanet in ArchiveContainer:
PlanetContainer.append(gameData.homePlanet)
ArchiveContainer.remove(gameData.homePlanet)
if gameData.homePlanet.oil > 1592: # 592+1000
playerShip.hull = 592
playerShip.oil = 1000
playerShip.X = 0
playerShip.Y = 25
playerShip.toX = 0
playerShip.toY = 0
playerShip.faceAngle = 180
gameData.homePlanet.oil -= 1592
else:
playerShip.hull = 0
DisplayMessage("You where shot and died. You lose.")
gameData = None
return "to menu"
for Thing in WreckContainer:
Thing.explosion += 0.1
if Thing.explosion > 10:
WreckContainer.remove(Thing)
playerShip.move()
if sectors.pixels2sector(playerShip.X, playerShip.Y) != sectors.pixels2sector(
playerShip.X - playerShip.toX, playerShip.Y - playerShip.toY
):
checkProgress("sector changed")
playerView.X = playerShip.X
playerView.Y = playerShip.Y
if playerShip.oil <= 0:
# Play('boom')
if gameData.homePlanet in ArchiveContainer:
PlanetContainer.append(gameData.homePlanet)
ArchiveContainer.remove(gameData.homePlanet)
if gameData.homePlanet.oil > 1592: # 592+1000
playerShip.hull = 592
playerShip.oil = 1000
playerShip.X = 0
playerShip.Y = 25
playerShip.toX = 0
playerShip.toY = 0
playerShip.faceAngle = 180
gameData.homePlanet.oil -= 1592
else:
playerShip.oil = 0
DisplayMessage(
"Your oilsupply is empty. You can't do anything anymore. You lose."
)
gameData = None
return "to menu"
playerShip.X = 0
playerShip.Y = 25
playerShip.toX = 0
playerShip.toY = 0
playerShip.faceAngle = 180
playerShip.oil = 1000
if Frames % 10 == 0:
try:
Distance = (
(playerShip.X - ArchiveContainer[ArchiveIndex].X) ** 2
+ (playerShip.Y + ArchiveContainer[ArchiveIndex].Y) ** 2
) ** 0.5
if Distance < 35000:
T = ArchiveContainer.pop(ArchiveIndex)
if type(T) == Planet:
PlanetContainer.append(T)
elif T.dead:
WreckContainer.append(T)
else:
ShipContainer.append(T)
ArchiveIndex = ArchiveIndex % len(ArchiveContainer)
else:
ArchiveIndex = (ArchiveIndex + 1) % len(ArchiveContainer)
except: # If the ArchiveContainer is empty
pass
|
"""
>= 0.9 A
>= 0.8 B
>= 0.7 C
>= 0.6 D
< 0.6 F
"""
score = input("Enter Score: ")
try:
s = float(score)
except:
print("please enter numeric numbers")
quit()
if s>1.0 or s< 0.0:
print("value out of range! please enter number btw 1.0 and 0.0")
elif s >= 0.9:
print("A")
elif s >=0.8:
print("B")
elif s >=0.7:
print("C")
elif s >=0.6:
print("D")
else:
print("F")
|
def names(l):
# list way
new = []
for i in l:
if not i in new:
new.append(i)
# set way
new = list(set(l))
print(new)
names(["Michele", "Robin", "Sara", "Michele"]) |
"""
https://leetcode.com/problems/find-the-difference/
Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
Input:
s = "abcd"
t = "abcde"
Output:
e
Explanation:
'e' is the letter that was added.
"""
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
dict_t = {}
for c in t:
if dict_t.get(c,0) > 0:
dict_t[c] = dict_t[c] + 1
else:
dict_t.setdefault(c,1)
for c in s:
if dict_t.get(c,0) > 0:
dict_t[c] = dict_t[c] - 1
result = ''
for key in dict_t.keys():
if dict_t[key] > 0:
result = key
return result
#測試程式
if __name__ == '__main__':
s = Solution()
print(s.findTheDifference('123','1234'))
|
mylist = [1, 2, 3]
# Imprime 1,2,3
for x in mylist:
print(x)
|
#Faça um programa que calcule a soma entre todos os números impares que são multiplos de três e que se encontram no intervalo de 1 até 500
ac = 0
cont = 0
for i in range(1,501,2):
if i % 3 == 0:
ac += i
cont += 1
print(i, end = ' ')
print('A Soma de todos os {} valores solicitados é {}'.format(cont,ac))
|
"""
141. Linked List Cycle
"""
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
slow = fast = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if slow == fast:
return True
return False |
#Print without newline or space
print("\n")
for j in range(10):
print("")
for i in range(10):
print(' @ ', end="")
print("\n") |
class Entry:
def __init__(self, obj, line_number = 1):
self.obj = obj
self.line_number = line_number
def __repr__(self):
return "In {}, line {}".format(self.obj.name, self.line_number)
class CallStack:
def __init__(self, initial = None):
self.__stack = [] if not initial else initial
def __repr__(self):
stk = "\n".join([str(entry) for entry in self.__stack])
return "Traceback (Most recent call last):\n" + stk + "\n"
__str__ = __repr__
def __len__(self):
return len(self.__stack)
def append(self, entry):
self.__stack.append(entry)
def pop(self):
last = self.__stack[-1]
self.__stack.pop()
return last
def __getitem__(self, index):
if isinstance(index, slice):
return CallStack(self.__stack[index])
else: return self.__stack[index]
|
class BaseConfig():
API_PREFIX = '/api'
TESTING = False
DEBUG = False
SECRET_KEY = '@!s3cr3t'
AGENT_SOCK = 'cmdsrv__0'
class DevConfig(BaseConfig):
FLASK_ENV = 'development'
DEBUG = True
CELERY_BROKER = 'redis://localhost:6379/0'
CELERY_RESULT_BACKEND = 'redis://localhost:6379/0'
REDIS_URL = "redis://localhost:6379/0"
IFACE = "eno2"
class ProductionConfig(BaseConfig):
FLASK_ENV = 'production'
CELERY_BROKER = 'redis://localhost:6379/0'
CELERY_RESULT_BACKEND = 'redis://localhost:6379/0'
REDIS_URL = "redis://localhost:6379/0"
class TestConfig(BaseConfig):
FLASK_ENV = 'development'
TESTING = True
DEBUG = True
# make celery execute tasks synchronously in the same process
CELERY_ALWAYS_EAGER = True
|
while True:
x,y=map(int,input().split())
if x==0 and y==0:
break
print(x+y)
|
def encode(json, schema):
payload = schema.Main()
payload.github = json['github']
payload.patreon = json['patreon']
payload.open_collective = json['open_collective']
payload.ko_fi = json['ko_fi']
payload.tidelift = json['tidelift']
payload.community_bridge = json['community_bridge']
payload.liberapay = json['liberapay']
payload.issuehunt = json['issuehunt']
payload.otechie = json['otechie']
payload.custom = json['custom']
return payload
def decode(payload):
return payload.__dict__
|
#!/usr/local/bin/python3
"""
This is written by Zhiyang Ong to try out Solutions 1-4
from [Sceenivasan, 2017].
Reference for Solutions 1, 2, 3, and 4 [Sceenivasan, 2017]:
Sreeram Sceenivasan, "How to implement a switch-case statement
in Python: No in-built switch statement here," from JAXenter.com,
Software {\rm \&}\ Support Media {GmbH}, Frankfurt, Germany,
October 24, 2017.
Available online from JAXenter.com at: https://jaxenter.com/implement-switch-case-statement-python-138315.html; June 26, 2020 was the last accessed date
See https://gist.github.com/eda-ricercatore/8cbb931f330af2b5e96edaa8b89ed0c4
for the public GitHub Gist of this.
"""
# --------------------------------------------------------
# Solution 1.
def switch_demo(argument):
switcher = {
1: "January",
2: "February",
3: "March",
4: "April",
5: "May",
6: "June",
7: "July",
8: "August",
9: "September",
10: "October",
11: "November",
12: "December"
}
#print(switcher.get(argument, "Invalid month"))
return switcher.get(argument, "Invalid month")
# --------------------------------------------------------
# Solution 2.
def one():
return "January"
def two():
return "February"
def three():
return "March"
def four():
return "April"
def five():
return "May"
def six():
return "June"
def seven():
return "July"
def eight():
return "August"
def nine():
return "September"
def ten():
return "October"
def eleven():
return "November"
def twelve():
return "December"
# For solution 4, create a case for the 93th month.
def new_month():
return "new-month-created"
"""
Redundant function.
For solution 4, create a catch-all case for invalid input.
def invalid_input():
return "Invalid month"
"""
"""
Create a dictionary with function names as values, rather
than basic data types such as strings and integers/floats,
since the values of a Python dictionary can be of any
data type.
Likewise, we can also use lambdas as values for a dictionary.
This enables users to use the dictionary "to execute ...
blocks of code within each function".
"""
def numbers_to_months(argument):
switcher = {
1: one,
2: two,
3: three,
4: four,
5: five,
6: six,
7: seven,
8: eight,
9: nine,
10: ten,
11: eleven,
12: twelve
}
# Get the function from switcher dictionary
func = switcher.get(argument, lambda: "Invalid month")
# Execute the function
#print(func())
return func()
# --------------------------------------------------------
# Solution 3.
class Switcher(object):
def numbers_to_months(self, argument):
#Dispatch method
method_name = 'month_' + str(argument)
# Get the method from 'self'. Default to a lambda.
method = getattr(self, method_name, lambda: "Invalid month")
# Call the method as we return it
return method()
def month_1(self):
return "January"
def month_2(self):
return "February"
def month_3(self):
return "March"
def month_4(self):
return "April"
def month_5(self):
return "May"
def month_6(self):
return "June"
def month_7(self):
return "July"
def month_8(self):
return "August"
def month_9(self):
return "September"
def month_10(self):
return "October"
def month_11(self):
return "November"
def month_12(self):
return "December"
# --------------------------------------------------------
# Solution 4.
switcher = {
1: one,
2: two,
3: three,
4: four,
5: five,
6: six,
7: seven,
8: eight,
9: nine,
10: ten,
11: eleven,
12: twelve
}
"""
Published Solution 4 in [Sceenivasan, 2017] fails to work
for the default case, or the catch-all case for cases
not covered in the dictionary named "switcher".
Used a lambda function to provide the catch-all case for
cases not covered in the dictionary named "switcher".
"""
def numbers_to_strings(argument):
# Get the function from switcher dictionary
#func = switcher.get(argument, "nothing")
func = switcher.get(argument, lambda: "Invalid month")
# Execute the function
return func()
# --------------------------------------------------------
# Solution from [patel, 2017]
def f(x):
return {
1 : "output for case 1",
2 : "output for case 2",
3 : "output for case 3"
}.get(x, "default case")
# --------------------------------------------------------
"""
Solution 5.
Modified solution from Stephan Schielke, April 8, 2017 at 15:19.
Use static functions with a dictionary.
"""
@staticmethod
def spring_months():
return "March-May"
@staticmethod
def summer_months():
return "June-August"
@staticmethod
def fall_months():
return "September-November"
@staticmethod
def winter_months():
return "December-February"
months_of_year = {
1: winter_months,
2: winter_months,
3: spring_months,
4: spring_months,
5: spring_months,
6: summer_months,
7: summer_months,
8: summer_months,
9: fall_months,
10: fall_months,
11: fall_months,
12: winter_months
}
# --------------------------------------------------------
"""
Solutions not considered:
+ From user5359735/IanMobbs, June 13, 2016 at 17:09,
- Reference: https://stackoverflow.com/a/11479840/1531728
* Comment from user to answer from Prashant Kumar,
last edited on December 3, 2014.
- Sanjay Manohar, July 26, 2017 at 14:26, mentioned that
putting code in constant string in (double) quotes
for evaluation using "eval" has multiple risks, such as:
* checking for errors by text editor and IDE.
+ Cannot use features of text editor and IDE, such
syntax highlighting.
* Not "optimized to bytecode at compilation."
* lambda functions can be used instead, but is
"considered un-Pythonic".
"""
###############################################################
# Main method for the program.
# If this is executed as a Python script,
if __name__ == "__main__":
print("=== Trying solutions from [Sceenivasan, 2017].")
#print("Get month for 9:",switch_demo(9),"=")
print("Trying Solution 1.")
print("= Testing: switch_demo().")
for x in range(1, 12+1):
print("Get month for:",x,"named:",switch_demo(x),"=")
print("Get month for 56798:",switch_demo(56798),"=")
print("Get month for -443:",switch_demo(-443),"=")
print("Trying Solution 2.")
print("= Testing: numbers_to_months().")
for x in range(1, 12+1):
print("Get month for:",x,"named:",numbers_to_months(x),"=")
print("Get month for 56798:",numbers_to_months(56798),"=")
print("Get month for -443:",numbers_to_months(-443),"=")
print("Trying Solution 3.")
print("= Testing: Switcher class solution with lambda function.")
a=Switcher()
for x in range(1, 12+1):
print("Get month for:",x,"named:",a.numbers_to_months(x),"=")
print("Get month for 56798:",a.numbers_to_months(56798),"=")
print("Get month for -443:",a.numbers_to_months(-443),"=")
print("Trying Solution 4.")
print("= Testing: numbers_to_strings() method with modification to dictionary.")
for x in range(1, 12+1):
print("Get month for:",x,"named:",numbers_to_strings(x),"=")
print(" - Modify the case for the 8th month to the 3rd month, March.")
switcher[8] = three
print("Get month for 8:",numbers_to_strings(8),"=")
print(" - Create a case for the 93th month.")
switcher[93] = new_month
print("Get month for 93:",numbers_to_strings(93),"=")
print("Get month for 56798:",numbers_to_strings(56798),"=")
print("Get month for -443:",numbers_to_strings(-443),"=")
"""
\cite{Bader2020a} describes multiple default data structures
supported by the Python Standard Library \cite{DrakeJr2016b}.
Here, the example uses a dictionary.
"""
print("Trying Solution 5.")
print("= Testing: dictionary-based solution using static functions.")
for x in range(1, 12+1):
print("Get season for:",x,":::",months_of_year[x].__func__(),"=")
print(" - Modify the case for the 8th month to the winter season.")
months_of_year[8] = winter_months
print("Get month for 8:",months_of_year[8].__func__(),"=")
print(" - Create a case for the 93th month.")
months_of_year[93] = spring_months
print("Get month for 93:",months_of_year[93].__func__(),"=")
try:
print("Get month for 56798:",months_of_year[56798].__func__(),"=")
except KeyError as invalid_key:
print("Cannot use invalid key to access a key:value pair in a Python dictionary.")
print("The key 56798 being used is invalid.")
try:
print("Get month for -443:",months_of_year[-443].__func__(),"=")
except KeyError as invalid_key:
print("Cannot use invalid key to access a key:value pair in a Python dictionary.")
print("The key -443 being used is invalid.")
"""
Additional resources that I looked at:
+ Prashant Kumar, Answer to "What is the Python equivalent for a case/switch statement? [duplicate]," Stack Exchange Inc., New York, NY, December 3, 2014. Available online from Stack Exchange Inc.: Stack Overflow: Questions at: https://stackoverflow.com/a/11479840/1531728; June 27, 2020 was the last accessed date.
- This is used as Solution 1 in [Sceenivasan, 2017].
- References the following:
* Shrutarshi Basu, "Switch-case statement in Python",
Powerful Python series, The ByteBaker, Cambridge, MA,
November 3, 2008.
Available online from The ByteBaker: Powerful Python at:
+ Raymond Hettinger, Answer to "Why doesn't Python have switch-case?," Stack Exchange Inc., New York, NY, October 12, 2017. Available online from Stack Exchange Inc.: Stack Overflow: Questions at: https://stackoverflow.com/a/46701087/1531728; June 27, 2020 was the last accessed date.
- "We considered it at one point, but without having a way to declare named constants, there is no way to generate an efficient jump table. So all we would be left with is syntactic sugar for something we could already do with if-elif-elif-else chains.
- "See PEP 275 and PEP 3103 for a full discussion."
* https://www.python.org/dev/peps/pep-0275/
* https://www.python.org/dev/peps/pep-3103/
- "Roughly the rationale is that the various proposals failed to live up to people's expections about what switch-case would do, and they failed to improve on existing solutions (like dictionary-based dispatch, if-elif-chains, getattr-based dispatch, or old-fashioned polymorphism dispatch to objects with differing implementations for the same method)."
+ wim glenn, Answer to "Why doesn't Python have switch-case?," Stack Exchange Inc., New York, NY, October 12, 2017. Available online from Stack Exchange Inc.: Stack Overflow: Questions at: https://stackoverflow.com/a/46701135/1531728; June 27, 2020 was the last accessed date.
- https://docs.python.org/3/faq/design.html#why-isn-t-there-a-switch-or-case-statement-in-python
+ vedant patel and Vincenzo Carrese, Answer to "Why doesn't Python have switch-case?," Stack Exchange Inc., New York, NY, December 20, 2017. Available online from Stack Exchange Inc.: Stack Overflow: Questions at: https://stackoverflow.com/a/47902285/1531728; June 27, 2020 was the last accessed date.
- [patel, 2017]
"""
print("Trying Solution from [patel, 2017].")
print("= Testing: dictionary method, alternate specification/declaration.")
"""
range(1, 3+2) results in 1, 2, 3, 4, since range(x,y)
results in x, x+1, ..., y-2, y-1.
"""
for x in range(1, 3+2):
#for x in range(1, 8):
print("Trying index:",x,"with output:",f(x),"=")
|
# Implement a MyCalendar class to store your events. A new event can be added if adding the event will not cause a double booking.
#
# Your class will have the method, book(int start, int end). Formally, this represents a booking on the half open interval [start, end), the range of real numbers x such that start <= x < end.
#
# A double booking happens when two events have some non-empty intersection (ie., there is some time that is common to both events.)
#
# For each call to the method MyCalendar.book, return true if the event can be added to the calendar successfully without causing a double booking. Otherwise, return false and do not add the event to the calendar.
#
# Your class will be called like this: MyCalendar cal = new MyCalendar(); MyCalendar.book(start, end)
# Example 1:
# MyCalendar();
# MyCalendar.book(10, 20); // returns true
# MyCalendar.book(15, 25); // returns false
# MyCalendar.book(20, 30); // returns true
# Explanation:
# The first event can be booked. The second can't because time 15 is already booked by another event.
# The third event can be booked, as the first event takes every time less than 20, but not including 20.
# Note:
#
# The number of calls to MyCalendar.book per test case will be at most 1000.
# In calls to MyCalendar.book(start, end), start and end are integers in the range [0, 10^9].
class MyCalendar(object):
def __init__(self):
pass
def book(self, start, end):
"""
:type start: int
:type end: int
:rtype: bool
"""
# Your MyCalendar object will be instantiated and called as such:
# obj = MyCalendar()
# param_1 = obj.book(start,end)
|
#!/usr/bin/python3
OPENVSWITCH_SERVICES_EXPRS = [r"ovsdb-\S+",
r"ovs-vswitch\S+",
r"ovn\S+"]
OVS_PKGS = [r"libc-bin",
r"openvswitch-switch",
r"ovn",
]
OVS_DAEMONS = {"ovs-vswitchd":
{"logs": "var/log/openvswitch/ovs-vswitchd.log"},
"ovsdb-server":
{"logs": "var/log/openvswitch/ovsdb-server.log"}}
|
#!/usr/bin/env python3
inputs = {}
reduced = {}
with open("input.txt") as f:
for line in f:
inp, to = map(lambda x: x.strip(), line.split("->"))
inputs[to] = inp.split(" ")
inputs["b"] = "956"
def reduce(name):
try:
return int(name)
except:
pass
try:
return int(inputs[name])
except:
pass
if name not in reduced:
exp = inputs[name]
if len(exp) == 1:
res = reduce(exp[0])
else:
op = exp[-2]
if op == "NOT":
res = ~reduce(exp[1]) & 0xffff
elif op == "AND":
res = reduce(exp[0]) & reduce(exp[2])
elif op == "OR":
res = reduce(exp[0]) | reduce(exp[2])
elif op == "LSHIFT":
res = reduce(exp[0]) << reduce(exp[2])
elif op == "RSHIFT":
res = reduce(exp[0]) >> reduce(exp[2])
reduced[name] = res
return reduced[name]
print(reduce("a"))
|
LCGDIR = '../lib/sunos5'
LIBDIR = '${LCGDIR}'
BF_PYTHON = '/usr/local'
BF_PYTHON_VERSION = '3.2'
BF_PYTHON_INC = '${BF_PYTHON}/include/python${BF_PYTHON_VERSION}'
BF_PYTHON_BINARY = '${BF_PYTHON}/bin/python${BF_PYTHON_VERSION}'
BF_PYTHON_LIB = 'python${BF_PYTHON_VERSION}' #BF_PYTHON+'/lib/python'+BF_PYTHON_VERSION+'/config/libpython'+BF_PYTHON_VERSION+'.a'
BF_PYTHON_LINKFLAGS = ['-Xlinker', '-export-dynamic']
WITH_BF_OPENAL = True
WITH_BF_STATICOPENAL = False
BF_OPENAL = '/usr/local'
BF_OPENAL_INC = '${BF_OPENAL}/include'
BF_OPENAL_LIBPATH = '${BF_OPENAL}/lib'
BF_OPENAL_LIB = 'openal'
# Warning, this static lib configuration is untested! users of this OS please confirm.
BF_OPENAL_LIB_STATIC = '${BF_OPENAL}/lib/libopenal.a'
# Warning, this static lib configuration is untested! users of this OS please confirm.
BF_CXX = '/usr'
WITH_BF_STATICCXX = False
BF_CXX_LIB_STATIC = '${BF_CXX}/lib/libstdc++.a'
WITH_BF_SDL = True
BF_SDL = '/usr/local' #$(shell sdl-config --prefix)
BF_SDL_INC = '${BF_SDL}/include/SDL' #$(shell $(BF_SDL)/bin/sdl-config --cflags)
BF_SDL_LIBPATH = '${BF_SDL}/lib'
BF_SDL_LIB = 'SDL' #BF_SDL #$(shell $(BF_SDL)/bin/sdl-config --libs) -lSDL_mixer
WITH_BF_OPENEXR = True
WITH_BF_STATICOPENEXR = False
BF_OPENEXR = '/usr/local'
BF_OPENEXR_INC = ['${BF_OPENEXR}/include', '${BF_OPENEXR}/include/OpenEXR' ]
BF_OPENEXR_LIBPATH = '${BF_OPENEXR}/lib'
BF_OPENEXR_LIB = 'Half IlmImf Iex Imath '
# Warning, this static lib configuration is untested! users of this OS please confirm.
BF_OPENEXR_LIB_STATIC = '${BF_OPENEXR}/lib/libHalf.a ${BF_OPENEXR}/lib/libIlmImf.a ${BF_OPENEXR}/lib/libIex.a ${BF_OPENEXR}/lib/libImath.a ${BF_OPENEXR}/lib/libIlmThread.a'
WITH_BF_DDS = True
WITH_BF_JPEG = True
BF_JPEG = '/usr/local'
BF_JPEG_INC = '${BF_JPEG}/include'
BF_JPEG_LIBPATH = '${BF_JPEG}/lib'
BF_JPEG_LIB = 'jpeg'
WITH_BF_PNG = True
BF_PNG = '/usr/local'
BF_PNG_INC = '${BF_PNG}/include'
BF_PNG_LIBPATH = '${BF_PNG}/lib'
BF_PNG_LIB = 'png'
BF_TIFF = '/usr/local'
BF_TIFF_INC = '${BF_TIFF}/include'
WITH_BF_ZLIB = True
BF_ZLIB = '/usr'
BF_ZLIB_INC = '${BF_ZLIB}/include'
BF_ZLIB_LIBPATH = '${BF_ZLIB}/lib'
BF_ZLIB_LIB = 'z'
WITH_BF_INTERNATIONAL = True
BF_GETTEXT = '/usr/local'
BF_GETTEXT_INC = '${BF_GETTEXT}/include'
BF_GETTEXT_LIB = 'gettextlib'
BF_GETTEXT_LIBPATH = '${BF_GETTEXT}/lib'
WITH_BF_GAMEENGINE=False
WITH_BF_PLAYER = False
WITH_BF_BULLET = True
BF_BULLET = '#extern/bullet2/src'
BF_BULLET_INC = '${BF_BULLET}'
BF_BULLET_LIB = 'extern_bullet'
#WITH_BF_NSPR = True
#BF_NSPR = $(LIBDIR)/nspr
#BF_NSPR_INC = -I$(BF_NSPR)/include -I$(BF_NSPR)/include/nspr
#BF_NSPR_LIB =
# Uncomment the following line to use Mozilla inplace of netscape
#CPPFLAGS += -DMOZ_NOT_NET
# Location of MOZILLA/Netscape header files...
#BF_MOZILLA = $(LIBDIR)/mozilla
#BF_MOZILLA_INC = -I$(BF_MOZILLA)/include/mozilla/nspr -I$(BF_MOZILLA)/include/mozilla -I$(BF_MOZILLA)/include/mozilla/xpcom -I$(BF_MOZILLA)/include/mozilla/idl
#BF_MOZILLA_LIB =
# Will fall back to look in BF_MOZILLA_INC/nspr and BF_MOZILLA_LIB
# if this is not set.
#
# Be paranoid regarding library creation (do not update archives)
#BF_PARANOID = True
# enable freetype2 support for text objects
BF_FREETYPE = '/usr/local'
BF_FREETYPE_INC = '${BF_FREETYPE}/include ${BF_FREETYPE}/include/freetype2'
BF_FREETYPE_LIBPATH = '${BF_FREETYPE}/lib'
BF_FREETYPE_LIB = 'freetype'
WITH_BF_QUICKTIME = False # -DWITH_QUICKTIME
BF_QUICKTIME = '/usr/local'
BF_QUICKTIME_INC = '${BF_QUICKTIME}/include'
WITH_BF_ICONV = True
BF_ICONV = "/usr"
BF_ICONV_INC = '${BF_ICONV}/include'
BF_ICONV_LIB = 'iconv'
BF_ICONV_LIBPATH = '${BF_ICONV}/lib'
# enable ffmpeg support
WITH_BF_FFMPEG = True # -DWITH_FFMPEG
BF_FFMPEG = '/usr/local'
BF_FFMPEG_INC = '${BF_FFMPEG}/include'
BF_FFMPEG_LIBPATH='${BF_FFMPEG}/lib'
BF_FFMPEG_LIB = 'avformat avcodec avutil avdevice'
# Mesa Libs should go here if your using them as well....
WITH_BF_STATICOPENGL = False
BF_OPENGL = '/usr/openwin'
BF_OPENGL_INC = '${BF_OPENGL}/include'
BF_OPENGL_LIB = 'GL GLU X11 Xi'
BF_OPENGL_LIBPATH = '${BF_OPENGL}/lib'
BF_OPENGL_LIB_STATIC = '${BF_OPENGL_LIBPATH}/libGL.a ${BF_OPENGL_LIBPATH}/libGLU.a ${BF_OPENGL_LIBPATH}/libXxf86vm.a ${BF_OPENGL_LIBPATH}/libX11.a ${BF_OPENGL_LIBPATH}/libXi.a ${BF_OPENGL_LIBPATH}/libXext.a ${BF_OPENGL_LIBPATH}/libXxf86vm.a'
##
CC = 'gcc'
CXX = 'g++'
##ifeq ($CPU),alpha)
## CFLAGS += -pipe -fPIC -funsigned-char -fno-strict-aliasing -mieee
CCFLAGS = ['-pipe','-fPIC','-funsigned-char','-fno-strict-aliasing']
CPPFLAGS = ['-DSUN_OGL_NO_VERTEX_MACROS']
CXXFLAGS = ['-pipe','-fPIC','-funsigned-char','-fno-strict-aliasing']
REL_CFLAGS = ['-DNDEBUG', '-O2']
REL_CCFLAGS = ['-DNDEBUG', '-O2']
##BF_DEPEND = True
##
##AR = ar
##ARFLAGS = ruv
##ARFLAGSQUIET = ru
##
C_WARN = ['-Wno-char-subscripts', '-Wdeclaration-after-statement']
CC_WARN = ['-Wall']
##FIX_STUBS_WARNINGS = -Wno-unused
LLIBS = ['c', 'm', 'dl', 'pthread', 'stdc++']
##LOPTS = --dynamic
##DYNLDFLAGS = -shared $(LDFLAGS)
BF_PROFILE_CCFLAGS = ['-pg', '-g ']
BF_PROFILE_LINKFLAGS = ['-pg']
BF_PROFILE = False
BF_DEBUG = False
BF_DEBUG_CCFLAGS = ['-D_DEBUG']
BF_BUILDDIR = '../build/sunos5'
BF_INSTALLDIR='../install/sunos5'
PLATFORM_LINKFLAGS = []
|
""" Connected client statistics """
class Statistics(object):
""" A connected client statistics """
def __init__(self, downspeed, online, upspeed):
self._downspeed = downspeed
self._online = online
self._upspeed = upspeed
def get_downspeed(self):
return self._downspeed
def get_online(self):
return self._online
def get_upspeed(self):
return self._upspeed
def create_statistic_from_json(json_entry):
# json_entry = json.loads(json_entry_as_string)
return Statistics(json_entry['downspeed'], json_entry['online'],
json_entry['upspeed'])
|
t=input()
while(t>0):
s=raw_input()
str=s.split(' ')
b=int(str[0])
c=int(str[1])
d=int(str[2])
print (c-b)+(c-d)
t=t-1
|
def generate_shared_public_key(my_private_key, their_public_pair, generator):
"""
Two parties each generate a private key and share their public key with the
other party over an insecure channel. The shared public key can be generated by
either side, but not by eavesdroppers. You can then use the entropy from the
shared public key to created a common symmetric key for encryption. (This
is beyond of the scope of pycoin.)
See also <https://en.wikipedia.org/wiki/Key_exchange>
:param my_private_key: an integer private key
:param their_public_pair: a pair ``(x, y)`` representing a public key for the ``generator``
:param generator: a :class:`Generator <pycoin.ecdsa.Generator.Generator>`
:returns: a :class:`Point <pycoin.ecdsa.Point.Point>`, which can be used as a shared
public key.
"""
p = generator.Point(*their_public_pair)
return my_private_key * p
|
__version__ = "0.1"
__requires__ = [
"apptools>=4.2.0",
"numpy>=1.6",
"traits>=4.4",
"enable>4.2",
"chaco>=4.4",
"fiona>=1.0.2",
"scimath>=4.1.2",
"shapely>=1.2.17",
"tables>=2.4.0",
"sdi",
]
|
# A plugin is supposed to define a setup function
# which returns the type that the plugin provides
#
# This plugin fails to do so
def useless():
print("Hello World")
|
""" This module is deprecated and has been moved to `//toolchains/built_tools/...` """
load("//foreign_cc/built_tools:ninja_build.bzl", _ninja_tool = "ninja_tool")
load(":deprecation.bzl", "print_deprecation")
print_deprecation()
ninja_tool = _ninja_tool
|
class Number:
def numSum(num):
count = []
for x in range(1, (num+1)):
count.append(x)
print(sum(count))
if __name__ == "__main__":
num = int(input("Enter A Number: "))
numSum(num)
|
num = int(input('Digite um numero inteiro: '))
print('''Escolha um das bases de conversão:
[ 1 ] converter para BINÁRIO
[ 2 ] converter para OCTAL
[ 3 ] converter para HEXADECIMAL ''')
opção = int(input('Sua opção: '))
if opção == 1:
print('{} convertido para BINÁRIO é igual a {}' .format(num, bin(num) [2:]))
elif opção == 2:
print('{} convertido para OCTAL é igual a {}' .format(num, oct(num) [2:]))
elif opção == 3:
print('{} convertido para HEXADECIMAL é igual a {}' .format(num, hex(num)[2:]))
else:
print('Opção inválida, tente novamente.') |
logging.info(" *** Step 3: Build features *** ".format())
# %% ===========================================================================
# Feature - Pure Breed Boolean column
# =============================================================================
def pure_breed(row):
# print(row)
mixed_breed_keywords = ['domestic', 'tabby', 'mixed']
# Mixed if labelled as such
if row['Breed1'] == 'Mixed Breed':
return False
# Possible pure if no second breed
elif row['Breed2'] == 'NA':
# Reject domestic keywords
if any([word in row['Breed1'].lower() for word in mixed_breed_keywords]):
return False
else:
return True
else:
return False
#%% Build the pipeline
this_pipeline = sk.pipeline.Pipeline([
('feat: Pure Breed', trf.MultipleToNewFeature(['Breed1','Breed2'], 'Pure Breed', pure_breed)),
])
logging.info("Created pipeline:")
for i, step in enumerate(this_pipeline.steps):
print(i, step[0], step[1].__str__())
#%% Fit Transform
original_cols = df_all.columns
df_all = this_pipeline.fit_transform(df_all)
logging.info("Pipeline complete. {} new columns.".format(len(df_all.columns) - len(original_cols)))
|
aws_access_key_id=None
aws_secret_access_key=None
img_bucket_name=None
|
# -*- coding: utf-8 -*-
"""Deep Go Patterns
======
Design Patterns
"""
|
"""
Python 字典测试
"""
dict = {'name':'goujinping','age':'21','sex':'man','school':'NEFU'}
print(dict)
print(dict['age']) #通过键访问相应的值
print(dict['name'])
for key in dict.keys(): #访问字典的键 dict2.keys(),返回一个列表
print(key)
for value in dict.values(): #访问字典的值 dict2.values(), 返回一个列表
print(value)
del dict['sex'] #删除字典元素和字典
print(dict)
del dict
print(dict) |
# -*- coding: utf-8 -*-
# Copyright © 2014 Cask Data, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in 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 Credential(object):
"""
Represents a credential required for authentication.
"""
def __init__(self, name, description, secret):
self.__name = name
self.__description = description
self.__secret = secret
def get_name(self):
return self.__name
def get_description(self):
return self.__description
def is_secret(self):
return self.__secret
|
def get_tickets(path):
with open(path, 'r') as fh:
yield fh.read().splitlines()
def get_new_range(_min, _max, value):
# print(_min, _max, value)
if value == 'F' or value == 'L':
mid = _min + (_max - _min) // 2
return (_min, mid)
if value == 'B' or value == 'R':
mid = _min + (_max - _min) // 2 + 1
return (mid, _max)
print("something is wrong")
def get_id(ticket):
# print(ticket)
range_min = 0
range_max = 127
tpl = (0, 127)
for item in ticket[0:7]:
tpl = get_new_range(range_min, range_max, item)
range_min, range_max = tpl
row = tpl[0]
range_min = 0
range_max = 7
tpl = (0, 7)
for item in ticket[-3:]:
tpl = get_new_range(range_min, range_max, item)
range_min, range_max = tpl
column = tpl[0]
return row * 8 + column
_file = 'resources/day5_input.txt'
_id = 0
ids = []
for tickets in get_tickets(_file):
for ticket in tickets:
ticket_id = get_id(ticket)
ids.append(ticket_id)
if ticket_id > _id:
_id = ticket_id
print("Day 5 - part I:", _id)
# print(ids)
for i in range(_id):
if i not in ids and i-1 in ids and i+1 in ids:
print("Day 5 - part II:", i) |
"""
About this package
"""
__version__ = '0.1.0'
__description__ = 'Python3 client code for ec_golanggrpc'
__author__ = 'Paul Hewlett'
__author_email__ = 'phewlett76@gmail.com'
__license__ = 'MIT'
|
class CrawlerCodeDTO(object):
"""
Object that contains grouped all data of the code
"""
def __init__(self, id, libs, comments, variable_names, function_names, class_name, lines_number, code):
self.id = id
self.libs = libs if len(libs) > 0 else []
self.comments = comments if len(comments) > 0 else []
self.variable_names = variable_names if len(variable_names) > 0 else []
self.function_names = function_names if len(function_names) > 0 else []
self.class_name = class_name if len(class_name) > 0 else []
self.lines_number = lines_number if lines_number else 1
self.score = 0.0
self.code = code
|
def cls_with_meta(mc, attrs):
class _x_(object):
__metaclass__ = mc
for k, v in attrs.items():
setattr(_x_, k, v)
return _x_
|
num = int(input('Digite um valor para saber seu fatorial: '))
d = num
for c in range(num-1,1,-1):
num += (num * c) - num
print('Calculando {}! = {}.'.format(d, num)) |
class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
head = ListNode(0, head)
p1, prev, p2 = head, head, head.next
while p2:
if p2.val < x:
if p1 == prev:
prev, p2 = p2, p2.next
else:
p1.next, p2.next, p2, prev.next = p2, p1.next, p2.next, p2.next
p1 = p1.next
else:
prev, p2 = p2, p2.next
return head.next
|
# Să se unifice două dicționare în care cheile sunt șiruri de caractere, iar valorile sunt de tip numeric.
# Astfel, în rezultat va apărea fiecare cheie distinctă, iar pentru o cheie care apare în ambele dicționare inițiale
# valoarea corespunzătoare va fi egală cu suma valorilor asociate cheii respective în cele două dicționare.
def dict_merge(d1, d2):
if type(d1) is not dict or type(d2) is not dict:
print("Error, parameters are not dictionaries.")
quit()
for k, v in d2.items():
d1[k] = d1.get(k, 0) + v
return d1
d1 = {"ana": 3, "are": 2, "mere": 5}
d2 = {"ion": 2, "are": 1, "pere": 2, "si": 2, "mere": 2}
d3 = dict_merge(d1, d2)
print(d3)
|
#
# PySNMP MIB module BLUECOAT-HOST-RESOURCES-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BLUECOAT-HOST-RESOURCES-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:39:39 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, ConstraintsIntersection, ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsIntersection", "ConstraintsUnion", "ValueSizeConstraint", "SingleValueConstraint")
blueCoatMgmt, = mibBuilder.importSymbols("BLUECOAT-MIB", "blueCoatMgmt")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
iso, Bits, Counter64, TimeTicks, IpAddress, Unsigned32, MibIdentifier, Counter32, ObjectIdentity, ModuleIdentity, Integer32, NotificationType, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "Bits", "Counter64", "TimeTicks", "IpAddress", "Unsigned32", "MibIdentifier", "Counter32", "ObjectIdentity", "ModuleIdentity", "Integer32", "NotificationType", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
blueCoatHostResourcesMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 3417, 2, 9))
blueCoatHostResourcesMIB.setRevisions(('2007-04-24 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: blueCoatHostResourcesMIB.setRevisionsDescriptions(('Marked as deprecated.',))
if mibBuilder.loadTexts: blueCoatHostResourcesMIB.setLastUpdated('200704240000Z')
if mibBuilder.loadTexts: blueCoatHostResourcesMIB.setOrganization('Blue Coat')
if mibBuilder.loadTexts: blueCoatHostResourcesMIB.setContactInfo('support@bluecoat.com')
if mibBuilder.loadTexts: blueCoatHostResourcesMIB.setDescription('Internal MIB defines Blue Coat device serial number for Blue Coat Director use.')
bchrDevice = MibIdentifier((1, 3, 6, 1, 4, 1, 3417, 2, 9, 1))
bchrSerial = MibScalar((1, 3, 6, 1, 4, 1, 3417, 2, 9, 1, 1), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 20))).setMaxAccess("readonly")
if mibBuilder.loadTexts: bchrSerial.setStatus('deprecated')
if mibBuilder.loadTexts: bchrSerial.setDescription('Serial number of the Blue Coat device.')
mibBuilder.exportSymbols("BLUECOAT-HOST-RESOURCES-MIB", bchrDevice=bchrDevice, blueCoatHostResourcesMIB=blueCoatHostResourcesMIB, bchrSerial=bchrSerial, PYSNMP_MODULE_ID=blueCoatHostResourcesMIB)
|
animales = ['Perro','Gato','Hamster','Conejo','Raton']
for animal in animales:
print(animal)
print('Un '+animal.title()+' sería una maravillosa mascota')
print('Cualquiera de estos animales sería una mascota fantastica')
print('//////////////////////////')
print("Los primeros tres elementos de la lista son:")
for animal in animales[:3]:
print(animal.title())
print('//////////////////////////')
print("Los tres elementos del centro de la lista son:")
for animal in animales[1:4]:
print(animal.title())
print('//////////////////////////')
print("Los tres ultimos elementos de la lista son:")
for animal in animales[2:]:
print(animal.title()) |
t = {}
t["0"] = ["-113", "Marginal"]
t["1"] = ["-111", "Marginal"]
t["2"] = ["-109", "Marginal"]
t["3"] = ["-107", "Marginal"]
t["4"] = ["-105", "Marginal"]
t["5"] = ["-103", "Marginal"]
t["6"] = ["-101", "Marginal"]
t["7"] = ["-99", "Marginal"]
t["8"] = ["-97", "Marginal"]
t["9"] = ["-95", "Marginal"]
t["10"] = ["-93", "OK"]
t["11"] = ["-91", "OK"]
t["12"] = ["-89", "OK"]
t["13"] = ["-87", "OK"]
t["14"] = ["-85", "OK"]
t["15"] = ["-83", "Good"]
t["16"] = ["-81", "Good"]
t["17"] = ["-79", "Good"]
t["18"] = ["-77", "Good"]
t["19"] = ["-75", "Good"]
t["20"] = ["-73", "Excellent"]
t["21"] = ["-71", "Excellent"]
t["22"] = ["-69", "Excellent"]
t["23"] = ["-67", "Excellent"]
t["24"] = ["-65", "Excellent"]
t["25"] = ["-63", "Excellent"]
t["26"] = ["-61", "Excellent"]
t["27"] = ["-59", "Excellent"]
t["28"] = ["-57", "Excellent"]
t["29"] = ["-55", "Excellent"]
t["30"] = ["-53", "Excellent"]
t["99"] = ["-53", "Excellent"]
|
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or 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.
# ===========================================================================
"""Precision calculation function of Ubuntu data"""
def get_p_at_n_in_m(data, n, m, ind):
"""Former n recall rate"""
pos_score = data[ind][0]
curr = data[ind:ind + m]
curr = sorted(curr, key=lambda x: x[0], reverse=True)
if curr[n - 1][0] <= pos_score:
return 1
return 0
def evaluate(file_path):
"""
Evaluation is done through a score file.
:param file_path: Score file path.
:return: A tuple of accuracy
"""
data = []
with open(file_path, 'r') as file:
for line in file:
line = line.strip()
tokens = line.split("\t")
if len(tokens) != 2:
continue
data.append((float(tokens[0]), int(tokens[1])))
# assert len(data) % 10 == 0
p_at_1_in_2 = 0.0
p_at_1_in_10 = 0.0
p_at_2_in_10 = 0.0
p_at_5_in_10 = 0.0
length = int(len(data) / 10)
for i in range(0, length):
ind = i * 10
assert data[ind][1] == 1
p_at_1_in_2 += get_p_at_n_in_m(data, 1, 2, ind)
p_at_1_in_10 += get_p_at_n_in_m(data, 1, 10, ind)
p_at_2_in_10 += get_p_at_n_in_m(data, 2, 10, ind)
p_at_5_in_10 += get_p_at_n_in_m(data, 5, 10, ind)
return (p_at_1_in_2 / length, p_at_1_in_10 / length, p_at_2_in_10 / length, p_at_5_in_10 / length)
def evaluate_m(logits, labels):
"""
Evaluate through network output.
:param logits: Network score.
:param labels: Actual label
:return: A tuple of accuracy
"""
data = []
for i in range(len(logits)):
data.append((float(logits[i]), int(labels[i])))
# assert len(data) % 10 == 0
p_at_1_in_2 = 0.0
p_at_1_in_10 = 0.0
p_at_2_in_10 = 0.0
p_at_5_in_10 = 0.0
length = int(len(data) / 10)
for i in range(0, length):
ind = i * 10
assert data[ind][1] == 1
p_at_1_in_2 += get_p_at_n_in_m(data, 1, 2, ind)
p_at_1_in_10 += get_p_at_n_in_m(data, 1, 10, ind)
p_at_2_in_10 += get_p_at_n_in_m(data, 2, 10, ind)
p_at_5_in_10 += get_p_at_n_in_m(data, 5, 10, ind)
return (p_at_1_in_2 / length, p_at_1_in_10 / length, p_at_2_in_10 / length, p_at_5_in_10 / length)
|
class Solution:
def longestWPI(self, hours: List[int]) -> int:
acc = 0
seen = {0 : -1}
mx_len = 0
for i, h in enumerate(hours):
if h > 8:
acc += 1
else:
acc -= 1
if acc > 0:
mx_len = i + 1
if acc not in seen:
seen[acc] = i
if (acc - 1) in seen:
mx_len = max(mx_len, i - seen[acc - 1])
return mx_len
|
#log in process
def login():
Username = input("Enter Username : ")
if Username == 'betterllama' or NewUsername:
Password = input("Enter Password : ")
else:
print("Username Incorrect")
if Password == 'omoshi' or NewPassword:
print("Welcome, " + Username)
else:
print("Password is incorrect")
#sign up + log in process
def signup(NewUsername = 'default', NewPassword = 'default'):
NewUsername = input("Choose a Username : ")
NewPassword = input("Choose a Password : ")
print("Would you like to log in now?")
x = input("Type 'yes' or 'no' : ")
if x == 'yes':
Username = input("Enter Username : ")
if Username == 'betterllama' or NewUsername:
Password = input("Enter Password : ")
else:
print("Username Incorrect")
if Password == 'omoshi' or NewPassword:
print("Welcome, " + Username)
else:
print("Password is incorrect")
else:
print("done")
#start sequence
def start():
print("Would you like to Login or Sign Up? ")
x = input("Type 'login' or 'signup' : ")
if x == 'login':
login()
else:
signup()
start()
|
# You are given a set of n rectangles in no particular order. They have varying
# widths and heights, but their bottom edges are collinear, so that they look
# like buildings on a skyline. For each rectangle, you’re given the x position of
# the left edge, the x position of the right edge, and the height. Your task is
# to draw an outline around the set of rectangles so that you can see what the
# skyline would look like when silhouetted at night.
#
# https://briangordon.github.io/2014/08/the-skyline-problem.html
# http://www.geeksforgeeks.org/divide-and-conquer-set-7-the-skyline-problem/
# https://leetcode.com/problems/the-skyline-problem/
class Building(object):
"""
To represent the rectangular building.
"""
def __init__(self,left,hi,right):
self.left = left
self.hi = hi
self.right = right
class Strip(object):
"""
Represent the strip in skyline silhouetted.
"""
def __init__(self,left,hi):
self.left = left
self.hi = hi
def __str__(self):
return ("({0},{1})".format(self.left,self.hi))
class Skyline(object):
"""
Creates the Skyline from Buildings.
"""
def __init__(self):
self.silhouette = []
self.strip_count = 0
def add_to_silhourette(self,strip):
# Strip is redundant if it has same height or left as previous
if self.strip_count > 0 and self.silhouette[-1].hi == strip.hi:
return
if self.strip_count > 0 and self.silhouette[-1].left == strip.left:
self.silhouette[-1].ht = max(self.silhouette[-1].ht, strip.ht)
self.silhouette.append(strip)
self.strip_count += 1
def find_silhoutte(self,building_arr, low, high):
if (low == high):
sk = Skyline()
sk.add_to_silhourette(Strip(building_arr[low][0],building_arr[low][1]))
sk.add_to_silhourette(Strip(building_arr[low][2],0))
return sk
mid = low + (high - low) // 2
sk_left = self.find_silhoutte(building_arr,low,mid)
sk_right = self.find_silhoutte(building_arr,mid+1,high)
return self.merge(sk_left,sk_right)
def displlay_silhoutte(self):
for sh in self.silhouette:
print(sh,end = ",")
print()
def merge(self,sk_left, sk_right):
"""
Merge the two skyline
"""
h1 , h2 = 0,0
result = Skyline()
i = 0
j = 0
while i < sk_left.strip_count or j < sk_right.strip_count:
if i >= sk_left.strip_count:
result.add_to_silhourette(sk_right.silhouette[j])
j += 1
elif j >= sk_right.strip_count:
result.add_to_silhourette(sk_left.silhouette[i])
i += 1
# check for the x-coordinate
elif sk_left.silhouette[i].left < sk_right.silhouette[j].left:
h1 = sk_left.silhouette[i].hi
mx_hi = max(h1,h2)
result.add_to_silhourette(Strip(sk_left.silhouette[i].left,mx_hi))
i += 1
else:
h2 = sk_right.silhouette[j].hi
mx_hi = max(h1,h2)
result.add_to_silhourette(Strip(sk_right.silhouette[j].left,mx_hi))
j += 1
return result
if __name__ == "__main__":
sk = Skyline()
#building_array = [(1,11,5), (2,6,7), (3,13,9), (12,7,16), (14,3,25),
# (19,18,22), (23,13,29), (24,4,28) ]
building_array = [(1,5,2),(2,5,6),(6,5,10),(10,5,15),(15,5,20)]
sky_line = sk.find_silhoutte(building_array,0, len(building_array) - 1)
sky_line.displlay_silhoutte()
|
# -*- coding: utf8 -*-
def js_test():
pass |
#!/usr/bin/env python
# -----------------------------------------------------------------------------
# This example will open a file and read it line by line, process each line,
# and write the processed line to standard out.
# -----------------------------------------------------------------------------
# Open a file for writing. Use 'a' instead of 'w' to append to the file.
outfile = open('jenny.txt', 'w')
# Create some data to write to a file. Need some numbers, text and a list
num = 867
num2 = 5309
txt = 'Jenny'
txt2 = 'Tommy Tutone'
list = ['Everclear', 'Foo Fighters', 'Green Day', 'Goo Goo Dolls']
# The 2.x version of Python formats strings using the method below. The 3.x
# version of python uses .format(). The method below will be phased out of
# python eventually but I use it here because it is compatible with Python
# 2.x, which is the default version of python in Ubuntu and BT5.
#
# UPDATE: The .format() string formatting method is supported in Python 2.6
# and higher.
outfile.write('%d-%d/%s was sung by %s\n' % (num, num2, txt, txt2))
outfile.write('and was covered by:\n')
for l in list:
outfile.write('%s\n' % (l))
# Close the file because we are done with it.
outfile.close()
|
"""
107. Word Break
https://www.lintcode.com/problem/word-break/description?_from=ladder&&fromId=160
DFS on dictionary
"""
class Solution:
"""
@param: s: A string
@param: dict: A dictionary of words dict
@return: A boolean
"""
def wordBreak(self, s, dict):
return self.dfs(s, dict, 0)
def dfs(self, s, word_lists, index):
if index == len(s):
return True
if index > len(s):
return False
for word in word_lists:
if s[index:].startswith(word):
if self.dfs(s, word_lists, index + len(word)):
return True
return False |
# A binary search template
"""
left, right = 0, len(array) - 1
while left <= right:
mid = left + (right - left) // 2
if array[mid] == target:
break or return result
elif array[mid] < target:
left = mid + 1
else:
right = mid - 1
""" |
class Solution:
def reverse(self, x: int) -> int:
if x == 0:
return 0
if x < -(2 ** 31) or x > (2 ** 31) - 1:
return 0
newNumber = 0
tempNumber = abs(x)
while tempNumber > 0:
newNumber = (newNumber * 10) + tempNumber % 10
tempNumber = tempNumber // 10
if newNumber < -(2 ** 31) or newNumber > (2 ** 31) - 1:
return 0
if x < 0:
return -1 * newNumber
else:
return newNumber
|
good = 0
good_2 = 0
with open("day2.txt") as f:
for line in f.readlines():
parts = line.strip().split()
print(parts)
cmin, cmax = [int(i) for i in parts[0].split('-')]
letter = parts[1][0]
pwd = parts[2]
print(cmin, cmax, letter, pwd)
count = pwd.count(letter)
if count >= cmin and count <= cmax:
good += 1
if (pwd[cmin - 1] == letter or pwd[cmax - 1] == letter) and not (pwd[cmin - 1] == letter and pwd[cmax - 1] == letter):
good_2 += 1
print(good, good_2)
|
description = 'PUMA multianalyzer device'
group = 'lowlevel'
includes = ['aliases']
level = False
devices = dict(
man = device('nicos_mlz.puma.devices.PumaMultiAnalyzer',
description = 'PUMA multi analyzer',
translations = ['ta1', 'ta2', 'ta3', 'ta4', 'ta5', 'ta6', 'ta7', 'ta8',
'ta9', 'ta10', 'ta11'],
rotations = ['ra1', 'ra2', 'ra3', 'ra4', 'ra5', 'ra6', 'ra7', 'ra8',
'ra9', 'ra10', 'ra11'],
),
muslit_t = device('nicos.devices.generic.Axis',
description = 'translation multianalyzer slit',
motor = device('nicos.devices.generic.virtual.VirtualMotor',
abslimits = (471, 565),
unit = 'mm',
),
precision = 1,
fmtstr = '%.2f',
),
)
for i in range(1, 12):
devices['ta%d' % i] = device('nicos.devices.generic.Axis',
description = 'Translation crystal %d multianalyzer' % i,
motor = device('nicos_mlz.puma.devices.virtual.VirtualReferenceMotor',
abslimits = (-125.1, 125.1),
userlimits = (-125, 125),
unit = 'mm',
refpos = 0.,
fmtstr = '%.3f',
speed = 5.0,
),
precision = 0.01,
lowlevel = level,
)
devices['ra%d' % i] = device('nicos.devices.generic.Axis',
description = 'Rotation crystal %d multianalyzer' % i,
motor = device('nicos_mlz.puma.devices.virtual.VirtualReferenceMotor',
abslimits = (-60.1, 0.5),
userlimits = (-60.05, 0.5),
unit = 'deg',
refpos = 0.1,
fmtstr = '%.3f',
speed = 1.0,
),
precision = 0.01,
lowlevel = level,
)
alias_config = {
'theta': {'ra6': 200},
}
|
# https://leetcode-cn.com/problems/bomb-enemy/
# 想象一下炸弹人游戏,在你面前有一个二维的网格来表示地图,网格中的格子分别被以下三种符号占据:
#
# 'W' 表示一堵墙
# 'E' 表示一个敌人
# '0'(数字 0)表示一个空位
#
# 请你计算一个炸弹最多能炸多少敌人。
#
# 由于炸弹的威力不足以穿透墙体,炸弹只能炸到同一行和同一列没被墙体挡住的敌人。
#
# 注意:
# 你只能把炸弹放在一个空的格子里
#
# 示例:
# 输入: [["0","E","0","0"],["E","0","W","E"],["0","E","0","0"]]
# 输出: 3
# 解释: 对于如下网格
#
# 0 E 0 0
# E 0 W E
# 0 E 0 0
#
# 假如在位置 (1,1) 放置炸弹的话,可以炸到 3 个敌人
#
# Related Topics 动态规划
def bomb_enemy(cells):
row_len, col_len = len(cells), len(cells[0])
result = 0
col_hits = [0] * col_len
row_hits = 0
for index_row, row in enumerate(cells):
for index_cell, cell in enumerate(row):
if index_cell == 0 or row[index_cell - 1] == "W":
row_hits = 0
k = index_cell
while k < col_len:
if row[k] == "W":
break
row_hits += row[k] == "E"
k += 1
if index_row == 0 or cells[index_row - 1][index_cell] == "W":
col_hits[index_cell] = 0
k = index_row
while k < row_len:
if cells[k][index_cell] == "W":
break
col_hits[index_cell] += cells[k][index_cell] == "E"
k += 1
if cell == "0":
result = max(result, row_hits + col_hits[index_cell])
return result
assert (
bomb_enemy([["0", "E", "0", "0"], ["E", "0", "W", "E"], ["0", "E", "0", "0"]]) == 3
)
assert (
bomb_enemy([["0", "W", "E", "W"], ["W", "W", "0", "W"], ["0", "W", "E", "W"]]) == 2
)
|
class Solution:
def longestPalindrome(self, s: str) -> str:
if not s:
return None
result = ''
maxPal = 0
record = [[0] * len(s) for i in range(len(s))]
for j in range(len(s)):
for i in range(j+1):
record[i][j] = ((s[i] == s[j]) and (j-i<=2 or record[i+1][j-1]))
if record[i][j] and j-i+1 > maxPal:
maxPal = j-i+1
result = s[i:j+1]
return result |
"""
entrada
nombre-->str-->n
horas_trabajadas-->int-->ht
precio_hora_normal-->int-->phn
horas _extras-->int-->hx
#hijos-->int-->hi
salidas
asignaciones-->str-->asi
deducciones-->str-->dd
sueldo_neto-->str-->sn
"""
n=str(input("escriba el nombre del trabador "))
ht=int(input("digite la cantidad de horas trabajadas "))
phn=int(input("digite el precio de la hora normal de trabajo "))
hx = int(input("digite la cantidad de horas extra trabajadas "))
hi=int(input("digite cuantos hijos tiene "))
if (hi==0):
ch=0
else:
ch=173000
ac=250000
ph=180000
asi=ac+ph+(ch*hi)
vhx = ht*0.25
hxt = vhx+ht
sb = (ht*phn)+hxt+asi
td = ((sb*0.05)+(sb*0.02)+(sb*0.07))
sn = sb-td
print(str(n), "tiene un total de " + str(asi), " en asignaciones")
print(str(n), "tiene un total de " + str(td), " en deducciones")
print(str(n), "tiene un sueldo neto de " + str(sn))
|
__author__ = 'Liu'
def quadrado_menores(n):
return [i ** 2 for i in range(1, n + 1) if i ** 2 <= n]
assert [1] == quadrado_menores(1)
assert [1, 4] == quadrado_menores(4)
assert [1, 4, 9] == quadrado_menores(9)
assert [1, 4, 9] == quadrado_menores(11)
def soma_quadrados(n):
if n > 0:
menores = quadrado_menores(n)
ultimo = menores[-1]
if ultimo == n:
return [n]
else:
lista_escolhida = gerar_solucao(menores, n)
while menores:
lista_escolhida_2 = gerar_solucao(menores, n)
if len(lista_escolhida_2) < len(lista_escolhida):
lista_escolhida = lista_escolhida_2
return lista_escolhida
return[0]
def gerar_solucao(menores, n):
ultimo = menores.pop()
lista_escolhida = [ultimo]
lista_escolhida.extend(soma_quadrados(n - ultimo))
return lista_escolhida
assert [0] == soma_quadrados(0)
assert [1] == soma_quadrados(1)
assert [4] == soma_quadrados(4)
assert [9] == soma_quadrados(9)
assert [1,1] == soma_quadrados(2)
assert [1,1,1] == soma_quadrados(3)
assert [4,1] == soma_quadrados(5)
assert [4,4,4] == soma_quadrados(12)
assert [9, 4] == soma_quadrados(13)
assert [9, 4, 1] == soma_quadrados(14)
numero = int (input("Adiciona o numero desejada: "))
print(soma_quadrados(numero))
|
try:
pass
except ImportError:
pass
if False:
pass
class GraphQLSchema(object):
"""Schema Definition
A Schema is created by supplying the root types of each type of operation, query and mutation (optional).
A schema definition is then supplied to the validator and executor.
Example:
MyAppSchema = GraphQLSchema(
query=MyAppQueryRootType,
mutation=MyAppMutationRootType,
)
Note: If an array of `directives` are provided to GraphQLSchema, that will be
the exact list of directives represented and allowed. If `directives` is not
provided then a default set of the specified directives (e.g. @include and
@skip) will be used. If you wish to provide *additional* directives to these
specified directives, you must explicitly declare them. Example:
MyAppSchema = GraphQLSchema(
...
directives=specified_directives.extend([MyCustomerDirective]),
)
"""
__slots__ = ("_query", "_mutation", "_subscription", "_type_map", "_directives", "_implementations", "_possible_type_map")
def __init__(self, query, mutation=None, subscription=None, directives=None, types=None):
assert isinstance(query, GraphQLObjectType), "Schema query must be Object Type but got: {}.".format(query)
if mutation:
assert isinstance(mutation, GraphQLObjectType), "Schema mutation must be Object Type but got: {}.".format(mutation)
if subscription:
assert isinstance(subscription, GraphQLObjectType), "Schema subscription must be Object Type but got: {}.".format(subscription)
if types:
assert isinstance(types, Iterable), "Schema types must be iterable if provided but got: {}.".format(types)
self._query = query
self._mutation = mutation
self._subscription = subscription
if directives is None:
directives = specified_directives
assert all(isinstance(d, GraphQLDirective) for d in directives), "Schema directives must be List[GraphQLDirective] if provided but got: {}.".format(directives)
self._directives = directives
initial_types = list(filter(None, [query, mutation, subscription, IntrospectionSchema]))
if types:
initial_types += types
self._type_map = GraphQLTypeMap(initial_types)
def get_query_type(self):
return self._query
def get_mutation_type(self):
return self._mutation
def get_subscription_type(self):
return self._subscription
def get_type_map(self):
return self._type_map
def get_type(self, name):
return self._type_map.get(name)
def get_directives(self):
return self._directives
def get_directive(self, name):
for directive in self.get_directives():
if directive.name == name:
return directive
return None
def get_possible_types(self, abstract_type):
return self._type_map.get_possible_types(abstract_type)
def is_possible_type(self, abstract_type, possible_type):
return self._type_map.is_possible_type(abstract_type, possible_type) |
a = 1
if a == 1:
print("ok")
else:
print("no")
py_builtins = 1
if py_builtins == 1:
print("ok")
else:
print("no")
for py_builtins in range(5):
a += py_builtins
print(a)
|
lista_notas = []
for x in range(4):
lista_notas.append(int(input("Me de um número ae meu chapa\n")))
media = 0
for nota in lista_notas:
media += nota / 4
print("Media: ", media)
|
""" html head """
def get_head(content):
""" xxx """
return_data = '<head>'+ content +'</head>'
return return_data
|
"""Exceptions for ReSpecTh Parser.
.. moduleauthor:: Kyle Niemeyer <kyle.niemeyer@gmail.com>
"""
class ParseError(Exception):
"""Base class for errors."""
pass
class KeywordError(ParseError):
"""Raised for errors in keyword parsing."""
def __init__(self, *keywords):
self.keywords = keywords
def __str__(self):
return repr('Error: {}.'.format(self.keywords))
class UndefinedElementError(KeywordError):
"""Raised for undefined elements."""
def __str__(self):
return repr('Error: Element not defined.\n{}'.format(self.keywords))
class MissingElementError(KeywordError):
"""Raised for missing required elements."""
def __str__(self):
return repr('Error: Required element {} is missing.'.format(
self.keywords))
class MissingAttributeError(KeywordError):
"""Raised for missing required attribute."""
def __str__(self):
return repr('Error: Required attribute {} of {} is missing.'.format(
self.keywords))
class UndefinedKeywordError(KeywordError):
"""Raised for undefined keywords."""
def __str__(self):
return repr('Error: Keyword not defined: {}'.format(self.keywords))
|
#Crie um programa onde o usuário possa digitar vários valores numéricos e cadastre-os em uma lista. Caso o #número já exista lá dentro, ele não será adicionado. No final, serão exibidos todos os valores únicos #digitados, em ordem crescente.
valores=[]
while True:
digitado=(int(input("Digite o valor: ")))
if digitado in valores:
del digitado
print("Valor ja existente! Nao sera adicionado...")
else:
valores.append(digitado)
resposta=" "
while resposta not in "sn":
resposta=str(input("Quer continuar [S/N]? ")).strip().lower()[0]
if resposta=="n":
break
valores.sort()
print("=-"*15)
print()
print(f"A sua lista é composta: {valores}")
print()
print("=-"*15) |
# encoding: UTF-8
{
"name":u'CoMPS',
'version': '1.0',
'category': u'Saúde',
'depends':[],
'data':[
'views/qweb/comps_template.xml',
'security/comps_security.xml',
'security/ir.model.access.csv',
'views/cadastro_usuarios_view.xml',
'views/cadastro_escola_view.xml',
'views/cadastro_avaliador_view.xml',
'views/cadastro_aluno_view.xml',
'views/avaliacao_imc_view.xml',
"views/avaliacao_abdominal_view.xml",
"views/avaliacao_perimetro_view.xml",
"views/avaliacao_dobras_cutaneas_view.xml",
"views/avaliacao_impulsao_horizontal_view.xml",
"views/avaliacao_sentar_alcancar_view.xml",
"views/avaliacao_preensao_manual_view.xml",
"views/avaliacao_lancamento_unilateral_view.xml",
"views/avaliacao_lancamento_simultaneo_view.xml",
"views/avaliacao_corrida_25m_view.xml",
"views/avaliacao_shutllerun_10x5m_view.xml",
"views/avaliacao_shutllerun_20m_view.xml",
"views/avaliacao_equilibrio_retaguarda_view.xml",
"views/avaliacao_saltos_laterais_view.xml",
"views/avaliacao_transposicao_lateral_view.xml",
"views/avaliacao_saltos_monopedais_perna_direita_view.xml",
"views/avaliacoes_pendentes_view.xml",
],
'css': [
'static/src/css/*.css',
],
'js': [
'static/src/js/*.js'
],
'installable': True,
'application': True,
'auto_install': False,
} |
"""
digit factorial chains
"""
factorial = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
def next_number(n):
factorial_sum = 0
while n != 0:
factorial_sum += factorial[n % 10]
n //= 10
return factorial_sum
def chain_len(n):
chain = []
while not chain.__contains__(n):
chain.append(n)
n = next_number(n)
return len(chain)
if __name__ == '__main__':
result = 0
for i in range(1000000):
if chain_len(i) == 60:
result += 1
print(result) |
flag = [""] * 36
flag[0] = chr(0x46)
flag[1] = chr(0x4c)
flag[2] = chr(0x41)
flag[3] = chr(0x47)
flag[4] = chr(0x7b)
flag[5] = chr(0x35)
flag[6] = chr(0x69)
flag[7] = chr(0x6d)
flag[8] = chr(0x70)
flag[9] = chr(0x31)
flag[10] = chr(0x65)
flag[11] = chr(0x5f)
flag[12] = chr(0x52)
flag[13] = chr(0x65)
flag[14] = chr(0x76)
flag[15] = chr(0x65)
flag[16] = chr(0x72)
flag[17] = chr(0x73)
flag[18] = chr(0x31)
flag[19] = chr(0x6e)
flag[20] = chr(0x67)
flag[21] = chr(0x5f)
flag[22] = chr(0x34)
flag[23] = chr(0x72)
flag[24] = chr(0x72)
flag[25] = chr(0x61)
flag[26] = chr(0x79)
flag[27] = chr(0x5f)
flag[28] = chr(0x35)
flag[29] = chr(0x74)
flag[30] = chr(0x72)
flag[31] = chr(0x69)
flag[32] = chr(0x6e)
flag[33] = chr(0x67)
flag[34] = chr(0x73)
flag[35] = chr(0x7d)
print("".join(flag))
# FLAG{5imp1e_Revers1ng_4rray_5trings}
|
def code_function():
#function begin############################################
global code
code="""
class {0}_scoreboard extends uvm_scoreboard;
//---------------------------------------
// declaring pkt_qu to store the pkt's recived from monitor
//---------------------------------------
{0}_seq_item pkt_qu[$];
//---------------------------------------
// sc_{0}
//---------------------------------------
bit [7:0] sc_{0} [4];
//---------------------------------------
//port to recive packets from monitor
//---------------------------------------
uvm_analysis_imp#({0}_seq_item, {0}_scoreboard) item_collected_export;
`uvm_component_utils({0}_scoreboard)
//---------------------------------------
// new - constructor
//---------------------------------------
function new (string name, uvm_component parent);
super.new(name, parent);
endfunction : new
//---------------------------------------
// build_phase - create port and initialize local {0}ory
//---------------------------------------
function void build_phase(uvm_phase phase);
super.build_phase(phase);
item_collected_export = new("item_collected_export", this);
foreach(sc_{0}[i]) sc_{0}[i] = 8'hFF;
endfunction: build_phase
//---------------------------------------
// write task - recives the pkt from monitor and pushes into queue
//---------------------------------------
virtual function void write({0}_seq_item pkt);
//pkt.print();
pkt_qu.push_back(pkt);
endfunction : write
//---------------------------------------
// run_phase - compare's the read data with the expected data(stored in local {0}ory)
// local {0}ory will be updated on the write operation.
//---------------------------------------
virtual task run_phase(uvm_phase phase);
{0}_seq_item {0}_pkt;
forever begin
wait(pkt_qu.size() > 0);
{0}_pkt = pkt_qu.pop_front();
if({0}_pkt.wr_en) begin
sc_{0}[{0}_pkt.addr] = {0}_pkt.wdata;
`uvm_info(get_type_name(),$sformatf("------ :: WRITE DATA :: ------"),UVM_LOW)
`uvm_info(get_type_name(),$sformatf("Addr: %0h",{0}_pkt.addr),UVM_LOW)
`uvm_info(get_type_name(),$sformatf("Data: %0h",{0}_pkt.wdata),UVM_LOW)
`uvm_info(get_type_name(),"------------------------------------",UVM_LOW)
end
else if({0}_pkt.rd_en) begin
if(sc_{0}[{0}_pkt.addr] == {0}_pkt.rdata) begin
`uvm_info(get_type_name(),$sformatf("------ :: READ DATA Match :: ------"),UVM_LOW)
`uvm_info(get_type_name(),$sformatf("Addr: %0h",{0}_pkt.addr),UVM_LOW)
`uvm_info(get_type_name(),$sformatf("Expected Data: %0h Actual Data: %0h",sc_{0}[{0}_pkt.addr],{0}_pkt.rdata),UVM_LOW)
`uvm_info(get_type_name(),"------------------------------------",UVM_LOW)
end
else begin
`uvm_error(get_type_name(),"------ :: READ DATA MisMatch :: ------")
`uvm_info(get_type_name(),$sformatf("Addr: %0h",{0}_pkt.addr),UVM_LOW)
`uvm_info(get_type_name(),$sformatf("Expected Data: %0h Actual Data: %0h",sc_{0}[{0}_pkt.addr],{0}_pkt.rdata),UVM_LOW)
`uvm_info(get_type_name(),"------------------------------------",UVM_LOW)
end
end
end
endtask : run_phase
endclass : {0}_scoreboard
""".format(protocol_name)
print(code)
#function end############################################
fh=open("protocol.csv","r")
for protocol_name in fh:
protocol_name=protocol_name.strip("\n")
fph=open('{0}_sb.sv'.format(protocol_name),"w")
code_function()
fph.write(code)
|
uno= Board('/dev/cu.wchusbserial1420')
led= Led(13)
led.setColor([0.84, 0.34, 0.67])
ledController= ExdTextInputBox(target= led, value="period", size="sm")
APP.STACK.add_widget(ledController)
|
a, b = map(int, input().split())
if a + b == 15:
print('+')
elif a*b == 15:
print('*')
else:
print('x')
|
class Solution:
def stoneGameV(self, stoneValue: List[int]) -> int:
n = len(stoneValue)
dp = [[0] * n for _ in range(n)]
mx = [[0] * n for _ in range(n)]
for i in range(n):
mx[i][i] = stoneValue[i]
for j in range(1, n):
mid = j
s = stoneValue[j]
rightHalf = 0
for i in range(j - 1, -1, -1):
s += stoneValue[i]
while (rightHalf + stoneValue[mid]) * 2 <= s:
rightHalf += stoneValue[mid]
mid -= 1
if rightHalf * 2 == s:
dp[i][j] = mx[i][mid]
else:
dp[i][j] = (0 if mid == i else mx[i][mid - 1])
if mid != j:
dp[i][j] = max(dp[i][j], mx[j][mid + 1])
mx[i][j] = max(mx[i][j - 1], dp[i][j] + s)
mx[j][i] = max(mx[j][i + 1], dp[i][j] + s)
return dp[0][n - 1]
|
# %% [404. Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/)
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
if not root:
return 0
r = self.sumOfLeftLeaves(root.right)
if (p := root.left) and not p.left and not p.right:
return root.left.val + r
return self.sumOfLeftLeaves(root.left) + r
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.