content
stringlengths 7
1.05M
|
|---|
"""
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
Solution:
1. Sort
2. Hashset
"""
# Sort
# TLE: while loop too slow
# Time: O(NlogN)
# Space: O(1)
class Solution(object):
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
l = len(nums)
if l == 0:
return 0
nums.sort()
max_len = 0
for i in range(l):
cur_len = 1
j = i + 1
while j < l:
if nums[j] == nums[j-1] + 1:
cur_len += 1
j += 1
elif nums[j] == nums[j-1]:
j += 1
else:
break
if cur_len > max_len:
max_len = cur_len
i = j
return max_len
# Sort
# Time: O(NlogN)
# Space: O(1)
class Solution(object):
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
l = len(nums)
if l == 0:
return 0
nums.sort()
max_len = 0
cur_len = 1
for i in range(1, l):
if nums[i] != nums[i-1]:
# jump duplicates
if nums[i] == nums[i-1] + 1:
cur_len += 1
else:
max_len = max(max_len, cur_len)
cur_len = 1
# in case of the last number is in the longest consecutive numbers
max_len = max(max_len, cur_len)
return max_len
# Sort
# Time: O(NlogN)
# Space: O(1)
class Solution(object):
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
l = len(nums)
if l < 2 :
return l
res = 0
cur_len = 1
nums = list(set(nums))
nums.sort()
for i in range(1, len(nums)) :
if nums[i] == nums[i-1]+1 :
cur_len += 1
else:
res = max(res, cur_len)
cur_len = 1
res = max(res, cur_len)
return res
# Set
# Time: O(N), since we visit each number once
# Space: O(1)
class Solution(object):
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# for each num I will check whether num-1 exists
# if yes, then I ignore this num
# Otherwise if num-1 doesn't exist, then I will go till I can find num+1
# so in a way I am only checking each number max once and once in set.
s = set(nums)
res = 0
for num in s:
cur_len = 1
if num - 1 not in s:
while num + 1 in s:
cur_len += 1
num += 1
res = max(res, cur_len)
return res
|
SHORT_DESCRIPTION = "Sorter organises/sorts files using a customised search function to group those that have similar characteristics into a single folder. Similar characteristics include file type, file name or part of the name and file category. You can put all letters documents into one folder, all images with the word home into another, all music by one artist in yet another folder, etc."
SOURCE_DESCRIPTION = "SOURCE (required)\nThis is the folder in which the sorting should be done i.e the folder containing the disorganised files."
DESTINATION_DESCRIPTION = "DESTINATION (optional)\nAn optional destination (a folder) where the user would want the sorted files/folders to be moved to."
RECURSIVE_DESCRIPTION = "LOOK INTO SUB-FOLDERS (optional)\nChecks into every child folder, starting from the source folder, and groups/sorts the files accordingly."
TYPES_DESCRIPTION = "SELECT FILE TYPES (optional)\nSelect the specific file types/formats to be sorted."
SEARCH_DESCRIPTION = "SEARCH FOR (optional)\nDirects Sorter to search and only group files with names containing this value. If this is enabled then, by default, Sort Folders option is enabled to enable the sorted files to be moved to a folder whose name will be the value provided here. The search is case-insensitive but the final folder will adopt the case styles."
GROUP_FOLDER_DESCRIPTION = "GROUP INTO FOLDER (optional)\nMoves all files (and folders) fitting the search descriptions into a folder named by the value provided in this option."
BY_EXTENSION_DESCRIPTION = "GROUP BY FILE TYPE (optional)\nGroups files in the destination and according to their file type. That is, all JPGs different from PDFs different from DOCXs."
CLEANUP_DESCRIPTION = "PERFORM CLEANUP (optional)\nLooks into the child folders of the source folder and removes those which are empty."
NOTE = "Note:\nIf you want a folder and its contents to be left as is (i.e. not to be sorted or affected in any way), just add a file named `.signore` (no extension) into the folder."
HELP_MESSAGE = "How it Works \n" + SHORT_DESCRIPTION + "\n\nBelow is a description of the fields required to achieve results using Sorter:\n\n" + SOURCE_DESCRIPTION + "\n\n" + DESTINATION_DESCRIPTION + \
"\n\n" + SEARCH_DESCRIPTION + "\n\n" + RECURSIVE_DESCRIPTION + \
"\n\n" + TYPES_DESCRIPTION + "\n\n" + \
GROUP_FOLDER_DESCRIPTION + "\n\n" + BY_EXTENSION_DESCRIPTION + "\n\n" + CLEANUP_DESCRIPTION + \
"\n\n" + NOTE
COPYRIGHT_MESSAGE = "Copyright \u00a9 2017\n\nAswa Paul\nAll rights reserved.\n\n"
HOMEPAGE = "https://giantas.github.io/sorter"
SOURCE_CODE = "https://github.com/giantas/sorter"
LICENSE = """BSD 3-Clause License
Copyright (c) 2017, Aswa Paul
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
|
n=int(input ('veverite'))
if n %2==0: print ('par')
else: print ('impar')
print('par' if n%2==0 else 'impar')
|
# pylint: disable=missing-class-docstring, disable=missing-function-docstring, missing-module-docstring/
#$ header class Point(public)
#$ header method __init__(Point, double, double)
#$ header method __del__(Point)
#$ header method translate(Point, double, double)
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __del__(self):
pass
def translate(self, a, b):
self.x = self.x + a
self.y = self.y + b
if __name__ == '__main__':
p = Point(0.0, 0.0)
x=p.x
p.x=x
a = p.x
a = p.x - 2
a = 2 * p.x - 2
a = 2 * (p.x + 6) - 2
p.y = a + 5
p.y = p.x + 5
p.translate(1.0, 2.0)
print(p.x, p.y)
print(a)
del p
|
# parsetab.py
# This file is automatically generated. Do not edit.
# pylint: disable=W,C,R
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'leftPLUSMINUSleftTIMESDIVIDEleftPOWERrightUMINUSCOMMA DATA DEF DIM DIVIDE END EQUALS FLOAT FOR GE GOSUB GOTO GT ID IF INTEGER LE LET LIST LPAREN LT MINUS NE NEW NEWLINE NEXT PLUS POWER PRINT READ REM RETURN RPAREN RUN SEMI STEP STOP STRING THEN TIMES TOprogram : program statement\n | statementprogram : errorstatement : INTEGER command NEWLINEstatement : RUN NEWLINE\n | LIST NEWLINE\n | NEW NEWLINEstatement : INTEGER NEWLINEstatement : INTEGER error NEWLINEstatement : NEWLINEcommand : LET variable EQUALS exprcommand : LET variable EQUALS errorcommand : READ varlistcommand : READ errorcommand : DATA numlistcommand : DATA errorcommand : PRINT plist optendcommand : PRINT erroroptend : COMMA \n | SEMI\n |command : PRINTcommand : GOTO INTEGERcommand : GOTO errorcommand : IF relexpr THEN INTEGERcommand : IF error THEN INTEGERcommand : IF relexpr THEN errorcommand : FOR ID EQUALS expr TO expr optstepcommand : FOR ID EQUALS error TO expr optstepcommand : FOR ID EQUALS expr TO error optstepcommand : FOR ID EQUALS expr TO expr STEP erroroptstep : STEP expr\n | emptycommand : NEXT IDcommand : NEXT errorcommand : ENDcommand : REMcommand : STOPcommand : DEF ID LPAREN ID RPAREN EQUALS exprcommand : DEF ID LPAREN ID RPAREN EQUALS errorcommand : DEF ID LPAREN error RPAREN EQUALS exprcommand : GOSUB INTEGERcommand : GOSUB errorcommand : RETURNcommand : DIM dimlistcommand : DIM errordimlist : dimlist COMMA dimitem\n | dimitemdimitem : ID LPAREN INTEGER RPARENdimitem : ID LPAREN INTEGER COMMA INTEGER RPARENexpr : expr PLUS expr\n | expr MINUS expr\n | expr TIMES expr\n | expr DIVIDE expr\n | expr POWER exprexpr : INTEGER\n | FLOATexpr : variableexpr : LPAREN expr RPARENexpr : MINUS expr %prec UMINUSrelexpr : expr LT expr\n | expr LE expr\n | expr GT expr\n | expr GE expr\n | expr EQUALS expr\n | expr NE exprvariable : ID\n | ID LPAREN expr RPAREN\n | ID LPAREN expr COMMA expr RPARENvarlist : varlist COMMA variable\n | variablenumlist : numlist COMMA number\n | numbernumber : INTEGER\n | FLOATnumber : MINUS INTEGER\n | MINUS FLOATplist : plist COMMA pitem\n | pitempitem : STRINGpitem : STRING exprpitem : exprempty : '
_lr_action_items = {'error':([0,4,14,15,16,17,18,20,25,27,69,86,94,95,127,137,142,],[3,12,36,39,45,55,57,61,64,66,99,111,120,122,135,148,152,]),'INTEGER':([0,1,2,3,5,9,11,15,16,17,18,25,28,29,30,31,32,43,47,49,53,69,70,72,76,79,80,81,82,83,86,87,88,89,90,91,92,93,94,97,126,127,128,132,137,138,142,145,],[4,4,-2,-3,-10,-1,-8,41,50,54,50,63,-5,-6,-7,-4,-9,73,50,50,50,50,50,41,50,50,50,50,50,50,110,112,50,50,50,50,50,50,50,124,50,50,50,139,50,50,50,50,]),'RUN':([0,1,2,3,5,9,11,28,29,30,31,32,],[6,6,-2,-3,-10,-1,-8,-5,-6,-7,-4,-9,]),'LIST':([0,1,2,3,5,9,11,28,29,30,31,32,],[7,7,-2,-3,-10,-1,-8,-5,-6,-7,-4,-9,]),'NEW':([0,1,2,3,5,9,11,28,29,30,31,32,],[8,8,-2,-3,-10,-1,-8,-5,-6,-7,-4,-9,]),'NEWLINE':([0,1,2,3,4,5,6,7,8,9,10,11,12,16,21,22,23,26,28,29,30,31,32,34,35,36,37,38,39,40,41,42,44,45,46,47,48,50,51,52,54,55,60,61,63,64,65,66,67,73,74,75,76,77,78,84,98,99,101,102,103,104,105,106,107,108,109,110,111,112,123,125,131,134,135,136,140,141,143,144,146,147,148,149,150,151,152,],[5,5,-2,-3,11,-10,28,29,30,-1,31,-8,32,-22,-36,-37,-38,-44,-5,-6,-7,-4,-9,-67,-13,-14,-71,-15,-16,-73,-74,-75,-21,-18,-79,-80,-82,-56,-57,-58,-23,-24,-34,-35,-42,-43,-45,-46,-48,-76,-77,-17,-19,-20,-81,-60,-11,-12,-70,-72,-78,-51,-52,-53,-54,-55,-59,-25,-27,-26,-47,-68,-49,-83,-83,-83,-69,-28,-33,-30,-29,-39,-40,-41,-50,-32,-31,]),'$end':([1,2,3,5,9,11,28,29,30,31,32,],[0,-2,-3,-10,-1,-8,-5,-6,-7,-4,-9,]),'LET':([4,],[13,]),'READ':([4,],[14,]),'DATA':([4,],[15,]),'PRINT':([4,],[16,]),'GOTO':([4,],[17,]),'IF':([4,],[18,]),'FOR':([4,],[19,]),'NEXT':([4,],[20,]),'END':([4,],[21,]),'REM':([4,],[22,]),'STOP':([4,],[23,]),'DEF':([4,],[24,]),'GOSUB':([4,],[25,]),'RETURN':([4,],[26,]),'DIM':([4,],[27,]),'ID':([13,14,16,18,19,20,24,27,47,49,53,69,70,71,76,79,80,81,82,83,88,89,90,91,92,93,94,95,96,126,127,128,137,138,142,145,],[34,34,34,34,59,60,62,68,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,121,68,34,34,34,34,34,34,34,]),'FLOAT':([15,16,18,43,47,49,53,69,70,72,76,79,80,81,82,83,88,89,90,91,92,93,94,126,127,128,137,138,142,145,],[42,51,51,74,51,51,51,51,51,42,51,51,51,51,51,51,51,51,51,51,51,51,51,51,51,51,51,51,51,51,]),'MINUS':([15,16,18,34,47,48,49,50,51,52,53,58,69,70,72,76,78,79,80,81,82,83,84,85,88,89,90,91,92,93,94,98,100,104,105,106,107,108,109,113,114,115,116,117,118,119,125,126,127,128,133,134,136,137,138,140,142,145,147,149,151,],[43,49,49,-67,49,80,49,-56,-57,-58,49,80,49,49,43,49,80,49,49,49,49,49,-60,80,49,49,49,49,49,49,49,80,80,-51,-52,-53,-54,-55,-59,80,80,80,80,80,80,80,-68,49,49,49,80,80,80,49,49,-69,49,49,80,80,80,]),'STRING':([16,76,],[47,47,]),'LPAREN':([16,18,34,47,49,53,62,68,69,70,76,79,80,81,82,83,88,89,90,91,92,93,94,126,127,128,137,138,142,145,],[53,53,70,53,53,53,95,97,53,53,53,53,53,53,53,53,53,53,53,53,53,53,53,53,53,53,53,53,53,53,]),'EQUALS':([33,34,50,51,52,58,59,84,104,105,106,107,108,109,125,129,130,140,],[69,-67,-56,-57,-58,92,94,-60,-51,-52,-53,-54,-55,-59,-68,137,138,-69,]),'COMMA':([34,35,37,38,40,41,42,44,46,47,48,50,51,52,65,67,73,74,78,84,100,101,102,103,104,105,106,107,108,109,123,124,125,131,140,150,],[-67,71,-71,72,-73,-74,-75,76,-79,-80,-82,-56,-57,-58,96,-48,-76,-77,-81,-60,126,-70,-72,-78,-51,-52,-53,-54,-55,-59,-47,132,-68,-49,-69,-50,]),'PLUS':([34,48,50,51,52,58,78,84,85,98,100,104,105,106,107,108,109,113,114,115,116,117,118,119,125,133,134,136,140,147,149,151,],[-67,79,-56,-57,-58,79,79,-60,79,79,79,-51,-52,-53,-54,-55,-59,79,79,79,79,79,79,79,-68,79,79,79,-69,79,79,79,]),'TIMES':([34,48,50,51,52,58,78,84,85,98,100,104,105,106,107,108,109,113,114,115,116,117,118,119,125,133,134,136,140,147,149,151,],[-67,81,-56,-57,-58,81,81,-60,81,81,81,81,81,-53,-54,-55,-59,81,81,81,81,81,81,81,-68,81,81,81,-69,81,81,81,]),'DIVIDE':([34,48,50,51,52,58,78,84,85,98,100,104,105,106,107,108,109,113,114,115,116,117,118,119,125,133,134,136,140,147,149,151,],[-67,82,-56,-57,-58,82,82,-60,82,82,82,82,82,-53,-54,-55,-59,82,82,82,82,82,82,82,-68,82,82,82,-69,82,82,82,]),'POWER':([34,48,50,51,52,58,78,84,85,98,100,104,105,106,107,108,109,113,114,115,116,117,118,119,125,133,134,136,140,147,149,151,],[-67,83,-56,-57,-58,83,83,-60,83,83,83,83,83,83,83,-55,-59,83,83,83,83,83,83,83,-68,83,83,83,-69,83,83,83,]),'SEMI':([34,44,46,47,48,50,51,52,78,84,103,104,105,106,107,108,109,125,140,],[-67,77,-79,-80,-82,-56,-57,-58,-81,-60,-78,-51,-52,-53,-54,-55,-59,-68,-69,]),'LT':([34,50,51,52,58,84,104,105,106,107,108,109,125,140,],[-67,-56,-57,-58,88,-60,-51,-52,-53,-54,-55,-59,-68,-69,]),'LE':([34,50,51,52,58,84,104,105,106,107,108,109,125,140,],[-67,-56,-57,-58,89,-60,-51,-52,-53,-54,-55,-59,-68,-69,]),'GT':([34,50,51,52,58,84,104,105,106,107,108,109,125,140,],[-67,-56,-57,-58,90,-60,-51,-52,-53,-54,-55,-59,-68,-69,]),'GE':([34,50,51,52,58,84,104,105,106,107,108,109,125,140,],[-67,-56,-57,-58,91,-60,-51,-52,-53,-54,-55,-59,-68,-69,]),'NE':([34,50,51,52,58,84,104,105,106,107,108,109,125,140,],[-67,-56,-57,-58,93,-60,-51,-52,-53,-54,-55,-59,-68,-69,]),'RPAREN':([34,50,51,52,84,85,100,104,105,106,107,108,109,121,122,124,125,133,139,140,],[-67,-56,-57,-58,-60,109,125,-51,-52,-53,-54,-55,-59,129,130,131,-68,140,150,-69,]),'THEN':([34,50,51,52,56,57,84,104,105,106,107,108,109,113,114,115,116,117,118,125,140,],[-67,-56,-57,-58,86,87,-60,-51,-52,-53,-54,-55,-59,-61,-62,-63,-64,-65,-66,-68,-69,]),'TO':([34,50,51,52,84,104,105,106,107,108,109,119,120,125,140,],[-67,-56,-57,-58,-60,-51,-52,-53,-54,-55,-59,127,128,-68,-69,]),'STEP':([34,50,51,52,84,104,105,106,107,108,109,125,134,135,136,140,],[-67,-56,-57,-58,-60,-51,-52,-53,-54,-55,-59,-68,142,145,145,-69,]),}
_lr_action = {}
for _k, _v in _lr_action_items.items():
for _x,_y in zip(_v[0],_v[1]):
if not _x in _lr_action: _lr_action[_x] = {}
_lr_action[_x][_k] = _y
del _lr_action_items
_lr_goto_items = {'program':([0,],[1,]),'statement':([0,1,],[2,9,]),'command':([4,],[10,]),'variable':([13,14,16,18,47,49,53,69,70,71,76,79,80,81,82,83,88,89,90,91,92,93,94,126,127,128,137,138,142,145,],[33,37,52,52,52,52,52,52,52,101,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,]),'varlist':([14,],[35,]),'numlist':([15,],[38,]),'number':([15,72,],[40,102,]),'plist':([16,],[44,]),'pitem':([16,76,],[46,103,]),'expr':([16,18,47,49,53,69,70,76,79,80,81,82,83,88,89,90,91,92,93,94,126,127,128,137,138,142,145,],[48,58,78,84,85,98,100,48,104,105,106,107,108,113,114,115,116,117,118,119,133,134,136,147,149,151,151,]),'relexpr':([18,],[56,]),'dimlist':([27,],[65,]),'dimitem':([27,96,],[67,123,]),'optend':([44,],[75,]),'optstep':([134,135,136,],[141,144,146,]),'empty':([134,135,136,],[143,143,143,]),}
_lr_goto = {}
for _k, _v in _lr_goto_items.items():
for _x, _y in zip(_v[0], _v[1]):
if not _x in _lr_goto: _lr_goto[_x] = {}
_lr_goto[_x][_k] = _y
del _lr_goto_items
_lr_productions = [
("S' -> program","S'",1,None,None,None),
('program -> program statement','program',2,'p_program','basparse.py',21),
('program -> statement','program',1,'p_program','basparse.py',22),
('program -> error','program',1,'p_program_error','basparse.py',41),
('statement -> INTEGER command NEWLINE','statement',3,'p_statement','basparse.py',49),
('statement -> RUN NEWLINE','statement',2,'p_statement_interactive','basparse.py',62),
('statement -> LIST NEWLINE','statement',2,'p_statement_interactive','basparse.py',63),
('statement -> NEW NEWLINE','statement',2,'p_statement_interactive','basparse.py',64),
('statement -> INTEGER NEWLINE','statement',2,'p_statement_blank','basparse.py',71),
('statement -> INTEGER error NEWLINE','statement',3,'p_statement_bad','basparse.py',78),
('statement -> NEWLINE','statement',1,'p_statement_newline','basparse.py',87),
('command -> LET variable EQUALS expr','command',4,'p_command_let','basparse.py',94),
('command -> LET variable EQUALS error','command',4,'p_command_let_bad','basparse.py',99),
('command -> READ varlist','command',2,'p_command_read','basparse.py',106),
('command -> READ error','command',2,'p_command_read_bad','basparse.py',111),
('command -> DATA numlist','command',2,'p_command_data','basparse.py',118),
('command -> DATA error','command',2,'p_command_data_bad','basparse.py',123),
('command -> PRINT plist optend','command',3,'p_command_print','basparse.py',130),
('command -> PRINT error','command',2,'p_command_print_bad','basparse.py',135),
('optend -> COMMA','optend',1,'p_optend','basparse.py',142),
('optend -> SEMI','optend',1,'p_optend','basparse.py',143),
('optend -> <empty>','optend',0,'p_optend','basparse.py',144),
('command -> PRINT','command',1,'p_command_print_empty','basparse.py',154),
('command -> GOTO INTEGER','command',2,'p_command_goto','basparse.py',161),
('command -> GOTO error','command',2,'p_command_goto_bad','basparse.py',166),
('command -> IF relexpr THEN INTEGER','command',4,'p_command_if','basparse.py',173),
('command -> IF error THEN INTEGER','command',4,'p_command_if_bad','basparse.py',178),
('command -> IF relexpr THEN error','command',4,'p_command_if_bad2','basparse.py',183),
('command -> FOR ID EQUALS expr TO expr optstep','command',7,'p_command_for','basparse.py',190),
('command -> FOR ID EQUALS error TO expr optstep','command',7,'p_command_for_bad_initial','basparse.py',195),
('command -> FOR ID EQUALS expr TO error optstep','command',7,'p_command_for_bad_final','basparse.py',200),
('command -> FOR ID EQUALS expr TO expr STEP error','command',8,'p_command_for_bad_step','basparse.py',205),
('optstep -> STEP expr','optstep',2,'p_optstep','basparse.py',212),
('optstep -> empty','optstep',1,'p_optstep','basparse.py',213),
('command -> NEXT ID','command',2,'p_command_next','basparse.py',223),
('command -> NEXT error','command',2,'p_command_next_bad','basparse.py',229),
('command -> END','command',1,'p_command_end','basparse.py',236),
('command -> REM','command',1,'p_command_rem','basparse.py',243),
('command -> STOP','command',1,'p_command_stop','basparse.py',250),
('command -> DEF ID LPAREN ID RPAREN EQUALS expr','command',7,'p_command_def','basparse.py',257),
('command -> DEF ID LPAREN ID RPAREN EQUALS error','command',7,'p_command_def_bad_rhs','basparse.py',262),
('command -> DEF ID LPAREN error RPAREN EQUALS expr','command',7,'p_command_def_bad_arg','basparse.py',267),
('command -> GOSUB INTEGER','command',2,'p_command_gosub','basparse.py',274),
('command -> GOSUB error','command',2,'p_command_gosub_bad','basparse.py',279),
('command -> RETURN','command',1,'p_command_return','basparse.py',286),
('command -> DIM dimlist','command',2,'p_command_dim','basparse.py',293),
('command -> DIM error','command',2,'p_command_dim_bad','basparse.py',298),
('dimlist -> dimlist COMMA dimitem','dimlist',3,'p_dimlist','basparse.py',305),
('dimlist -> dimitem','dimlist',1,'p_dimlist','basparse.py',306),
('dimitem -> ID LPAREN INTEGER RPAREN','dimitem',4,'p_dimitem_single','basparse.py',317),
('dimitem -> ID LPAREN INTEGER COMMA INTEGER RPAREN','dimitem',6,'p_dimitem_double','basparse.py',322),
('expr -> expr PLUS expr','expr',3,'p_expr_binary','basparse.py',329),
('expr -> expr MINUS expr','expr',3,'p_expr_binary','basparse.py',330),
('expr -> expr TIMES expr','expr',3,'p_expr_binary','basparse.py',331),
('expr -> expr DIVIDE expr','expr',3,'p_expr_binary','basparse.py',332),
('expr -> expr POWER expr','expr',3,'p_expr_binary','basparse.py',333),
('expr -> INTEGER','expr',1,'p_expr_number','basparse.py',339),
('expr -> FLOAT','expr',1,'p_expr_number','basparse.py',340),
('expr -> variable','expr',1,'p_expr_variable','basparse.py',345),
('expr -> LPAREN expr RPAREN','expr',3,'p_expr_group','basparse.py',350),
('expr -> MINUS expr','expr',2,'p_expr_unary','basparse.py',355),
('relexpr -> expr LT expr','relexpr',3,'p_relexpr','basparse.py',362),
('relexpr -> expr LE expr','relexpr',3,'p_relexpr','basparse.py',363),
('relexpr -> expr GT expr','relexpr',3,'p_relexpr','basparse.py',364),
('relexpr -> expr GE expr','relexpr',3,'p_relexpr','basparse.py',365),
('relexpr -> expr EQUALS expr','relexpr',3,'p_relexpr','basparse.py',366),
('relexpr -> expr NE expr','relexpr',3,'p_relexpr','basparse.py',367),
('variable -> ID','variable',1,'p_variable','basparse.py',374),
('variable -> ID LPAREN expr RPAREN','variable',4,'p_variable','basparse.py',375),
('variable -> ID LPAREN expr COMMA expr RPAREN','variable',6,'p_variable','basparse.py',376),
('varlist -> varlist COMMA variable','varlist',3,'p_varlist','basparse.py',388),
('varlist -> variable','varlist',1,'p_varlist','basparse.py',389),
('numlist -> numlist COMMA number','numlist',3,'p_numlist','basparse.py',400),
('numlist -> number','numlist',1,'p_numlist','basparse.py',401),
('number -> INTEGER','number',1,'p_number','basparse.py',413),
('number -> FLOAT','number',1,'p_number','basparse.py',414),
('number -> MINUS INTEGER','number',2,'p_number_signed','basparse.py',421),
('number -> MINUS FLOAT','number',2,'p_number_signed','basparse.py',422),
('plist -> plist COMMA pitem','plist',3,'p_plist','basparse.py',430),
('plist -> pitem','plist',1,'p_plist','basparse.py',431),
('pitem -> STRING','pitem',1,'p_item_string','basparse.py',440),
('pitem -> STRING expr','pitem',2,'p_item_string_expr','basparse.py',445),
('pitem -> expr','pitem',1,'p_item_expr','basparse.py',450),
('empty -> <empty>','empty',0,'p_empty','basparse.py',457),
]
|
#-*- coding: utf8 -*-
class P3PMiddleware(object):
def process_response(self, request, response):
response['P3P'] = 'CP="CAO PSA OUR"'
return response
|
N, M = 510, 10010
big_num = 0x3F3F3F3F
dist = [big_num] * N
def bf():
# 初始化
dist[1] = 0
# 遍历k次,更新所有边
for _ in range(k):
bak = dist[:] # 备份一下距离,防止被错误更新(copylist的方式还有 bak=list(dist))
for j in range(m):
a, b, w = edge[j]
dist[b] = min(dist[b], bak[a] + w)
# 因为有可能有负权,所以dist[n]可能是一个和bignum差不多大的数
if dist[n] > big_num // 2:
return "impossible"
return dist[n]
n, m, k = map(int, input().split())
edge = []
for i in range(m):
a, b, c = map(int, input().split())
edge.append([a, b, c])
t = bf()
print(t)
|
#!/usr/bin/env python
# Exercicio 3.3 - Complete a tabela a seguir utilizando a = True, b = false e c = True
print (' ')
a = True
b = False
c = True
# Expressões e resultados
a1 = a and a
b1 = b and b
c1 = not c
d1 = not b
e1 = not a
f1 = a and b
g1 = b and c
h1 = a or c
i1 = b or c
j1 = c or a
k1 = c or b
l1 = c or c
m1 = b or b
#Resultados na tela
print (f'a and a -/- {a1}')
print (f'b and b -/- {b1}')
print (f'not c -/- {c1}')
print (f'not b -/- {d1}')
print (f'not a -/- {e1}')
print (f'a and b -/- {f1}')
print (f'b and c -/- {g1}')
print (f'a or c -/- {h1}')
print (f'b or c -/- {i1}')
print (f'c or a -/- {j1}')
print (f'c or b -/- {k1}')
print (f'c or c -/- {l1}')
print (f'b or b -/- {m1}')
print (' ')
|
# Copyright 2018 Databricks, Inc.
VERSION = '0.7.0.dev'
|
#!/usr/bin/env python
'''
This script prints Hello World!
'''
print('Hello, World!')
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def main():
""" Повторите строку столько раз, сколько в ней символов. """
# Code goes over here.
a = str(input())
for i in range(len(a)):
print(a)
return 0
if __name__ == "__main__":
main()
|
__all__ = ["InvalidECFGFormatException"]
class InvalidECFGFormatException(Exception):
pass
|
r=int(input('banyaknya angka:'))
data=[]
for i in range (r): #v
n=int(input("Enter Integer {}:".format(i+1))) #v
data.append(n) #v
m=10**(r-1)
for i in range (r):
y=int(data[i]*m)
print(y)
m=m/10
#print(r);
|
def define_display_nodes(tree,nodemap,unscoped_vectors=False,looped_definition=False):
if unscoped_vectors:
s = ''
else:
s = '\t\t\tstd::vector<MPILib::NodeId> display_nodes;\n'
display_nodes = tree.findall('.//Display')
for dn in display_nodes:
node_id = str(nodemap[dn.attrib['node']])
if looped_definition:
node_id = str(len(nodemap))+'*i+'+node_id
s += '\t\t\tdisplay_nodes.push_back('+ node_id + ');\n'
s += '\n'
return s
def define_rate_nodes(tree, nodemap,unscoped_vectors=False,looped_definition=False):
if unscoped_vectors:
s = ''
else:
s = '\t\t\tstd::vector<MPILib::NodeId> rate_nodes;\n'
s += '\t\t\tstd::vector<MPILib::Time> rate_node_intervals;\n'
rate_nodes = tree.findall('.//Rate')
for rn in rate_nodes:
node_id = str(nodemap[rn.attrib['node']])
if looped_definition:
node_id = str(len(nodemap))+'*i+'+node_id
t_interval = rn.attrib['t_interval']
s += '\t\t\trate_nodes.push_back('+ node_id + ');\n'
s += '\t\t\trate_node_intervals.push_back('+ t_interval + ');\n'
s += '\n'
return s
def define_density_nodes(tree,nodemap,unscoped_vectors=False,looped_definition=False):
if unscoped_vectors:
s = ''
else:
s = '\t\t\tstd::vector<MPILib::NodeId> density_nodes;\n'
s += '\t\t\tstd::vector<MPILib::Time> density_node_start_times;\n'
s += '\t\t\tstd::vector<MPILib::Time> density_node_end_times;\n'
s += '\t\t\tstd::vector<MPILib::Time> density_node_intervals;\n'
density_nodes = tree.findall('.//Density')
for dn in density_nodes:
node_id = str(nodemap[dn.attrib['node']])
if looped_definition:
node_id = str(len(nodemap))+'*i+'+node_id
t_start = dn.attrib['t_start']
t_end = dn.attrib['t_end']
t_interval = dn.attrib['t_interval']
s += '\t\t\tdensity_nodes.push_back('+ node_id + ');\n'
s += '\t\t\tdensity_node_start_times.push_back('+ t_start + ');\n'
s += '\t\t\tdensity_node_end_times.push_back('+ t_end + ');\n'
s += '\t\t\tdensity_node_intervals.push_back('+ t_interval + ');\n'
s += '\n'
return s
|
def factorial(n):
if n==0:
return 1
else:
return factorial(n-1)*n
print(factorial(80))
|
# two_tasks.py
def task_reformat_temperature_data():
"""Reformats the raw temperature data file for easier analysis"""
return {
'file_dep': ['UK_Tmean_data.txt'],
'targets': ['UK_Tmean_data.reformatted.txt'],
'actions': ['python reformat_weather_data.py UK_Tmean_data.txt > UK_Tmean_data.reformatted.txt'],
}
def task_reformat_sunshine_data():
"""Reformats the raw sunshine data file for easier analysis"""
return {
'file_dep': ['UK_Sunshine_data.txt'],
'targets': ['UK_Sunshine_data.reformatted.txt'],
'actions': ['python reformat_weather_data.py UK_Sunshine_data.txt > UK_Sunshine_data.reformatted.txt'],
}
|
#Make sure that we handle keyword-only arguments correctly
def f(a, *varargs, kw1, kw2="has-default"):
pass
#OK
f(1, 2, 3, kw1=1)
f(1, 2, kw1=1, kw2=2)
#Not OK
f(1, 2, 3, kw1=1, kw3=3)
f(1, 2, 3, kw3=3)
#ODASA-5897
def analyze_member_access(msg, *, original, override, chk: 'default' = None):
pass
def ok():
return analyze_member_access(msg, original=original, chk=chk)
def bad():
return analyze_member_access(msg, original, chk=chk)
|
class Parser():
def __init__(self, config):
self._config_args = config
@property
def experiment_args(self):
return self._config_args["Experiment"]
@property
def train_dataset_args(self):
return self._config_args["Dataset - metatrain"]
@property
def valid_dataset_args(self):
return self._config_args["Dataset - metatest"]
@property
def model_args(self):
return self._config_args["Model"]
@property
def maml_args(self):
return self._config_args["MAML"]
@property
def training_args(self):
return self._config_args["training"]
def parse(self):
return self.experiment_args, self.train_dataset_args, self.valid_dataset_args, self.model_args, self.maml_args, self.training_args
|
# -*- coding: utf-8 -*-
"""
__author__ = "Jani Yli-Kantola"
__copyright__ = ""
__credits__ = ["Harri Hirvonsalo", "Aleksi Palomäki"]
__license__ = "MIT"
__version__ = "1.3.0"
__maintainer__ = "Jani Yli-Kantola"
__contact__ = "https://github.com/HIIT/mydata-stack"
__status__ = "Development"
"""
schema_sl_init_sink = {
"$schema": "http://json-schema.org/draft-04/schema#",
"definitions": {},
"properties": {
"code": {
"type": "string"
},
"data": {
"properties": {
"attributes": {
"properties": {
"pop_key": {
"properties": {
"crv": {
"type": "string"
},
"kid": {
"type": "string"
},
"kty": {
"type": "string"
},
"x": {
"type": "string"
},
"y": {
"type": "string"
}
},
"required": [
"crv",
"y",
"x",
"kid",
"kty"
],
"type": "object"
},
"slr_id": {
"type": "string"
}
},
"required": [
"slr_id",
"pop_key"
],
"type": "object"
}
},
"required": [
"attributes"
],
"type": "object"
}
},
"required": [
"code",
"data"
],
"type": "object"
}
schema_sl_init_source = {
"$schema": "http://json-schema.org/draft-04/schema#",
"definitions": {},
"properties": {
"code": {
"type": "string"
},
"data": {
"properties": {
"attributes": {
"properties": {
"slr_id": {
"type": "string"
}
},
"required": [
"slr_id"
],
"type": "object"
}
},
"required": [
"attributes"
],
"type": "object"
}
},
"required": [
"code",
"data"
],
"type": "object"
}
schema_sl_sign = {
"$schema": "http://json-schema.org/draft-04/schema#",
"definitions": {},
"properties": {
"code": {
"type": "string"
},
"data": {
"properties": {
"attributes": {
"properties": {
"iat": {
"type": "integer"
},
"link_id": {
"type": "string"
},
"operator_id": {
"type": "string"
},
"operator_key": {
"properties": {
"crv": {
"type": "string"
},
"kid": {
"type": "string"
},
"kty": {
"type": "string"
},
"x": {
"type": "string"
},
"y": {
"type": "string"
}
},
"required": [
"crv",
"y",
"x",
"kid",
"kty"
],
"type": "object"
},
"service_id": {
"type": "string"
},
"surrogate_id": {
"type": "string"
},
"version": {
"type": "string"
}
},
"required": [
"operator_id",
"surrogate_id",
"link_id",
"operator_key",
"version",
"iat",
"service_id"
],
"type": "object"
},
"type": {
"type": "string"
}
},
"required": [
"attributes",
"type"
],
"type": "object"
}
},
"required": [
"code",
"data"
],
"type": "object"
}
schema_sl_store = {
"$schema": "http://json-schema.org/draft-04/schema#",
"definitions": {},
"id": "http://example.com/example.json",
"properties": {
"code": {
"type": "string"
},
"data": {
"properties": {
"slr": {
"properties": {
"attributes": {
"properties": {
"payload": {
"type": "string"
},
"signatures": {
"items": {
"properties": {
"header": {
"properties": {
"kid": {
"type": "string"
}
},
"required": [
"kid"
],
"type": "object"
},
"protected": {
"type": "string"
},
"signature": {
"type": "string"
}
},
"required": [
"header",
"protected",
"signature"
],
"type": "object"
},
"type": "array"
}
},
"required": [
"signatures",
"payload"
],
"type": "object"
},
"id": {
"type": "string"
},
"type": {
"type": "string"
}
},
"required": [
"attributes",
"type",
"id"
],
"type": "object"
},
"ssr": {
"properties": {
"attributes": {
"properties": {
"iat": {
"type": "integer"
},
"prev_record_id": {
"type": "string"
},
"record_id": {
"type": "string"
},
"sl_status": {
"type": "string"
},
"slr_id": {
"type": "string"
},
"surrogate_id": {
"type": "string"
},
"version": {
"type": "string"
}
},
"required": [
"slr_id",
"surrogate_id",
"sl_status",
"version",
"record_id",
"iat",
"prev_record_id"
],
"type": "object"
},
"type": {
"type": "string"
}
},
"required": [
"attributes",
"type"
],
"type": "object"
}
},
"required": [
"slr",
"ssr"
],
"type": "object"
}
},
"required": [
"code",
"data"
],
"type": "object"
}
schema_sls_to_sign_by_account = {
"$schema": "http://json-schema.org/draft-04/schema#",
"definitions": {},
"id": "http://example.com/example.json",
"properties": {
"data": {
"properties": {
"attributes": {
"properties": {
"iat": {
"type": "integer"
},
"prev_record_id": {
"type": "string"
},
"record_id": {
"type": "string"
},
"sl_status": {
"type": "string"
},
"slr_id": {
"type": "string"
},
"surrogate_id": {
"type": "string"
},
"version": {
"type": "string"
}
},
"required": [
"slr_id",
"surrogate_id",
"sl_status",
"version",
"record_id",
"iat",
"prev_record_id"
],
"type": "object"
},
"type": {
"type": "string"
}
},
"required": [
"attributes",
"type"
],
"type": "object"
}
},
"required": [
"data"
],
"type": "object"
}
schema_sls_signed_by_operator = {
"$schema": "http://json-schema.org/draft-04/schema#",
"definitions": {},
"id": "http://example.com/example.json",
"properties": {
"data": {
"properties": {
"ssr": {
"properties": {
"attributes": {
"properties": {
"header": {
"properties": {
"kid": {
"type": "string"
}
},
"required": [
"kid"
],
"type": "object"
},
"payload": {
"type": "string"
},
"protected": {
"type": "string"
},
"signature": {
"type": "string"
}
},
"required": [
"header",
"protected",
"payload",
"signature"
],
"type": "object"
},
"id": {
"type": "string"
},
"type": {
"type": "string"
}
},
"required": [
"attributes",
"type",
"id"
],
"type": "object"
},
"ssr_payload": {
"properties": {
"attributes": {
"properties": {
"iat": {
"type": "integer"
},
"prev_record_id": {
"type": "string"
},
"record_id": {
"type": "string"
},
"sl_status": {
"type": "string"
},
"slr_id": {
"type": "string"
},
"surrogate_id": {
"type": "string"
},
"version": {
"type": "string"
}
},
"required": [
"slr_id",
"surrogate_id",
"sl_status",
"version",
"record_id",
"iat",
"prev_record_id"
],
"type": "object"
}
},
"required": [
"attributes"
],
"type": "object"
}
},
"required": [
"ssr_payload",
"ssr"
],
"type": "object"
}
},
"required": [
"data"
],
"type": "object"
}
|
'''
According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970."
Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):
Any live cell with fewer than two live neighbors dies, as if caused by under-population.
Any live cell with two or three live neighbors lives on to the next generation.
Any live cell with more than three live neighbors dies, as if by over-population..
Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
Write a function to compute the next state (after one update) of the board given its current state.
Follow up:
Could you solve it in-place? Remember that the board needs to be updated at the same time: You cannot update some cells first and then use their updated values to update other cells.
In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches the border of the array. How would you address these problems?
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
'''
class Solution(object):
def gameOfLife(self, board):
"""
:type board: List[List[int]]
:rtype: void Do not return anything, modify board in-place instead.
"""
if not board:
return
n = len(board)
m = len(board[0])
copy_board = [[board[i][j] for j in xrange(m)] for i in xrange(n)]
for i in xrange(n):
for j in xrange(m):
live_neighbors = 0
for x, y in [(1, 0), (-1, 0), (0, 1), (0, -1), (-1, -1), (-1, 1), (1, -1), (1, 1)]:
ii = i + x
jj = j + y
if 0 <= ii < n and 0 <= jj < m:
if copy_board[ii][jj] == 1:
live_neighbors += 1
if copy_board[i][j] == 1:
if live_neighbors < 2:
board[i][j] = 0
elif live_neighbors < 4:
board[i][j] = 1
else:
board[i][j] = 0
elif copy_board[i][j] == 0:
if live_neighbors == 3:
board[i][j] = 1
else:
board[i][j] = 0
|
class X:
def __init__(self,x):
print("Inside X ", x)
class Y:
def __init__(self):
print("Inside Y")
class Z(X,Y):
def __init__(self):
super().__init__(10)
print("Inside Z")
obj = Z()
|
# -*- coding: utf-8 -*-
valor = float(input())
if 0 < valor <= 25:
print('Intervalo [0, 25]')
elif 25 < valor <= 50:
print('Intervalo (25, 50]')
elif 50 < valor <= 75:
print('Intervalo (50, 75]')
elif 75 < valor <= 100:
print('Intervalo (75, 100]')
else:
print('Fora de intervalo')
|
"""
Consider the following:
A string,
, of length where
.
An integer,
, where is a factor of
.
We can split
into subsegments where each subsegment, , consists of a contiguous block of characters in . Then, use each to create string
such that:
The characters in
are a subsequence of the characters in
.
Any repeat occurrence of a character is removed from the string such that each character in
occurs exactly once. In other words, if the character at some index in occurs at a previous index in , then do not include the character in string
.
Given
and , print lines where each line denotes string
.
Input Format
The first line contains a single string denoting
.
The second line contains an integer,
, denoting the length of each subsegment.
Constraints
, where is the length of It is guaranteed that is a multiple of
.
Output Format
Print
lines where each line contains string
.
Sample Input
AABCAAADA
3
Sample Output
AB
CA
AD
Explanation
String
is split into equal parts of length . We convert each to by removing any subsequent occurrences non-distinct characters in
:
We then print each on a new line.
"""
S, N = input(), int(input())
for part in zip(*[iter(S)] * N):
d = dict()
print(''.join([d.setdefault(c, c) for c in part if c not in d]))
|
# Write your code below this line 👇
def prime_checker(number):
prime = True
for a in range(2, number):
if number % a == 0:
prime = False
if prime == True:
print(f"{number} is a prime number")
else:
print(f"{number} isn't a prime number")
# Write your code above this line 👆
# Do NOT change any of the code below👇
n = int(input("Check this number: "))
prime_checker(number=n)
|
# -*- coding: utf-8 -*-
"""
Transcriptions and targets for the parser
"""
# Example (1) most simple full sign transcription:
# one dominant hand, one orientation (must have two symbols), one location,
# one movement
{
" ": # segmented into types
{
"symmetry": "",
"dominant_hand": "", # hamfinger2
"nondominant_hand": "",
"handshape_change": "",
"dominant_orientation": "", # hamextfingeru,hampalmu
"nondominant_orientation": "",
"dominant_location": "", # hamchest
"nondominant_location": "",
"dominant_movement": "", # hammoveo
"nondominant_movement": ""
}
}
# Example (2) most simple two-handed sign with symmetry:
# one symmetry symbol, one dominant hand, one orientation, one location,
# one movement
{
" ":
{
"symmetry": "", #hamsymmpar
"dominant_hand": "", # hamfinger2
"nondominant_hand": "",
"handshape_change": "",
"dominant_orientation": "", # hamextfingeru,hampalmu
"nondominant_orientation": "",
"dominant_location": "", # hamchest
"nondominant_location": "",
"dominant_movement": "", # hammoveo
"nondominant_movement": ""
}
}
# Example (3) two-handed sign completely asymmetrical:
# one dominant hand, one nondominant hand; orientations, locations,
# and movements for each hand
{
" ":
{
"symmetry": "",
"dominant_hand": "", # hamfinger2
"nondominant_hand": "", # hamflathand
"handshape_change": "",
"dominant_orientation": "", # hamextfingeru,hampalml
"nondominant_orientation": "", # hamextfingero,hampalmd
"dominant_location": "", # hamshoulders,hamlrat (sequence matters!)
"nondominant_location": "", # hamlrat,hamchest (sequence matters!)
"dominant_movement": "", # hammovedo
"nondominant_movement": "" # hamnomotion
}
}
# Example (4) one-handed sign with handshape change:
# one dominant hand and handshape change; no orientation provided,
# two locations, and movement as handshape change
{
" ":
{"symmetry": "",
"dominant_hand": "",
"nondominant_hand": "",
"handshape_change": "",
"dominant_orientation": "",
"nondominant_orientation": "",
"dominant_location": ["", ""],# beginning and ending locations
"nondominant_location": "",
"dominant_movement": "",
"nondominant_movement": ""
}
}
|
# SPDX-FileCopyrightText: Copyright (C) 2020-2021 Ryan Finnie
# SPDX-License-Identifier: MIT
def numfmt(
num,
fmt="{num.real:0.02f} {num.prefix}",
binary=False,
rollover=1.0,
limit=0,
prefixes=None,
):
"""Formats a number with decimal or binary prefixes
num: Input number
fmt: Format string of default repr/str output
binary: If True, use divide by 1024 and use IEC binary prefixes
rollover: Threshold to roll over to the next prefix
limit: Stop after a specified number of rollovers
prefixes: List of (decimal, binary) prefix strings, ascending
"""
# SPDX-SnippetComment: Originally from https://github.com/rfinnie/rf-pymods
# SPDX-SnippetCopyrightText: Copyright (C) 2020-2021 Ryan Finnie
# SPDX-LicenseInfoInSnippet: MIT
class NumberFormat(float):
prefix = ""
fmt = "{num.real:0.02f} {num.prefix}"
def __str__(self):
return self.fmt.format(num=self)
def __repr__(self):
return str(self)
if prefixes is None:
prefixes = [
("k", "Ki"),
("M", "Mi"),
("G", "Gi"),
("T", "Ti"),
("P", "Pi"),
("E", "Ei"),
("Z", "Zi"),
("Y", "Yi"),
]
divisor = 1024 if binary else 1000
if limit <= 0 or limit > len(prefixes):
limit = len(prefixes)
count = 0
p = ""
for prefix in prefixes:
if num < (divisor * rollover):
break
if count >= limit:
break
count += 1
num = num / float(divisor)
p = prefix[1] if binary else prefix[0]
ret = NumberFormat(num)
ret.fmt = fmt
ret.prefix = p
return ret
|
# Aula 13 - Desafio 47: Contagem de numeros pares
# Mostrar na tela todos os numeros pares entre 1 e 50
print('Entre 1 e 50, sao numeros pares:')
for n in range(2, 51, 2):
print(n, end=' ')
|
word1=input()
word2=input()
dict={}
alphabet="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
for char in alphabet:
dict[char]=0
for ch in word1:
dict[ch]+=1
for ch in word2:
dict[ch]-=1
flag=False
sum=0
for char in dict:
count=dict[char]
sum+=count
if count == 1:
flag=True
if flag and count>1:
flag=False
break
if flag and sum==0:
print("Yes")
else:
print("No")
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Source code meta data
__author__ = 'Dalwar Hossain'
__email__ = 'dalwar.hossain@protonmail.com'
|
tm20 = toi = h = 0
print('-' * 25)
print(' CADASTRANDO PESSOAS ')
print('-' * 25)
while True:
id = int(input('digite a idade '))
sex = ' '
while sex not in 'MF':
sex = str(input('digite o sexo')).upper()
if id >= 18:
toi += 1
if sex == 'M':
h += 1
if sex == 'f' and id < 18:
tm20 += 1
r = ' '
while r not in "SN":
r = str(input('quer continuar?[s/n]')).upper()
if r == 'N':
break
print(f' {toi} pessoas tem mais de 18 anos')
print(f'o total de homens foi {h}')
print(f'total de mulheres com menos de 20 anos {tm20}')
|
# vim: set encoding=utf-8
# Copyright (c) 2016 Intel Corporation
#
# 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.
#
def filter_by_tags(self, tags_values_dict):
"""
Filter the rows based on dictionary of {"tag":"value"}(applying 'and' operation on dictionary) from column holding xml string
Ex: tags_values_dict -> {"00080018":"1.3.6.1.4.1.14519.5.2.1.7308.2101.234736319276602547946349519685", "00080070":"SIEMENS", "00080020":"20030315"}
Parameters
----------
:param tags_values_dict: (dict(str, str)) dictionary of tags and values from xml string in metadata.
Examples
--------
>>> dicom_path = "../datasets/dicom_uncompressed"
>>> dicom = tc.dicom.import_dcm(dicom_path)
>>> dicom.metadata.count()
3
<skip>
>>> dicom.metadata.inspect(truncate=30)
[#] id metadata
=======================================
[0] 0 <?xml version="1.0" encodin...
[1] 1 <?xml version="1.0" encodin...
[2] 2 <?xml version="1.0" encodin...
</skip>
#Part of xml string looks as below
<?xml version="1.0" encoding="UTF-8"?>
<NativeDicomModel xml:space="preserve">
<DicomAttribute keyword="FileMetaInformationVersion" tag="00020001" vr="OB"><InlineBinary>AAE=</InlineBinary></DicomAttribute>
<DicomAttribute keyword="MediaStorageSOPClassUID" tag="00020002" vr="UI"><Value number="1">1.2.840.10008.5.1.4.1.1.4</Value></DicomAttribute>
<DicomAttribute keyword="MediaStorageSOPInstanceUID" tag="00020003" vr="UI"><Value number="1">1.3.6.1.4.1.14519.5.2.1.7308.2101.234736319276602547946349519685</Value></DicomAttribute>
...
>>> tags_values_dict = {"00080018":"1.3.6.1.4.1.14519.5.2.1.7308.2101.234736319276602547946349519685", "00080070":"SIEMENS", "00080020":"20030315"}
>>> dicom.filter_by_tags(tags_values_dict)
>>> dicom.metadata.count()
1
<skip>
#After filter
>>> dicom.metadata.inspect(truncate=30)
[#] id metadata
=======================================
[0] 0 <?xml version="1.0" encodin...
>>> dicom.pixeldata.inspect(truncate=30)
[#] id imagematrix
=====================================================
[0] 0 [[ 0. 0. 0. ..., 0. 0. 0.]
[ 0. 125. 103. ..., 120. 213. 319.]
[ 0. 117. 94. ..., 135. 223. 325.]
...,
[ 0. 62. 21. ..., 896. 886. 854.]
[ 0. 63. 23. ..., 941. 872. 897.]
[ 0. 60. 30. ..., 951. 822. 906.]]
</skip>
"""
if not isinstance(tags_values_dict, dict):
raise TypeError("tags_values_dict should be a type of dict, but found type as %" % type(tags_values_dict))
for tag, value in tags_values_dict.iteritems():
if not isinstance(tag, basestring) or not isinstance(value, basestring):
raise TypeError("both tag and value should be of <type 'str'>")
#Always scala dicom is invoked, as python joins are expensive compared to serailizations.
def f(scala_dicom):
scala_dicom.filterByTags(self._tc.jutils.convert.to_scala_map(tags_values_dict))
self._call_scala(f)
|
# De uitwerking van 4-autoencoder.py moet hiervoor gedraaid worden!
voorspeller = tf.keras.models.Sequential([
tf.keras.layers.Dense(200, activation=tf.nn.relu),
tf.keras.layers.Dense(50, activation=tf.nn.relu),
tf.keras.layers.Dense(50, activation=tf.nn.relu),
tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])
voorspeller.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
voorspeller.fit(xtr, ytr, epochs=10)
print(voorspeller.evaluate(xtr, ytr))
print("Performance op ruizige getallen:")
print(voorspeller.evaluate(xruis, y))
print("Performance van hetzelfde netwerk op door auto-encoder gereconstrueerde getallen:")
print(voorspeller.evaluate(reconstructed, y))
print("Als het goed is, flinke winst!")
|
# -*- coding: utf-8 -*-
u"""
Levenshtein Distance
The Levenshtein distance between two words is the minimal number of
edits that turn one word into the other. Here, "edit" means a
single-letter addition, single-letter deletion, or exchange of a
letter with another letter.
http://en.wikipedia.org/wiki/Levenshtein_distance
EXAMPLES::
>>> from sage_bootstrap.levenshtein import Levenshtein
>>> Levenshtein(5)(u'Queensryche', u'Queensrÿche')
1
"""
#*****************************************************************************
# Copyright (C) 2015 Volker Braun <vbraun.name@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
# http://www.gnu.org/licenses/
#*****************************************************************************
class DistanceExceeded(Exception):
pass
class Levenshtein(object):
def __init__(self, limit):
"""
Levenshtein Distance with Maximum Distance Cutoff
Args:
limit (int): if the distance exceeds the limit, a
:class:`DistanceExceeded` is raised and the
computation is aborted.
EXAMPLES::
>>> from sage_bootstrap.levenshtein import Levenshtein
>>> lev3 = Levenshtein(3)
>>> lev3(u'saturday', u'sunday')
3
>>> lev3(u'kitten', u'sitting')
3
>>> lev2 = Levenshtein(2)
>>> lev2(u'kitten', u'sitting')
Traceback (most recent call last):
...
DistanceExceeded
"""
self._limit = limit
def __call__(self, a, b):
"""
calculate the levenshtein distance
args:
a,b (str): the two strings to compare
returns:
int: the Levenshtein distance if it is less or equal to
the distance limit.
Example::
>>> from app.scoring.levenshtein import Levenshtein
>>> lev3 = Levenshtein(3)
>>> lev3(u'Saturday', u'Sunday')
3
"""
n, m = len(a), len(b)
if n > m:
# Optimization to use O(min(n,m)) space
a, b, n, m = b, a, m, n
curr = range(n+1)
for i in range(1, m+1):
prev, curr = curr, [i]+[0]*n
for j in range(1, n+1):
cost_add, cost_del = prev[j]+1, curr[j-1]+1
cost_change = prev[j-1]
if a[j-1] != b[i-1]:
cost_change += 1
curr[j] = min(cost_add, cost_del, cost_change)
if min(curr) > self._limit:
raise DistanceExceeded
if curr[n] > self._limit:
raise DistanceExceeded
return curr[n]
|
# Time: O(logn)
# Space: O(1)
class Solution(object):
def fixedPoint(self, A):
"""
:type A: List[int]
:rtype: int
"""
left, right = 0, len(A)-1
while left <= right:
mid = left + (right-left)//2
if A[mid] >= mid:
right = mid-1
else:
left = mid+1
return left if A[left] == left else -1
|
# -*- coding: utf-8 -*-
def get_m2_name(self):
"""Return the name of the current area unit
Parameters
----------
self : Unit
A Unit object
Returns
-------
unit_name : str
Name of the current unit
"""
if self.unit_m2 == 1:
return "mm²"
else:
return "m²"
|
# model settings
model = dict(
type='ImageClassifier',
pretrained=None,
backbone=dict(
type='OmzBackboneCls',
mode='train',
model_path='public/mobilenet-v2/FP32/mobilenet-v2.xml',
last_layer_name='relu6_4',
normalized_img_input=True
),
neck=dict(
type='GlobalAveragePooling'),
head=dict(
type='LinearClsHead',
num_classes=1000,
in_channels=1280,
loss=dict(type='CrossEntropyLoss', loss_weight=1.0),
))
|
class Environment(object):
def __init__(self):
pass
def act(self, state, action):
pass
def end_state(self, state):
return True
def reset(self):
pass
def available_actions(self):
return None
|
class NodeCalculator:
@staticmethod
def calculate_node_size(node, relationships):
linked_tables = list()
size = 0
for table_key, table_value in relationships.items():
if table_key == node:
for table in relationships[table_key]:
linked_tables.append(table)
if len(linked_tables) == 0:
size = 1
return size
else:
if node in linked_tables:
linked_tables = [table for table in linked_tables if table != node]
for table in linked_tables:
for table_key, table_value in relationships.items():
if table_key == table:
for table in relationships[table_key]:
if table not in linked_tables:
linked_tables.append(table)
size = size + len(linked_tables)
return size
@staticmethod
def calculate_usage_score(node, relationships):
linked_nodes = list()
for node_key, node_value in relationships.items():
if node in node_value:
linked_nodes.append(node_key)
used_keys = list()
for node_source in linked_nodes:
for node_key, node_value in relationships.items():
if node_source in node_value and node_key not in used_keys:
linked_nodes.append(node_key)
used_keys.append(node_key)
score = len(linked_nodes)
return score
@staticmethod
def calculate_root_score_level_0(root_scores, levels, grouped_weights):
for node_level_0 in levels[0]:
for weight in grouped_weights.keys():
if node_level_0 in grouped_weights[weight]:
root_scores[node_level_0] = weight
return root_scores
@staticmethod
def list_unique_nodes(relationships):
unique_nodes = list()
for node in relationships:
unique_nodes.append(node)
for relationship in relationships:
for node in relationships[relationship]:
if node not in unique_nodes:
unique_nodes.append(node)
return unique_nodes
@staticmethod
def calculate_root_score_remaining_levels(levels, root_scores, relationships, grouped_weights):
level = 1
max_level = NodeCalculator.find_max_level(levels=levels) - 1
unique_nodes = NodeCalculator.list_unique_nodes(relationships=relationships)
while level <= max_level:
if level in levels:
for node in levels[level]:
if node in unique_nodes:
node_weight = 0
for weight in grouped_weights.keys():
if node in grouped_weights[weight]:
node_weight = weight
all_present = 1
if node in relationships:
for source in relationships[node]:
if source not in root_scores:
all_present = 0
if all_present == 1:
if node in relationships:
for source in relationships[node]:
node_weight += root_scores[source]
root_scores[node] = node_weight
level += 1
return root_scores
@staticmethod
def calculate_root_scores(levels, relationships, grouped_weights):
root_scores = dict()
root_scores = NodeCalculator.calculate_root_score_level_0(root_scores=root_scores,
grouped_weights=grouped_weights, levels=levels)
root_scores = NodeCalculator.calculate_root_score_remaining_levels(root_scores=root_scores,
grouped_weights=grouped_weights,
relationships=relationships, levels=levels)
return root_scores
@staticmethod
def undouble_list(list_objects):
list_objects = list(set(list_objects))
return list_objects
@staticmethod
def check_level(levels, level):
if len(levels[level]) > 0:
level += 1
return level
@staticmethod
def list_max_level_nodes(nodes, relationships):
max_nodes = list()
to_do_nodes = list()
for node in nodes:
present = 0
for key in relationships.keys():
if node in relationships[key]:
present = 1
if present == 0:
max_nodes.append(node)
else:
to_do_nodes.append(node)
max_nodes = NodeCalculator.undouble_list(list_objects=max_nodes)
to_do_nodes = NodeCalculator.undouble_list(list_objects=to_do_nodes)
return to_do_nodes, max_nodes
@staticmethod
def list_level_0(level, levels, golden_sources, nodes):
levels[level] = list()
to_do_nodes = list()
for node in nodes:
if node in golden_sources:
levels[level].append(node)
else:
to_do_nodes.append(node)
to_do_nodes = NodeCalculator.undouble_list(list_objects=to_do_nodes)
levels[level] = NodeCalculator.undouble_list(list_objects=levels[level])
return to_do_nodes, levels
@staticmethod
def list_level_1(level, levels, nodes, relationships, golden_sources):
levels[level] = list()
to_do_nodes = list()
for node in nodes:
if node not in relationships and node not in golden_sources:
levels[level].append(node)
else:
to_do_nodes.append(node)
to_do_nodes = NodeCalculator.undouble_list(list_objects=to_do_nodes)
levels[level] = NodeCalculator.undouble_list(list_objects=levels[level])
return to_do_nodes, levels
@staticmethod
def list_level_2(level, levels, nodes, relationships):
levels[level] = list()
to_do_nodes = list()
for node in nodes:
present = 0
for key in relationships.keys():
for source in relationships[key]:
if source in nodes:
present = 1
if present == 0:
levels[level].append(node)
else:
to_do_nodes.append(node)
to_do_nodes = NodeCalculator.undouble_list(list_objects=to_do_nodes)
levels[level] = NodeCalculator.undouble_list(list_objects=levels[level])
return to_do_nodes, levels
@staticmethod
def dict_remaining_levels(nodes, level, relationships):
to_do_levels = dict()
for node in nodes:
check_level = level
level_up_nodes = list()
for source in relationships[node]:
if source in nodes:
level_up_nodes.append(source)
for level_up_node in level_up_nodes:
check_level += 1
for source in relationships[level_up_node]:
if source in nodes and source not in level_up_nodes:
level_up_nodes.append(source)
# else:
# check_level -= 1
if check_level in to_do_levels:
to_do_levels[check_level].append(node)
else:
to_do_levels[check_level] = [node]
test = list()
for key in to_do_levels.keys():
test.append(key)
test.sort()
return to_do_levels
@staticmethod
def combine_levels(levels, to_do_levels):
levels = {**levels, **to_do_levels}
return levels
@staticmethod
def find_max_level(levels):
max_level = 0
for key in levels.keys():
if key > max_level:
max_level = key
max_level += 1
return max_level
@staticmethod
def add_max_level(levels, level, max_nodes):
levels[level] = max_nodes
return levels
@staticmethod
def calculate_levels(golden_sources, nodes, relationships):
levels = dict()
level = 0
# On level 0 only the golden sources will be placed. The golden sources are the absolute primitive of the
# hierarchy, and should thus be placed on the absolute bottom of the hierarchy.
nodes, levels = NodeCalculator.list_level_0(level=level, levels=levels, golden_sources=golden_sources,
nodes=nodes)
level = NodeCalculator.check_level(levels=levels, level=level)
# Now we first check if we can also spot the absolute root objects. An absolute root object follows these
# conditions:
# [*] Not a Golden Source
# [*] Is a key in the relationships dictionary
# [*] Is not present as a source for any of the keys in the relationships dictionary
nodes, max_nodes = NodeCalculator.list_max_level_nodes(nodes=nodes, relationships=relationships)
# On level 1, we will place all the object that follow these conditions:
# [*] Not a Golden Source
# [*] Not a key in the relationships dictionary
nodes, levels = NodeCalculator.list_level_1(level=level, levels=levels, golden_sources=golden_sources,
nodes=nodes, relationships=relationships)
level = NodeCalculator.check_level(levels=levels, level=level)
# On level 2, we will place all the object that follow these conditions:
# [*] Not a Golden Source
# [*] Is a key in the relationships dictionary
# [*] No connection with other objects, except for the objects in level 0 & 1
nodes, levels = NodeCalculator.list_level_2(level=level, levels=levels, nodes=nodes,
relationships=relationships)
level = NodeCalculator.check_level(levels=levels, level=level)
# For the remaining levels, we take the following steps for each remaining node:
# [1] Check for the remaining node's sources, if any of these sources are also present in the list of the
# remaining networkers
# [2] If former is the case, we append this source to a checklist.
# [3] We iterate over every node of this list and up the level's value by one.
# [4] During this iteration, we check if this node also has any sources that is in the first list.
# [5] If former is the case, we check if this node is not already present in the checklist. If this is not the
# case, we add it to the checklist
# [6] After all the iterations have ended, we put the level as a key to a dictionary, append the node to a list
# of this key
to_do_levels = NodeCalculator.dict_remaining_levels(nodes=nodes, level=level, relationships=relationships)
levels = NodeCalculator.combine_levels(levels=levels, to_do_levels=to_do_levels)
level = NodeCalculator.find_max_level(levels=levels)
levels = NodeCalculator.add_max_level(levels=levels, level=level, max_nodes=max_nodes)
"""
EXAMPLE:
5 'test_db_1.example_table_a'
4 'test_db_1.example_table_b'
3 'test_db_2.example_table_b'
2 'test_db_2.example_table_a', 'test_db_4.example_table_a'
1 'test_db_3.example_table_c', 'test_db_3.example_table_b', 'test_db_2.example_table_c', 'test_db_3.example_table_a'
0 'golden_source.example_table_a', 'golden_source.example_table_b'
"""
return levels
|
# Question(#1143): Given two strings text1 and text2, return the length of their longest common subsequence.
# Solution: Use the longest common susequence dynamic programming algorithm
def longestCommonSubsequence(text1: str, text2: str) -> int:
grid = [[0 for _ in range(len(text2)+1)] for _ in range(len(text1)+1)]
for i in range(1, len(text1)+1):
for j in range(1, len(text2)+1):
if text1[i-1] == text2[j-1]:
grid[i][j] = 1 + grid[i-1][j-1]
else:
grid[i][j] = max(grid[i][j-1], grid[i-1][j])
return grid[-1][-1]
|
"""
gnmi_tools - Basic GNMI operations on a device
"""
__copyright__ = "Copyright (c) 2020 Cisco Systems, Inc. and/or its affiliates"
__version__ = "0.1"
__author__ = "Marcelo Reis"
__email__ = "mareis@cisco.com"
__url__ = "https://github.com/reismarcelo/gnmi_hello"
|
class Setting:
""" Сущность: данные настроек """
def __init__(self, **kwargs):
self.day_change_time = kwargs.get('day_change_time')
self.hello_message = dict()
self.memo = dict()
self.hello_message['EN'] = kwargs.get('hello_message_EN')
self.hello_message['RU'] = kwargs.get('hello_message_RU')
self.memo['EN'] = kwargs.get('memo_EN')
self.memo['RU'] = kwargs.get('memo_RU')
self.promo_on_startup_enabled = kwargs.get('promo_on_startup_enabled')
def do_dict(self):
""" Возвращает словарь со всеми параметрами комнаты """
return self.__dict__
|
print("Let's do Factorial") #printing the operation what we are performing
def factorial(number): #defining the factorial method
result = 1 # result is intially defined with 1. if we define initially with 0 the factorial will be 0.
if number == 0: # if number is equals to 0, it prints 1.
print("The factorial of 0 is 1")
elif number < 0: # if number is negative number , it prints error message
print("Error..Enter only whole numbers")
else:
for i in range(1, number+1): # we are using range function for multiplication of numbers
result = result * i # multiplication of numbers is factorial. result is stored in result variable
print("The Factorial of" ,number, "is : ", result) # result will be printed
number = int(input("Enter the number: ")) # Input is taken from user
factorial(number) # Function is called
|
name = "glew"
version = "2.1.0"
authors = [
"Milan Ikits",
"Marcelo Magallon",
"Nigel Stewart"
]
description = \
"""
The OpenGL Extension Wrangler Library (GLEW) is a cross-platform open-source C/C++ extension loading library.
"""
requires = [
"cmake-3+",
"gcc-6+"
]
variants = [
["platform-linux"]
]
tools = [
"glewinfo",
"visualinfo"
]
build_system = "cmake"
with scope("config") as config:
config.build_thread_count = "logical_cores"
uuid = "glew-{version}".format(version=str(version))
def commands():
env.PATH.prepend("{root}/bin")
env.LD_LIBRARY_PATH.prepend("{root}/lib64")
env.PKG_CONFIG_PATH.prepend("{root}/lib64/pkgconfig")
env.CMAKE_MODULE_PATH.prepend("{root}/lib64/cmake/glew")
# Helper environment variables.
env.GLEW_BINARY_PATH.set("{root}/bin")
env.GLEW_INCLUDE_PATH.set("{root}/include")
env.GLEW_LIBRARY_PATH.set("{root}/lib64")
|
#!/usr/bin/env python
include = "$chrs".replace("[", "").replace("]", "").replace(" ", "").split(",")
ref = "$reference"
with open(ref) as ifh, open("include.bed", "w") as ofh:
for line in ifh:
toks = line.strip().split("\\t")
if toks[0] in include:
print(toks[0], 0, toks[1], sep="\\t", file=ofh)
|
# Modify the program to show the numbers from 50 to 100
x=50
while x<=100:
print(x)
x=x+1
|
# Number of queens
print("Enter the number of queens")
N = int(input())
# chessboard
# NxN matrix with all elements 0
board = [[0]*N for _ in range(N)]
def is_attack(i, j):
# checking if there is a queen in row or column
for k in range(0, N):
if board[i][k] == 1 or board[k][j] == 1:
return True
# checking diagonals
for k in range(0, N):
for l in range(0, N):
if (k+l == i+j) or (k-l == i-j):
if board[k][l] == 1:
return True
return False
def N_queen(n):
# if n is 0, solution found
if n == 0:
return True
for i in range(0, N):
for j in range(0, N):
'''checking if we can place a queen here or not
queen will not be placed if the place is being attacked
or already occupied'''
if (not(is_attack(i, j))) and (board[i][j] != 1):
board[i][j] = 1
# recursion
# wether we can put the next queen with this arrangment or not
if N_queen(n-1) == True:
return True
board[i][j] = 0
return False
N_queen(N)
for i in board:
print(i)
|
class Device(object):
"""Device.
:param id: Unique identifier for the device.
:type id: str
:param name: The name of the device.
:type name: str
"""
def __init__(self, data=None):
if data is None:
data = {}
self.id = data.get('id', None)
self.name = data.get('name', None)
|
#
# @lc app=leetcode id=297 lang=python3
#
# [297] Serialize and Deserialize Binary Tree
#
# https://leetcode.com/problems/serialize-and-deserialize-binary-tree/description/
#
# algorithms
# Hard (46.18%)
# Likes: 2721
# Dislikes: 136
# Total Accepted: 300.9K
# Total Submissions: 651K
# Testcase Example: '[1,2,3,null,null,4,5]'
#
# Serialization is the process of converting a data structure or object into a
# sequence of bits so that it can be stored in a file or memory buffer, or
# transmitted across a network connection link to be reconstructed later in the
# same or another computer environment.
#
# Design an algorithm to serialize and deserialize a binary tree. There is no
# restriction on how your serialization/deserialization algorithm should work.
# You just need to ensure that a binary tree can be serialized to a string and
# this string can be deserialized to the original tree structure.
#
# Example:
#
#
# You may serialize the following tree:
#
# 1
# / \
# 2 3
# / \
# 4 5
#
# as "[1,2,3,null,null,4,5]"
#
#
# Clarification: The above format is the same as how LeetCode serializes a
# binary tree. You do not necessarily need to follow this format, so please be
# creative and come up with different approaches yourself.
#
# Note: Do not use class member/global/static variables to store states. Your
# serialize and deserialize algorithms should be stateless.
#
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
LEFT = 0
RIGHT = 1
POSITIONS = [LEFT, RIGHT]
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
bfs = collections.deque([root])
serial_builder = []
while len(bfs) > 0:
curr = bfs.popleft()
if curr is not None:
serial_builder.append(str(curr.val))
bfs.append(curr.left)
bfs.append(curr.right)
serial_builder.append(',')
while len(serial_builder) > 0 and serial_builder[-1] == ',':
serial_builder.pop()
return ''.join(reversed(serial_builder))
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
deserial = data.split(',')
root = TreeNode(-1)
bfs = collections.deque([(root, RIGHT)])
while len(deserial) > 0:
curr_serial_val = deserial.pop()
curr_parent, insert_pos = bfs.popleft()
if curr_serial_val:
curr_val = int(curr_serial_val)
new_node = TreeNode(curr_val)
if insert_pos == LEFT:
curr_parent.left = new_node
else:
curr_parent.right = new_node
for p in POSITIONS:
bfs.append((new_node, p))
return root.right
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))
# @lc code=end
|
start_inventory = 20
num_items = start_inventory
while num_items > 0:
print("We have " + str(num_items) + " items in inventory.")
user_purchase = input("How many would you like to buy? ")
if int(user_purchase) > num_items:
print("Not Enough Stock")
else:
num_items = num_items - int(user_purchase)
print("All out!")
|
#AULA 7: OPERADORES ARITMÉTICOS
nome = input('Qual é o seu nome?\n')
print('Prazer em te conhecer, {:20}.' .format(nome))
#Com :20, posso fazer 20 espaços (centralizado).
#Além disso, posso informar a direção desses espaços com :> (direita) ou :< (esquerda).
n1 = int(input('Um valor: '))
n2 = int(input('Outro número: '))
print('A soma vale {}' .format(n1 + n2))
#Soma rápida para mostrar na tela.
n1 = int(input('Um novo valor: '))
n2 = int(input('Outro novo valor: '))
s = n1 + n2
p = n1 * n2
d = n1 / n2
di = n1 // n2
e = n1 ** n2
print(' Soma: {}\n Produto: {}\n Divisão: {:.3f}\n' .format(s, p, d), end= ' ')
print('Divisão inteira: {}\n Potência: {}\n' .format(di, e))
# end=' ' serve para não quebrar a linha.
#Para quebrar linhas em uma string, use \n.
#:.2f = duas casas decimais flutuantes (pontos)
|
# Users: Make a class called User. Create two attributes called first_name and last_name,
# and then create several other attributes that are typically stored in a user profile.
# Make a method called describe_user() that prints a summary of the user’s information.
# Make another method called greet_user() that prints a personalized greeting to the user.
# Create several instances representing different users, and call both methods for each user.
class User:
"""Creating a user"""
def __init__(self, first_name, last_name, username, email, location):
self.first_name = first_name
self.last_name = last_name
self.email = email
self.location = location
self.username = username
def describe_user(self):
"""Describing a user"""
print(f' First Name: {self.first_name.title()}')
print(f' Last Name: {self.last_name.title()}')
print(f" Username: {self.username}")
print(f" Email: {self.email}")
print(f" Location: {self.location}")
def greet_user(self):
print(f'\n Hello {self.username}!')
user1 = User('carolina', 'rolo', 'c_rolo', 'carol.rolo@hotmail.com', 'floripa')
user1.describe_user()
user1.greet_user()
user2 = User('carla', 'rolo', 'carlinha', 'carlota.rolo@hotmail.com', 'sao paulo')
user2.describe_user()
user2.greet_user()
|
first_list = range(11)
second_list = range(1,12)
ziplist = list(zip(first_list, second_list))
def square(a, b):
return (a*a) + (b*b) + 2 * a * b
# output = [square(item[0], item[1]) for item in ziplist]
output = [square(a, b) for a, b in ziplist]
print(output)
def square2(pair):
a = pair[0]
b = pair[1]
return (a*a) + (b*b) + 2 * a * b
map_list = list(map(square2, ziplist))
print(map_list)
|
class Quest:
def __init__(self, dbRow):
self.id = dbRow[0]
self.name = dbRow[1]
self.description = dbRow[2]
self.objective = dbRow[3]
self.questType = dbRow[4]
self.category = dbRow[5]
self.location = dbRow[6]
self.stars = dbRow[7]
self.zenny = dbRow[8]
def __repr__(self):
return f"{self.__dict__!r}"
|
r"""
cgtasknet is a library for training spiking neural
networks with cognitive tasks
"""
|
termination = 4000000
previous = 1
current = 2
total = 2
while(True):
new = current+ previous
previous = current
current = new
if(current >= termination):
break
if(current % 2 == 0):
total = total + current
print(total)
|
power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate Leakage': 0.00662954,
'Peak Dynamic': 0.0,
'Runtime Dynamic': 0.0,
'Subthreshold Leakage': 0.0691322,
'Subthreshold Leakage with power gating': 0.0259246},
'Core': [{'Area': 32.6082,
'Execution Unit/Area': 8.2042,
'Execution Unit/Complex ALUs/Area': 0.235435,
'Execution Unit/Complex ALUs/Gate Leakage': 0.0132646,
'Execution Unit/Complex ALUs/Peak Dynamic': 0.0980777,
'Execution Unit/Complex ALUs/Runtime Dynamic': 0.279723,
'Execution Unit/Complex ALUs/Subthreshold Leakage': 0.20111,
'Execution Unit/Complex ALUs/Subthreshold Leakage with power gating': 0.0754163,
'Execution Unit/Floating Point Units/Area': 4.6585,
'Execution Unit/Floating Point Units/Gate Leakage': 0.0656156,
'Execution Unit/Floating Point Units/Peak Dynamic': 0.394,
'Execution Unit/Floating Point Units/Runtime Dynamic': 0.304033,
'Execution Unit/Floating Point Units/Subthreshold Leakage': 0.994829,
'Execution Unit/Floating Point Units/Subthreshold Leakage with power gating': 0.373061,
'Execution Unit/Gate Leakage': 0.122718,
'Execution Unit/Instruction Scheduler/Area': 2.17927,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Area': 0.328073,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Gate Leakage': 0.00115349,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Peak Dynamic': 1.20978,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Runtime Dynamic': 0.148207,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage': 0.017004,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage with power gating': 0.00962066,
'Execution Unit/Instruction Scheduler/Gate Leakage': 0.00730101,
'Execution Unit/Instruction Scheduler/Instruction Window/Area': 1.00996,
'Execution Unit/Instruction Scheduler/Instruction Window/Gate Leakage': 0.00529112,
'Execution Unit/Instruction Scheduler/Instruction Window/Peak Dynamic': 2.07911,
'Execution Unit/Instruction Scheduler/Instruction Window/Runtime Dynamic': 0.256641,
'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage': 0.0800117,
'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage with power gating': 0.0455351,
'Execution Unit/Instruction Scheduler/Peak Dynamic': 4.84781,
'Execution Unit/Instruction Scheduler/ROB/Area': 0.841232,
'Execution Unit/Instruction Scheduler/ROB/Gate Leakage': 0.000856399,
'Execution Unit/Instruction Scheduler/ROB/Peak Dynamic': 1.55892,
'Execution Unit/Instruction Scheduler/ROB/Runtime Dynamic': 0.147191,
'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage': 0.0178624,
'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage with power gating': 0.00897339,
'Execution Unit/Instruction Scheduler/Runtime Dynamic': 0.55204,
'Execution Unit/Instruction Scheduler/Subthreshold Leakage': 0.114878,
'Execution Unit/Instruction Scheduler/Subthreshold Leakage with power gating': 0.0641291,
'Execution Unit/Integer ALUs/Area': 0.47087,
'Execution Unit/Integer ALUs/Gate Leakage': 0.0265291,
'Execution Unit/Integer ALUs/Peak Dynamic': 0.0860909,
'Execution Unit/Integer ALUs/Runtime Dynamic': 0.101344,
'Execution Unit/Integer ALUs/Subthreshold Leakage': 0.40222,
'Execution Unit/Integer ALUs/Subthreshold Leakage with power gating': 0.150833,
'Execution Unit/Peak Dynamic': 5.81603,
'Execution Unit/Register Files/Area': 0.570804,
'Execution Unit/Register Files/Floating Point RF/Area': 0.208131,
'Execution Unit/Register Files/Floating Point RF/Gate Leakage': 0.000232788,
'Execution Unit/Register Files/Floating Point RF/Peak Dynamic': 0.0744351,
'Execution Unit/Register Files/Floating Point RF/Runtime Dynamic': 0.00537263,
'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage': 0.00399698,
'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage with power gating': 0.00176968,
'Execution Unit/Register Files/Gate Leakage': 0.000622708,
'Execution Unit/Register Files/Integer RF/Area': 0.362673,
'Execution Unit/Register Files/Integer RF/Gate Leakage': 0.00038992,
'Execution Unit/Register Files/Integer RF/Peak Dynamic': 0.0810849,
'Execution Unit/Register Files/Integer RF/Runtime Dynamic': 0.0397339,
'Execution Unit/Register Files/Integer RF/Subthreshold Leakage': 0.00614175,
'Execution Unit/Register Files/Integer RF/Subthreshold Leakage with power gating': 0.00246675,
'Execution Unit/Register Files/Peak Dynamic': 0.15552,
'Execution Unit/Register Files/Runtime Dynamic': 0.0451065,
'Execution Unit/Register Files/Subthreshold Leakage': 0.0101387,
'Execution Unit/Register Files/Subthreshold Leakage with power gating': 0.00423643,
'Execution Unit/Results Broadcast Bus/Area Overhead': 0.0442632,
'Execution Unit/Results Broadcast Bus/Gate Leakage': 0.00607074,
'Execution Unit/Results Broadcast Bus/Peak Dynamic': 0.222804,
'Execution Unit/Results Broadcast Bus/Runtime Dynamic': 0.402293,
'Execution Unit/Results Broadcast Bus/Subthreshold Leakage': 0.0920413,
'Execution Unit/Results Broadcast Bus/Subthreshold Leakage with power gating': 0.0345155,
'Execution Unit/Runtime Dynamic': 1.68454,
'Execution Unit/Subthreshold Leakage': 1.83518,
'Execution Unit/Subthreshold Leakage with power gating': 0.709678,
'Gate Leakage': 0.372997,
'Instruction Fetch Unit/Area': 5.86007,
'Instruction Fetch Unit/Branch Predictor/Area': 0.138516,
'Instruction Fetch Unit/Branch Predictor/Chooser/Area': 0.0435221,
'Instruction Fetch Unit/Branch Predictor/Chooser/Gate Leakage': 0.000278362,
'Instruction Fetch Unit/Branch Predictor/Chooser/Peak Dynamic': 0.0168831,
'Instruction Fetch Unit/Branch Predictor/Chooser/Runtime Dynamic': 0.000225002,
'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage': 0.00759719,
'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage with power gating': 0.0039236,
'Instruction Fetch Unit/Branch Predictor/Gate Leakage': 0.000757657,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Area': 0.0435221,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Gate Leakage': 0.000278362,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Peak Dynamic': 0.0168831,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Runtime Dynamic': 0.000225002,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage': 0.00759719,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage with power gating': 0.0039236,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Area': 0.0257064,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Gate Leakage': 0.000154548,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Peak Dynamic': 0.0142575,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Runtime Dynamic': 0.000194444,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage': 0.00384344,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage with power gating': 0.00198631,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Area': 0.0151917,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Gate Leakage': 8.00196e-05,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Peak Dynamic': 0.00527447,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Runtime Dynamic': 7.44341e-05,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage': 0.00181347,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage with power gating': 0.000957045,
'Instruction Fetch Unit/Branch Predictor/Peak Dynamic': 0.0597838,
'Instruction Fetch Unit/Branch Predictor/RAS/Area': 0.0105732,
'Instruction Fetch Unit/Branch Predictor/RAS/Gate Leakage': 4.63858e-05,
'Instruction Fetch Unit/Branch Predictor/RAS/Peak Dynamic': 0.0117602,
'Instruction Fetch Unit/Branch Predictor/RAS/Runtime Dynamic': 0.000570781,
'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage': 0.000932505,
'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage with power gating': 0.000494733,
'Instruction Fetch Unit/Branch Predictor/Runtime Dynamic': 0.00121523,
'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage': 0.0199703,
'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage with power gating': 0.0103282,
'Instruction Fetch Unit/Branch Target Buffer/Area': 0.64954,
'Instruction Fetch Unit/Branch Target Buffer/Gate Leakage': 0.00272758,
'Instruction Fetch Unit/Branch Target Buffer/Peak Dynamic': 0.177867,
'Instruction Fetch Unit/Branch Target Buffer/Runtime Dynamic': 0.00221206,
'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage': 0.0811682,
'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage with power gating': 0.0435357,
'Instruction Fetch Unit/Gate Leakage': 0.0590479,
'Instruction Fetch Unit/Instruction Buffer/Area': 0.0226323,
'Instruction Fetch Unit/Instruction Buffer/Gate Leakage': 6.83558e-05,
'Instruction Fetch Unit/Instruction Buffer/Peak Dynamic': 0.606827,
'Instruction Fetch Unit/Instruction Buffer/Runtime Dynamic': 0.0381972,
'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage': 0.00151885,
'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage with power gating': 0.000701682,
'Instruction Fetch Unit/Instruction Cache/Area': 3.14635,
'Instruction Fetch Unit/Instruction Cache/Gate Leakage': 0.029931,
'Instruction Fetch Unit/Instruction Cache/Peak Dynamic': 2.42967,
'Instruction Fetch Unit/Instruction Cache/Runtime Dynamic': 0.0551552,
'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage': 0.367022,
'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage with power gating': 0.180386,
'Instruction Fetch Unit/Instruction Decoder/Area': 1.85799,
'Instruction Fetch Unit/Instruction Decoder/Gate Leakage': 0.0222493,
'Instruction Fetch Unit/Instruction Decoder/Peak Dynamic': 1.37404,
'Instruction Fetch Unit/Instruction Decoder/Runtime Dynamic': 0.129735,
'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage': 0.442943,
'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage with power gating': 0.166104,
'Instruction Fetch Unit/Peak Dynamic': 4.76791,
'Instruction Fetch Unit/Runtime Dynamic': 0.226515,
'Instruction Fetch Unit/Subthreshold Leakage': 0.932587,
'Instruction Fetch Unit/Subthreshold Leakage with power gating': 0.408542,
'L2/Area': 4.53318,
'L2/Gate Leakage': 0.015464,
'L2/Peak Dynamic': 0.0140516,
'L2/Runtime Dynamic': 0.00517116,
'L2/Subthreshold Leakage': 0.834142,
'L2/Subthreshold Leakage with power gating': 0.401066,
'Load Store Unit/Area': 8.80969,
'Load Store Unit/Data Cache/Area': 6.84535,
'Load Store Unit/Data Cache/Gate Leakage': 0.0279261,
'Load Store Unit/Data Cache/Peak Dynamic': 1.57809,
'Load Store Unit/Data Cache/Runtime Dynamic': 0.182297,
'Load Store Unit/Data Cache/Subthreshold Leakage': 0.527675,
'Load Store Unit/Data Cache/Subthreshold Leakage with power gating': 0.25085,
'Load Store Unit/Gate Leakage': 0.0351387,
'Load Store Unit/LoadQ/Area': 0.0836782,
'Load Store Unit/LoadQ/Gate Leakage': 0.00059896,
'Load Store Unit/LoadQ/Peak Dynamic': 0.0110311,
'Load Store Unit/LoadQ/Runtime Dynamic': 0.0110311,
'Load Store Unit/LoadQ/Subthreshold Leakage': 0.00941961,
'Load Store Unit/LoadQ/Subthreshold Leakage with power gating': 0.00536918,
'Load Store Unit/Peak Dynamic': 1.63039,
'Load Store Unit/Runtime Dynamic': 0.247729,
'Load Store Unit/StoreQ/Area': 0.322079,
'Load Store Unit/StoreQ/Gate Leakage': 0.00329971,
'Load Store Unit/StoreQ/Peak Dynamic': 0.0272009,
'Load Store Unit/StoreQ/Runtime Dynamic': 0.0544015,
'Load Store Unit/StoreQ/Subthreshold Leakage': 0.0345621,
'Load Store Unit/StoreQ/Subthreshold Leakage with power gating': 0.0197004,
'Load Store Unit/Subthreshold Leakage': 0.591622,
'Load Store Unit/Subthreshold Leakage with power gating': 0.283406,
'Memory Management Unit/Area': 0.434579,
'Memory Management Unit/Dtlb/Area': 0.0879726,
'Memory Management Unit/Dtlb/Gate Leakage': 0.00088729,
'Memory Management Unit/Dtlb/Peak Dynamic': 0.0096537,
'Memory Management Unit/Dtlb/Runtime Dynamic': 0.00986453,
'Memory Management Unit/Dtlb/Subthreshold Leakage': 0.0155699,
'Memory Management Unit/Dtlb/Subthreshold Leakage with power gating': 0.00887485,
'Memory Management Unit/Gate Leakage': 0.00813591,
'Memory Management Unit/Itlb/Area': 0.301552,
'Memory Management Unit/Itlb/Gate Leakage': 0.00393464,
'Memory Management Unit/Itlb/Peak Dynamic': 0.151068,
'Memory Management Unit/Itlb/Runtime Dynamic': 0.00904231,
'Memory Management Unit/Itlb/Subthreshold Leakage': 0.0413758,
'Memory Management Unit/Itlb/Subthreshold Leakage with power gating': 0.0235842,
'Memory Management Unit/Peak Dynamic': 0.326256,
'Memory Management Unit/Runtime Dynamic': 0.0189068,
'Memory Management Unit/Subthreshold Leakage': 0.0769113,
'Memory Management Unit/Subthreshold Leakage with power gating': 0.0399462,
'Peak Dynamic': 17.1163,
'Renaming Unit/Area': 0.369768,
'Renaming Unit/FP Front End RAT/Area': 0.168486,
'Renaming Unit/FP Front End RAT/Gate Leakage': 0.00489731,
'Renaming Unit/FP Front End RAT/Peak Dynamic': 3.33511,
'Renaming Unit/FP Front End RAT/Runtime Dynamic': 0.259687,
'Renaming Unit/FP Front End RAT/Subthreshold Leakage': 0.0437281,
'Renaming Unit/FP Front End RAT/Subthreshold Leakage with power gating': 0.024925,
'Renaming Unit/Free List/Area': 0.0414755,
'Renaming Unit/Free List/Gate Leakage': 4.15911e-05,
'Renaming Unit/Free List/Peak Dynamic': 0.0401324,
'Renaming Unit/Free List/Runtime Dynamic': 0.0107034,
'Renaming Unit/Free List/Subthreshold Leakage': 0.000670426,
'Renaming Unit/Free List/Subthreshold Leakage with power gating': 0.000377987,
'Renaming Unit/Gate Leakage': 0.00863632,
'Renaming Unit/Int Front End RAT/Area': 0.114751,
'Renaming Unit/Int Front End RAT/Gate Leakage': 0.00038343,
'Renaming Unit/Int Front End RAT/Peak Dynamic': 0.86945,
'Renaming Unit/Int Front End RAT/Runtime Dynamic': 0.0719334,
'Renaming Unit/Int Front End RAT/Subthreshold Leakage': 0.00611897,
'Renaming Unit/Int Front End RAT/Subthreshold Leakage with power gating': 0.00348781,
'Renaming Unit/Peak Dynamic': 4.56169,
'Renaming Unit/Runtime Dynamic': 0.342324,
'Renaming Unit/Subthreshold Leakage': 0.070483,
'Renaming Unit/Subthreshold Leakage with power gating': 0.0362779,
'Runtime Dynamic': 2.52519,
'Subthreshold Leakage': 6.21877,
'Subthreshold Leakage with power gating': 2.58311},
{'Area': 32.0201,
'Execution Unit/Area': 7.68434,
'Execution Unit/Complex ALUs/Area': 0.235435,
'Execution Unit/Complex ALUs/Gate Leakage': 0.0132646,
'Execution Unit/Complex ALUs/Peak Dynamic': 0.0982865,
'Execution Unit/Complex ALUs/Runtime Dynamic': 0.279887,
'Execution Unit/Complex ALUs/Subthreshold Leakage': 0.20111,
'Execution Unit/Complex ALUs/Subthreshold Leakage with power gating': 0.0754163,
'Execution Unit/Floating Point Units/Area': 4.6585,
'Execution Unit/Floating Point Units/Gate Leakage': 0.0656156,
'Execution Unit/Floating Point Units/Peak Dynamic': 0.394843,
'Execution Unit/Floating Point Units/Runtime Dynamic': 0.304033,
'Execution Unit/Floating Point Units/Subthreshold Leakage': 0.994829,
'Execution Unit/Floating Point Units/Subthreshold Leakage with power gating': 0.373061,
'Execution Unit/Gate Leakage': 0.120359,
'Execution Unit/Instruction Scheduler/Area': 1.66526,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Area': 0.275653,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Gate Leakage': 0.000977433,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Peak Dynamic': 1.04181,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Runtime Dynamic': 0.123408,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage': 0.0143453,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage with power gating': 0.00810519,
'Execution Unit/Instruction Scheduler/Gate Leakage': 0.00568913,
'Execution Unit/Instruction Scheduler/Instruction Window/Area': 0.805223,
'Execution Unit/Instruction Scheduler/Instruction Window/Gate Leakage': 0.00414562,
'Execution Unit/Instruction Scheduler/Instruction Window/Peak Dynamic': 1.6763,
'Execution Unit/Instruction Scheduler/Instruction Window/Runtime Dynamic': 0.199053,
'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage': 0.0625755,
'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage with power gating': 0.0355964,
'Execution Unit/Instruction Scheduler/Peak Dynamic': 3.82262,
'Execution Unit/Instruction Scheduler/ROB/Area': 0.584388,
'Execution Unit/Instruction Scheduler/ROB/Gate Leakage': 0.00056608,
'Execution Unit/Instruction Scheduler/ROB/Peak Dynamic': 1.10451,
'Execution Unit/Instruction Scheduler/ROB/Runtime Dynamic': 0.100475,
'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage': 0.00906853,
'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage with power gating': 0.00364446,
'Execution Unit/Instruction Scheduler/Runtime Dynamic': 0.422937,
'Execution Unit/Instruction Scheduler/Subthreshold Leakage': 0.0859892,
'Execution Unit/Instruction Scheduler/Subthreshold Leakage with power gating': 0.047346,
'Execution Unit/Integer ALUs/Area': 0.47087,
'Execution Unit/Integer ALUs/Gate Leakage': 0.0265291,
'Execution Unit/Integer ALUs/Peak Dynamic': 0.0806077,
'Execution Unit/Integer ALUs/Runtime Dynamic': 0.101344,
'Execution Unit/Integer ALUs/Subthreshold Leakage': 0.40222,
'Execution Unit/Integer ALUs/Subthreshold Leakage with power gating': 0.150833,
'Execution Unit/Peak Dynamic': 4.75412,
'Execution Unit/Register Files/Area': 0.570804,
'Execution Unit/Register Files/Floating Point RF/Area': 0.208131,
'Execution Unit/Register Files/Floating Point RF/Gate Leakage': 0.000232788,
'Execution Unit/Register Files/Floating Point RF/Peak Dynamic': 0.0745942,
'Execution Unit/Register Files/Floating Point RF/Runtime Dynamic': 0.0051763,
'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage': 0.00399698,
'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage with power gating': 0.00176968,
'Execution Unit/Register Files/Gate Leakage': 0.000622708,
'Execution Unit/Register Files/Integer RF/Area': 0.362673,
'Execution Unit/Register Files/Integer RF/Gate Leakage': 0.00038992,
'Execution Unit/Register Files/Integer RF/Peak Dynamic': 0.0797547,
'Execution Unit/Register Files/Integer RF/Runtime Dynamic': 0.0382819,
'Execution Unit/Register Files/Integer RF/Subthreshold Leakage': 0.00614175,
'Execution Unit/Register Files/Integer RF/Subthreshold Leakage with power gating': 0.00246675,
'Execution Unit/Register Files/Peak Dynamic': 0.154349,
'Execution Unit/Register Files/Runtime Dynamic': 0.0434582,
'Execution Unit/Register Files/Subthreshold Leakage': 0.0101387,
'Execution Unit/Register Files/Subthreshold Leakage with power gating': 0.00423643,
'Execution Unit/Results Broadcast Bus/Area Overhead': 0.0390912,
'Execution Unit/Results Broadcast Bus/Gate Leakage': 0.00537402,
'Execution Unit/Results Broadcast Bus/Peak Dynamic': 0.192598,
'Execution Unit/Results Broadcast Bus/Runtime Dynamic': 0.345046,
'Execution Unit/Results Broadcast Bus/Subthreshold Leakage': 0.081478,
'Execution Unit/Results Broadcast Bus/Subthreshold Leakage with power gating': 0.0305543,
'Execution Unit/Runtime Dynamic': 1.49671,
'Execution Unit/Subthreshold Leakage': 1.79543,
'Execution Unit/Subthreshold Leakage with power gating': 0.688821,
'Gate Leakage': 0.368936,
'Instruction Fetch Unit/Area': 5.85939,
'Instruction Fetch Unit/Branch Predictor/Area': 0.138516,
'Instruction Fetch Unit/Branch Predictor/Chooser/Area': 0.0435221,
'Instruction Fetch Unit/Branch Predictor/Chooser/Gate Leakage': 0.000278362,
'Instruction Fetch Unit/Branch Predictor/Chooser/Peak Dynamic': 0.0168831,
'Instruction Fetch Unit/Branch Predictor/Chooser/Runtime Dynamic': 0.000196117,
'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage': 0.00759719,
'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage with power gating': 0.0039236,
'Instruction Fetch Unit/Branch Predictor/Gate Leakage': 0.000757657,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Area': 0.0435221,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Gate Leakage': 0.000278362,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Peak Dynamic': 0.0168831,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Runtime Dynamic': 0.000196117,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage': 0.00759719,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage with power gating': 0.0039236,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Area': 0.0257064,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Gate Leakage': 0.000154548,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Peak Dynamic': 0.0142575,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Runtime Dynamic': 0.000169484,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage': 0.00384344,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage with power gating': 0.00198631,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Area': 0.0151917,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Gate Leakage': 8.00196e-05,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Peak Dynamic': 0.00527447,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Runtime Dynamic': 6.48802e-05,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage': 0.00181347,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage with power gating': 0.000957045,
'Instruction Fetch Unit/Branch Predictor/Peak Dynamic': 0.0597838,
'Instruction Fetch Unit/Branch Predictor/RAS/Area': 0.0105732,
'Instruction Fetch Unit/Branch Predictor/RAS/Gate Leakage': 4.63858e-05,
'Instruction Fetch Unit/Branch Predictor/RAS/Peak Dynamic': 0.0117602,
'Instruction Fetch Unit/Branch Predictor/RAS/Runtime Dynamic': 0.000549923,
'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage': 0.000932505,
'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage with power gating': 0.000494733,
'Instruction Fetch Unit/Branch Predictor/Runtime Dynamic': 0.00111164,
'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage': 0.0199703,
'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage with power gating': 0.0103282,
'Instruction Fetch Unit/Branch Target Buffer/Area': 0.64954,
'Instruction Fetch Unit/Branch Target Buffer/Gate Leakage': 0.00272758,
'Instruction Fetch Unit/Branch Target Buffer/Peak Dynamic': 0.177867,
'Instruction Fetch Unit/Branch Target Buffer/Runtime Dynamic': 0.00192802,
'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage': 0.0811682,
'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage with power gating': 0.0435357,
'Instruction Fetch Unit/Gate Leakage': 0.0589979,
'Instruction Fetch Unit/Instruction Buffer/Area': 0.0226323,
'Instruction Fetch Unit/Instruction Buffer/Gate Leakage': 6.83558e-05,
'Instruction Fetch Unit/Instruction Buffer/Peak Dynamic': 0.606827,
'Instruction Fetch Unit/Instruction Buffer/Runtime Dynamic': 0.0368014,
'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage': 0.00151885,
'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage with power gating': 0.000701682,
'Instruction Fetch Unit/Instruction Cache/Area': 3.14635,
'Instruction Fetch Unit/Instruction Cache/Gate Leakage': 0.029931,
'Instruction Fetch Unit/Instruction Cache/Peak Dynamic': 2.34089,
'Instruction Fetch Unit/Instruction Cache/Runtime Dynamic': 0.0552637,
'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage': 0.367022,
'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage with power gating': 0.180386,
'Instruction Fetch Unit/Instruction Decoder/Area': 1.85799,
'Instruction Fetch Unit/Instruction Decoder/Gate Leakage': 0.0222493,
'Instruction Fetch Unit/Instruction Decoder/Peak Dynamic': 1.37404,
'Instruction Fetch Unit/Instruction Decoder/Runtime Dynamic': 0.124994,
'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage': 0.442943,
'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage with power gating': 0.166104,
'Instruction Fetch Unit/Peak Dynamic': 4.67301,
'Instruction Fetch Unit/Runtime Dynamic': 0.220099,
'Instruction Fetch Unit/Subthreshold Leakage': 0.932286,
'Instruction Fetch Unit/Subthreshold Leakage with power gating': 0.40843,
'L2/Area': 4.53318,
'L2/Gate Leakage': 0.015464,
'L2/Peak Dynamic': 0.0129726,
'L2/Runtime Dynamic': 0.00485966,
'L2/Subthreshold Leakage': 0.834142,
'L2/Subthreshold Leakage with power gating': 0.401066,
'Load Store Unit/Area': 8.80901,
'Load Store Unit/Data Cache/Area': 6.84535,
'Load Store Unit/Data Cache/Gate Leakage': 0.0279261,
'Load Store Unit/Data Cache/Peak Dynamic': 1.53514,
'Load Store Unit/Data Cache/Runtime Dynamic': 0.160709,
'Load Store Unit/Data Cache/Subthreshold Leakage': 0.527675,
'Load Store Unit/Data Cache/Subthreshold Leakage with power gating': 0.25085,
'Load Store Unit/Gate Leakage': 0.0350888,
'Load Store Unit/LoadQ/Area': 0.0836782,
'Load Store Unit/LoadQ/Gate Leakage': 0.00059896,
'Load Store Unit/LoadQ/Peak Dynamic': 0.00964176,
'Load Store Unit/LoadQ/Runtime Dynamic': 0.00964166,
'Load Store Unit/LoadQ/Subthreshold Leakage': 0.00941961,
'Load Store Unit/LoadQ/Subthreshold Leakage with power gating': 0.00536918,
'Load Store Unit/Peak Dynamic': 1.58067,
'Load Store Unit/Runtime Dynamic': 0.2179,
'Load Store Unit/StoreQ/Area': 0.322079,
'Load Store Unit/StoreQ/Gate Leakage': 0.00329971,
'Load Store Unit/StoreQ/Peak Dynamic': 0.0237749,
'Load Store Unit/StoreQ/Runtime Dynamic': 0.0475494,
'Load Store Unit/StoreQ/Subthreshold Leakage': 0.0345621,
'Load Store Unit/StoreQ/Subthreshold Leakage with power gating': 0.0197004,
'Load Store Unit/Subthreshold Leakage': 0.591321,
'Load Store Unit/Subthreshold Leakage with power gating': 0.283293,
'Memory Management Unit/Area': 0.4339,
'Memory Management Unit/Dtlb/Area': 0.0879726,
'Memory Management Unit/Dtlb/Gate Leakage': 0.00088729,
'Memory Management Unit/Dtlb/Peak Dynamic': 0.0084378,
'Memory Management Unit/Dtlb/Runtime Dynamic': 0.00863242,
'Memory Management Unit/Dtlb/Subthreshold Leakage': 0.0155699,
'Memory Management Unit/Dtlb/Subthreshold Leakage with power gating': 0.00887485,
'Memory Management Unit/Gate Leakage': 0.00808595,
'Memory Management Unit/Itlb/Area': 0.301552,
'Memory Management Unit/Itlb/Gate Leakage': 0.00393464,
'Memory Management Unit/Itlb/Peak Dynamic': 0.145548,
'Memory Management Unit/Itlb/Runtime Dynamic': 0.00906,
'Memory Management Unit/Itlb/Subthreshold Leakage': 0.0413758,
'Memory Management Unit/Itlb/Subthreshold Leakage with power gating': 0.0235842,
'Memory Management Unit/Peak Dynamic': 0.316151,
'Memory Management Unit/Runtime Dynamic': 0.0176924,
'Memory Management Unit/Subthreshold Leakage': 0.0766103,
'Memory Management Unit/Subthreshold Leakage with power gating': 0.0398333,
'Peak Dynamic': 14.9264,
'Renaming Unit/Area': 0.303608,
'Renaming Unit/FP Front End RAT/Area': 0.131045,
'Renaming Unit/FP Front End RAT/Gate Leakage': 0.00351123,
'Renaming Unit/FP Front End RAT/Peak Dynamic': 2.51468,
'Renaming Unit/FP Front End RAT/Runtime Dynamic': 0.196223,
'Renaming Unit/FP Front End RAT/Subthreshold Leakage': 0.0308571,
'Renaming Unit/FP Front End RAT/Subthreshold Leakage with power gating': 0.0175885,
'Renaming Unit/Free List/Area': 0.0340654,
'Renaming Unit/Free List/Gate Leakage': 2.5481e-05,
'Renaming Unit/Free List/Peak Dynamic': 0.0306032,
'Renaming Unit/Free List/Runtime Dynamic': 0.00795584,
'Renaming Unit/Free List/Subthreshold Leakage': 0.000370144,
'Renaming Unit/Free List/Subthreshold Leakage with power gating': 0.000201064,
'Renaming Unit/Gate Leakage': 0.00708398,
'Renaming Unit/Int Front End RAT/Area': 0.0941223,
'Renaming Unit/Int Front End RAT/Gate Leakage': 0.000283242,
'Renaming Unit/Int Front End RAT/Peak Dynamic': 0.731965,
'Renaming Unit/Int Front End RAT/Runtime Dynamic': 0.0588229,
'Renaming Unit/Int Front End RAT/Subthreshold Leakage': 0.00435488,
'Renaming Unit/Int Front End RAT/Subthreshold Leakage with power gating': 0.00248228,
'Renaming Unit/Peak Dynamic': 3.58947,
'Renaming Unit/Runtime Dynamic': 0.263002,
'Renaming Unit/Subthreshold Leakage': 0.0552466,
'Renaming Unit/Subthreshold Leakage with power gating': 0.0276461,
'Runtime Dynamic': 2.22026,
'Subthreshold Leakage': 6.16288,
'Subthreshold Leakage with power gating': 2.55328},
{'Area': 32.0201,
'Execution Unit/Area': 7.68434,
'Execution Unit/Complex ALUs/Area': 0.235435,
'Execution Unit/Complex ALUs/Gate Leakage': 0.0132646,
'Execution Unit/Complex ALUs/Peak Dynamic': 0.0978179,
'Execution Unit/Complex ALUs/Runtime Dynamic': 0.279519,
'Execution Unit/Complex ALUs/Subthreshold Leakage': 0.20111,
'Execution Unit/Complex ALUs/Subthreshold Leakage with power gating': 0.0754163,
'Execution Unit/Floating Point Units/Area': 4.6585,
'Execution Unit/Floating Point Units/Gate Leakage': 0.0656156,
'Execution Unit/Floating Point Units/Peak Dynamic': 0.392958,
'Execution Unit/Floating Point Units/Runtime Dynamic': 0.304033,
'Execution Unit/Floating Point Units/Subthreshold Leakage': 0.994829,
'Execution Unit/Floating Point Units/Subthreshold Leakage with power gating': 0.373061,
'Execution Unit/Gate Leakage': 0.120359,
'Execution Unit/Instruction Scheduler/Area': 1.66526,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Area': 0.275653,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Gate Leakage': 0.000977433,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Peak Dynamic': 1.04181,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Runtime Dynamic': 0.123829,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage': 0.0143453,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage with power gating': 0.00810519,
'Execution Unit/Instruction Scheduler/Gate Leakage': 0.00568913,
'Execution Unit/Instruction Scheduler/Instruction Window/Area': 0.805223,
'Execution Unit/Instruction Scheduler/Instruction Window/Gate Leakage': 0.00414562,
'Execution Unit/Instruction Scheduler/Instruction Window/Peak Dynamic': 1.6763,
'Execution Unit/Instruction Scheduler/Instruction Window/Runtime Dynamic': 0.199732,
'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage': 0.0625755,
'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage with power gating': 0.0355964,
'Execution Unit/Instruction Scheduler/Peak Dynamic': 3.82262,
'Execution Unit/Instruction Scheduler/ROB/Area': 0.584388,
'Execution Unit/Instruction Scheduler/ROB/Gate Leakage': 0.00056608,
'Execution Unit/Instruction Scheduler/ROB/Peak Dynamic': 1.10451,
'Execution Unit/Instruction Scheduler/ROB/Runtime Dynamic': 0.100818,
'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage': 0.00906853,
'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage with power gating': 0.00364446,
'Execution Unit/Instruction Scheduler/Runtime Dynamic': 0.424379,
'Execution Unit/Instruction Scheduler/Subthreshold Leakage': 0.0859892,
'Execution Unit/Instruction Scheduler/Subthreshold Leakage with power gating': 0.047346,
'Execution Unit/Integer ALUs/Area': 0.47087,
'Execution Unit/Integer ALUs/Gate Leakage': 0.0265291,
'Execution Unit/Integer ALUs/Peak Dynamic': 0.081378,
'Execution Unit/Integer ALUs/Runtime Dynamic': 0.101344,
'Execution Unit/Integer ALUs/Subthreshold Leakage': 0.40222,
'Execution Unit/Integer ALUs/Subthreshold Leakage with power gating': 0.150833,
'Execution Unit/Peak Dynamic': 4.75194,
'Execution Unit/Register Files/Area': 0.570804,
'Execution Unit/Register Files/Floating Point RF/Area': 0.208131,
'Execution Unit/Register Files/Floating Point RF/Gate Leakage': 0.000232788,
'Execution Unit/Register Files/Floating Point RF/Peak Dynamic': 0.0742381,
'Execution Unit/Register Files/Floating Point RF/Runtime Dynamic': 0.00519396,
'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage': 0.00399698,
'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage with power gating': 0.00176968,
'Execution Unit/Register Files/Gate Leakage': 0.000622708,
'Execution Unit/Register Files/Integer RF/Area': 0.362673,
'Execution Unit/Register Files/Integer RF/Gate Leakage': 0.00038992,
'Execution Unit/Register Files/Integer RF/Peak Dynamic': 0.0796807,
'Execution Unit/Register Files/Integer RF/Runtime Dynamic': 0.0384125,
'Execution Unit/Register Files/Integer RF/Subthreshold Leakage': 0.00614175,
'Execution Unit/Register Files/Integer RF/Subthreshold Leakage with power gating': 0.00246675,
'Execution Unit/Register Files/Peak Dynamic': 0.153919,
'Execution Unit/Register Files/Runtime Dynamic': 0.0436065,
'Execution Unit/Register Files/Subthreshold Leakage': 0.0101387,
'Execution Unit/Register Files/Subthreshold Leakage with power gating': 0.00423643,
'Execution Unit/Results Broadcast Bus/Area Overhead': 0.0390912,
'Execution Unit/Results Broadcast Bus/Gate Leakage': 0.00537402,
'Execution Unit/Results Broadcast Bus/Peak Dynamic': 0.192325,
'Execution Unit/Results Broadcast Bus/Runtime Dynamic': 0.345489,
'Execution Unit/Results Broadcast Bus/Subthreshold Leakage': 0.081478,
'Execution Unit/Results Broadcast Bus/Subthreshold Leakage with power gating': 0.0305543,
'Execution Unit/Runtime Dynamic': 1.49837,
'Execution Unit/Subthreshold Leakage': 1.79543,
'Execution Unit/Subthreshold Leakage with power gating': 0.688821,
'Gate Leakage': 0.368936,
'Instruction Fetch Unit/Area': 5.85939,
'Instruction Fetch Unit/Branch Predictor/Area': 0.138516,
'Instruction Fetch Unit/Branch Predictor/Chooser/Area': 0.0435221,
'Instruction Fetch Unit/Branch Predictor/Chooser/Gate Leakage': 0.000278362,
'Instruction Fetch Unit/Branch Predictor/Chooser/Peak Dynamic': 0.0168831,
'Instruction Fetch Unit/Branch Predictor/Chooser/Runtime Dynamic': 0.000199387,
'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage': 0.00759719,
'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage with power gating': 0.0039236,
'Instruction Fetch Unit/Branch Predictor/Gate Leakage': 0.000757657,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Area': 0.0435221,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Gate Leakage': 0.000278362,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Peak Dynamic': 0.0168831,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Runtime Dynamic': 0.000199387,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage': 0.00759719,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage with power gating': 0.0039236,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Area': 0.0257064,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Gate Leakage': 0.000154548,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Peak Dynamic': 0.0142575,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Runtime Dynamic': 0.000172309,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage': 0.00384344,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage with power gating': 0.00198631,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Area': 0.0151917,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Gate Leakage': 8.00196e-05,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Peak Dynamic': 0.00527447,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Runtime Dynamic': 6.59614e-05,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage': 0.00181347,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage with power gating': 0.000957045,
'Instruction Fetch Unit/Branch Predictor/Peak Dynamic': 0.0597838,
'Instruction Fetch Unit/Branch Predictor/RAS/Area': 0.0105732,
'Instruction Fetch Unit/Branch Predictor/RAS/Gate Leakage': 4.63858e-05,
'Instruction Fetch Unit/Branch Predictor/RAS/Peak Dynamic': 0.0117602,
'Instruction Fetch Unit/Branch Predictor/RAS/Runtime Dynamic': 0.000551799,
'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage': 0.000932505,
'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage with power gating': 0.000494733,
'Instruction Fetch Unit/Branch Predictor/Runtime Dynamic': 0.00112288,
'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage': 0.0199703,
'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage with power gating': 0.0103282,
'Instruction Fetch Unit/Branch Target Buffer/Area': 0.64954,
'Instruction Fetch Unit/Branch Target Buffer/Gate Leakage': 0.00272758,
'Instruction Fetch Unit/Branch Target Buffer/Peak Dynamic': 0.177867,
'Instruction Fetch Unit/Branch Target Buffer/Runtime Dynamic': 0.0019602,
'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage': 0.0811682,
'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage with power gating': 0.0435357,
'Instruction Fetch Unit/Gate Leakage': 0.0589979,
'Instruction Fetch Unit/Instruction Buffer/Area': 0.0226323,
'Instruction Fetch Unit/Instruction Buffer/Gate Leakage': 6.83558e-05,
'Instruction Fetch Unit/Instruction Buffer/Peak Dynamic': 0.606827,
'Instruction Fetch Unit/Instruction Buffer/Runtime Dynamic': 0.0369269,
'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage': 0.00151885,
'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage with power gating': 0.000701682,
'Instruction Fetch Unit/Instruction Cache/Area': 3.14635,
'Instruction Fetch Unit/Instruction Cache/Gate Leakage': 0.029931,
'Instruction Fetch Unit/Instruction Cache/Peak Dynamic': 2.34887,
'Instruction Fetch Unit/Instruction Cache/Runtime Dynamic': 0.0549932,
'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage': 0.367022,
'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage with power gating': 0.180386,
'Instruction Fetch Unit/Instruction Decoder/Area': 1.85799,
'Instruction Fetch Unit/Instruction Decoder/Gate Leakage': 0.0222493,
'Instruction Fetch Unit/Instruction Decoder/Peak Dynamic': 1.37404,
'Instruction Fetch Unit/Instruction Decoder/Runtime Dynamic': 0.12542,
'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage': 0.442943,
'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage with power gating': 0.166104,
'Instruction Fetch Unit/Peak Dynamic': 4.68138,
'Instruction Fetch Unit/Runtime Dynamic': 0.220424,
'Instruction Fetch Unit/Subthreshold Leakage': 0.932286,
'Instruction Fetch Unit/Subthreshold Leakage with power gating': 0.40843,
'L2/Area': 4.53318,
'L2/Gate Leakage': 0.015464,
'L2/Peak Dynamic': 0.013049,
'L2/Runtime Dynamic': 0.0049262,
'L2/Subthreshold Leakage': 0.834142,
'L2/Subthreshold Leakage with power gating': 0.401066,
'Load Store Unit/Area': 8.80901,
'Load Store Unit/Data Cache/Area': 6.84535,
'Load Store Unit/Data Cache/Gate Leakage': 0.0279261,
'Load Store Unit/Data Cache/Peak Dynamic': 1.54336,
'Load Store Unit/Data Cache/Runtime Dynamic': 0.164681,
'Load Store Unit/Data Cache/Subthreshold Leakage': 0.527675,
'Load Store Unit/Data Cache/Subthreshold Leakage with power gating': 0.25085,
'Load Store Unit/Gate Leakage': 0.0350888,
'Load Store Unit/LoadQ/Area': 0.0836782,
'Load Store Unit/LoadQ/Gate Leakage': 0.00059896,
'Load Store Unit/LoadQ/Peak Dynamic': 0.00990766,
'Load Store Unit/LoadQ/Runtime Dynamic': 0.00990762,
'Load Store Unit/LoadQ/Subthreshold Leakage': 0.00941961,
'Load Store Unit/LoadQ/Subthreshold Leakage with power gating': 0.00536918,
'Load Store Unit/Peak Dynamic': 1.59015,
'Load Store Unit/Runtime Dynamic': 0.22345,
'Load Store Unit/StoreQ/Area': 0.322079,
'Load Store Unit/StoreQ/Gate Leakage': 0.00329971,
'Load Store Unit/StoreQ/Peak Dynamic': 0.0244306,
'Load Store Unit/StoreQ/Runtime Dynamic': 0.048861,
'Load Store Unit/StoreQ/Subthreshold Leakage': 0.0345621,
'Load Store Unit/StoreQ/Subthreshold Leakage with power gating': 0.0197004,
'Load Store Unit/Subthreshold Leakage': 0.591321,
'Load Store Unit/Subthreshold Leakage with power gating': 0.283293,
'Memory Management Unit/Area': 0.4339,
'Memory Management Unit/Dtlb/Area': 0.0879726,
'Memory Management Unit/Dtlb/Gate Leakage': 0.00088729,
'Memory Management Unit/Dtlb/Peak Dynamic': 0.0086705,
'Memory Management Unit/Dtlb/Runtime Dynamic': 0.00886632,
'Memory Management Unit/Dtlb/Subthreshold Leakage': 0.0155699,
'Memory Management Unit/Dtlb/Subthreshold Leakage with power gating': 0.00887485,
'Memory Management Unit/Gate Leakage': 0.00808595,
'Memory Management Unit/Itlb/Area': 0.301552,
'Memory Management Unit/Itlb/Gate Leakage': 0.00393464,
'Memory Management Unit/Itlb/Peak Dynamic': 0.146044,
'Memory Management Unit/Itlb/Runtime Dynamic': 0.00901559,
'Memory Management Unit/Itlb/Subthreshold Leakage': 0.0413758,
'Memory Management Unit/Itlb/Subthreshold Leakage with power gating': 0.0235842,
'Memory Management Unit/Peak Dynamic': 0.317047,
'Memory Management Unit/Runtime Dynamic': 0.0178819,
'Memory Management Unit/Subthreshold Leakage': 0.0766103,
'Memory Management Unit/Subthreshold Leakage with power gating': 0.0398333,
'Peak Dynamic': 14.943,
'Renaming Unit/Area': 0.303608,
'Renaming Unit/FP Front End RAT/Area': 0.131045,
'Renaming Unit/FP Front End RAT/Gate Leakage': 0.00351123,
'Renaming Unit/FP Front End RAT/Peak Dynamic': 2.51468,
'Renaming Unit/FP Front End RAT/Runtime Dynamic': 0.195287,
'Renaming Unit/FP Front End RAT/Subthreshold Leakage': 0.0308571,
'Renaming Unit/FP Front End RAT/Subthreshold Leakage with power gating': 0.0175885,
'Renaming Unit/Free List/Area': 0.0340654,
'Renaming Unit/Free List/Gate Leakage': 2.5481e-05,
'Renaming Unit/Free List/Peak Dynamic': 0.0306032,
'Renaming Unit/Free List/Runtime Dynamic': 0.00796344,
'Renaming Unit/Free List/Subthreshold Leakage': 0.000370144,
'Renaming Unit/Free List/Subthreshold Leakage with power gating': 0.000201064,
'Renaming Unit/Gate Leakage': 0.00708398,
'Renaming Unit/Int Front End RAT/Area': 0.0941223,
'Renaming Unit/Int Front End RAT/Gate Leakage': 0.000283242,
'Renaming Unit/Int Front End RAT/Peak Dynamic': 0.731965,
'Renaming Unit/Int Front End RAT/Runtime Dynamic': 0.0590762,
'Renaming Unit/Int Front End RAT/Subthreshold Leakage': 0.00435488,
'Renaming Unit/Int Front End RAT/Subthreshold Leakage with power gating': 0.00248228,
'Renaming Unit/Peak Dynamic': 3.58947,
'Renaming Unit/Runtime Dynamic': 0.262327,
'Renaming Unit/Subthreshold Leakage': 0.0552466,
'Renaming Unit/Subthreshold Leakage with power gating': 0.0276461,
'Runtime Dynamic': 2.22738,
'Subthreshold Leakage': 6.16288,
'Subthreshold Leakage with power gating': 2.55328},
{'Area': 32.0201,
'Execution Unit/Area': 7.68434,
'Execution Unit/Complex ALUs/Area': 0.235435,
'Execution Unit/Complex ALUs/Gate Leakage': 0.0132646,
'Execution Unit/Complex ALUs/Peak Dynamic': 0.0979794,
'Execution Unit/Complex ALUs/Runtime Dynamic': 0.279646,
'Execution Unit/Complex ALUs/Subthreshold Leakage': 0.20111,
'Execution Unit/Complex ALUs/Subthreshold Leakage with power gating': 0.0754163,
'Execution Unit/Floating Point Units/Area': 4.6585,
'Execution Unit/Floating Point Units/Gate Leakage': 0.0656156,
'Execution Unit/Floating Point Units/Peak Dynamic': 0.393608,
'Execution Unit/Floating Point Units/Runtime Dynamic': 0.304033,
'Execution Unit/Floating Point Units/Subthreshold Leakage': 0.994829,
'Execution Unit/Floating Point Units/Subthreshold Leakage with power gating': 0.373061,
'Execution Unit/Gate Leakage': 0.120359,
'Execution Unit/Instruction Scheduler/Area': 1.66526,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Area': 0.275653,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Gate Leakage': 0.000977433,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Peak Dynamic': 1.04181,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Runtime Dynamic': 0.123725,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage': 0.0143453,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage with power gating': 0.00810519,
'Execution Unit/Instruction Scheduler/Gate Leakage': 0.00568913,
'Execution Unit/Instruction Scheduler/Instruction Window/Area': 0.805223,
'Execution Unit/Instruction Scheduler/Instruction Window/Gate Leakage': 0.00414562,
'Execution Unit/Instruction Scheduler/Instruction Window/Peak Dynamic': 1.6763,
'Execution Unit/Instruction Scheduler/Instruction Window/Runtime Dynamic': 0.199564,
'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage': 0.0625755,
'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage with power gating': 0.0355964,
'Execution Unit/Instruction Scheduler/Peak Dynamic': 3.82262,
'Execution Unit/Instruction Scheduler/ROB/Area': 0.584388,
'Execution Unit/Instruction Scheduler/ROB/Gate Leakage': 0.00056608,
'Execution Unit/Instruction Scheduler/ROB/Peak Dynamic': 1.10451,
'Execution Unit/Instruction Scheduler/ROB/Runtime Dynamic': 0.100733,
'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage': 0.00906853,
'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage with power gating': 0.00364446,
'Execution Unit/Instruction Scheduler/Runtime Dynamic': 0.424022,
'Execution Unit/Instruction Scheduler/Subthreshold Leakage': 0.0859892,
'Execution Unit/Instruction Scheduler/Subthreshold Leakage with power gating': 0.047346,
'Execution Unit/Integer ALUs/Area': 0.47087,
'Execution Unit/Integer ALUs/Gate Leakage': 0.0265291,
'Execution Unit/Integer ALUs/Peak Dynamic': 0.0811593,
'Execution Unit/Integer ALUs/Runtime Dynamic': 0.101344,
'Execution Unit/Integer ALUs/Subthreshold Leakage': 0.40222,
'Execution Unit/Integer ALUs/Subthreshold Leakage with power gating': 0.150833,
'Execution Unit/Peak Dynamic': 4.75278,
'Execution Unit/Register Files/Area': 0.570804,
'Execution Unit/Register Files/Floating Point RF/Area': 0.208131,
'Execution Unit/Register Files/Floating Point RF/Gate Leakage': 0.000232788,
'Execution Unit/Register Files/Floating Point RF/Peak Dynamic': 0.074361,
'Execution Unit/Register Files/Floating Point RF/Runtime Dynamic': 0.00518958,
'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage': 0.00399698,
'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage with power gating': 0.00176968,
'Execution Unit/Register Files/Gate Leakage': 0.000622708,
'Execution Unit/Register Files/Integer RF/Area': 0.362673,
'Execution Unit/Register Files/Integer RF/Gate Leakage': 0.00038992,
'Execution Unit/Register Files/Integer RF/Peak Dynamic': 0.0797187,
'Execution Unit/Register Files/Integer RF/Runtime Dynamic': 0.0383801,
'Execution Unit/Register Files/Integer RF/Subthreshold Leakage': 0.00614175,
'Execution Unit/Register Files/Integer RF/Subthreshold Leakage with power gating': 0.00246675,
'Execution Unit/Register Files/Peak Dynamic': 0.15408,
'Execution Unit/Register Files/Runtime Dynamic': 0.0435697,
'Execution Unit/Register Files/Subthreshold Leakage': 0.0101387,
'Execution Unit/Register Files/Subthreshold Leakage with power gating': 0.00423643,
'Execution Unit/Results Broadcast Bus/Area Overhead': 0.0390912,
'Execution Unit/Results Broadcast Bus/Gate Leakage': 0.00537402,
'Execution Unit/Results Broadcast Bus/Peak Dynamic': 0.192445,
'Execution Unit/Results Broadcast Bus/Runtime Dynamic': 0.345389,
'Execution Unit/Results Broadcast Bus/Subthreshold Leakage': 0.081478,
'Execution Unit/Results Broadcast Bus/Subthreshold Leakage with power gating': 0.0305543,
'Execution Unit/Runtime Dynamic': 1.498,
'Execution Unit/Subthreshold Leakage': 1.79543,
'Execution Unit/Subthreshold Leakage with power gating': 0.688821,
'Gate Leakage': 0.368936,
'Instruction Fetch Unit/Area': 5.85939,
'Instruction Fetch Unit/Branch Predictor/Area': 0.138516,
'Instruction Fetch Unit/Branch Predictor/Chooser/Area': 0.0435221,
'Instruction Fetch Unit/Branch Predictor/Chooser/Gate Leakage': 0.000278362,
'Instruction Fetch Unit/Branch Predictor/Chooser/Peak Dynamic': 0.0168831,
'Instruction Fetch Unit/Branch Predictor/Chooser/Runtime Dynamic': 0.000197415,
'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage': 0.00759719,
'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage with power gating': 0.0039236,
'Instruction Fetch Unit/Branch Predictor/Gate Leakage': 0.000757657,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Area': 0.0435221,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Gate Leakage': 0.000278362,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Peak Dynamic': 0.0168831,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Runtime Dynamic': 0.000197415,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage': 0.00759719,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage with power gating': 0.0039236,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Area': 0.0257064,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Gate Leakage': 0.000154548,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Peak Dynamic': 0.0142575,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Runtime Dynamic': 0.000170604,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage': 0.00384344,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage with power gating': 0.00198631,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Area': 0.0151917,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Gate Leakage': 8.00196e-05,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Peak Dynamic': 0.00527447,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Runtime Dynamic': 6.53086e-05,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage': 0.00181347,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage with power gating': 0.000957045,
'Instruction Fetch Unit/Branch Predictor/Peak Dynamic': 0.0597838,
'Instruction Fetch Unit/Branch Predictor/RAS/Area': 0.0105732,
'Instruction Fetch Unit/Branch Predictor/RAS/Gate Leakage': 4.63858e-05,
'Instruction Fetch Unit/Branch Predictor/RAS/Peak Dynamic': 0.0117602,
'Instruction Fetch Unit/Branch Predictor/RAS/Runtime Dynamic': 0.000551334,
'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage': 0.000932505,
'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage with power gating': 0.000494733,
'Instruction Fetch Unit/Branch Predictor/Runtime Dynamic': 0.00111677,
'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage': 0.0199703,
'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage with power gating': 0.0103282,
'Instruction Fetch Unit/Branch Target Buffer/Area': 0.64954,
'Instruction Fetch Unit/Branch Target Buffer/Gate Leakage': 0.00272758,
'Instruction Fetch Unit/Branch Target Buffer/Peak Dynamic': 0.177867,
'Instruction Fetch Unit/Branch Target Buffer/Runtime Dynamic': 0.00194081,
'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage': 0.0811682,
'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage with power gating': 0.0435357,
'Instruction Fetch Unit/Gate Leakage': 0.0589979,
'Instruction Fetch Unit/Instruction Buffer/Area': 0.0226323,
'Instruction Fetch Unit/Instruction Buffer/Gate Leakage': 6.83558e-05,
'Instruction Fetch Unit/Instruction Buffer/Peak Dynamic': 0.606827,
'Instruction Fetch Unit/Instruction Buffer/Runtime Dynamic': 0.0368958,
'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage': 0.00151885,
'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage with power gating': 0.000701682,
'Instruction Fetch Unit/Instruction Cache/Area': 3.14635,
'Instruction Fetch Unit/Instruction Cache/Gate Leakage': 0.029931,
'Instruction Fetch Unit/Instruction Cache/Peak Dynamic': 2.34689,
'Instruction Fetch Unit/Instruction Cache/Runtime Dynamic': 0.0550619,
'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage': 0.367022,
'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage with power gating': 0.180386,
'Instruction Fetch Unit/Instruction Decoder/Area': 1.85799,
'Instruction Fetch Unit/Instruction Decoder/Gate Leakage': 0.0222493,
'Instruction Fetch Unit/Instruction Decoder/Peak Dynamic': 1.37404,
'Instruction Fetch Unit/Instruction Decoder/Runtime Dynamic': 0.125315,
'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage': 0.442943,
'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage with power gating': 0.166104,
'Instruction Fetch Unit/Peak Dynamic': 4.6793,
'Instruction Fetch Unit/Runtime Dynamic': 0.22033,
'Instruction Fetch Unit/Subthreshold Leakage': 0.932286,
'Instruction Fetch Unit/Subthreshold Leakage with power gating': 0.40843,
'L2/Area': 4.53318,
'L2/Gate Leakage': 0.015464,
'L2/Peak Dynamic': 0.0131558,
'L2/Runtime Dynamic': 0.0049838,
'L2/Subthreshold Leakage': 0.834142,
'L2/Subthreshold Leakage with power gating': 0.401066,
'Load Store Unit/Area': 8.80901,
'Load Store Unit/Data Cache/Area': 6.84535,
'Load Store Unit/Data Cache/Gate Leakage': 0.0279261,
'Load Store Unit/Data Cache/Peak Dynamic': 1.5413,
'Load Store Unit/Data Cache/Runtime Dynamic': 0.163934,
'Load Store Unit/Data Cache/Subthreshold Leakage': 0.527675,
'Load Store Unit/Data Cache/Subthreshold Leakage with power gating': 0.25085,
'Load Store Unit/Gate Leakage': 0.0350888,
'Load Store Unit/LoadQ/Area': 0.0836782,
'Load Store Unit/LoadQ/Gate Leakage': 0.00059896,
'Load Store Unit/LoadQ/Peak Dynamic': 0.00984081,
'Load Store Unit/LoadQ/Runtime Dynamic': 0.0098409,
'Load Store Unit/LoadQ/Subthreshold Leakage': 0.00941961,
'Load Store Unit/LoadQ/Subthreshold Leakage with power gating': 0.00536918,
'Load Store Unit/Peak Dynamic': 1.58777,
'Load Store Unit/Runtime Dynamic': 0.222306,
'Load Store Unit/StoreQ/Area': 0.322079,
'Load Store Unit/StoreQ/Gate Leakage': 0.00329971,
'Load Store Unit/StoreQ/Peak Dynamic': 0.0242658,
'Load Store Unit/StoreQ/Runtime Dynamic': 0.048532,
'Load Store Unit/StoreQ/Subthreshold Leakage': 0.0345621,
'Load Store Unit/StoreQ/Subthreshold Leakage with power gating': 0.0197004,
'Load Store Unit/Subthreshold Leakage': 0.591321,
'Load Store Unit/Subthreshold Leakage with power gating': 0.283293,
'Memory Management Unit/Area': 0.4339,
'Memory Management Unit/Dtlb/Area': 0.0879726,
'Memory Management Unit/Dtlb/Gate Leakage': 0.00088729,
'Memory Management Unit/Dtlb/Peak Dynamic': 0.008612,
'Memory Management Unit/Dtlb/Runtime Dynamic': 0.00880954,
'Memory Management Unit/Dtlb/Subthreshold Leakage': 0.0155699,
'Memory Management Unit/Dtlb/Subthreshold Leakage with power gating': 0.00887485,
'Memory Management Unit/Gate Leakage': 0.00808595,
'Memory Management Unit/Itlb/Area': 0.301552,
'Memory Management Unit/Itlb/Gate Leakage': 0.00393464,
'Memory Management Unit/Itlb/Peak Dynamic': 0.145921,
'Memory Management Unit/Itlb/Runtime Dynamic': 0.00902684,
'Memory Management Unit/Itlb/Subthreshold Leakage': 0.0413758,
'Memory Management Unit/Itlb/Subthreshold Leakage with power gating': 0.0235842,
'Memory Management Unit/Peak Dynamic': 0.316824,
'Memory Management Unit/Runtime Dynamic': 0.0178364,
'Memory Management Unit/Subthreshold Leakage': 0.0766103,
'Memory Management Unit/Subthreshold Leakage with power gating': 0.0398333,
'Peak Dynamic': 14.9393,
'Renaming Unit/Area': 0.303608,
'Renaming Unit/FP Front End RAT/Area': 0.131045,
'Renaming Unit/FP Front End RAT/Gate Leakage': 0.00351123,
'Renaming Unit/FP Front End RAT/Peak Dynamic': 2.51468,
'Renaming Unit/FP Front End RAT/Runtime Dynamic': 0.195609,
'Renaming Unit/FP Front End RAT/Subthreshold Leakage': 0.0308571,
'Renaming Unit/FP Front End RAT/Subthreshold Leakage with power gating': 0.0175885,
'Renaming Unit/Free List/Area': 0.0340654,
'Renaming Unit/Free List/Gate Leakage': 2.5481e-05,
'Renaming Unit/Free List/Peak Dynamic': 0.0306032,
'Renaming Unit/Free List/Runtime Dynamic': 0.00796266,
'Renaming Unit/Free List/Subthreshold Leakage': 0.000370144,
'Renaming Unit/Free List/Subthreshold Leakage with power gating': 0.000201064,
'Renaming Unit/Gate Leakage': 0.00708398,
'Renaming Unit/Int Front End RAT/Area': 0.0941223,
'Renaming Unit/Int Front End RAT/Gate Leakage': 0.000283242,
'Renaming Unit/Int Front End RAT/Peak Dynamic': 0.731965,
'Renaming Unit/Int Front End RAT/Runtime Dynamic': 0.0590131,
'Renaming Unit/Int Front End RAT/Subthreshold Leakage': 0.00435488,
'Renaming Unit/Int Front End RAT/Subthreshold Leakage with power gating': 0.00248228,
'Renaming Unit/Peak Dynamic': 3.58947,
'Renaming Unit/Runtime Dynamic': 0.262585,
'Renaming Unit/Subthreshold Leakage': 0.0552466,
'Renaming Unit/Subthreshold Leakage with power gating': 0.0276461,
'Runtime Dynamic': 2.22605,
'Subthreshold Leakage': 6.16288,
'Subthreshold Leakage with power gating': 2.55328}],
'DRAM': {'Area': 0,
'Gate Leakage': 0,
'Peak Dynamic': 1.2868175454447888,
'Runtime Dynamic': 1.2868175454447888,
'Subthreshold Leakage': 4.252,
'Subthreshold Leakage with power gating': 4.252},
'L3': [{'Area': 61.9075,
'Gate Leakage': 0.0484137,
'Peak Dynamic': 0.0451325,
'Runtime Dynamic': 0.0231622,
'Subthreshold Leakage': 6.80085,
'Subthreshold Leakage with power gating': 3.32364}],
'Processor': {'Area': 191.908,
'Gate Leakage': 1.53485,
'Peak Dynamic': 61.9702,
'Peak Power': 95.0824,
'Runtime Dynamic': 9.22203,
'Subthreshold Leakage': 31.5774,
'Subthreshold Leakage with power gating': 13.9484,
'Total Cores/Area': 128.669,
'Total Cores/Gate Leakage': 1.4798,
'Total Cores/Peak Dynamic': 61.9251,
'Total Cores/Runtime Dynamic': 9.19887,
'Total Cores/Subthreshold Leakage': 24.7074,
'Total Cores/Subthreshold Leakage with power gating': 10.2429,
'Total L3s/Area': 61.9075,
'Total L3s/Gate Leakage': 0.0484137,
'Total L3s/Peak Dynamic': 0.0451325,
'Total L3s/Runtime Dynamic': 0.0231622,
'Total L3s/Subthreshold Leakage': 6.80085,
'Total L3s/Subthreshold Leakage with power gating': 3.32364,
'Total Leakage': 33.1122,
'Total NoCs/Area': 1.33155,
'Total NoCs/Gate Leakage': 0.00662954,
'Total NoCs/Peak Dynamic': 0.0,
'Total NoCs/Runtime Dynamic': 0.0,
'Total NoCs/Subthreshold Leakage': 0.0691322,
'Total NoCs/Subthreshold Leakage with power gating': 0.0259246}}
|
__inner_signs__ = ['{', '}', '[', ']', '(', ')', ',', '', ':']
class __Str:
"""
the class contain string methods
"""
@staticmethod
def space_encoder(_str: str):
"""
will encode spaces inside list in string.
:param _str: list in string
:return: return encoded string
"""
_numeric_flag = False
_str = list(_str)
_space_index_st = 0
for _index in range(len(_str)):
if _str[_index] == ' ':
if _str[_index - 1] not in __inner_signs__ and _str[_index + 1] not in __inner_signs__ and not _numeric_flag:
_str[_index] = 'र'
if _space_index_st == 0:
_space_index_st = _index
else:
_str[_index] = ''
else:
if _str[_index] in __inner_signs__:
_numeric_flag = True
if (not _str[_index].isnumeric()) and _str[_index] != ' ' and _str[_index] != '' and (_str[_index] not in __inner_signs__):
_numeric_flag = False
if _space_index_st > 0 and _str[_index] == ',':
for _ind in range(_space_index_st, _index):
_str[_ind] = ''
_space_index_st = 0
return ''.join(_str)
@staticmethod
def space_decoder(_str: str):
"""
will decode spaces inside list in string.
:param _str: list in string
:return: return encoded string
"""
_str = list(_str)
for _index in range(len(_str)):
if _str[_index] == 'र':
_str[_index] = ' '
return ''.join(_str)
|
def assign_ROSCO_values(wt_opt, modeling_options, control):
# ROSCO tuning parameters
wt_opt['tune_rosco_ivc.PC_omega'] = control['pitch']['PC_omega']
wt_opt['tune_rosco_ivc.PC_zeta'] = control['pitch']['PC_zeta']
wt_opt['tune_rosco_ivc.VS_omega'] = control['torque']['VS_omega']
wt_opt['tune_rosco_ivc.VS_zeta'] = control['torque']['VS_zeta']
if modeling_options['Level3']['ROSCO']['Flp_Mode'] > 0:
wt_opt['tune_rosco_ivc.Flp_omega'] = control['dac']['Flp_omega']
wt_opt['tune_rosco_ivc.Flp_zeta'] = control['dac']['Flp_zeta']
if 'IPC' in control.keys():
wt_opt['tune_rosco_ivc.IPC_KI'] = control['IPC']['IPC_gain_1P']
# # other optional parameters
wt_opt['tune_rosco_ivc.max_pitch'] = control['pitch']['max_pitch']
wt_opt['tune_rosco_ivc.min_pitch'] = control['pitch']['min_pitch']
wt_opt['tune_rosco_ivc.vs_minspd'] = control['torque']['VS_minspd']
wt_opt['tune_rosco_ivc.ss_vsgain'] = control['setpoint_smooth']['ss_vsgain']
wt_opt['tune_rosco_ivc.ss_pcgain'] = control['setpoint_smooth']['ss_pcgain']
wt_opt['tune_rosco_ivc.ps_percent'] = control['pitch']['ps_percent']
# Check for proper Flp_Mode, print warning
if modeling_options['WISDEM']['RotorSE']['n_tab'] > 1 and modeling_options['Level3']['ROSCO']['Flp_Mode'] == 0:
raise Exception('A distributed aerodynamic control device is specified in the geometry yaml, but Flp_Mode is zero in the modeling options.')
if modeling_options['WISDEM']['RotorSE']['n_tab'] == 1 and modeling_options['Level3']['ROSCO']['Flp_Mode'] > 0:
raise Exception('Flp_Mode is non zero in the modeling options, but no distributed aerodynamic control device is specified in the geometry yaml.')
return wt_opt
|
# Tuples
# Assignment 1
tuple_numbers = (1, 2, 3, 4, 5)
tuple_groceries = ('coconuts', 'bananas', 'onions', 'spinach', 'tomatoes', 'cilantro', 'milk')
groceries_inventory = ('coconuts', 'tomatoes', 'onions', 'coconuts', 'bananas', 'onions', 'spinach', 'tomatoes', 'cilantro', 'milk', 'spinach', 'tomatoes', 'cilantro', 'tomatoes')
tuple_nested =((1, 2, 3), ["Python", "Database", "System"], 'Coding')
tuple_numbers_100s = (100, 200, 300, 400, 500)
# Print 3rd item from tuple_groceries
print("*" * 50)
print("The 3rd item of tuple_groceries :", tuple_groceries[2])
# Print the length of tuple_groceries
print("*" * 50)
print("The length of tuple_groceries :", len(tuple_groceries))
# Print the reverse of tuple_numbers & tuples_names
print("*" * 50)
tuple_groceries_rev = tuple(reversed(tuple_groceries))
print("Reverse of tuple_groceries :", tuple_groceries_rev)
# Print "Python" from "tuple_nested"
print("*" * 50)
print(tuple_nested[1][0])
# Unpack tuple_groceries tuple and print them
print("*" * 50)
print("Unpacking...")
g1, g2, g3, g4, g5, g6, g7, = tuple_groceries
print(g1)
print(g1)
print(g2)
print(g3)
print(g4)
print(g5)
print(g6)
print(g7)
# Swap tuple_numbers and tuple_numbers_100s
print("*" * 50)
print("Swapping...")
tuple_numbers, tuple_numbers_100s = tuple_numbers_100s, tuple_numbers
print("tuple_numbers_100s :", tuple_numbers_100s)
print("tuple_numbers :", tuple_numbers)
# Construct a new tuple "tuples_a" by extracting
# bananas, onions, spinach from tuples_groceries
print("*" * 50)
print("Subset items.... bananas, onions, spinach")
tuples_a = tuple_groceries[1:4]
print("tuples_a :", tuples_a)
# Count the number of times coconuts is listed in groceries_inventory tuple
print("*" * 50)
print("Count the number of times coconuts...")
coconut_count = groceries_inventory.count("coconuts")
print("coconuts :", coconut_count)
|
class QueryToken:
"""A placeholder token for dry-run query output"""
def __str__(self) -> str:
return "?"
def __repr__(self) -> str:
return "?"
|
class Solution:
def minMeetingRooms(self, intervals: list[list[int]]) -> int:
start = sorted([i[0] for i in intervals])
end = sorted(i[1] for i in intervals)
result = count = 0
s, e = 0, 0
while s < len(intervals):
if start[s] < end[e]:
s += 1
count += 1
else:
e += 1
count -= 1
result = max(result, count)
return result
|
def sum_multidimensional_list_v1(lst):
sum_nums = 0
for row in range(len(lst)):
for col in range(len(lst[row])):
sum_nums += lst[row][col]
return sum_nums
def sum_multidimensional_list_v2(lst):
sum_nums = 0
for row in lst:
for col in row:
sum_nums += col
return sum_nums
|
__version_info__ = ('3', '5', '1')
__version__ = '.'.join(__version_info__)
class TwilioException(Exception):
pass
class TwilioRestException(TwilioException):
def __init__(self, status, uri, msg="", code=None):
self.uri = uri
self.status = status
self.msg = msg
self.code = code
def __str__(self):
return "HTTP ERROR %s: %s \n %s" % (self.status, self.msg, self.uri)
|
#!/usr/bin/env python3
#-*-coding:UTF-8-*-
def CinDico(caractere, dictionnaire):
"""
Fonction permettant de détecter la présence d'un code dans le dictionnaire construit par Decompress.
:param caractere: Paramètre correspondant au code d'un caractère ou d'une suite de caractères compressé.
:param dictionnaire: Liste correspondant au dictionnaire en cours d'utilisation et construit par Decompress()
:return test: Variable de type Integer ayant pour valeur -1 si le code ne se trouve pas dans le dictionnaire entrée en paramètre ou la position du code dans le dictionnaire en cas de détection. Cela permet à Decompress de récupérer la suite de caractères correspondante.
"""
test = -1
for i in range(0, len(dictionnaire)):
if caractere == dictionnaire[i][0]:
test = i
return test
def startDecompress(fileName):
"""
Fonction générique permettant de décompresser suivant l'algorithme de compression utilisé.
:param fileName: Chemin d'accès de l'archive dont on souhaite la décompression.
"""
lines=LectureFichier(fileName)
fileOut=fileName.split(".")[0]+".txt"
Decompress(lines,fileOut)
def LectureFichier(chemin):
"""
Fonction permettant de lire l'archive et de produire une liste formatée pour la décompression par la fonction Decompress().
LectureFichier produit d'abord une liste contenant chaque ligne de l'archive compressée.
La compression ayant ajouté 2 "\n" dans l'archive, LectureFichier cherche donc un élément de la liste correspondant à "b'\n'" afin de collecter tout ce qui se toruve avant comme étant du texte à décoder et tout ce qui se trouve après comme étant le bit de poids fort manquant à chaque caractère.
Par la suite, LectureFichier lit chaque bit de poids fort et l'ajoute au code du caractère auquel il devrait appartenir.
Enfin, chaque code est casté en string puis le "0b" restant suite au cast est retiré afin de ne garder qu'une suite de bit.
Enfin, la fonction retourne la liste correctement formatée et exploitable par Decompress()
:param chemin: Paramètre contenant le chemin d'accès de l'archive à décompresser.
:raise IndexError: Afin de coder les 9ème bits en hexadecimal, il a fallu ajouter des 0 non significatifs à la fin de la liste des 9ème bits. En effet, nous devions posséder une liste de 9ème bits divisible par 8 pour coder en hexadécimal d'où l'ajout de zéro. Cela entraîne ici une erreur IndexError étant donné qu'il n'existe pas de code en hexadécimal pour les 9ème bits ajoutés artificiellement. On sort alors de la boucle for en provoquant un break une fois cette erreur rencontrée (qui correspondra donc au premier 9ème bits non significatifs).
:return ligne: Liste formatée des codes de caractères sur 9 bits prête à être interprêtée par Decompress()
"""
fichier = open(chemin, 'rb')
ligne = fichier.readlines()
binary = ""
n = len(ligne)
ninebit = ""
sauv = 0
for i in range(0, n):
if ligne[i] == b'\n' :
sauv = i
for i in range(1, sauv):
ligne[0] = ligne[0] + ligne[i]
for i in range(sauv+1, n):
ligne[sauv] = ligne[sauv] + ligne[i]
ligne = [ligne[0], ligne[sauv][1:]]
for i in range(0, len(ligne[1])):
bit9 = str(bin(ligne[1][i]))
n = len(bit9) - 2
zero = ""
for k in range(0, 8-n):
zero = zero + "0"
bit9 = zero + bit9[2:]
ninebit = ninebit + bit9
for j in range(0, len(bit9)) :
try :
carac = str(bin(ligne[0][8*i + j]))
except IndexError :
break
n = len(carac) - 2
zero = ""
for k in range(0, 8-n):
zero = zero + "0"
carac = "0b" + zero + carac[2:]
binary = binary + "0b" + bit9[j] + carac[2:] + " "
ligne = binary.split("0b")
ligne.remove('')
fichier.close()
return ligne
def Decompress(caracteres,fileOut):
"""
Decompress est la fonction servant à décoder un texte compressé en suivant la méthode de l'algorithme LZW.
Elle s'appuie sur la fonction LectureFichier afin de recevoir une liste correctement formatée pour la décompression.
:param caracteres: Il s'agit d'une liste dont chaque élément correspond au code ASCII ou du dictionnaire d'un caractère ou d'une suite de caractère compressé. Ce code doit être exprimé en bit, type string sans le 0b ajouté par le type bytes. LectureFichier() peut fournir une telle liste formatée à partir d'un fichier texte.
:param fileOut: Paramètre contenant le chemin d'accès souhaité par l'utilisateur pour écriture du fichier décompressé.
:raise IndexError: Lors du premier ajout au dictionnaire, la liste est vide. Or, dans le try, nous essayons de récupérer le dernier indice du code ajouté au dictionnaire. Cela générère une erreur IndexError qui est gérée dans le except. En effet, dans ce cas, nous ajoutons au dictionnaire le code avec pour indice 256 ce qui permet de l'initialiser et de ne plus rencontrer l'erreur par la suite.
"""
resultat = open(fileOut, 'w')
dictionnaire = []
resultat.write(chr(int(caracteres[0], 2)))
w = chr(int(caracteres[0], 2))
for i in range(1, len(caracteres)):
presence = CinDico(int(caracteres[i], 2), dictionnaire)
test_code = int(caracteres[i], 2)
if test_code > 255 and presence != -1 :
entree = dictionnaire[presence][1]
elif test_code > 255 and presence == -1 :
entree = w + w[0]
else :
entree = chr(test_code)
resultat.write(entree)
try :
dictionnaire.append([dictionnaire[-1][0] + 1, w + entree[0]])
except IndexError :
dictionnaire.append([256, w + entree[0]])
if len(dictionnaire) == 256 :
dictionnaire = []
w = entree
resultat.close()
return "Opération Réussie !"
|
"""
URL: https://codeforces.com/problemset/problem/112/A
Author: Safiul Kabir [safiulanik at gmail.com]
"""
s1 = input().lower()
s2 = input().lower()
if s1 == s2:
print(0)
elif s1 < s2:
print(-1)
else:
print(1)
|
###exercicio 50
s = 0
for c in range (0, 6):
n = int(input('Digite um numero: '))
if n%2 == 0:
s += n
print ('{}'.format(s))
print ('Fim!!!')
|
valor1 = 16
valor2 = 61
if valor1 > valor2:
print('{} é maior.'.format(valor1))
else:
print('{} é maior.'.format(valor2))
|
total = 0
for number in range(1, 10 + 1):
print(number)
total = total + number
print(total)
|
#Using the range function we create a list of numbers from 0 to 99 https://docs.python.org/2/library/functions.html#range
#Each number in the list is FizzBuzz tested
#If the number is a multiple of 3 and a multiple of 5 - print "FizzBuzz"
#If the number is only a multiple of 3 - print "Fizz"
#If the number is only a multiple of 5 - print "Buzz"
#If the number is not a multiple of 3 or 5 - print the number
for i in range (100):
if i % 3 == 0 and i % 5 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
|
'''面试题55-2:平衡二叉树
输入一棵二叉树的根节点,判断该树是不是平衡二叉树。
如果某二叉树中任意节点的左、右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
'''
class Node(object):
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
class BST(object):
def __init__(self):
self.root = None
def add(self, ele):
if ele is None:
return
self.root = self.__add(self.root, ele)
def __add(self, node: Node, ele):
if node is None:
return Node(ele)
if ele > node.value:
node.right = self.__add(node.right, ele)
else:
node.left = self.__add(node.left, ele)
return node
def in_order(self):
if self.root is None:
return
self.__in_order(self.root)
def __in_order(self, node):
if node.left is not None:
self.__in_order(node.left)
print(node.value, end=' ')
if node.right is not None:
self.__in_order(node.right)
def is_balanced(root):
if root is None:
return False
return __is_balanced(root, [0])
def __is_balanced(root, depth):
if root is None:
depth[0] = 0
return True
l_depth = [0]
r_depth = [0]
if __is_balanced(root.left, l_depth) and __is_balanced(root.right, r_depth):
dif = l_depth[0] - r_depth[0]
if dif >= -1 and dif <= 1:
depth[0] = l_depth[0] + 1 if l_depth[0] > r_depth[0] else r_depth[0] + 1
return True
return False
if __name__ == "__main__":
datas = [[None], [5,3,2,4,7,6,8], [1,2,3],[1]]
for data in datas:
bst = BST()
for i in data:
bst.add(i)
print(data, is_balanced(bst.root))
|
class Foo:
[mix_Case, var2] = range(2)
def bar():
'''
>>> class Foo():
... mix_Case = 0
'''
pass
|
n = 0
while True:
n = int(input('Digite o número que deseja ver a tabuada (negativo para parar): '))
if n < 0:
print('-=' * 40)
print('Programa de tabuada encerrando. Volte sempre!')
break
for i in range(1,11):
print(f'{n} x {i} = {i*n}')
print('-='*40)
|
""" TEMPORARY FIX """
def pause(*args):
print("TRYING TO PAUSE")
def stop(*args):
print("TRYING TO STOP")
|
def print_to_file(file, cases):
print(len(cases), file=file)
for arr in cases:
print(len(arr), file=file)
print(*arr, file=file)
|
# Desenvolva um programa que leia as duas notas de um aluno, calcule e mostre a sua média
print('***Calculadora de Notas***\n')
n1 = float(input('Digite a primeira nota: '))
n2 = float(input('Digite a segunda nota: '))
nf = (n1+n2)/2
print('-'*20)
print('A média do aluno é {:.1f}.'.format(nf))
if (nf>=5):
print('O aluno foi aprovado!')
else:
print('O aluno foi reprovado.')
|
FEATURES = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "LineString",
"coordinates": [
[-122.3141965, 47.6598870],
[-122.3132940, 47.6598762],
],
},
"properties": {},
},
{
"type": "Feature",
"geometry": {
"type": "LineString",
"coordinates": [
[-122.3144401, 47.6598872],
[-122.3141965, 47.6598870],
],
},
"properties": {},
},
{
"type": "Feature",
"geometry": {
"type": "LineString",
"coordinates": [
[-122.3141965, 47.6598870],
[-122.3142026, 47.6597293],
],
},
"properties": {},
},
{
"type": "Feature",
"geometry": {
"type": "LineString",
"coordinates": [
[-122.3141795, 47.6605333],
[-122.3141965, 47.6598870],
],
},
"properties": {},
},
],
}
|
#
# Nidan
#
# (C) 2017 Michele <o-zone@zerozone.it> Pinassi
class Config: pass
|
class CyclicDependencyError(ValueError):
pass
def topological_sort_as_sets(dependency_graph):
"""
Variation of Kahn's algorithm (1962) that returns sets.
Take a dependency graph as a dictionary of node => dependencies.
Yield sets of items in topological order, where the first set contains
all nodes without dependencies, and each following set contains all
nodes that may depend on the nodes only in the previously yielded sets.
"""
todo = dependency_graph.copy()
while todo:
current = {node for node, deps in todo.items() if not deps}
if not current:
raise CyclicDependencyError('Cyclic dependency in graph: {}'.format(
', '.join(repr(x) for x in todo.items())))
yield current
# remove current from todo's nodes & dependencies
todo = {node: (dependencies - current) for node, dependencies in
todo.items() if node not in current}
def stable_topological_sort(nodes, dependency_graph):
result = []
for layer in topological_sort_as_sets(dependency_graph):
for node in nodes:
if node in layer:
result.append(node)
return result
|
#Faça um program que leia o nome completo de uma pessoa, mostrando em seguinda o primeiro e último nome separados.
#EX: Ana Maria de Sousa/ primeiro = Ana/ segundo = Sousa
nome = str(input('Digite seu nome completo: ')).strip().upper()
nomes = nome.split()
print('Muito prazer em te conhecer!')
print('Seu primeiro nome é {}'.format(nomes[0]))
print('Seu último nome é {}'.format(nomes[len(nomes) - 1]))
|
# Given a binary matrix A, we want to flip the image horizontally, then invert
# it, and return the resulting image.
# To flip an image horizontally means that each row of the image is reversed.
# For example, flipping [1, 1, 0] horizontally results in [0, 1, 1].
# To invert an image means that each 0 is replaced by 1, and each 1 is replaced
# by 0. For example, inverting [0, 1, 1] results in [1, 0, 0].
class Solution:
def flipAndInvertImage(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
return [[1 - v for v in row[::-1]] for row in A]
|
'''
This problem was asked by Google.
Given two singly linked lists that intersect at some point, find the intersecting node. The lists are non-cyclical.
For example, given A = 3 -> 7 -> 8 -> 10 and B = 99 -> 1 -> 8 -> 10, return the node with value 8.
In this example, assume nodes with the same value are the exact same node objects.
Do this in O(M + N) time (where M and N are the lengths of the lists) and constant space.
'''
"""
Assuming some thing like this
list1 = 1->2->3->7->8->10
list2 = 99->1->8->10
so visualizing:
1
2
3
7
99->1->8->10
"""
class LinkedList:
def __init__(self, data, next=None):
self.data = data
self.next = next
def print_list(list):
if list is None:
return
print(list.data)
print_list(list.next)
def find_intersection(list1, list2):# O(M*K)
pointerL2 = list2
while pointerL2:
pointerL1 = list1
while pointerL1:
if pointerL1 == pointerL2: # found intersection
return pointerL1.data
pointerL1 = pointerL1.next
pointerL2 = pointerL2.next
def find_intersection_2(list1, list2):# O(M+K)
# idea store pointer values to a dictionary
# return when match found
dict_visited = {} # dict of visited nodes
pointer = list1
while pointer:
dict_visited[id(pointer)] = None # just add the key no need to store a value
pointer = pointer.next
pointer = list2
while pointer:
if id(pointer) in dict_visited:
return ('intersection point at: {}'.format(pointer.data))
pointer = pointer.next
return 'No Intersection'
if __name__ == '__main__':
common_tail = LinkedList(8, next=LinkedList(10))
l1 = LinkedList(1, next=LinkedList(2,next=LinkedList(3, next=LinkedList(7, next=common_tail))))
l2 = LinkedList(99, next=LinkedList(1, next=common_tail))
# print_list(l1)
# print('\n')
# print_list(l2)
# print('\n')
print(find_intersection_2(l1,l2))
|
def lazyproperty(fn):
attr_name = '__' + fn.__name__
@property
def _lazyprop(self):
if not hasattr(self, attr_name):
setattr(self, attr_name, fn(self))
return getattr(self, attr_name)
return _lazyprop
|
stud = {
'Madhan':24,
'Raj':30,
'Narayanan':29
}
for s1 in stud.keys():
print(s1)
phone_numbers = {"John Smith": "+37682929928", "Marry Simpons": "+423998200919"}
for key,value in phone_numbers.items():
print("{} has phone number {}".format(key,value))
names = {
'Girija':53,
'Subramanian':62,
'Narayanan':29,
'Gopal':65,
'Vijayam':65
}
for n1 in names.keys():
print(n1)
for n2 in names.values():
print(n2)
|
"""load gtest third party"""
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def repo():
http_archive(
name = "com_google_googletest",
sha256 = "353571c2440176ded91c2de6d6cd88ddd41401d14692ec1f99e35d013feda55a",
urls = ["https://github.com/google/googletest/archive/refs/tags/release-1.11.0.zip"],
strip_prefix = "googletest-release-1.11.0",
)
|
# -*- coding: utf-8 -*-
latest_posts = db(Posts).select(orderby=~Posts.created_on, limitby=(0,5))
most_liked = db(Posts).select(orderby=~Posts.likes, limitby=(0,5))
all_categories = db(Categories).select(limitby=(0,5))
|
spam = ['cat', 'bat', 'rat', 'elephant']
print(spam[2])
spam2 = [['fish', 'shark'], 'bat', 'rat', 'elephant']
print(spam2[0])
print(spam2[0][1])
spam[2:4] = ['CAT', 'MOOSE', 'BEAR']
print(spam)
del spam[2]
print(spam)
print('MOOSE' in spam)
# Iterate over lists by item or index
for item in spam:
print(item)
for i in range(0, len(spam)):
print(spam[i])
print(len(spam))
cat = ['fat', 'orange', 'loud']
size, color, disposition = cat
print(size)
print(color)
print(disposition)
# swap variables
a = 'AAA'
b = 'BBB'
a, b = b, a
print(a)
print(b)
|
class Node():
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinaryTree():
def __init__(self, root):
self.root = Node(root)
def print_tree(self, traversal_type):
if traversal_type == "preorder":
return self.preorder_print(self.root, "")
elif traversal_type == "inorder":
return self.inorder_print(self.root, "")
elif traversal_type == "postorder":
return self.postorder_print(self.root, "")
else:
return f"traversal type is not supported"
def preorder_print(self, start, traversal):
""" Root -> Left -> Right """
if start:
traversal+=(str(start.value)+"-")
traversal = self.preorder_print(start.left, traversal)
traversal = self.preorder_print(start.right, traversal)
return traversal
def inorder_print(self, start, traversal):
"""Left -> Root -> Right """
if start:
traversal = self.inorder_print(start.left, traversal)
traversal += (str(start.value) + "-")
traversal = self.inorder_print(start.right, traversal)
return traversal
def postorder_print(self, start, traversal):
""" Left -> Right -> Root """
if start:
traversal = self.inorder_print(start.left, traversal)
traversal = self.inorder_print(start.right, traversal)
traversal += (str(start.value) + "-")
return traversal
tree = BinaryTree(1)
tree.root.left = Node(2)
tree.root.right = Node(3)
tree.root.left.left = Node(4)
tree.root.left.right = Node(5)
tree.root.right.left = Node(6)
tree.root.right.right = Node(7)
tree.root.right.right.right = Node(8)
print(tree.print_tree("preorder"))
print(tree.print_tree("inorder"))
print(tree.print_tree("postorder"))
|
def pattern(n):
if n==0:
return ""
res=[]
for i in range(n-1):
res.append(" "*(n-1)+str((i+1)%10))
temp="".join(str(i%10) for i in range(1, n))
res.append(temp+str(n%10)+temp[::-1])
for i in range(n-1, 0, -1):
res.append(" "*(n-1)+str(i%10))
return "\n".join(res)+"\n"
|
# ------------------------------
# 63. Unique Paths II
#
# Description:
# Follow up for "Unique Paths":
#
# Now consider if some obstacles are added to the grids. How many unique paths would there be?
# An obstacle and empty space is marked as 1 and 0 respectively in the grid.
# For example,
# There is one obstacle in the middle of a 3x3 grid as illustrated below.
# [
# [0,0,0],
# [0,1,0],
# [0,0,0]
# ]
# The total number of unique paths is 2.
#
# Version: 1.0
# 01/16/18 by Jianfa
# ------------------------------
class Solution(object):
def uniquePathsWithObstacles(self, obstacleGrid):
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
if not obstacleGrid or not obstacleGrid[0] or obstacleGrid[0][0] == 1:
return 0
for m in range(len(obstacleGrid)):
for n in range(len(obstacleGrid[0])):
if obstacleGrid[m][n] == 1:
obstacleGrid[m][n] = -1
obstacleGrid[0][0] = 1
for m in range(len(obstacleGrid)):
for n in range(len(obstacleGrid[0])):
if m == 0 and n > 0:
if obstacleGrid[m][n-1] == -1:
obstacleGrid[m][n] = 0
elif obstacleGrid[m][n] == -1:
obstacleGrid[m][n] = 0
else:
obstacleGrid[m][n] = obstacleGrid[m][n-1]
elif n == 0 and m > 0:
if obstacleGrid[m-1][n] == -1:
obstacleGrid[m][n] = 0
elif obstacleGrid[m][n] == -1:
obstacleGrid[m][n] = 0
else:
obstacleGrid[m][n] = obstacleGrid[m-1][n]
elif m != 0 and n != 0:
if obstacleGrid[m][n] == -1:
obstacleGrid[m][n] = 0
else:
obstacleGrid[m][n] = obstacleGrid[m-1][n] + obstacleGrid[m][n-1]
return obstacleGrid[m][n]
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Think about some edge situation.
# If the start point is 1, then return 0.
# Turn the grid to a state grid at first. When a unit is 1, then I change it to -1, which
# represents an obstacle state. Then start to counting. When meeting an obstacle, count 0.
# Calculate dynamically.
|
lista = [3, 41, 12, 9, 74, 15]
maior_numero = None
for x in lista:
if maior_numero is None or x > maior_numero:
maior_numero = x
print("A lista é composta por estes números: " + str(lista))
print("O maior número da lista é o " + str(maior_numero) + ".")
|
class Config:
gateId = 0
route = ""
port = "COM3"
def __init__(self, gateId, route):
self.gateId=gateId
self.route=route
|
# linked list class
# class for "node" or in common terms "element"
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class LinkedList:
def __init__(self):
self.head = None # points to the head of the linked list
def insert_at_begining(self, data):
# node with value of "data" and next element will be the head
# we add the element to the beginning and set the "Next" argument to the previous head
# this puts the current data to the beginning of the list.
node = Node(data, self.head)
# we then set the current node as the head.
self.head = node
def insert_at_end(self, data):
# if linked list is empty set the current data to the head.
if self.head is None:
self.head = Node(data, None)
return
# iterate through the entire linked list
# once we hit an itr that is None we know we're at the end
# we then set that node to the current data then set the next element to None
itr = self.head
while itr.next:
itr = itr.next
itr.next = Node(data, None)
# insert a list of values as a linked list
def insert_values(self, data_list):
self.head = None
for data in data_list:
self.insert_at_end(data)
def get_length(self):
count = 0
itr = self.head
while itr:
count += 1
itr = itr.next
return count
def remove_at(self, index):
# if the index is less then 0 or greater than the count, its invalid
if index < 0 or index >= self.get_length():
raise Exception('not valid index')
# if index is 0 then just point the head to the next element.
# python handles garbage
if index==0:
self.head = self.head.next
# keep count of where we are
count = 0
# start at the head
itr = self.head
# iter through linked list
while itr:
# if we reach the index BEFORE the index to drop move that index to the next.next
# skipping the one we want to drop python garbage will clean.
if count == index - 1:
itr.next = itr.next.next
break
# if not n-1 count + 1 move to next.
itr = itr.next
count += 1
def insert_at(self, index, data):
if index < 0 or index >= self.get_length():
raise Exception('invalid index')
if index == 0:
self.insert_at_begining(data)
count = 0
itr = self.head
while itr:
if count == index - 1:
node = Node(data,itr.next)
itr.next = node
break
itr = itr.next
count += 1
def insert_after_value(self, data_after, data_to_insert):
# look for a value then insert after that value
# use insert value?
if self.head is None:
return
if self.head.data==data_after:
self.head.next = Node(data_to_insert,self.head.next)
return
itr = self.head
while itr:
if itr.data == data_after:
itr.next = Node(data_to_insert, itr.next)
break
itr = itr.next
def remove_by_value(self, data_to_remove):
if self.head is None:
return
if self.head.data == data_to_remove:
self.head = self.head.next
return
itr = self.head
while itr.next:
if itr.next.data == data_to_remove:
itr.next = itr.next.next
break
itr = itr.next
# following links and print
def print(self):
# if the list is empty print nothing
if self.head is None:
print("list is empty")
return
# while itr is anything other than None, print it, else quit.
itr = self.head
linked_list = ''
while itr:
linked_list += str(itr.data) + ' --> '
itr = itr.next
print(linked_list)
if __name__ == '__main__':
ll = LinkedList()
ll.insert_values(["banana","mango","grapes","orange"])
ll.print()
ll.insert_after_value("mango","apple") # insert apple after mango
ll.print()
ll.remove_by_value("orange") # remove orange from linked list
ll.print()
ll.remove_by_value("figs")
ll.print()
ll.remove_by_value("banana")
ll.remove_by_value("mango")
ll.remove_by_value("apple")
ll.remove_by_value("grapes")
ll.print()
|
"""
https://www.youtube.com/watch?v=UflHuQj6MVA&list=RDCMUCnxhETjJtTPs37hOZ7vQ88g&index=2
https://www.geeksforgeeks.org/longest-palindrome-substring-set-1/
"""
def longest_palindromic_substring(s):
n = len(s)
table = [[0 for x in range(n)] for y in range(n)]
# all strings of length 1 are palindrome
start = 0
max_len = 1
for i in range(n):
table[i][i] = 1
for i in range(n-1):
if s[i] == s[i+1]:
table[i][i+1] = 1
start = i
max_len = 2
for k in range(3, n):
for i in range(n - k + 1):
j = i + k - 1
if table[i+1][j-1] and s[i] == s[j]:
table[i][j] = 1
if k > max_len:
max_len = k
start = i
print(s[start:start+max_len])
return max_len
longest_palindromic_substring("aaaabbaa")
|
n = int(input())
matrix = [list(map(int, input().split(" "))) for _ in range(n)]
total = 0
for i in range(n):
value = matrix[i][i]
total += value
print(total)
|
PROBLEM_PID_MAX_LENGTH = 32
PROBLEM_TITLE_MAX_LENGTH = 128
PROBLEM_SECTION_MAX_LENGTH = 4096
PROBLEM_SAMPLE_MAX_LENGTH = 1024
|
__author__ = 'shukkkur'
'''
https://codeforces.com/problemset/problem/200/B
'''
n = int(input())
props = list(map(int, input().split()))
total = sum([p/100 for p in props])
print((total/n)*100)
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
prev = None
curr = head
length = 0
while curr:
curr = curr.next
length += 1
half = length // 2
curr = head
for _ in range(half):
next = curr.next
curr.next = prev
prev, curr = curr, next
left = prev
right = curr if length % 2 == 0 else curr.next
while left and right:
if left.val != right.val:
return False
left, right = left.next, right.next
return True
|
#!/usr/bin/env python3
"""
Initializaiton
+--------------------------------------------------------------------------+
| Copyright 2019 St. Jude Children's Research Hospital |
| |
| Licensed under a modified version of the Apache License, Version 2.0 |
| (the "License") for academic research use only; you may not use this |
| file except in compliance with the License. To inquire about commercial |
| use, please contact the St. Jude Office of Technology Licensing at |
| scott.elmer@stjude.org. |
| |
| 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. |
+--------------------------------------------------------------------------+
"""
__version__ = "0.1.0"
|
students = []
class Student:
# Python 没有权限控制, 所有的方法都是 public ,可以通过规范命名去说明
# class property
school_name = "SHICHENGZHOGNXUE"
def __init__(self, name, stu_id=110):
# instance property
self.name = name
self.stu_id = stu_id
students.append(self)
def get_name_capitalize(self):
return self.name.capitalize()
def __str__(self):
return "Student name is {0}, id is {1}".format(self.name, self.stu_id)
class HighSchoolStudent(Student):
def __str__(self):
result_str = super().__str__()
return "This is High School ,{0}".format(result_str)
|
# Learn python - Full Course for Beginners [Tutorial]
# https://www.youtube.com/watch?v=rfscVS0vtbw
# freeCodeCamp.org
# Course developed by Mike Dane.
# Exercise: While Loop
# Date: 30 Aug 2021
# A while loop is a structure that allows code to be executed multiple times until condition is false
# a loop condition , loop guard, keep loop if true
# while loop a powerful structure
i = 1
while i <= 10:
print(i)
i += 1 # i = i + 1 python shorthand i +- 1
print("Done with loop")
# Guessing Game - without limits
secret_word = "giraffe"
guess = ""
while guess != secret_word:
guess = input("Enter guess: ")
print("You win!")
# Guessing Game - introduce guess limits
secret_word = "giraffe"
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False
while guess != secret_word and not(out_of_guesses):
if guess_count < guess_limit:
guess = input("Enter guess: ")
guess_count += 1
else:
out_of_guesses = True
if out_of_guesses:
print("Out of Guesses, You Lose!")
else:
print("You win! Well Done!")
# Guessing Game - I was playing with shaping the code differently
secret_word = "giraffe"
guess = ""
guess_count = 0
guess_limit = 4
while guess != secret_word and guess_count < guess_limit:
guess = input("Enter guess: ")
guess_count += 1
if guess_count < guess_limit:
print("Out of Guesses, You Lose!")
else:
print("You win! It took you " + str(guess_count) + " guesses. Well Done!")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.