content
stringlengths 7
1.05M
| fixed_cases
stringlengths 1
1.28M
|
|---|---|
class Solution:
"""
@param nums: The integer array.
@param target: Target to find.
@return: The first position of target. Position starts from 0.
"""
def binarySearch(self, nums, target):
left = 0
right = len(nums) - 1
while right != left:
mid = (left + right) // 2
if nums[mid] == target:
while mid > 0 and nums[mid - 1] == nums[mid]:
mid -= 1
return mid
elif nums[mid] > target:
right = mid
else:
if left == mid:
left += 1
else:
left = mid
return -1
|
class Solution:
"""
@param nums: The integer array.
@param target: Target to find.
@return: The first position of target. Position starts from 0.
"""
def binary_search(self, nums, target):
left = 0
right = len(nums) - 1
while right != left:
mid = (left + right) // 2
if nums[mid] == target:
while mid > 0 and nums[mid - 1] == nums[mid]:
mid -= 1
return mid
elif nums[mid] > target:
right = mid
elif left == mid:
left += 1
else:
left = mid
return -1
|
'''
This solution worked out because it has a time complexity of O(N)
'''
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(A):
# write your code in Python 3.6
lengthy = len(A)
if (lengthy == 0 or lengthy == 1):
return 0
diffies =[]
maxy = sum(A)
tempy = 0
for i in range(0, lengthy-1, 1):
tempy = tempy + A[i]
diffies.append(abs(maxy-tempy-tempy))
print('diffies ',diffies)
# print(min(diffies))
return(min(diffies))
|
"""
This solution worked out because it has a time complexity of O(N)
"""
def solution(A):
lengthy = len(A)
if lengthy == 0 or lengthy == 1:
return 0
diffies = []
maxy = sum(A)
tempy = 0
for i in range(0, lengthy - 1, 1):
tempy = tempy + A[i]
diffies.append(abs(maxy - tempy - tempy))
print('diffies ', diffies)
return min(diffies)
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
if not root:
return ""
paths = []
self.binaryTreePathsHelper(root, paths, [])
return paths
def binaryTreePathsHelper(self, root, paths, currentRoute):
if root:
currentRoute.append(str(root.val))
if not root.left and not root.right: # If the node is a leaf
paths.append("->".join(currentRoute))
else:
if root.left:
self.binaryTreePathsHelper(root.left, paths, currentRoute)
if root.right:
self.binaryTreePathsHelper(root.right, paths, currentRoute)
currentRoute.pop()
|
class Solution(object):
def binary_tree_paths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
if not root:
return ''
paths = []
self.binaryTreePathsHelper(root, paths, [])
return paths
def binary_tree_paths_helper(self, root, paths, currentRoute):
if root:
currentRoute.append(str(root.val))
if not root.left and (not root.right):
paths.append('->'.join(currentRoute))
else:
if root.left:
self.binaryTreePathsHelper(root.left, paths, currentRoute)
if root.right:
self.binaryTreePathsHelper(root.right, paths, currentRoute)
currentRoute.pop()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# =============================================================================
#
# =============================================================================
__author__ = 'Chet Coenen'
__copyright__ = 'Copyright 2020'
__credits__ = ['Chet Coenen']
__license__ = '/LICENSE'
__version__ = '1.0'
__maintainer__ = 'Chet Coenen'
__email__ = 'chet.m.coenen@icloud.com'
__socials__ = '@Denimbeard'
__status__ = 'Complete'
__description__ = 'et of code to convert a whole number from base 10 to variable base without directly using base conversions'
__date__ = '30 November 2020 at 15:42'
#==============================================================================
n = int(input("Input a whole number to convert from base 10: "))
#User inputs a whole positive number, converted to an int
b = int(input("Input a base to convert into: "))
#User inputs the new base for their number, converted to an int
def toDigits(n, b):
#Convert a positive number n to its digit representation in base b.
digits = []
#Digits is an empty array that will fill with the math
while n > 0:
#While your whole number is greater than 0 do the following
digits.insert(0, n % b)
#Insert into position 0 of digits array the remainder of n/b
n = n // b
#Your whole number now equals the previous whole number divided by b, rounded down
return digits
#Print the array named digits
list = toDigits(n, b)
#Sets the resulting array to the variable list
def convert(list):
#Converts the array into a single number
res = int("".join(map(str, list)))
return res
cr = convert(list)
print("The number {n} converted to base {b} is: {cr}." .format(n=n, b=b, cr=cr))
#Gives results
|
__author__ = 'Chet Coenen'
__copyright__ = 'Copyright 2020'
__credits__ = ['Chet Coenen']
__license__ = '/LICENSE'
__version__ = '1.0'
__maintainer__ = 'Chet Coenen'
__email__ = 'chet.m.coenen@icloud.com'
__socials__ = '@Denimbeard'
__status__ = 'Complete'
__description__ = 'et of code to convert a whole number from base 10 to variable base without directly using base conversions'
__date__ = '30 November 2020 at 15:42'
n = int(input('Input a whole number to convert from base 10: '))
b = int(input('Input a base to convert into: '))
def to_digits(n, b):
digits = []
while n > 0:
digits.insert(0, n % b)
n = n // b
return digits
list = to_digits(n, b)
def convert(list):
res = int(''.join(map(str, list)))
return res
cr = convert(list)
print('The number {n} converted to base {b} is: {cr}.'.format(n=n, b=b, cr=cr))
|
# coding: utf-8
"""
https://leetcode.com/problems/min-stack/
"""
class MinStack:
def __init__(self):
self.array = []
def push(self, x: int) -> None:
self.array.append(x)
def pop(self) -> None:
self.array.pop()
def top(self) -> int:
return self.array[-1]
def getMin(self) -> int:
return min(self.array)
class MinStack2:
def __init__(self):
self.stack = []
# We use an extra variable to track the minimum value.
self.min_value = float('inf')
def push(self, x: int) -> None:
self.stack.append(x)
if x < self.min_value:
self.min_value = x
def pop(self) -> None:
popped = self.stack.pop()
if popped == self.min_value:
if self.stack:
self.min_value = min(self.stack)
else:
self.min_value = float('inf')
def top(self) -> int:
return self.stack[-1]
def getMin(self) -> int:
if self.min_value == float('inf'):
return self.stack[0]
return self.min_value
class MinStack3:
def __init__(self):
self.stack = []
# We keep track of the minimum value for each push(),
# and push the minimum value into track_stack.
# NOTE: The length of both stacks are always equal.
# https://www.geeksforgeeks.org/tracking-current-maximum-element-in-a-stack/
self.track_stack = []
def push(self, x: int) -> None:
self.stack.append(x)
try:
current_min = self.track_stack[-1]
except IndexError:
self.track_stack.append(x)
else:
if x < current_min:
# There is a new minimum value.
current_min = x
else:
# The minimum is still the same as the last push().
pass
self.track_stack.append(current_min)
def pop(self) -> None:
self.stack.pop()
self.track_stack.pop()
def top(self) -> int:
return self.stack[-1]
def getMin(self) -> int:
return self.track_stack[-1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
|
"""
https://leetcode.com/problems/min-stack/
"""
class Minstack:
def __init__(self):
self.array = []
def push(self, x: int) -> None:
self.array.append(x)
def pop(self) -> None:
self.array.pop()
def top(self) -> int:
return self.array[-1]
def get_min(self) -> int:
return min(self.array)
class Minstack2:
def __init__(self):
self.stack = []
self.min_value = float('inf')
def push(self, x: int) -> None:
self.stack.append(x)
if x < self.min_value:
self.min_value = x
def pop(self) -> None:
popped = self.stack.pop()
if popped == self.min_value:
if self.stack:
self.min_value = min(self.stack)
else:
self.min_value = float('inf')
def top(self) -> int:
return self.stack[-1]
def get_min(self) -> int:
if self.min_value == float('inf'):
return self.stack[0]
return self.min_value
class Minstack3:
def __init__(self):
self.stack = []
self.track_stack = []
def push(self, x: int) -> None:
self.stack.append(x)
try:
current_min = self.track_stack[-1]
except IndexError:
self.track_stack.append(x)
else:
if x < current_min:
current_min = x
else:
pass
self.track_stack.append(current_min)
def pop(self) -> None:
self.stack.pop()
self.track_stack.pop()
def top(self) -> int:
return self.stack[-1]
def get_min(self) -> int:
return self.track_stack[-1]
|
# vim:tw=50
"""Tuples
You have already seen one kind of sequence: the
string. Strings are a sequence of one-character
strings - they're strings all the way down. They
are also **immutable**: once you have defined one,
it can never change.
Another immutable seqeunce type in Python is the
**tuple**. You define a tuple by separating values
by commas, thus:
10, 20, 30 # This is a 3-element tuple.
They are usually set apart with parentheses, e.g.,
|(10, 20, 30)|, though these are not always
required (the empty tuple |()|, however, does
require parentheses). It's usually best to just
use them.
Tuples, as is true of every other Python sequence,
support **indexing**, accessing a single element
with the |[]| notation:
print(my_tuple[10]) # Get element 10.
Exercises
- Create a one-element tuple and print it out,
e.g., |a = 4,| (the trailing comma is required).
- Try comparing two tuples to each other using
standard comparison operators, like |<| or |>=|.
How does the comparison work?
"""
# A basic tuple.
a = 1, 3, 'hey', 2
print(a)
# Usually you see them with parentheses:
b = (1, 3, 'hey', 2)
print(b)
print("b has", len(b), "elements")
# Indexing is easy:
print("first element", b[0])
print("third element", b[2])
# Even from the right side (the 'back'):
print("last element", b[-1])
print("penultimate", b[-2])
# Parentheses are always required for the empty
# tuple:
print("empty", ())
# And single-element tuples have to have a comma:
print("singleton", (5,)) # A tuple
print("not a tuple", (5)) # A number
# They are immutable, though: you can't change
# them.
b[1] = 'new value' # oops
|
"""Tuples
You have already seen one kind of sequence: the
string. Strings are a sequence of one-character
strings - they're strings all the way down. They
are also **immutable**: once you have defined one,
it can never change.
Another immutable seqeunce type in Python is the
**tuple**. You define a tuple by separating values
by commas, thus:
10, 20, 30 # This is a 3-element tuple.
They are usually set apart with parentheses, e.g.,
|(10, 20, 30)|, though these are not always
required (the empty tuple |()|, however, does
require parentheses). It's usually best to just
use them.
Tuples, as is true of every other Python sequence,
support **indexing**, accessing a single element
with the |[]| notation:
print(my_tuple[10]) # Get element 10.
Exercises
- Create a one-element tuple and print it out,
e.g., |a = 4,| (the trailing comma is required).
- Try comparing two tuples to each other using
standard comparison operators, like |<| or |>=|.
How does the comparison work?
"""
a = (1, 3, 'hey', 2)
print(a)
b = (1, 3, 'hey', 2)
print(b)
print('b has', len(b), 'elements')
print('first element', b[0])
print('third element', b[2])
print('last element', b[-1])
print('penultimate', b[-2])
print('empty', ())
print('singleton', (5,))
print('not a tuple', 5)
b[1] = 'new value'
|
"""
# COMBINATION SUM II
Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.
Each number in candidates may only be used once in the combination.
Note: The solution set must not contain duplicate combinations.
Example 1:
Input: candidates = [10,1,2,7,6,1,5], target = 8
Output:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]
Example 2:
Input: candidates = [2,5,2,1,2], target = 5
Output:
[
[1,2,2],
[5]
]
Constraints:
1 <= candidates.length <= 100
1 <= candidates[i] <= 50
1 <= target <= 30
"""
def combinationSum2(candidates, target):
candidates.sort()
return combo(candidates, target)
def combo(candidates, target):
if len(candidates) == 0 or target < min(candidates):
return []
result = []
if target in candidates:
result.append([target])
for i, x in enumerate(candidates):
if i > 0 and x == candidates[i - 1]:
continue
y = combo(candidates[i+1:], target - x)
if len(y) == 0:
continue
for t in y:
t.append(x)
result.append(t)
return result
|
"""
# COMBINATION SUM II
Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.
Each number in candidates may only be used once in the combination.
Note: The solution set must not contain duplicate combinations.
Example 1:
Input: candidates = [10,1,2,7,6,1,5], target = 8
Output:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]
Example 2:
Input: candidates = [2,5,2,1,2], target = 5
Output:
[
[1,2,2],
[5]
]
Constraints:
1 <= candidates.length <= 100
1 <= candidates[i] <= 50
1 <= target <= 30
"""
def combination_sum2(candidates, target):
candidates.sort()
return combo(candidates, target)
def combo(candidates, target):
if len(candidates) == 0 or target < min(candidates):
return []
result = []
if target in candidates:
result.append([target])
for (i, x) in enumerate(candidates):
if i > 0 and x == candidates[i - 1]:
continue
y = combo(candidates[i + 1:], target - x)
if len(y) == 0:
continue
for t in y:
t.append(x)
result.append(t)
return result
|
# EASY
# find all multiples less than n
# ex Input 6
# arr = [1:True, 2:True ,3:True ,4:True ,5:True ]
# start from 2, mark 2*2, 2*3, 2*4 ... False
# Time O(N^2) Space O(N)
class Solution:
def countPrimes(self, n: int) -> int:
arr = [1 for _ in range(n)]
count = 0
for i in range(2,n):
j = 2
while arr[i] and i*j < n:
arr[i*j] = 0
j += 1
for i in range(2,n):
if arr[i]:
count+= 1
return count
|
class Solution:
def count_primes(self, n: int) -> int:
arr = [1 for _ in range(n)]
count = 0
for i in range(2, n):
j = 2
while arr[i] and i * j < n:
arr[i * j] = 0
j += 1
for i in range(2, n):
if arr[i]:
count += 1
return count
|
class ViewModel:
current_model = None
def __init__(self, view):
self.view = view
def switch(self, model):
self.clear_annotation()
self.current_model = model
self.view.show(model)
def get_current_id(self):
return self.current_model.identifier
def clear_annotation(self):
self.view.clear_annotation()
def show_annotation(self, annotation):
self.view.show_annotation(annotation)
|
class Viewmodel:
current_model = None
def __init__(self, view):
self.view = view
def switch(self, model):
self.clear_annotation()
self.current_model = model
self.view.show(model)
def get_current_id(self):
return self.current_model.identifier
def clear_annotation(self):
self.view.clear_annotation()
def show_annotation(self, annotation):
self.view.show_annotation(annotation)
|
var1 = "Hello World"
var2 = 100
# while something is true do stuff
while(var2 < 110):
print("still less than 110!")
var2 += 1
else:
print(f"Not less than 110: var2 = {var2}")
|
var1 = 'Hello World'
var2 = 100
while var2 < 110:
print('still less than 110!')
var2 += 1
else:
print(f'Not less than 110: var2 = {var2}')
|
def sort_carries(carries):
sorted_results = {"loss": [], "no_gain": [], "short_gain": [], "med_gain": [], "big_gain": []}
for carry in carries:
if carry < 0:
sorted_results["loss"].append(carry)
elif carry == 0:
sorted_results["no_gain"].append(carry)
elif 0 < carry < 5:
sorted_results["short_gain"].append(carry)
elif 5 <= carry < 10:
sorted_results["med_gain"].append(carry)
elif carry >= 10:
sorted_results["big_gain"].append(carry)
return sorted_results
def bucket_carry_counts(raw_carries):
sorted_carries = sort_carries(raw_carries)
bucketed_carries = {'loss': len(sorted_carries['loss']),
'no_gain': len(sorted_carries['no_gain']),
'short_gain': len(sorted_carries['short_gain']),
'med_gain': len(sorted_carries['med_gain']),
'big_gain': len(sorted_carries['big_gain'])}
return bucketed_carries
|
def sort_carries(carries):
sorted_results = {'loss': [], 'no_gain': [], 'short_gain': [], 'med_gain': [], 'big_gain': []}
for carry in carries:
if carry < 0:
sorted_results['loss'].append(carry)
elif carry == 0:
sorted_results['no_gain'].append(carry)
elif 0 < carry < 5:
sorted_results['short_gain'].append(carry)
elif 5 <= carry < 10:
sorted_results['med_gain'].append(carry)
elif carry >= 10:
sorted_results['big_gain'].append(carry)
return sorted_results
def bucket_carry_counts(raw_carries):
sorted_carries = sort_carries(raw_carries)
bucketed_carries = {'loss': len(sorted_carries['loss']), 'no_gain': len(sorted_carries['no_gain']), 'short_gain': len(sorted_carries['short_gain']), 'med_gain': len(sorted_carries['med_gain']), 'big_gain': len(sorted_carries['big_gain'])}
return bucketed_carries
|
#
# PySNMP MIB module CXPhysicalInterfaceManager-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CXPhysicalInterfaceManager-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:17:44 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueSizeConstraint", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsIntersection")
cxPortManager, = mibBuilder.importSymbols("CXProduct-SMI", "cxPortManager")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
ObjectIdentity, IpAddress, MibIdentifier, Gauge32, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, Unsigned32, Counter64, Counter32, iso, TimeTicks, Bits, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "ObjectIdentity", "IpAddress", "MibIdentifier", "Gauge32", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "Unsigned32", "Counter64", "Counter32", "iso", "TimeTicks", "Bits", "NotificationType")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
cxPhyIfTable = MibTable((1, 3, 6, 1, 4, 1, 495, 2, 1, 5, 16, 3), )
if mibBuilder.loadTexts: cxPhyIfTable.setStatus('mandatory')
cxPhyIfEntry = MibTableRow((1, 3, 6, 1, 4, 1, 495, 2, 1, 5, 16, 3, 1), ).setIndexNames((0, "CXPhysicalInterfaceManager-MIB", "cxPhyIfIndex"))
if mibBuilder.loadTexts: cxPhyIfEntry.setStatus('mandatory')
cxPhyIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 5, 16, 3, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cxPhyIfIndex.setStatus('mandatory')
cxPhyIfType = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 5, 16, 3, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28))).clone(namedValues=NamedValues(("others", 1), ("v24", 2), ("v35", 3), ("x21", 4), ("v34", 5), ("u-isdn-bri", 6), ("st-isdn-bri", 8), ("dds-56k", 10), ("dds-t1e1", 11), ("fxs-voice", 12), ("fxo-voice", 13), ("em-voice", 14), ("ethernet", 15), ("token-ring", 16), ("v35-eu", 17), ("hsIO", 18), ("usIO", 19), ("lanIO", 20), ("elIO", 21), ("voxIO", 22), ("tlIO", 23), ("t1e1IO", 24), ("dvc", 25), ("multi-io", 26), ("fast-ethernet", 27), ("atm-cell-io", 28)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cxPhyIfType.setStatus('mandatory')
mibBuilder.exportSymbols("CXPhysicalInterfaceManager-MIB", cxPhyIfIndex=cxPhyIfIndex, cxPhyIfTable=cxPhyIfTable, cxPhyIfEntry=cxPhyIfEntry, cxPhyIfType=cxPhyIfType)
|
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_size_constraint, single_value_constraint, value_range_constraint, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'ValueSizeConstraint', 'SingleValueConstraint', 'ValueRangeConstraint', 'ConstraintsIntersection')
(cx_port_manager,) = mibBuilder.importSymbols('CXProduct-SMI', 'cxPortManager')
(notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance')
(object_identity, ip_address, mib_identifier, gauge32, integer32, mib_scalar, mib_table, mib_table_row, mib_table_column, module_identity, unsigned32, counter64, counter32, iso, time_ticks, bits, notification_type) = mibBuilder.importSymbols('SNMPv2-SMI', 'ObjectIdentity', 'IpAddress', 'MibIdentifier', 'Gauge32', 'Integer32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'ModuleIdentity', 'Unsigned32', 'Counter64', 'Counter32', 'iso', 'TimeTicks', 'Bits', 'NotificationType')
(textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString')
cx_phy_if_table = mib_table((1, 3, 6, 1, 4, 1, 495, 2, 1, 5, 16, 3))
if mibBuilder.loadTexts:
cxPhyIfTable.setStatus('mandatory')
cx_phy_if_entry = mib_table_row((1, 3, 6, 1, 4, 1, 495, 2, 1, 5, 16, 3, 1)).setIndexNames((0, 'CXPhysicalInterfaceManager-MIB', 'cxPhyIfIndex'))
if mibBuilder.loadTexts:
cxPhyIfEntry.setStatus('mandatory')
cx_phy_if_index = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 5, 16, 3, 1, 1), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cxPhyIfIndex.setStatus('mandatory')
cx_phy_if_type = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 5, 16, 3, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28))).clone(namedValues=named_values(('others', 1), ('v24', 2), ('v35', 3), ('x21', 4), ('v34', 5), ('u-isdn-bri', 6), ('st-isdn-bri', 8), ('dds-56k', 10), ('dds-t1e1', 11), ('fxs-voice', 12), ('fxo-voice', 13), ('em-voice', 14), ('ethernet', 15), ('token-ring', 16), ('v35-eu', 17), ('hsIO', 18), ('usIO', 19), ('lanIO', 20), ('elIO', 21), ('voxIO', 22), ('tlIO', 23), ('t1e1IO', 24), ('dvc', 25), ('multi-io', 26), ('fast-ethernet', 27), ('atm-cell-io', 28)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cxPhyIfType.setStatus('mandatory')
mibBuilder.exportSymbols('CXPhysicalInterfaceManager-MIB', cxPhyIfIndex=cxPhyIfIndex, cxPhyIfTable=cxPhyIfTable, cxPhyIfEntry=cxPhyIfEntry, cxPhyIfType=cxPhyIfType)
|
def df_to_lower(data, cols=None):
'''Convert all string values to lowercase
data : pandas dataframe
The dataframe to be cleaned
cols : str, list, or None
If None, an attempt will be made to turn
all string columns into lowercase.
'''
if isinstance(cols, str):
cols = [cols]
elif cols is None:
cols = data.columns
for col in cols:
try:
data[col] = data[col].str.lower()
except AttributeError:
pass
return data
|
def df_to_lower(data, cols=None):
"""Convert all string values to lowercase
data : pandas dataframe
The dataframe to be cleaned
cols : str, list, or None
If None, an attempt will be made to turn
all string columns into lowercase.
"""
if isinstance(cols, str):
cols = [cols]
elif cols is None:
cols = data.columns
for col in cols:
try:
data[col] = data[col].str.lower()
except AttributeError:
pass
return data
|
def exercise_1():
a_word = "hello world"
f = open("exo1.txt",'a')
f.write(a_word)
f.close()
def save_list2file(sentences, filename):
f = open(filename,"w")
f.close()
|
def exercise_1():
a_word = 'hello world'
f = open('exo1.txt', 'a')
f.write(a_word)
f.close()
def save_list2file(sentences, filename):
f = open(filename, 'w')
f.close()
|
'''
The .pivot_table() method has several useful arguments, including fill_value and margins.
fill_value replaces missing values with a real value (known as imputation). What to replace missing values with is a topic big enough to have its own course (Dealing with Missing Data in Python), but the simplest thing to do is to substitute a dummy value.
margins is a shortcut for when you pivoted by two variables, but also wanted to pivot by each of those variables separately: it gives the row and column totals of the pivot table contents.
In this exercise, you'll practice using these arguments to up your pivot table skills, which will help you crunch numbers more efficiently!
'''
# Print mean weekly_sales by department and type; fill missing values with 0
print(sales.pivot_table(values="weekly_sales", index="type", columns="department", fill_value=0))
# Print the mean weekly_sales by department and type; fill missing values with 0s; sum all rows and cols
print(sales.pivot_table(values="weekly_sales", index="department", columns="type", fill_value=0, margins=True))
|
"""
The .pivot_table() method has several useful arguments, including fill_value and margins.
fill_value replaces missing values with a real value (known as imputation). What to replace missing values with is a topic big enough to have its own course (Dealing with Missing Data in Python), but the simplest thing to do is to substitute a dummy value.
margins is a shortcut for when you pivoted by two variables, but also wanted to pivot by each of those variables separately: it gives the row and column totals of the pivot table contents.
In this exercise, you'll practice using these arguments to up your pivot table skills, which will help you crunch numbers more efficiently!
"""
print(sales.pivot_table(values='weekly_sales', index='type', columns='department', fill_value=0))
print(sales.pivot_table(values='weekly_sales', index='department', columns='type', fill_value=0, margins=True))
|
def matrix_rank(x):
"""
Returns the rank of a Galois field matrix.
References
----------
* https://numpy.org/doc/stable/reference/generated/numpy.linalg.matrix_rank.html
Examples
--------
.. ipython:: python
GF = galois.GF(31)
A = GF.Identity(4); A
np.linalg.matrix_rank(A)
One column is a linear combination of another.
.. ipython:: python
GF = galois.GF(31)
A = GF.Random((4,4)); A
A[:,2] = A[:,1] * GF(17); A
np.linalg.matrix_rank(A)
One row is a linear combination of another.
.. ipython:: python
GF = galois.GF(31)
A = GF.Random((4,4)); A
A[3,:] = A[2,:] * GF(8); A
np.linalg.matrix_rank(A)
"""
return
def matrix_power(x):
"""
Raises a square Galois field matrix to an integer power.
References
----------
* https://numpy.org/doc/stable/reference/generated/numpy.linalg.matrix_power.html
Examples
--------
.. ipython:: python
GF = galois.GF(31)
A = GF.Random((3,3)); A
np.linalg.matrix_power(A, 3)
A @ A @ A
.. ipython:: python
GF = galois.GF(31)
# Ensure A is full rank and invertible
while True:
A = GF.Random((3,3))
if np.linalg.matrix_rank(A) == 3:
break
A
np.linalg.matrix_power(A, -3)
A_inv = np.linalg.inv(A)
A_inv @ A_inv @ A_inv
"""
return
def det(A):
"""
Computes the determinant of the matrix.
References
----------
* https://numpy.org/doc/stable/reference/generated/numpy.linalg.det.html
Examples
--------
.. ipython:: python
GF = galois.GF(31)
A = GF.Random((2,2)); A
np.linalg.det(A)
A[0,0]*A[1,1] - A[0,1]*A[1,0]
"""
return
def inv(A):
"""
Computes the inverse of the matrix.
References
----------
* https://numpy.org/doc/stable/reference/generated/numpy.linalg.inv.html
Examples
--------
.. ipython:: python
GF = galois.GF(31)
# Ensure A is full rank and invertible
while True:
A = GF.Random((3,3))
if np.linalg.matrix_rank(A) == 3:
break
A
A_inv = np.linalg.inv(A); A_inv
A_inv @ A
"""
return
def solve(x):
"""
Solves the system of linear equations.
References
----------
* https://numpy.org/doc/stable/reference/generated/numpy.linalg.solve.html
Examples
--------
.. ipython:: python
GF = galois.GF(31)
# Ensure A is full rank and invertible
while True:
A = GF.Random((4,4))
if np.linalg.matrix_rank(A) == 4:
break
A
b = GF.Random(4); b
x = np.linalg.solve(A, b); x
A @ x
.. ipython:: python
GF = galois.GF(31)
# Ensure A is full rank and invertible
while True:
A = GF.Random((4,4))
if np.linalg.matrix_rank(A) == 4:
break
A
B = GF.Random((4,2)); B
X = np.linalg.solve(A, B); X
A @ X
"""
return
|
def matrix_rank(x):
"""
Returns the rank of a Galois field matrix.
References
----------
* https://numpy.org/doc/stable/reference/generated/numpy.linalg.matrix_rank.html
Examples
--------
.. ipython:: python
GF = galois.GF(31)
A = GF.Identity(4); A
np.linalg.matrix_rank(A)
One column is a linear combination of another.
.. ipython:: python
GF = galois.GF(31)
A = GF.Random((4,4)); A
A[:,2] = A[:,1] * GF(17); A
np.linalg.matrix_rank(A)
One row is a linear combination of another.
.. ipython:: python
GF = galois.GF(31)
A = GF.Random((4,4)); A
A[3,:] = A[2,:] * GF(8); A
np.linalg.matrix_rank(A)
"""
return
def matrix_power(x):
"""
Raises a square Galois field matrix to an integer power.
References
----------
* https://numpy.org/doc/stable/reference/generated/numpy.linalg.matrix_power.html
Examples
--------
.. ipython:: python
GF = galois.GF(31)
A = GF.Random((3,3)); A
np.linalg.matrix_power(A, 3)
A @ A @ A
.. ipython:: python
GF = galois.GF(31)
# Ensure A is full rank and invertible
while True:
A = GF.Random((3,3))
if np.linalg.matrix_rank(A) == 3:
break
A
np.linalg.matrix_power(A, -3)
A_inv = np.linalg.inv(A)
A_inv @ A_inv @ A_inv
"""
return
def det(A):
"""
Computes the determinant of the matrix.
References
----------
* https://numpy.org/doc/stable/reference/generated/numpy.linalg.det.html
Examples
--------
.. ipython:: python
GF = galois.GF(31)
A = GF.Random((2,2)); A
np.linalg.det(A)
A[0,0]*A[1,1] - A[0,1]*A[1,0]
"""
return
def inv(A):
"""
Computes the inverse of the matrix.
References
----------
* https://numpy.org/doc/stable/reference/generated/numpy.linalg.inv.html
Examples
--------
.. ipython:: python
GF = galois.GF(31)
# Ensure A is full rank and invertible
while True:
A = GF.Random((3,3))
if np.linalg.matrix_rank(A) == 3:
break
A
A_inv = np.linalg.inv(A); A_inv
A_inv @ A
"""
return
def solve(x):
"""
Solves the system of linear equations.
References
----------
* https://numpy.org/doc/stable/reference/generated/numpy.linalg.solve.html
Examples
--------
.. ipython:: python
GF = galois.GF(31)
# Ensure A is full rank and invertible
while True:
A = GF.Random((4,4))
if np.linalg.matrix_rank(A) == 4:
break
A
b = GF.Random(4); b
x = np.linalg.solve(A, b); x
A @ x
.. ipython:: python
GF = galois.GF(31)
# Ensure A is full rank and invertible
while True:
A = GF.Random((4,4))
if np.linalg.matrix_rank(A) == 4:
break
A
B = GF.Random((4,2)); B
X = np.linalg.solve(A, B); X
A @ X
"""
return
|
def make_differences(arr):
diff_arr = [0] * (len(arr) - 1)
for i in range(1, len(arr)):
diff_arr[i - 1] = arr[i] - arr[i - 1]
return diff_arr
def paths_reconstruction(arr):
num_paths_arr = [0] * len(arr)
num_paths_arr[-1] = 1
for i in range(len(arr) - 2, -1, -1):
num_paths = 0
for j in range(1, 4):
if i + j >= len(arr):
break
if arr[i+j] - arr[i] > 3:
break
num_paths += num_paths_arr[i + j]
num_paths_arr[i] = num_paths
return num_paths_arr[0]
|
def make_differences(arr):
diff_arr = [0] * (len(arr) - 1)
for i in range(1, len(arr)):
diff_arr[i - 1] = arr[i] - arr[i - 1]
return diff_arr
def paths_reconstruction(arr):
num_paths_arr = [0] * len(arr)
num_paths_arr[-1] = 1
for i in range(len(arr) - 2, -1, -1):
num_paths = 0
for j in range(1, 4):
if i + j >= len(arr):
break
if arr[i + j] - arr[i] > 3:
break
num_paths += num_paths_arr[i + j]
num_paths_arr[i] = num_paths
return num_paths_arr[0]
|
class EmptyDicomSeriesException(Exception):
"""
Exception that is raised when the given folder does not contain dcm-files.
"""
def __init__(self, *args):
if not args:
args = ('The specified path does not contain dcm-files. Please ensure that '
'the path points to a folder containing a DICOM-series.', )
Exception.__init__(self, *args)
|
class Emptydicomseriesexception(Exception):
"""
Exception that is raised when the given folder does not contain dcm-files.
"""
def __init__(self, *args):
if not args:
args = ('The specified path does not contain dcm-files. Please ensure that the path points to a folder containing a DICOM-series.',)
Exception.__init__(self, *args)
|
#DictExample8.py
student = {"name":"sumit","college":"stanford","grade":"A"}
#this will prints whole key and values pairs using items()
for x in student.items():
print(x)
print("-----------------------------------------------------")
#you can also store key and value in two differnet variable like
for x,y in student.items():
print(x,"-",y)
|
student = {'name': 'sumit', 'college': 'stanford', 'grade': 'A'}
for x in student.items():
print(x)
print('-----------------------------------------------------')
for (x, y) in student.items():
print(x, '-', y)
|
# -*- coding: utf-8 -*-
def uninstall(portal, reinstall=False):
"""
launch uninstall profile
"""
setup_tool = portal.portal_setup
setup_tool.runAllImportStepsFromProfile(
'profile-Products.PloneGlossary:uninstall')
|
def uninstall(portal, reinstall=False):
"""
launch uninstall profile
"""
setup_tool = portal.portal_setup
setup_tool.runAllImportStepsFromProfile('profile-Products.PloneGlossary:uninstall')
|
class config:
global auth; auth = "YOUR TOKEN" # Enter your discord token for Auto-Login.
global prefix; prefix = "$" # Enter your prefix for selfbot.
global nitro_sniper; nitro_sniper = "true" # 'true' to enable nitro sniper, 'false' to disable.
global giveaway_sniper; giveaway_sniper = "true" # 'true' to enable giveaway sniper, 'false' to disable.
|
class Config:
global auth
auth = 'YOUR TOKEN'
global prefix
prefix = '$'
global nitro_sniper
nitro_sniper = 'true'
global giveaway_sniper
giveaway_sniper = 'true'
|
#
# PySNMP MIB module HUAWEI-IMA-MIB (http://pysnmp.sf.net)
# ASN.1 source http://mibs.snmplabs.com:80/asn1/HUAWEI-IMA-MIB
# Produced by pysmi-0.0.7 at Sun Jul 3 11:25:20 2016
# On host localhost.localdomain platform Linux version 3.10.0-229.7.2.el7.x86_64 by user root
# Using Python version 2.7.5 (default, Jun 24 2015, 00:41:19)
#
(Integer, ObjectIdentifier, OctetString,) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier",
"OctetString")
(NamedValues,) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
(ConstraintsUnion, SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint,
ValueRangeConstraint,) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "SingleValueConstraint",
"ConstraintsIntersection", "ValueSizeConstraint",
"ValueRangeConstraint")
(hwDatacomm,) = mibBuilder.importSymbols("HUAWEI-MIB", "hwDatacomm")
(ifIndex, InterfaceIndexOrZero, InterfaceIndex,) = mibBuilder.importSymbols("IF-MIB", "ifIndex", "InterfaceIndexOrZero",
"InterfaceIndex")
(NotificationGroup, ModuleCompliance, ObjectGroup,) = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup",
"ModuleCompliance", "ObjectGroup")
(Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, MibIdentifier, IpAddress, TimeTicks,
Counter64, Unsigned32, enterprises, ModuleIdentity, Gauge32, iso, ObjectIdentity, Bits,
Counter32,) = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "MibScalar", "MibTable", "MibTableRow",
"MibTableColumn", "NotificationType", "MibIdentifier", "IpAddress", "TimeTicks",
"Counter64", "Unsigned32", "enterprises", "ModuleIdentity", "Gauge32", "iso",
"ObjectIdentity", "Bits", "Counter32")
(DisplayString, RowStatus, TextualConvention, DateAndTime,) = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString",
"RowStatus", "TextualConvention",
"DateAndTime")
hwImaMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176))
hwImaMibObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1))
hwImaMibConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 2))
hwImaNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 3))
class MilliSeconds(Integer32, TextualConvention):
pass
class ImaGroupState(Integer32, TextualConvention):
subtypeSpec = Integer32.subtypeSpec + SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, )
namedValues = NamedValues(("notConfigured", 1), ("startUp", 2), ("startUpAck", 3), ("configAbortUnsupportedM", 4),
("configAbortIncompatibleSymmetry", 5), ("configAbortOther", 6), ("insufficientLinks", 7),
("blocked", 8), ("operational", 9), ("configAbortUnsupportedImaVersion", 10), )
class ImaGroupSymmetry(Integer32, TextualConvention):
subtypeSpec = Integer32.subtypeSpec + SingleValueConstraint(1, 2, 3, )
namedValues = NamedValues(("symmetricOperation", 1), ("asymmetricOperation", 2), ("asymmetricConfiguration", 3), )
class ImaFrameLength(Integer32, TextualConvention):
subtypeSpec = Integer32.subtypeSpec + SingleValueConstraint(1, 2, 3, 4, )
namedValues = NamedValues(("m32", 1), ("m64", 2), ("m128", 3), ("m256", 4), )
class ImaLinkState(Integer32, TextualConvention):
subtypeSpec = Integer32.subtypeSpec + SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, )
namedValues = NamedValues(("notInGroup", 1), ("unusableNoGivenReason", 2), ("unusableFault", 3),
("unusableMisconnected", 4), ("unusableInhibited", 5), ("unusableFailed", 6),
("usable", 7), ("active", 8), )
hwImaGroupTable = MibTable((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1), )
hwImaGroupEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1), ).setIndexNames(
(0, "HUAWEI-IMA-MIB", "hwImaGroupIfIndex"))
hwImaGroupIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 1), InterfaceIndex()).setMaxAccess(
"readonly")
hwImaGroupNeState = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 2), ImaGroupState()).setMaxAccess(
"readonly")
hwImaGroupFeState = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 3), ImaGroupState()).setMaxAccess(
"readonly")
hwImaGroupSymmetry = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 4), ImaGroupSymmetry()).setMaxAccess(
"readonly")
hwImaGroupMinNumTxLinks = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 5),
Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 32))).setMaxAccess(
"readcreate")
hwImaGroupMinNumRxLinks = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 6),
Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 32))).setMaxAccess(
"readcreate")
hwImaGroupTxTimingRefLink = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 7),
InterfaceIndexOrZero()).setMaxAccess("readonly")
hwImaGroupRxTimingRefLink = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 8),
InterfaceIndexOrZero()).setMaxAccess("readonly")
hwImaGroupTxImaId = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 9),
Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess(
"readonly")
hwImaGroupRxImaId = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 10),
Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess(
"readonly")
hwImaGroupTxFrameLength = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 11),
ImaFrameLength()).setMaxAccess("readcreate")
hwImaGroupRxFrameLength = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 12),
ImaFrameLength()).setMaxAccess("readonly")
hwImaGroupDiffDelayMax = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 13),
MilliSeconds().subtype(subtypeSpec=ValueRangeConstraint(25, 120))).setMaxAccess(
"readcreate")
hwImaGroupAlphaValue = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 14),
Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2))).setMaxAccess(
"readonly")
hwImaGroupBetaValue = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 15),
Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 5))).setMaxAccess(
"readonly")
hwImaGroupGammaValue = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 16),
Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 5))).setMaxAccess(
"readonly")
hwImaGroupNumTxActLinks = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 17), Gauge32()).setMaxAccess(
"readonly")
hwImaGroupNumRxActLinks = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 18), Gauge32()).setMaxAccess(
"readonly")
hwImaGroupTxOamLabelValue = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 19),
Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess(
"readonly")
hwImaGroupRxOamLabelValue = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 20),
Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess(
"readonly")
hwImaGroupFirstLinkIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 21),
InterfaceIndex()).setMaxAccess("readonly")
hwImaGroupName = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 22), OctetString()).setMaxAccess(
"accessiblefornotify")
hwImaLinkTable = MibTable((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 2), )
hwImaLinkEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 2, 1), ).setIndexNames(
(0, "HUAWEI-IMA-MIB", "hwImaLinkIfIndex"))
hwImaLinkIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 2, 1, 1), InterfaceIndex())
hwImaLinkGroupIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 2, 1, 2), InterfaceIndex()).setMaxAccess(
"readcreate")
hwImaLinkNeTxState = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 2, 1, 3), ImaLinkState()).setMaxAccess(
"readonly")
hwImaLinkNeRxState = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 2, 1, 4), ImaLinkState()).setMaxAccess(
"readonly")
hwImaLinkFeTxState = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 2, 1, 5), ImaLinkState()).setMaxAccess(
"readonly")
hwImaLinkFeRxState = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 2, 1, 6), ImaLinkState()).setMaxAccess(
"readonly")
hwImaLinkRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 2, 1, 51), RowStatus()).setMaxAccess(
"readcreate")
hwImaLinkName = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 2, 1, 52), OctetString()).setMaxAccess(
"accessiblefornotify")
hwImaAlarmTable = MibTable((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 3), )
hwImaAlarmEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 3, 1), ).setIndexNames(
(0, "HUAWEI-IMA-MIB", "hwImaAlarmIfIndex"))
hwImaAlarmIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 3, 1, 1), Integer32())
hwImaGroupNeDownEn = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 3, 1, 2), Integer32()).setMaxAccess(
"readwrite")
hwImaGroupFeDownEn = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 3, 1, 3), Integer32()).setMaxAccess(
"readwrite")
hwImaGroupTxClkMismatchEn = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 3, 1, 4), Integer32()).setMaxAccess(
"readwrite")
hwImaLinkLifEn = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 3, 1, 5), Integer32()).setMaxAccess("readwrite")
hwImaLinkLodsEn = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 3, 1, 6), Integer32()).setMaxAccess(
"readwrite")
hwImaLinkRfiEn = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 3, 1, 7), Integer32()).setMaxAccess("readwrite")
hwImaLinkFeTxUnusableEn = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 3, 1, 8), Integer32()).setMaxAccess(
"readwrite")
hwImaLinkFeRxUnusableEn = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 3, 1, 9), Integer32()).setMaxAccess(
"readwrite")
hwIMAAllEn = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 3, 1, 10), Integer32()).setMaxAccess("readwrite")
hwImaMibGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 2, 1))
hwImaMibCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 2, 2))
hwImaMibCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 2, 2, 1)).setObjects(
*(("HUAWEI-IMA-MIB", "hwImaGroupGroup"), ("HUAWEI-IMA-MIB", "hwImaLinkGroup"),))
hwImaGroupGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 2, 1, 1)).setObjects(*(
("HUAWEI-IMA-MIB", "hwImaGroupIfIndex"), ("HUAWEI-IMA-MIB", "hwImaGroupNeState"),
("HUAWEI-IMA-MIB", "hwImaGroupFeState"), ("HUAWEI-IMA-MIB", "hwImaGroupSymmetry"),
("HUAWEI-IMA-MIB", "hwImaGroupMinNumTxLinks"), ("HUAWEI-IMA-MIB", "hwImaGroupMinNumRxLinks"),
("HUAWEI-IMA-MIB", "hwImaGroupTxTimingRefLink"), ("HUAWEI-IMA-MIB", "hwImaGroupRxTimingRefLink"),
("HUAWEI-IMA-MIB", "hwImaGroupTxImaId"), ("HUAWEI-IMA-MIB", "hwImaGroupRxImaId"),
("HUAWEI-IMA-MIB", "hwImaGroupTxFrameLength"), ("HUAWEI-IMA-MIB", "hwImaGroupRxFrameLength"),
("HUAWEI-IMA-MIB", "hwImaGroupDiffDelayMax"), ("HUAWEI-IMA-MIB", "hwImaGroupAlphaValue"),
("HUAWEI-IMA-MIB", "hwImaGroupBetaValue"), ("HUAWEI-IMA-MIB", "hwImaGroupGammaValue"),
("HUAWEI-IMA-MIB", "hwImaGroupNumTxActLinks"), ("HUAWEI-IMA-MIB", "hwImaGroupNumRxActLinks"),
("HUAWEI-IMA-MIB", "hwImaGroupTxOamLabelValue"), ("HUAWEI-IMA-MIB", "hwImaGroupRxOamLabelValue"),
("HUAWEI-IMA-MIB", "hwImaGroupFirstLinkIfIndex"),))
hwImaLinkGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 2, 1, 2)).setObjects(*(
("HUAWEI-IMA-MIB", "hwImaLinkGroupIfIndex"), ("HUAWEI-IMA-MIB", "hwImaLinkNeTxState"),
("HUAWEI-IMA-MIB", "hwImaLinkNeRxState"), ("HUAWEI-IMA-MIB", "hwImaLinkFeTxState"),
("HUAWEI-IMA-MIB", "hwImaLinkFeRxState"), ("HUAWEI-IMA-MIB", "hwImaLinkRowStatus"),))
hwImaGroupNeDownAlarm = NotificationType((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 3, 1)).setObjects(
*(("HUAWEI-IMA-MIB", "hwImaGroupName"),))
hwImaGroupNeDownAlarmResume = NotificationType((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 3, 2)).setObjects(
*(("HUAWEI-IMA-MIB", "hwImaGroupName"),))
hwImaGroupFeDownAlarm = NotificationType((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 3, 3)).setObjects(
*(("HUAWEI-IMA-MIB", "hwImaGroupName"),))
hwImaGroupFeDownAlarmResume = NotificationType((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 3, 4)).setObjects(
*(("HUAWEI-IMA-MIB", "hwImaGroupName"),))
hwImaGroupTxClkMismatch = NotificationType((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 3, 5)).setObjects(
*(("HUAWEI-IMA-MIB", "hwImaGroupName"),))
hwImaGroupTxClkMismatchResume = NotificationType((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 3, 6)).setObjects(
*(("HUAWEI-IMA-MIB", "hwImaGroupName"),))
hwImaLinkLifAlarm = NotificationType((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 3, 7)).setObjects(
*(("HUAWEI-IMA-MIB", "hwImaLinkName"),))
hwImaLinkLifAlarmResume = NotificationType((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 3, 8)).setObjects(
*(("HUAWEI-IMA-MIB", "hwImaLinkName"),))
hwImaLinkLodsAlarm = NotificationType((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 3, 9)).setObjects(
*(("HUAWEI-IMA-MIB", "hwImaLinkName"),))
hwImaLinkLodsAlarmResume = NotificationType((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 3, 10)).setObjects(
*(("HUAWEI-IMA-MIB", "hwImaLinkName"),))
hwImaLinkRfiAlarm = NotificationType((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 3, 11)).setObjects(
*(("HUAWEI-IMA-MIB", "hwImaLinkName"),))
hwImaLinkRfiAlarmResume = NotificationType((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 3, 12)).setObjects(
*(("HUAWEI-IMA-MIB", "hwImaLinkName"),))
hwImaLinkFeTxUnusableAlarm = NotificationType((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 3, 13)).setObjects(
*(("HUAWEI-IMA-MIB", "hwImaLinkName"),))
hwImaLinkFeTxUnusableAlarmResume = NotificationType((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 3, 14)).setObjects(
*(("HUAWEI-IMA-MIB", "hwImaLinkName"),))
hwImaLinkFeRxUnusableAlarm = NotificationType((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 3, 15)).setObjects(
*(("HUAWEI-IMA-MIB", "hwImaLinkName"),))
hwImaLinkFeRxUnusableAlarmResume = NotificationType((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 3, 16)).setObjects(
*(("HUAWEI-IMA-MIB", "hwImaLinkName"),))
mibBuilder.exportSymbols("HUAWEI-IMA-MIB", hwImaGroupFirstLinkIfIndex=hwImaGroupFirstLinkIfIndex,
hwImaLinkFeRxState=hwImaLinkFeRxState, PYSNMP_MODULE_ID=hwImaMIB,
hwImaLinkRfiEn=hwImaLinkRfiEn, hwImaGroupNumRxActLinks=hwImaGroupNumRxActLinks,
hwImaLinkRfiAlarmResume=hwImaLinkRfiAlarmResume, hwImaLinkLifAlarm=hwImaLinkLifAlarm,
hwImaGroupTxClkMismatch=hwImaGroupTxClkMismatch,
hwImaGroupRxOamLabelValue=hwImaGroupRxOamLabelValue, hwImaLinkLifEn=hwImaLinkLifEn,
hwImaGroupFeDownAlarmResume=hwImaGroupFeDownAlarmResume, hwImaLinkNeRxState=hwImaLinkNeRxState,
hwImaGroupFeDownAlarm=hwImaGroupFeDownAlarm, ImaGroupState=ImaGroupState,
hwImaAlarmIfIndex=hwImaAlarmIfIndex, hwImaGroupNeDownEn=hwImaGroupNeDownEn,
hwImaLinkEntry=hwImaLinkEntry, hwImaGroupRxTimingRefLink=hwImaGroupRxTimingRefLink,
hwImaGroupNeDownAlarm=hwImaGroupNeDownAlarm, hwImaGroupTable=hwImaGroupTable,
hwImaLinkFeTxState=hwImaLinkFeTxState, ImaGroupSymmetry=ImaGroupSymmetry,
hwImaLinkName=hwImaLinkName, hwImaLinkLodsEn=hwImaLinkLodsEn,
hwImaGroupFeState=hwImaGroupFeState, hwImaLinkIfIndex=hwImaLinkIfIndex,
hwImaGroupMinNumRxLinks=hwImaGroupMinNumRxLinks, hwImaMIB=hwImaMIB,
hwImaGroupGroup=hwImaGroupGroup, hwImaLinkFeTxUnusableEn=hwImaLinkFeTxUnusableEn,
hwImaNotifications=hwImaNotifications, hwImaGroupFeDownEn=hwImaGroupFeDownEn,
hwImaGroupTxImaId=hwImaGroupTxImaId, hwImaGroupTxFrameLength=hwImaGroupTxFrameLength,
hwIMAAllEn=hwIMAAllEn, ImaLinkState=ImaLinkState,
hwImaLinkFeRxUnusableAlarm=hwImaLinkFeRxUnusableAlarm,
hwImaLinkFeRxUnusableAlarmResume=hwImaLinkFeRxUnusableAlarmResume,
hwImaLinkLifAlarmResume=hwImaLinkLifAlarmResume,
hwImaGroupNeDownAlarmResume=hwImaGroupNeDownAlarmResume, hwImaGroupEntry=hwImaGroupEntry,
hwImaMibCompliances=hwImaMibCompliances, hwImaAlarmEntry=hwImaAlarmEntry,
hwImaLinkRowStatus=hwImaLinkRowStatus, hwImaLinkLodsAlarm=hwImaLinkLodsAlarm,
hwImaGroupNeState=hwImaGroupNeState, hwImaMibCompliance=hwImaMibCompliance,
hwImaLinkFeTxUnusableAlarm=hwImaLinkFeTxUnusableAlarm, hwImaGroupIfIndex=hwImaGroupIfIndex,
hwImaGroupTxClkMismatchEn=hwImaGroupTxClkMismatchEn,
hwImaGroupDiffDelayMax=hwImaGroupDiffDelayMax, hwImaGroupRxFrameLength=hwImaGroupRxFrameLength,
hwImaGroupTxClkMismatchResume=hwImaGroupTxClkMismatchResume,
hwImaGroupTxOamLabelValue=hwImaGroupTxOamLabelValue,
hwImaGroupTxTimingRefLink=hwImaGroupTxTimingRefLink, hwImaGroupBetaValue=hwImaGroupBetaValue,
hwImaGroupName=hwImaGroupName, hwImaMibGroups=hwImaMibGroups,
hwImaGroupRxImaId=hwImaGroupRxImaId, hwImaLinkFeRxUnusableEn=hwImaLinkFeRxUnusableEn,
hwImaAlarmTable=hwImaAlarmTable, hwImaLinkNeTxState=hwImaLinkNeTxState,
hwImaGroupSymmetry=hwImaGroupSymmetry, hwImaMibConformance=hwImaMibConformance,
hwImaMibObjects=hwImaMibObjects, MilliSeconds=MilliSeconds,
hwImaGroupMinNumTxLinks=hwImaGroupMinNumTxLinks, hwImaLinkTable=hwImaLinkTable,
hwImaLinkGroup=hwImaLinkGroup, hwImaLinkRfiAlarm=hwImaLinkRfiAlarm,
ImaFrameLength=ImaFrameLength, hwImaGroupGammaValue=hwImaGroupGammaValue,
hwImaGroupAlphaValue=hwImaGroupAlphaValue, hwImaLinkLodsAlarmResume=hwImaLinkLodsAlarmResume,
hwImaGroupNumTxActLinks=hwImaGroupNumTxActLinks,
hwImaLinkFeTxUnusableAlarmResume=hwImaLinkFeTxUnusableAlarmResume,
hwImaLinkGroupIfIndex=hwImaLinkGroupIfIndex)
|
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, constraints_intersection, value_size_constraint, value_range_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'SingleValueConstraint', 'ConstraintsIntersection', 'ValueSizeConstraint', 'ValueRangeConstraint')
(hw_datacomm,) = mibBuilder.importSymbols('HUAWEI-MIB', 'hwDatacomm')
(if_index, interface_index_or_zero, interface_index) = mibBuilder.importSymbols('IF-MIB', 'ifIndex', 'InterfaceIndexOrZero', 'InterfaceIndex')
(notification_group, module_compliance, object_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance', 'ObjectGroup')
(integer32, mib_scalar, mib_table, mib_table_row, mib_table_column, notification_type, mib_identifier, ip_address, time_ticks, counter64, unsigned32, enterprises, module_identity, gauge32, iso, object_identity, bits, counter32) = mibBuilder.importSymbols('SNMPv2-SMI', 'Integer32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'NotificationType', 'MibIdentifier', 'IpAddress', 'TimeTicks', 'Counter64', 'Unsigned32', 'enterprises', 'ModuleIdentity', 'Gauge32', 'iso', 'ObjectIdentity', 'Bits', 'Counter32')
(display_string, row_status, textual_convention, date_and_time) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'RowStatus', 'TextualConvention', 'DateAndTime')
hw_ima_mib = module_identity((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176))
hw_ima_mib_objects = mib_identifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1))
hw_ima_mib_conformance = mib_identifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 2))
hw_ima_notifications = mib_identifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 3))
class Milliseconds(Integer32, TextualConvention):
pass
class Imagroupstate(Integer32, TextualConvention):
subtype_spec = Integer32.subtypeSpec + single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
named_values = named_values(('notConfigured', 1), ('startUp', 2), ('startUpAck', 3), ('configAbortUnsupportedM', 4), ('configAbortIncompatibleSymmetry', 5), ('configAbortOther', 6), ('insufficientLinks', 7), ('blocked', 8), ('operational', 9), ('configAbortUnsupportedImaVersion', 10))
class Imagroupsymmetry(Integer32, TextualConvention):
subtype_spec = Integer32.subtypeSpec + single_value_constraint(1, 2, 3)
named_values = named_values(('symmetricOperation', 1), ('asymmetricOperation', 2), ('asymmetricConfiguration', 3))
class Imaframelength(Integer32, TextualConvention):
subtype_spec = Integer32.subtypeSpec + single_value_constraint(1, 2, 3, 4)
named_values = named_values(('m32', 1), ('m64', 2), ('m128', 3), ('m256', 4))
class Imalinkstate(Integer32, TextualConvention):
subtype_spec = Integer32.subtypeSpec + single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8)
named_values = named_values(('notInGroup', 1), ('unusableNoGivenReason', 2), ('unusableFault', 3), ('unusableMisconnected', 4), ('unusableInhibited', 5), ('unusableFailed', 6), ('usable', 7), ('active', 8))
hw_ima_group_table = mib_table((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1))
hw_ima_group_entry = mib_table_row((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1)).setIndexNames((0, 'HUAWEI-IMA-MIB', 'hwImaGroupIfIndex'))
hw_ima_group_if_index = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 1), interface_index()).setMaxAccess('readonly')
hw_ima_group_ne_state = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 2), ima_group_state()).setMaxAccess('readonly')
hw_ima_group_fe_state = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 3), ima_group_state()).setMaxAccess('readonly')
hw_ima_group_symmetry = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 4), ima_group_symmetry()).setMaxAccess('readonly')
hw_ima_group_min_num_tx_links = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 5), integer32().subtype(subtypeSpec=value_range_constraint(1, 32))).setMaxAccess('readcreate')
hw_ima_group_min_num_rx_links = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 6), integer32().subtype(subtypeSpec=value_range_constraint(1, 32))).setMaxAccess('readcreate')
hw_ima_group_tx_timing_ref_link = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 7), interface_index_or_zero()).setMaxAccess('readonly')
hw_ima_group_rx_timing_ref_link = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 8), interface_index_or_zero()).setMaxAccess('readonly')
hw_ima_group_tx_ima_id = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 9), integer32().subtype(subtypeSpec=value_range_constraint(0, 255))).setMaxAccess('readonly')
hw_ima_group_rx_ima_id = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 10), integer32().subtype(subtypeSpec=value_range_constraint(0, 255))).setMaxAccess('readonly')
hw_ima_group_tx_frame_length = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 11), ima_frame_length()).setMaxAccess('readcreate')
hw_ima_group_rx_frame_length = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 12), ima_frame_length()).setMaxAccess('readonly')
hw_ima_group_diff_delay_max = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 13), milli_seconds().subtype(subtypeSpec=value_range_constraint(25, 120))).setMaxAccess('readcreate')
hw_ima_group_alpha_value = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 14), integer32().subtype(subtypeSpec=value_range_constraint(1, 2))).setMaxAccess('readonly')
hw_ima_group_beta_value = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 15), integer32().subtype(subtypeSpec=value_range_constraint(1, 5))).setMaxAccess('readonly')
hw_ima_group_gamma_value = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 16), integer32().subtype(subtypeSpec=value_range_constraint(1, 5))).setMaxAccess('readonly')
hw_ima_group_num_tx_act_links = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 17), gauge32()).setMaxAccess('readonly')
hw_ima_group_num_rx_act_links = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 18), gauge32()).setMaxAccess('readonly')
hw_ima_group_tx_oam_label_value = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 19), integer32().subtype(subtypeSpec=value_range_constraint(1, 255))).setMaxAccess('readonly')
hw_ima_group_rx_oam_label_value = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 20), integer32().subtype(subtypeSpec=value_range_constraint(0, 255))).setMaxAccess('readonly')
hw_ima_group_first_link_if_index = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 21), interface_index()).setMaxAccess('readonly')
hw_ima_group_name = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 1, 1, 22), octet_string()).setMaxAccess('accessiblefornotify')
hw_ima_link_table = mib_table((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 2))
hw_ima_link_entry = mib_table_row((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 2, 1)).setIndexNames((0, 'HUAWEI-IMA-MIB', 'hwImaLinkIfIndex'))
hw_ima_link_if_index = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 2, 1, 1), interface_index())
hw_ima_link_group_if_index = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 2, 1, 2), interface_index()).setMaxAccess('readcreate')
hw_ima_link_ne_tx_state = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 2, 1, 3), ima_link_state()).setMaxAccess('readonly')
hw_ima_link_ne_rx_state = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 2, 1, 4), ima_link_state()).setMaxAccess('readonly')
hw_ima_link_fe_tx_state = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 2, 1, 5), ima_link_state()).setMaxAccess('readonly')
hw_ima_link_fe_rx_state = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 2, 1, 6), ima_link_state()).setMaxAccess('readonly')
hw_ima_link_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 2, 1, 51), row_status()).setMaxAccess('readcreate')
hw_ima_link_name = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 2, 1, 52), octet_string()).setMaxAccess('accessiblefornotify')
hw_ima_alarm_table = mib_table((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 3))
hw_ima_alarm_entry = mib_table_row((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 3, 1)).setIndexNames((0, 'HUAWEI-IMA-MIB', 'hwImaAlarmIfIndex'))
hw_ima_alarm_if_index = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 3, 1, 1), integer32())
hw_ima_group_ne_down_en = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 3, 1, 2), integer32()).setMaxAccess('readwrite')
hw_ima_group_fe_down_en = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 3, 1, 3), integer32()).setMaxAccess('readwrite')
hw_ima_group_tx_clk_mismatch_en = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 3, 1, 4), integer32()).setMaxAccess('readwrite')
hw_ima_link_lif_en = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 3, 1, 5), integer32()).setMaxAccess('readwrite')
hw_ima_link_lods_en = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 3, 1, 6), integer32()).setMaxAccess('readwrite')
hw_ima_link_rfi_en = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 3, 1, 7), integer32()).setMaxAccess('readwrite')
hw_ima_link_fe_tx_unusable_en = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 3, 1, 8), integer32()).setMaxAccess('readwrite')
hw_ima_link_fe_rx_unusable_en = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 3, 1, 9), integer32()).setMaxAccess('readwrite')
hw_ima_all_en = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 1, 3, 1, 10), integer32()).setMaxAccess('readwrite')
hw_ima_mib_groups = mib_identifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 2, 1))
hw_ima_mib_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 2, 2))
hw_ima_mib_compliance = module_compliance((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 2, 2, 1)).setObjects(*(('HUAWEI-IMA-MIB', 'hwImaGroupGroup'), ('HUAWEI-IMA-MIB', 'hwImaLinkGroup')))
hw_ima_group_group = object_group((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 2, 1, 1)).setObjects(*(('HUAWEI-IMA-MIB', 'hwImaGroupIfIndex'), ('HUAWEI-IMA-MIB', 'hwImaGroupNeState'), ('HUAWEI-IMA-MIB', 'hwImaGroupFeState'), ('HUAWEI-IMA-MIB', 'hwImaGroupSymmetry'), ('HUAWEI-IMA-MIB', 'hwImaGroupMinNumTxLinks'), ('HUAWEI-IMA-MIB', 'hwImaGroupMinNumRxLinks'), ('HUAWEI-IMA-MIB', 'hwImaGroupTxTimingRefLink'), ('HUAWEI-IMA-MIB', 'hwImaGroupRxTimingRefLink'), ('HUAWEI-IMA-MIB', 'hwImaGroupTxImaId'), ('HUAWEI-IMA-MIB', 'hwImaGroupRxImaId'), ('HUAWEI-IMA-MIB', 'hwImaGroupTxFrameLength'), ('HUAWEI-IMA-MIB', 'hwImaGroupRxFrameLength'), ('HUAWEI-IMA-MIB', 'hwImaGroupDiffDelayMax'), ('HUAWEI-IMA-MIB', 'hwImaGroupAlphaValue'), ('HUAWEI-IMA-MIB', 'hwImaGroupBetaValue'), ('HUAWEI-IMA-MIB', 'hwImaGroupGammaValue'), ('HUAWEI-IMA-MIB', 'hwImaGroupNumTxActLinks'), ('HUAWEI-IMA-MIB', 'hwImaGroupNumRxActLinks'), ('HUAWEI-IMA-MIB', 'hwImaGroupTxOamLabelValue'), ('HUAWEI-IMA-MIB', 'hwImaGroupRxOamLabelValue'), ('HUAWEI-IMA-MIB', 'hwImaGroupFirstLinkIfIndex')))
hw_ima_link_group = object_group((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 2, 1, 2)).setObjects(*(('HUAWEI-IMA-MIB', 'hwImaLinkGroupIfIndex'), ('HUAWEI-IMA-MIB', 'hwImaLinkNeTxState'), ('HUAWEI-IMA-MIB', 'hwImaLinkNeRxState'), ('HUAWEI-IMA-MIB', 'hwImaLinkFeTxState'), ('HUAWEI-IMA-MIB', 'hwImaLinkFeRxState'), ('HUAWEI-IMA-MIB', 'hwImaLinkRowStatus')))
hw_ima_group_ne_down_alarm = notification_type((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 3, 1)).setObjects(*(('HUAWEI-IMA-MIB', 'hwImaGroupName'),))
hw_ima_group_ne_down_alarm_resume = notification_type((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 3, 2)).setObjects(*(('HUAWEI-IMA-MIB', 'hwImaGroupName'),))
hw_ima_group_fe_down_alarm = notification_type((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 3, 3)).setObjects(*(('HUAWEI-IMA-MIB', 'hwImaGroupName'),))
hw_ima_group_fe_down_alarm_resume = notification_type((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 3, 4)).setObjects(*(('HUAWEI-IMA-MIB', 'hwImaGroupName'),))
hw_ima_group_tx_clk_mismatch = notification_type((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 3, 5)).setObjects(*(('HUAWEI-IMA-MIB', 'hwImaGroupName'),))
hw_ima_group_tx_clk_mismatch_resume = notification_type((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 3, 6)).setObjects(*(('HUAWEI-IMA-MIB', 'hwImaGroupName'),))
hw_ima_link_lif_alarm = notification_type((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 3, 7)).setObjects(*(('HUAWEI-IMA-MIB', 'hwImaLinkName'),))
hw_ima_link_lif_alarm_resume = notification_type((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 3, 8)).setObjects(*(('HUAWEI-IMA-MIB', 'hwImaLinkName'),))
hw_ima_link_lods_alarm = notification_type((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 3, 9)).setObjects(*(('HUAWEI-IMA-MIB', 'hwImaLinkName'),))
hw_ima_link_lods_alarm_resume = notification_type((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 3, 10)).setObjects(*(('HUAWEI-IMA-MIB', 'hwImaLinkName'),))
hw_ima_link_rfi_alarm = notification_type((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 3, 11)).setObjects(*(('HUAWEI-IMA-MIB', 'hwImaLinkName'),))
hw_ima_link_rfi_alarm_resume = notification_type((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 3, 12)).setObjects(*(('HUAWEI-IMA-MIB', 'hwImaLinkName'),))
hw_ima_link_fe_tx_unusable_alarm = notification_type((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 3, 13)).setObjects(*(('HUAWEI-IMA-MIB', 'hwImaLinkName'),))
hw_ima_link_fe_tx_unusable_alarm_resume = notification_type((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 3, 14)).setObjects(*(('HUAWEI-IMA-MIB', 'hwImaLinkName'),))
hw_ima_link_fe_rx_unusable_alarm = notification_type((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 3, 15)).setObjects(*(('HUAWEI-IMA-MIB', 'hwImaLinkName'),))
hw_ima_link_fe_rx_unusable_alarm_resume = notification_type((1, 3, 6, 1, 4, 1, 2011, 5, 25, 176, 3, 16)).setObjects(*(('HUAWEI-IMA-MIB', 'hwImaLinkName'),))
mibBuilder.exportSymbols('HUAWEI-IMA-MIB', hwImaGroupFirstLinkIfIndex=hwImaGroupFirstLinkIfIndex, hwImaLinkFeRxState=hwImaLinkFeRxState, PYSNMP_MODULE_ID=hwImaMIB, hwImaLinkRfiEn=hwImaLinkRfiEn, hwImaGroupNumRxActLinks=hwImaGroupNumRxActLinks, hwImaLinkRfiAlarmResume=hwImaLinkRfiAlarmResume, hwImaLinkLifAlarm=hwImaLinkLifAlarm, hwImaGroupTxClkMismatch=hwImaGroupTxClkMismatch, hwImaGroupRxOamLabelValue=hwImaGroupRxOamLabelValue, hwImaLinkLifEn=hwImaLinkLifEn, hwImaGroupFeDownAlarmResume=hwImaGroupFeDownAlarmResume, hwImaLinkNeRxState=hwImaLinkNeRxState, hwImaGroupFeDownAlarm=hwImaGroupFeDownAlarm, ImaGroupState=ImaGroupState, hwImaAlarmIfIndex=hwImaAlarmIfIndex, hwImaGroupNeDownEn=hwImaGroupNeDownEn, hwImaLinkEntry=hwImaLinkEntry, hwImaGroupRxTimingRefLink=hwImaGroupRxTimingRefLink, hwImaGroupNeDownAlarm=hwImaGroupNeDownAlarm, hwImaGroupTable=hwImaGroupTable, hwImaLinkFeTxState=hwImaLinkFeTxState, ImaGroupSymmetry=ImaGroupSymmetry, hwImaLinkName=hwImaLinkName, hwImaLinkLodsEn=hwImaLinkLodsEn, hwImaGroupFeState=hwImaGroupFeState, hwImaLinkIfIndex=hwImaLinkIfIndex, hwImaGroupMinNumRxLinks=hwImaGroupMinNumRxLinks, hwImaMIB=hwImaMIB, hwImaGroupGroup=hwImaGroupGroup, hwImaLinkFeTxUnusableEn=hwImaLinkFeTxUnusableEn, hwImaNotifications=hwImaNotifications, hwImaGroupFeDownEn=hwImaGroupFeDownEn, hwImaGroupTxImaId=hwImaGroupTxImaId, hwImaGroupTxFrameLength=hwImaGroupTxFrameLength, hwIMAAllEn=hwIMAAllEn, ImaLinkState=ImaLinkState, hwImaLinkFeRxUnusableAlarm=hwImaLinkFeRxUnusableAlarm, hwImaLinkFeRxUnusableAlarmResume=hwImaLinkFeRxUnusableAlarmResume, hwImaLinkLifAlarmResume=hwImaLinkLifAlarmResume, hwImaGroupNeDownAlarmResume=hwImaGroupNeDownAlarmResume, hwImaGroupEntry=hwImaGroupEntry, hwImaMibCompliances=hwImaMibCompliances, hwImaAlarmEntry=hwImaAlarmEntry, hwImaLinkRowStatus=hwImaLinkRowStatus, hwImaLinkLodsAlarm=hwImaLinkLodsAlarm, hwImaGroupNeState=hwImaGroupNeState, hwImaMibCompliance=hwImaMibCompliance, hwImaLinkFeTxUnusableAlarm=hwImaLinkFeTxUnusableAlarm, hwImaGroupIfIndex=hwImaGroupIfIndex, hwImaGroupTxClkMismatchEn=hwImaGroupTxClkMismatchEn, hwImaGroupDiffDelayMax=hwImaGroupDiffDelayMax, hwImaGroupRxFrameLength=hwImaGroupRxFrameLength, hwImaGroupTxClkMismatchResume=hwImaGroupTxClkMismatchResume, hwImaGroupTxOamLabelValue=hwImaGroupTxOamLabelValue, hwImaGroupTxTimingRefLink=hwImaGroupTxTimingRefLink, hwImaGroupBetaValue=hwImaGroupBetaValue, hwImaGroupName=hwImaGroupName, hwImaMibGroups=hwImaMibGroups, hwImaGroupRxImaId=hwImaGroupRxImaId, hwImaLinkFeRxUnusableEn=hwImaLinkFeRxUnusableEn, hwImaAlarmTable=hwImaAlarmTable, hwImaLinkNeTxState=hwImaLinkNeTxState, hwImaGroupSymmetry=hwImaGroupSymmetry, hwImaMibConformance=hwImaMibConformance, hwImaMibObjects=hwImaMibObjects, MilliSeconds=MilliSeconds, hwImaGroupMinNumTxLinks=hwImaGroupMinNumTxLinks, hwImaLinkTable=hwImaLinkTable, hwImaLinkGroup=hwImaLinkGroup, hwImaLinkRfiAlarm=hwImaLinkRfiAlarm, ImaFrameLength=ImaFrameLength, hwImaGroupGammaValue=hwImaGroupGammaValue, hwImaGroupAlphaValue=hwImaGroupAlphaValue, hwImaLinkLodsAlarmResume=hwImaLinkLodsAlarmResume, hwImaGroupNumTxActLinks=hwImaGroupNumTxActLinks, hwImaLinkFeTxUnusableAlarmResume=hwImaLinkFeTxUnusableAlarmResume, hwImaLinkGroupIfIndex=hwImaLinkGroupIfIndex)
|
def sort_a_little_bit(items, begin_index, end_index):
left_index = begin_index
pivot_index = end_index
pivot_value = items[pivot_index]
while pivot_index != left_index:
item = items[left_index]
if item <= pivot_value:
left_index += 1
continue
items[left_index] = items[pivot_index - 1]
items[pivot_index - 1] = pivot_value
items[pivot_index] = item
pivot_index -= 1
return pivot_index
def sort_all(items, begin_index, end_index):
if end_index <= begin_index:
return
pivot_index = sort_a_little_bit(items, begin_index, end_index)
sort_all(items, begin_index, pivot_index - 1)
sort_all(items, pivot_index + 1, end_index)
def quicksort(items):
sort_all(items, 0, len(items) - 1)
def rearrange_digits(input_list):
"""
Rearrange Array Elements so as to form two number such that their sum is maximum.
Args:
input_list(list): Input List
Returns:
(int),(int): Two maximum sums
"""
if len(input_list) <= 0:
return -1, -1
if len(input_list) == 1:
return input_list[0], 0
quicksort(input_list)
# num1 is bigger
num2_len = len(input_list) // 2
num1_len = len(input_list) - num2_len
num1_index = num1_len - 1
num2_index = num2_len - 1
num1 = [''] * num1_len
num2 = [''] * num2_len
for i, element in enumerate(input_list):
if i % 2 == 0:
num1[num1_index] = str(element)
num1_index -= 1
else:
num2[num2_index] = str(element)
num2_index -= 1
return int("".join(num1)), int("".join(num2))
def test_function(test_case):
output = rearrange_digits(test_case[0])
solution = test_case[1]
if sum(output) == sum(solution):
print("Pass")
else:
print("Fail")
if __name__ == '__main__':
test_function([[1, 2, 3, 4, 5], [542, 31]])
test_function([[4, 6, 2, 5, 9, 8], [964, 852]])
# corner case
test_function([[], [-1, -1]])
test_function([[3], [3, 0]])
|
def sort_a_little_bit(items, begin_index, end_index):
left_index = begin_index
pivot_index = end_index
pivot_value = items[pivot_index]
while pivot_index != left_index:
item = items[left_index]
if item <= pivot_value:
left_index += 1
continue
items[left_index] = items[pivot_index - 1]
items[pivot_index - 1] = pivot_value
items[pivot_index] = item
pivot_index -= 1
return pivot_index
def sort_all(items, begin_index, end_index):
if end_index <= begin_index:
return
pivot_index = sort_a_little_bit(items, begin_index, end_index)
sort_all(items, begin_index, pivot_index - 1)
sort_all(items, pivot_index + 1, end_index)
def quicksort(items):
sort_all(items, 0, len(items) - 1)
def rearrange_digits(input_list):
"""
Rearrange Array Elements so as to form two number such that their sum is maximum.
Args:
input_list(list): Input List
Returns:
(int),(int): Two maximum sums
"""
if len(input_list) <= 0:
return (-1, -1)
if len(input_list) == 1:
return (input_list[0], 0)
quicksort(input_list)
num2_len = len(input_list) // 2
num1_len = len(input_list) - num2_len
num1_index = num1_len - 1
num2_index = num2_len - 1
num1 = [''] * num1_len
num2 = [''] * num2_len
for (i, element) in enumerate(input_list):
if i % 2 == 0:
num1[num1_index] = str(element)
num1_index -= 1
else:
num2[num2_index] = str(element)
num2_index -= 1
return (int(''.join(num1)), int(''.join(num2)))
def test_function(test_case):
output = rearrange_digits(test_case[0])
solution = test_case[1]
if sum(output) == sum(solution):
print('Pass')
else:
print('Fail')
if __name__ == '__main__':
test_function([[1, 2, 3, 4, 5], [542, 31]])
test_function([[4, 6, 2, 5, 9, 8], [964, 852]])
test_function([[], [-1, -1]])
test_function([[3], [3, 0]])
|
@auth.requires_membership('admin')
def album():
grid = SQLFORM.grid(db.t_mtalbum)
return dict(grid=grid)
@auth.requires_membership('admin')
def dataset():
grid = SQLFORM.grid(db.t_mtdataset)
return dict(grid=grid)
@auth.requires_membership('admin')
def item():
grid = SQLFORM.grid(db.t_mtitem)
return dict(grid=grid)
@auth.requires_membership('admin')
def itemtype():
grid = SQLFORM.grid(db.t_mtitemtype)
return dict(grid=grid)
@auth.requires_membership('admin')
def search():
grid = SQLFORM.grid(db.t_mtsearch)
return dict(grid=grid)
@auth.requires_membership('admin')
def user():
grid = SQLFORM.grid(db.t_mtuser)
return dict(grid=grid)
|
@auth.requires_membership('admin')
def album():
grid = SQLFORM.grid(db.t_mtalbum)
return dict(grid=grid)
@auth.requires_membership('admin')
def dataset():
grid = SQLFORM.grid(db.t_mtdataset)
return dict(grid=grid)
@auth.requires_membership('admin')
def item():
grid = SQLFORM.grid(db.t_mtitem)
return dict(grid=grid)
@auth.requires_membership('admin')
def itemtype():
grid = SQLFORM.grid(db.t_mtitemtype)
return dict(grid=grid)
@auth.requires_membership('admin')
def search():
grid = SQLFORM.grid(db.t_mtsearch)
return dict(grid=grid)
@auth.requires_membership('admin')
def user():
grid = SQLFORM.grid(db.t_mtuser)
return dict(grid=grid)
|
n = int(input().strip())
value1 = 0
value2 = 0
for i in range(n):
a_t = [int(a_temp) for a_temp in input().strip().split(' ')]
value1 += a_t[i]
value2 += a_t[-1-i]
print(abs(value2-value1))
|
n = int(input().strip())
value1 = 0
value2 = 0
for i in range(n):
a_t = [int(a_temp) for a_temp in input().strip().split(' ')]
value1 += a_t[i]
value2 += a_t[-1 - i]
print(abs(value2 - value1))
|
def test(): # noqa
assert 1 + 1 == 2
def test_multi_line_args(math_fixture, *args, **kwargs): # noqa
assert 1 + 1 == 2
|
def test():
assert 1 + 1 == 2
def test_multi_line_args(math_fixture, *args, **kwargs):
assert 1 + 1 == 2
|
def checkio(str_number, radix):
try:
return int(str_number,radix)
except:
return -1
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio("AF", 16) == 175, "Hex"
assert checkio("101", 2) == 5, "Bin"
assert checkio("101", 5) == 26, "5 base"
assert checkio("Z", 36) == 35, "Z base"
assert checkio("AB", 10) == -1, "B > A = 10"
print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")
|
def checkio(str_number, radix):
try:
return int(str_number, radix)
except:
return -1
if __name__ == '__main__':
assert checkio('AF', 16) == 175, 'Hex'
assert checkio('101', 2) == 5, 'Bin'
assert checkio('101', 5) == 26, '5 base'
assert checkio('Z', 36) == 35, 'Z base'
assert checkio('AB', 10) == -1, 'B > A = 10'
print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")
|
async def _asyncWrapWith(res, wrapper_fn):
result = await res
return wrapper_fn(result["id"])
def wrapWith(res, wrapper_fn):
if isinstance(res, dict):
return wrapper_fn(res)
else:
return _asyncWrapWith(res, wrapper_fn)
|
async def _asyncWrapWith(res, wrapper_fn):
result = await res
return wrapper_fn(result['id'])
def wrap_with(res, wrapper_fn):
if isinstance(res, dict):
return wrapper_fn(res)
else:
return _async_wrap_with(res, wrapper_fn)
|
#!/usr/bin/env python
# encoding: utf-8
def run(whatweb, pluginname):
whatweb.recog_from_file(pluginname, "themes\default\Wikiwyg\Wikiwy\Phpwiki.js", "phpwiki")
|
def run(whatweb, pluginname):
whatweb.recog_from_file(pluginname, 'themes\\default\\Wikiwyg\\Wikiwy\\Phpwiki.js', 'phpwiki')
|
__author__ = "Prikly Grayp"
__license__ = "MIT"
__version__ = "1.0.0"
__email__ = "priklygrayp@gmail.com"
__status__ = "Development"
def first(iterable):
iterator = iter(iterable)
try:
return next(iterator)
except StopIteration:
raise ValueError('iterable is empty')
first(['Spring', 'Summer', 'Autumn', 'Winter'])
|
__author__ = 'Prikly Grayp'
__license__ = 'MIT'
__version__ = '1.0.0'
__email__ = 'priklygrayp@gmail.com'
__status__ = 'Development'
def first(iterable):
iterator = iter(iterable)
try:
return next(iterator)
except StopIteration:
raise value_error('iterable is empty')
first(['Spring', 'Summer', 'Autumn', 'Winter'])
|
# https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/submissions/
class Solution:
def kidsWithCandies(self, candies: [int], extraCandies: int) -> [bool]:
maxCandies = max(candies, default=0)
return [True if v + extraCandies >= maxCandies else False for v in candies]
|
class Solution:
def kids_with_candies(self, candies: [int], extraCandies: int) -> [bool]:
max_candies = max(candies, default=0)
return [True if v + extraCandies >= maxCandies else False for v in candies]
|
# Alternating Characters
# Developer: Murillo Grubler
# Link: https://www.hackerrank.com/challenges/alternating-characters/problem
# Time complexity: O(n)
def alternatingCharacters(s):
sumChars = 0
for i in range(len(s)):
if i == 0 or tempChar != s[i]:
tempChar = s[i]
continue
if tempChar == s[i]:
sumChars += 1
return sumChars
q = int(input().strip())
for a0 in range(q):
print(alternatingCharacters(input().strip()))
|
def alternating_characters(s):
sum_chars = 0
for i in range(len(s)):
if i == 0 or tempChar != s[i]:
temp_char = s[i]
continue
if tempChar == s[i]:
sum_chars += 1
return sumChars
q = int(input().strip())
for a0 in range(q):
print(alternating_characters(input().strip()))
|
# A simple use of user defined functions in python
def greet_user(name):
print(f"Hi {name}!")
print("Welcome Aboard!")
print("Start")
greet_user("Kwadwo")
greet_user("Sammy")
print("finish")
|
def greet_user(name):
print(f'Hi {name}!')
print('Welcome Aboard!')
print('Start')
greet_user('Kwadwo')
greet_user('Sammy')
print('finish')
|
#!/usr/bin/env python3
""" binary_tree contains methods to search a binary tree
"""
def is_valid_binary_search_tree(node):
"""
Traverses tree depth first in order
"""
return is_valid_bst(node, float('-inf'), float('inf'))
def is_valid_bst(node, value_min, value_max):
"""
Traverses tree depth first in order
Note the tree may be a subtree of a larger tree.
The method may be called recursively.
Tree does not have to be "balanced", may have more levels than necessary.
Duplicate values are not allowed.
https://en.wikipedia.org/wiki/Binary_search_tree
https://en.wikipedia.org/wiki/Tree_traversal
http://stackoverflow.com/questions/10832496/finding-if-a-binary-tree-is-a-binary-search-tree?noredirect=1&lq=1
http://stackoverflow.com/questions/499995/how-do-you-validate-a-binary-search-tree#759851
http://stackoverflow.com/questions/300935/are-duplicate-keys-allowed-in-the-definition-of-binary-search-trees#300968
http://stackoverflow.com/questions/7604966/maximum-and-minimum-values-for-ints#7604981
value_min: initial call should set to float('-inf')
value_max: initial call should set to float('inf')
:return True if node is None or is the root of a valid binary search tree
return False if node value is None or node isn't the root of a valid binary search tree
return False if tree contains a duplicate value
"""
print("is_valid_binary_search_tree")
if node is None:
# e.g. parent node doesn't have a node at this child
return True
if node.value is None:
return False
if (node.value > value_min
and node.value < value_max
and is_valid_bst(node.left, value_min, node.value)
and is_valid_bst(node.right, node.value, value_max)):
return True
else:
return False
|
""" binary_tree contains methods to search a binary tree
"""
def is_valid_binary_search_tree(node):
"""
Traverses tree depth first in order
"""
return is_valid_bst(node, float('-inf'), float('inf'))
def is_valid_bst(node, value_min, value_max):
"""
Traverses tree depth first in order
Note the tree may be a subtree of a larger tree.
The method may be called recursively.
Tree does not have to be "balanced", may have more levels than necessary.
Duplicate values are not allowed.
https://en.wikipedia.org/wiki/Binary_search_tree
https://en.wikipedia.org/wiki/Tree_traversal
http://stackoverflow.com/questions/10832496/finding-if-a-binary-tree-is-a-binary-search-tree?noredirect=1&lq=1
http://stackoverflow.com/questions/499995/how-do-you-validate-a-binary-search-tree#759851
http://stackoverflow.com/questions/300935/are-duplicate-keys-allowed-in-the-definition-of-binary-search-trees#300968
http://stackoverflow.com/questions/7604966/maximum-and-minimum-values-for-ints#7604981
value_min: initial call should set to float('-inf')
value_max: initial call should set to float('inf')
:return True if node is None or is the root of a valid binary search tree
return False if node value is None or node isn't the root of a valid binary search tree
return False if tree contains a duplicate value
"""
print('is_valid_binary_search_tree')
if node is None:
return True
if node.value is None:
return False
if node.value > value_min and node.value < value_max and is_valid_bst(node.left, value_min, node.value) and is_valid_bst(node.right, node.value, value_max):
return True
else:
return False
|
"""
In a given grid, each cell can have one of three values:
- the value 0 representing an empty cell;
- the value 1 representing a fresh orange;
- the value 2 representing a rotten orange.
Every minute, any fresh orange that is adjacent (4-directionally) to a
rotten orange becomes rotten.
Return the minimum number of minutes that must elapse until no cell has a
fresh orange. If this is impossible, return -1 instead.
Example:
Input: [[2,1,1],[1,1,0],[0,1,1]]
Output: 4
Example:
Input: [[2,1,1],[0,1,1],[1,0,1]]
Output: -1
Explanation: The orange in the bottom left corner (row 2, column 0) is
never rotten, because rotting only happens 4-directiona
Note:
1. 1 <= grid.length <= 10
2. 1 <= grid[0].length <= 10
3. grid[i][j] is only 0, 1, or 2.
"""
#Difficulty: Medium
#303 / 303 test cases passed.
#Runtime: 52 ms
#Memory Usage: 13.7 MB
#Runtime: 52 ms, faster than 84.00% of Python3 online submissions for Rotting Oranges.
#Memory Usage: 13.7 MB, less than 91.03% of Python3 online submissions for Rotting Oranges.
class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
minutes = 0
self.rows = len(grid)
self.cols = len(grid[0])
self.rotten_value = 2
self.rotting = True
while self.rotting and self.checkForFreshOranges(grid):
self.rotting = False
for i in range(self.rows):
for j in range(self.cols):
if grid[i][j] == self.rotten_value:
self.rottenOrange(grid, i - 1, j)
self.rottenOrange(grid, i, j - 1)
self.rottenOrange(grid, i, j + 1)
self.rottenOrange(grid, i + 1, j)
if self.rotting:
minutes += 1
self.rotten_value += 1
if not self.rotting:
return -1
return minutes
def rottenOrange(self, grid, i, j):
if i < 0 or i >= len(grid) or j < 0 or j >= len(grid[i]):
return
if grid[i][j] == 1:
grid[i][j] += self.rotten_value
self.rotting = True
def checkForFreshOranges(self, grid):
for i in range(self.rows):
for j in range(self.cols):
if grid[i][j] == 1:
return True
return False
|
"""
In a given grid, each cell can have one of three values:
- the value 0 representing an empty cell;
- the value 1 representing a fresh orange;
- the value 2 representing a rotten orange.
Every minute, any fresh orange that is adjacent (4-directionally) to a
rotten orange becomes rotten.
Return the minimum number of minutes that must elapse until no cell has a
fresh orange. If this is impossible, return -1 instead.
Example:
Input: [[2,1,1],[1,1,0],[0,1,1]]
Output: 4
Example:
Input: [[2,1,1],[0,1,1],[1,0,1]]
Output: -1
Explanation: The orange in the bottom left corner (row 2, column 0) is
never rotten, because rotting only happens 4-directiona
Note:
1. 1 <= grid.length <= 10
2. 1 <= grid[0].length <= 10
3. grid[i][j] is only 0, 1, or 2.
"""
class Solution:
def oranges_rotting(self, grid: List[List[int]]) -> int:
minutes = 0
self.rows = len(grid)
self.cols = len(grid[0])
self.rotten_value = 2
self.rotting = True
while self.rotting and self.checkForFreshOranges(grid):
self.rotting = False
for i in range(self.rows):
for j in range(self.cols):
if grid[i][j] == self.rotten_value:
self.rottenOrange(grid, i - 1, j)
self.rottenOrange(grid, i, j - 1)
self.rottenOrange(grid, i, j + 1)
self.rottenOrange(grid, i + 1, j)
if self.rotting:
minutes += 1
self.rotten_value += 1
if not self.rotting:
return -1
return minutes
def rotten_orange(self, grid, i, j):
if i < 0 or i >= len(grid) or j < 0 or (j >= len(grid[i])):
return
if grid[i][j] == 1:
grid[i][j] += self.rotten_value
self.rotting = True
def check_for_fresh_oranges(self, grid):
for i in range(self.rows):
for j in range(self.cols):
if grid[i][j] == 1:
return True
return False
|
"""
A proxy provides a surrogate or place holder to provide
access to an object.
Ex1:
Use an extra level of indirection to support distributed,
controlled, or conditional access.
"""
class SubjectInterface:
"""
Define the common interface for RealSubject and Proxy so that a
Proxy can be used anywhere a RealSubject is expected.
"""
def request(self):
raise NotImplementedError()
class Proxy(SubjectInterface):
"""
Maintain a reference that lets the proxy access the real subject.
Provide an interface identical to Subject's.
"""
def __init__(self, real_subject):
self.real_subject = real_subject
def request(self):
print('Proxy may be doing something, like controlling request access.')
self.real_subject.request()
class RealSubject(SubjectInterface):
"""
Define the real object that the proxy represents.
"""
def request(self):
print('The real thing is dealing with the request')
real_subject = RealSubject()
real_subject.request()
proxy = Proxy(real_subject)
proxy.request()
|
"""
A proxy provides a surrogate or place holder to provide
access to an object.
Ex1:
Use an extra level of indirection to support distributed,
controlled, or conditional access.
"""
class Subjectinterface:
"""
Define the common interface for RealSubject and Proxy so that a
Proxy can be used anywhere a RealSubject is expected.
"""
def request(self):
raise not_implemented_error()
class Proxy(SubjectInterface):
"""
Maintain a reference that lets the proxy access the real subject.
Provide an interface identical to Subject's.
"""
def __init__(self, real_subject):
self.real_subject = real_subject
def request(self):
print('Proxy may be doing something, like controlling request access.')
self.real_subject.request()
class Realsubject(SubjectInterface):
"""
Define the real object that the proxy represents.
"""
def request(self):
print('The real thing is dealing with the request')
real_subject = real_subject()
real_subject.request()
proxy = proxy(real_subject)
proxy.request()
|
"""
30 Dec 2015.
code interpretation by Dealga McArdle of this paper.
http://www.cc.gatech.edu/~jarek/graphics/papers/04PolygonBooleansMargalit.pdf
It's the first thing that came up after a 'polygon unions' Google search. This repo
is an attempt at getting that psuedo code into a working state. It might be over my
head but won't know until attempted.
"""
''' Table 1 --------------------------------------------------
1 = island, 0 = hole
polygonorientation [polygonAtype, polygonBtype, oper]
contains indicators which specify whether the two input polygons should have
the same or opposite orientations according to the oper. and polygon types.
'''
SM = "same"
OP = "opposite"
polygonorientation = {
(1, 1): {'AnB': SM, 'AuB': SM, 'A-B': OP, 'B-A': OP},
(1, 0): {'AnB': OP, 'AuB': OP, 'A-B': SM, 'B-A': SM},
(0, 1): {'AnB': OP, 'AuB': OP, 'A-B': SM, 'B-A': SM},
(0, 0): {'AnB': SM, 'AuB': SM, 'A-B': OP, 'B-A': OP}
}
''' Table 2 --------------------------------------------------
fragmenttype [ polygonAtype, polygonBtype, oper, polygon]
contains the type of edge fragments, besides the boundary line fragments,
to be selected for insertion into the line fragments table according to the
operations and the polygon types.
'''
IO = ['inside', 'outside']
OI = ['outside', 'inside']
II = ['inside', 'inside']
OO = ['outside', 'outside']
fragmenttype = {
(1, 1): {'AnB': II, 'AuB': OO, 'A-B': OI, 'B-A': IO},
(1, 0): {'AnB': OI, 'AuB': IO, 'A-B': II, 'B-A': OO},
(0, 1): {'AnB': IO, 'AuB': OI, 'A-B': OO, 'B-A': II},
(0, 0): {'AnB': OO, 'AuB': II, 'A-B': IO, 'B-A': OI}
}
''' Table 3 --------------------------------------------------
boundaryfragment [polygonAtype, polygonBtype, situation, oper, reg]
contains indicators which specifies how many boundary edge fragments
are to be selected given the edge fragments situation for regular and
non-regular operations. The table is according to the operation and the
polygon types.
'''
...
''' Table 4 --------------------------------------------------
resltorientation [polygonAtype, polygonBtype, oper]
'''
def polygon_operation(Oper, Reg, A, B, Atype, Btype, Out):
def find_intersection(segment_one, segment_two, point):
"""
https://stackoverflow.com/a/19550879/1243487
original:
return True if the two line segments intersect
False otherwise. If intersection then point is given
the coordinate
interpretation:
return [] if no intersection and [x, y] if there is one.
"""
(p0, p1), (p2, p3) = segment_one, segment_two
segment_one_dx = p1[0] - p0[0]
segment_one_dy = p1[1] - p0[1]
segment_two_dx = p3[0] - p2[0]
segment_two_dy = p3[1] - p2[1]
denom = (segment_one_dx * segment_two_dy) - (segment_two_dx * segment_one_dy)
if denom == 0:
return [] # collinear
denom_is_positive = denom > 0
s02_x = p0[0] - p2[0]
s02_y = p0[1] - p2[1]
s_numer = segment_one_dx * s02_y - segment_one_dy * s02_x
if (s_numer < 0) == denom_is_positive:
return [] # no collision
t_numer = segment_two_dx * s02_y - segment_two_dy * s02_x
if (t_numer < 0) == denom_is_positive:
return [] # no collision
if (s_numer > denom) == denom_is_positive or (t_numer > denom) == denom_is_positive:
return [] # no collision
t = t_numer / denom
return [ p0[0] + (t * segment_one_dx), p0[1] + (t * segment_one_dy) ]
def inside_polygon(v, polygon):
"""
finds and returns the following
- whether the v is inside or outside the boundary of polygon
- check for every edge of polygon if point on the edge
- 1] and if not, whether the edge intersects with a ray that
- begins at the point v and is directed in the X-axis direction
- 2] if point v is on the edge, the function returns 'boundary'
If the edge intersects with the raw, except at the edge's
lower endpoint, a counter is incremented.
When all edges are checked, the procedure returns 'inside' if
the counter is an odd number or 'outside' if the counter is even.
"""
...
def insertV(dsv, point, io_type):
''' 3rd param enum [inside, outside, boundary]
inserts into the vertex ring, DSV, the point, with the type
io_type.
'''
...
def insertE(fragment, reg):
""" Inserts an edge frament into the edge fragments table, EF, if
it is not already there. If regular output result polygons are
required and non-boundary edge fragment is to be inserted, the
procedure checks whether the same edge fragment with the opposite
direction is already in EF, if So. it does not insert the
edge-fragment and it deletes the existing edge fragment with
the opposite direction from the edge fragments table
"""
...
def deleteE(fragment):
""" Deletes an edge fragment from edge fragments table """
...
def search_nextE(point):
""" Searches and returns from the edge fragments table an edge fragment
whose first endpoint is point
"""
...
def organizeE():
""" organizes the edge fragments table to allow fast search
and deletion operations """
...
def find_orientation(polygon):
""" returns 'clockwise' or 'counterclockwise'. CW / CCW
it finds the vertex with the minimum X value and compares the slopes
of the two edges attached to this vertex in order to find the
orientation
"""
...
def change_orientation(polygon):
""" self explanatory, reverses vertices """
...
''' Find and set the orientations of the input polygons '''
orientationA = find_orientation(A)
orientationB = find_orientation(B)
if polygonorientation[(Atype, Btype)][Oper] == 'same':
if not (orientationA == orientationB):
change_orientation(B)
elif orientationA == orientationB:
change_orientation(B)
''' Initiate the verts rings and classify the vertices '''
for v in A:
insertV(AV, v, inside_polyon(v, B))
for v in B:
insertV(BV, v, inside_polyon(v, A))
''' Find intersections '''
|
"""
30 Dec 2015.
code interpretation by Dealga McArdle of this paper.
http://www.cc.gatech.edu/~jarek/graphics/papers/04PolygonBooleansMargalit.pdf
It's the first thing that came up after a 'polygon unions' Google search. This repo
is an attempt at getting that psuedo code into a working state. It might be over my
head but won't know until attempted.
"""
' Table 1 --------------------------------------------------\n 1 = island, 0 = hole\n\n polygonorientation [polygonAtype, polygonBtype, oper]\n\n contains indicators which specify whether the two input polygons should have\n the same or opposite orientations according to the oper. and polygon types.\n\n'
sm = 'same'
op = 'opposite'
polygonorientation = {(1, 1): {'AnB': SM, 'AuB': SM, 'A-B': OP, 'B-A': OP}, (1, 0): {'AnB': OP, 'AuB': OP, 'A-B': SM, 'B-A': SM}, (0, 1): {'AnB': OP, 'AuB': OP, 'A-B': SM, 'B-A': SM}, (0, 0): {'AnB': SM, 'AuB': SM, 'A-B': OP, 'B-A': OP}}
' Table 2 --------------------------------------------------\n\n fragmenttype [ polygonAtype, polygonBtype, oper, polygon]\n\n contains the type of edge fragments, besides the boundary line fragments,\n to be selected for insertion into the line fragments table according to the\n operations and the polygon types.\n'
io = ['inside', 'outside']
oi = ['outside', 'inside']
ii = ['inside', 'inside']
oo = ['outside', 'outside']
fragmenttype = {(1, 1): {'AnB': II, 'AuB': OO, 'A-B': OI, 'B-A': IO}, (1, 0): {'AnB': OI, 'AuB': IO, 'A-B': II, 'B-A': OO}, (0, 1): {'AnB': IO, 'AuB': OI, 'A-B': OO, 'B-A': II}, (0, 0): {'AnB': OO, 'AuB': II, 'A-B': IO, 'B-A': OI}}
' Table 3 --------------------------------------------------\n\n boundaryfragment [polygonAtype, polygonBtype, situation, oper, reg]\n\n contains indicators which specifies how many boundary edge fragments\n are to be selected given the edge fragments situation for regular and\n non-regular operations. The table is according to the operation and the\n polygon types.\n\n'
...
' Table 4 --------------------------------------------------\n\n resltorientation [polygonAtype, polygonBtype, oper]\n\n'
def polygon_operation(Oper, Reg, A, B, Atype, Btype, Out):
def find_intersection(segment_one, segment_two, point):
"""
https://stackoverflow.com/a/19550879/1243487
original:
return True if the two line segments intersect
False otherwise. If intersection then point is given
the coordinate
interpretation:
return [] if no intersection and [x, y] if there is one.
"""
((p0, p1), (p2, p3)) = (segment_one, segment_two)
segment_one_dx = p1[0] - p0[0]
segment_one_dy = p1[1] - p0[1]
segment_two_dx = p3[0] - p2[0]
segment_two_dy = p3[1] - p2[1]
denom = segment_one_dx * segment_two_dy - segment_two_dx * segment_one_dy
if denom == 0:
return []
denom_is_positive = denom > 0
s02_x = p0[0] - p2[0]
s02_y = p0[1] - p2[1]
s_numer = segment_one_dx * s02_y - segment_one_dy * s02_x
if (s_numer < 0) == denom_is_positive:
return []
t_numer = segment_two_dx * s02_y - segment_two_dy * s02_x
if (t_numer < 0) == denom_is_positive:
return []
if (s_numer > denom) == denom_is_positive or (t_numer > denom) == denom_is_positive:
return []
t = t_numer / denom
return [p0[0] + t * segment_one_dx, p0[1] + t * segment_one_dy]
def inside_polygon(v, polygon):
"""
finds and returns the following
- whether the v is inside or outside the boundary of polygon
- check for every edge of polygon if point on the edge
- 1] and if not, whether the edge intersects with a ray that
- begins at the point v and is directed in the X-axis direction
- 2] if point v is on the edge, the function returns 'boundary'
If the edge intersects with the raw, except at the edge's
lower endpoint, a counter is incremented.
When all edges are checked, the procedure returns 'inside' if
the counter is an odd number or 'outside' if the counter is even.
"""
...
def insert_v(dsv, point, io_type):
""" 3rd param enum [inside, outside, boundary]
inserts into the vertex ring, DSV, the point, with the type
io_type.
"""
...
def insert_e(fragment, reg):
""" Inserts an edge frament into the edge fragments table, EF, if
it is not already there. If regular output result polygons are
required and non-boundary edge fragment is to be inserted, the
procedure checks whether the same edge fragment with the opposite
direction is already in EF, if So. it does not insert the
edge-fragment and it deletes the existing edge fragment with
the opposite direction from the edge fragments table
"""
...
def delete_e(fragment):
""" Deletes an edge fragment from edge fragments table """
...
def search_next_e(point):
""" Searches and returns from the edge fragments table an edge fragment
whose first endpoint is point
"""
...
def organize_e():
""" organizes the edge fragments table to allow fast search
and deletion operations """
...
def find_orientation(polygon):
""" returns 'clockwise' or 'counterclockwise'. CW / CCW
it finds the vertex with the minimum X value and compares the slopes
of the two edges attached to this vertex in order to find the
orientation
"""
...
def change_orientation(polygon):
""" self explanatory, reverses vertices """
...
' Find and set the orientations of the input polygons '
orientation_a = find_orientation(A)
orientation_b = find_orientation(B)
if polygonorientation[Atype, Btype][Oper] == 'same':
if not orientationA == orientationB:
change_orientation(B)
elif orientationA == orientationB:
change_orientation(B)
' Initiate the verts rings and classify the vertices '
for v in A:
insert_v(AV, v, inside_polyon(v, B))
for v in B:
insert_v(BV, v, inside_polyon(v, A))
' Find intersections '
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
dummyHead = ListNode(float('-inf'), head)
currentNode = dummyHead.next
while currentNode and currentNode.next:
if currentNode.val <= currentNode.next.val:
currentNode = currentNode.next
else:
tempNode = currentNode.next
currentNode.next = tempNode.next
iterator = dummyHead
while iterator.next and iterator.next.val <= tempNode.val:
iterator = iterator.next
tempNode.next = iterator.next
iterator.next = tempNode
return dummyHead.next
|
class Solution:
def insertion_sort_list(self, head: ListNode) -> ListNode:
dummy_head = list_node(float('-inf'), head)
current_node = dummyHead.next
while currentNode and currentNode.next:
if currentNode.val <= currentNode.next.val:
current_node = currentNode.next
else:
temp_node = currentNode.next
currentNode.next = tempNode.next
iterator = dummyHead
while iterator.next and iterator.next.val <= tempNode.val:
iterator = iterator.next
tempNode.next = iterator.next
iterator.next = tempNode
return dummyHead.next
|
def Factorial_Head(n):
# Base Case: 0! = 1
if(n == 0):
return 1
# Recursion
result1 = Factorial_Head(n-1)
result2 = n * result1
return result2
def Factorial_Tail(n, accumulator):
# Base Case: 0! = 1
if( n == 0):
return accumulator
# Recursion
return Factorial_Tail(n-1, n*accumulator)
# n = 5
# 1st loop: n=5, accumulator= 1
# 2nd loop: n=4, accumulator= 5
# 3rd loop: n=3, accumulator= 20
# 4th loop: n=2, accumulator= 60
# 5th loop: n=1, accumulator= 120 (answer)
n = 5
head = Factorial_Head(n)
print(f"Factorial {n} using HEAD Recursion: {head}")
n = 6
tail = Factorial_Tail(n, 1)
print(f"Factorial {n} using TAIL Recursion: {tail}")
|
def factorial__head(n):
if n == 0:
return 1
result1 = factorial__head(n - 1)
result2 = n * result1
return result2
def factorial__tail(n, accumulator):
if n == 0:
return accumulator
return factorial__tail(n - 1, n * accumulator)
n = 5
head = factorial__head(n)
print(f'Factorial {n} using HEAD Recursion: {head}')
n = 6
tail = factorial__tail(n, 1)
print(f'Factorial {n} using TAIL Recursion: {tail}')
|
class palin:
def __init__(self,string):
self.string=string
s=self.string
a=[]
for i in s:
a.append(i)
b=[]
for i in range(len(a)-1,-1,-1):
b.append(a[i])
if(a==b):
print('True')
else:
print('False')
# if __name__=='__main__':
# obj=palin('kaif')
# obj.check()
|
class Palin:
def __init__(self, string):
self.string = string
s = self.string
a = []
for i in s:
a.append(i)
b = []
for i in range(len(a) - 1, -1, -1):
b.append(a[i])
if a == b:
print('True')
else:
print('False')
|
class UnboundDataPullException(Exception):
pass
class DataPullInProgressError(Exception):
pass
|
class Unbounddatapullexception(Exception):
pass
class Datapullinprogresserror(Exception):
pass
|
print("To define a new function, you use 'def+<your_function_name>+(+<your_params_comma_separated>+)', example: 'def myFunction(param1, param2, ..., paramn)'")
# Creating a simple function and calling it
print("Creating simple function and calling it")
def sayHello(name):
print("Hello",name)
sayHello("balam909")
# Defining a simple function with default params
print("Creating a simple function with default params")
def giveMeTwoNumbersAndAText(number1, number2, myText="This is my default text"):
print("number1:",number1,"number2:",number2,"myText:",myText)
print("This function receive 3 parameters, if we have 'default values' defined, we can call this function without send the parameter(s) that has a default value asigned")
print("The function 'giveMeTwoNumbersAndAText' has 2 parameters with non default value and 1 parameter with a default value")
print("The function looks like this: 'giveMeTwoNumbersAndAText(number1, number2, myText=\"This is my default text\")'")
print("This is a call with the 3 parameters: giveMeTwoNumbersAndAText(1,2,\"Look at this awesome value\")")
giveMeTwoNumbersAndAText(1,2,"Look at this awesome value")
print("This is a call with 2 parameters: giveMeTwoNumbersAndAText(1,2)")
giveMeTwoNumbersAndAText(1,2)
print("If you do not have a default value for a param, you can not call the function without it")
print("For example: 'giveMeTwoNumbersAndAText(1)' will result in an error")
print("The default value is evaluated only once, when we define the function, so it not possible to change it arround the execution")
print("In python we can follow the argument order, or we can add the 'key,value' pair")
print("A valid example could be giveMeTwoNumbersAndAText(1, myText=\"Some Text\", number2=10)")
giveMeTwoNumbersAndAText(1, myText="Some Text", number2=10)
print("Once we use the 'key/value' definition, we have to use the 'key/value' for the next elements, an invalid call for this case looks like this: giveMeTwoNumbersAndAText(1, myText=\"Some Text\", 10)")
# Defining a function receiving pocitional arguments
print("Defining a function receiving pocitional arguments")
def sayAbunchOfWords(*args):
for arg in args:
print(arg)
print("A call with cero arg")
sayAbunchOfWords()
print("A call with one arg")
sayAbunchOfWords("one")
print("A call with two args")
sayAbunchOfWords("one","two")
print("A call with three arg")
sayAbunchOfWords("one","two","three")
# Defining a function receiving a dictionary
print("Defining a function receiving a dictionary")
def printMyDictionary(**myDictionary):
for key in myDictionary.keys():
print("The key:",key+"_k",",","The value:",myDictionary[key]+"_v")
print("This is the function call with a dictionary as an input")
printMyDictionary(param1="param1", param2="param2", param3="param3")
|
print("To define a new function, you use 'def+<your_function_name>+(+<your_params_comma_separated>+)', example: 'def myFunction(param1, param2, ..., paramn)'")
print('Creating simple function and calling it')
def say_hello(name):
print('Hello', name)
say_hello('balam909')
print('Creating a simple function with default params')
def give_me_two_numbers_and_a_text(number1, number2, myText='This is my default text'):
print('number1:', number1, 'number2:', number2, 'myText:', myText)
print("This function receive 3 parameters, if we have 'default values' defined, we can call this function without send the parameter(s) that has a default value asigned")
print("The function 'giveMeTwoNumbersAndAText' has 2 parameters with non default value and 1 parameter with a default value")
print('The function looks like this: \'giveMeTwoNumbersAndAText(number1, number2, myText="This is my default text")\'')
print('This is a call with the 3 parameters: giveMeTwoNumbersAndAText(1,2,"Look at this awesome value")')
give_me_two_numbers_and_a_text(1, 2, 'Look at this awesome value')
print('This is a call with 2 parameters: giveMeTwoNumbersAndAText(1,2)')
give_me_two_numbers_and_a_text(1, 2)
print('If you do not have a default value for a param, you can not call the function without it')
print("For example: 'giveMeTwoNumbersAndAText(1)' will result in an error")
print('The default value is evaluated only once, when we define the function, so it not possible to change it arround the execution')
print("In python we can follow the argument order, or we can add the 'key,value' pair")
print('A valid example could be giveMeTwoNumbersAndAText(1, myText="Some Text", number2=10)')
give_me_two_numbers_and_a_text(1, myText='Some Text', number2=10)
print('Once we use the \'key/value\' definition, we have to use the \'key/value\' for the next elements, an invalid call for this case looks like this: giveMeTwoNumbersAndAText(1, myText="Some Text", 10)')
print('Defining a function receiving pocitional arguments')
def say_abunch_of_words(*args):
for arg in args:
print(arg)
print('A call with cero arg')
say_abunch_of_words()
print('A call with one arg')
say_abunch_of_words('one')
print('A call with two args')
say_abunch_of_words('one', 'two')
print('A call with three arg')
say_abunch_of_words('one', 'two', 'three')
print('Defining a function receiving a dictionary')
def print_my_dictionary(**myDictionary):
for key in myDictionary.keys():
print('The key:', key + '_k', ',', 'The value:', myDictionary[key] + '_v')
print('This is the function call with a dictionary as an input')
print_my_dictionary(param1='param1', param2='param2', param3='param3')
|
ecn_show_config_output="""\
Profile: AZURE_LOSSLESS
----------------------- -------
red_max_threshold 2097152
wred_green_enable true
ecn ecn_all
green_min_threshold 1048576
red_min_threshold 1048576
wred_yellow_enable true
yellow_min_threshold 1048576
green_max_threshold 2097152
green_drop_probability 5
yellow_max_threshold 2097152
wred_red_enable true
yellow_drop_probability 5
red_drop_probability 5
----------------------- -------
"""
testData = {
'ecn_show_config' : {'cmd' : ['show'],
'args' : [],
'rc' : 0,
'rc_output': ecn_show_config_output
},
'ecn_cfg_gmin' : {'cmd' : ['config'],
'args' : ['-profile', 'AZURE_LOSSLESS', '-gmin', '1048600'],
'rc' : 0,
'cmp_args' : ['AZURE_LOSSLESS,green_min_threshold,1048600']
},
'ecn_cfg_gmax' : {'cmd' : ['config'],
'args' : ['-profile', 'AZURE_LOSSLESS', '-gmax', '2097153'],
'rc' : 0,
'cmp_args' : ['AZURE_LOSSLESS,green_max_threshold,2097153']
},
'ecn_cfg_ymin' : {'cmd' : ['config'],
'args' : ['-profile', 'AZURE_LOSSLESS', '-ymin', '1048600'],
'rc' : 0,
'cmp_args' : ['AZURE_LOSSLESS,yellow_min_threshold,1048600']
},
'ecn_cfg_ymax' : {'cmd' : ['config'],
'args' : ['-profile', 'AZURE_LOSSLESS', '-ymax', '2097153'],
'rc' : 0,
'cmp_args' : ['AZURE_LOSSLESS,yellow_max_threshold,2097153']
},
'ecn_cfg_rmin' : {'cmd' : ['config'],
'args' : ['-profile', 'AZURE_LOSSLESS', '-rmin', '1048600'],
'rc' : 0,
'cmp_args' : ['AZURE_LOSSLESS,red_min_threshold,1048600']
},
'ecn_cfg_rmax' : {'cmd' : ['config'],
'args' : ['-profile', 'AZURE_LOSSLESS', '-rmax', '2097153'],
'rc' : 0,
'cmp_args' : ['AZURE_LOSSLESS,red_max_threshold,2097153']
},
'ecn_cfg_rdrop' : {'cmd' : ['config'],
'args' : ['-profile', 'AZURE_LOSSLESS', '-rdrop', '10'],
'rc' : 0,
'cmp_args' : ['AZURE_LOSSLESS,red_drop_probability,10']
},
'ecn_cfg_ydrop' : {'cmd' : ['config'],
'args' : ['-profile', 'AZURE_LOSSLESS', '-ydrop', '11'],
'rc' : 0,
'cmp_args' : ['AZURE_LOSSLESS,yellow_drop_probability,11']
},
'ecn_cfg_gdrop' : {'cmd' : ['config'],
'args' : ['-profile', 'AZURE_LOSSLESS', '-gdrop', '12'],
'rc' : 0,
'cmp_args' : ['AZURE_LOSSLESS,green_drop_probability,12']
},
'ecn_cfg_multi_set' : {'cmd' : ['config'],
'args' : ['-profile', 'AZURE_LOSSLESS', '-gdrop', '12', '-gmax', '2097153'],
'rc' : 0,
'cmp_args' : ['AZURE_LOSSLESS,green_drop_probability,12',
'AZURE_LOSSLESS,green_max_threshold,2097153'
]
},
'ecn_cfg_gmin_gmax_invalid' : {'cmd' : ['config'],
'args' : ['-profile', 'AZURE_LOSSLESS', '-gmax', '2097153', '-gmin', '2097154'],
'rc' : 1,
'rc_msg' : 'Invalid gmin (2097154) and gmax (2097153). gmin should be smaller than gmax'
},
'ecn_cfg_ymin_ymax_invalid' : {'cmd' : ['config'],
'args' : ['-profile', 'AZURE_LOSSLESS', '-ymax', '2097153', '-ymin', '2097154'],
'rc' : 1,
'rc_msg' : 'Invalid ymin (2097154) and ymax (2097153). ymin should be smaller than ymax'
},
'ecn_cfg_rmin_rmax_invalid' : {'cmd' : ['config'],
'args' : ['-profile', 'AZURE_LOSSLESS', '-rmax', '2097153', '-rmin', '2097154'],
'rc' : 1,
'rc_msg' : 'Invalid rmin (2097154) and rmax (2097153). rmin should be smaller than rmax'
},
'ecn_cfg_rmax_invalid' : {'cmd' : ['config'],
'args' : ['-profile', 'AZURE_LOSSLESS', '-rmax', '-2097153'],
'rc' : 1,
'rc_msg' : 'Invalid rmax (-2097153). rmax should be an non-negative integer'
},
'ecn_cfg_rdrop_invalid' : {'cmd' : ['config'],
'args' : ['-profile', 'AZURE_LOSSLESS', '-rdrop', '105'],
'rc' : 1,
'rc_msg' : 'Invalid value for "-rdrop": 105 is not in the valid range of 0 to 100'
}
}
|
ecn_show_config_output = 'Profile: AZURE_LOSSLESS\n----------------------- -------\nred_max_threshold 2097152\nwred_green_enable true\necn ecn_all\ngreen_min_threshold 1048576\nred_min_threshold 1048576\nwred_yellow_enable true\nyellow_min_threshold 1048576\ngreen_max_threshold 2097152\ngreen_drop_probability 5\nyellow_max_threshold 2097152\nwred_red_enable true\nyellow_drop_probability 5\nred_drop_probability 5\n----------------------- -------\n\n'
test_data = {'ecn_show_config': {'cmd': ['show'], 'args': [], 'rc': 0, 'rc_output': ecn_show_config_output}, 'ecn_cfg_gmin': {'cmd': ['config'], 'args': ['-profile', 'AZURE_LOSSLESS', '-gmin', '1048600'], 'rc': 0, 'cmp_args': ['AZURE_LOSSLESS,green_min_threshold,1048600']}, 'ecn_cfg_gmax': {'cmd': ['config'], 'args': ['-profile', 'AZURE_LOSSLESS', '-gmax', '2097153'], 'rc': 0, 'cmp_args': ['AZURE_LOSSLESS,green_max_threshold,2097153']}, 'ecn_cfg_ymin': {'cmd': ['config'], 'args': ['-profile', 'AZURE_LOSSLESS', '-ymin', '1048600'], 'rc': 0, 'cmp_args': ['AZURE_LOSSLESS,yellow_min_threshold,1048600']}, 'ecn_cfg_ymax': {'cmd': ['config'], 'args': ['-profile', 'AZURE_LOSSLESS', '-ymax', '2097153'], 'rc': 0, 'cmp_args': ['AZURE_LOSSLESS,yellow_max_threshold,2097153']}, 'ecn_cfg_rmin': {'cmd': ['config'], 'args': ['-profile', 'AZURE_LOSSLESS', '-rmin', '1048600'], 'rc': 0, 'cmp_args': ['AZURE_LOSSLESS,red_min_threshold,1048600']}, 'ecn_cfg_rmax': {'cmd': ['config'], 'args': ['-profile', 'AZURE_LOSSLESS', '-rmax', '2097153'], 'rc': 0, 'cmp_args': ['AZURE_LOSSLESS,red_max_threshold,2097153']}, 'ecn_cfg_rdrop': {'cmd': ['config'], 'args': ['-profile', 'AZURE_LOSSLESS', '-rdrop', '10'], 'rc': 0, 'cmp_args': ['AZURE_LOSSLESS,red_drop_probability,10']}, 'ecn_cfg_ydrop': {'cmd': ['config'], 'args': ['-profile', 'AZURE_LOSSLESS', '-ydrop', '11'], 'rc': 0, 'cmp_args': ['AZURE_LOSSLESS,yellow_drop_probability,11']}, 'ecn_cfg_gdrop': {'cmd': ['config'], 'args': ['-profile', 'AZURE_LOSSLESS', '-gdrop', '12'], 'rc': 0, 'cmp_args': ['AZURE_LOSSLESS,green_drop_probability,12']}, 'ecn_cfg_multi_set': {'cmd': ['config'], 'args': ['-profile', 'AZURE_LOSSLESS', '-gdrop', '12', '-gmax', '2097153'], 'rc': 0, 'cmp_args': ['AZURE_LOSSLESS,green_drop_probability,12', 'AZURE_LOSSLESS,green_max_threshold,2097153']}, 'ecn_cfg_gmin_gmax_invalid': {'cmd': ['config'], 'args': ['-profile', 'AZURE_LOSSLESS', '-gmax', '2097153', '-gmin', '2097154'], 'rc': 1, 'rc_msg': 'Invalid gmin (2097154) and gmax (2097153). gmin should be smaller than gmax'}, 'ecn_cfg_ymin_ymax_invalid': {'cmd': ['config'], 'args': ['-profile', 'AZURE_LOSSLESS', '-ymax', '2097153', '-ymin', '2097154'], 'rc': 1, 'rc_msg': 'Invalid ymin (2097154) and ymax (2097153). ymin should be smaller than ymax'}, 'ecn_cfg_rmin_rmax_invalid': {'cmd': ['config'], 'args': ['-profile', 'AZURE_LOSSLESS', '-rmax', '2097153', '-rmin', '2097154'], 'rc': 1, 'rc_msg': 'Invalid rmin (2097154) and rmax (2097153). rmin should be smaller than rmax'}, 'ecn_cfg_rmax_invalid': {'cmd': ['config'], 'args': ['-profile', 'AZURE_LOSSLESS', '-rmax', '-2097153'], 'rc': 1, 'rc_msg': 'Invalid rmax (-2097153). rmax should be an non-negative integer'}, 'ecn_cfg_rdrop_invalid': {'cmd': ['config'], 'args': ['-profile', 'AZURE_LOSSLESS', '-rdrop', '105'], 'rc': 1, 'rc_msg': 'Invalid value for "-rdrop": 105 is not in the valid range of 0 to 100'}}
|
# package org.apache.helix.store
#from org.apache.helix.store import *
class HelixPropertyListener:
def onDataChange(self, path):
"""
Returns void
Parameters:
path: String
"""
pass
def onDataCreate(self, path):
"""
Returns void
Parameters:
path: String
"""
pass
def onDataDelete(self, path):
"""
Returns void
Parameters:
path: String
"""
pass
|
class Helixpropertylistener:
def on_data_change(self, path):
"""
Returns void
Parameters:
path: String
"""
pass
def on_data_create(self, path):
"""
Returns void
Parameters:
path: String
"""
pass
def on_data_delete(self, path):
"""
Returns void
Parameters:
path: String
"""
pass
|
class Credentials:
"""
Class that generates new instances of credentials.
"""
credentials_list = [] #empty user list
def __init__(self,account,username,password):
self.account = account
self.username = username
self.password = password
def save_credentials(self):
'''
save_credentials method saves credentials objects into credentials_list
'''
Credentials.credentials_list.append(self)
def delete_credentials(self):
'''
delete_credentials method deletes a saved credential from the credentials_list
'''
Credentials.credentials_list.remove(self)
@classmethod
def find_by_account(cls,account):
'''
Method that takes in a account and returns a credentials that matches that account.
Args:
account: Phone account to search for
Returns :
Credentials of person that matches the account.
'''
for credentials in cls.credentials_list:
if credentials.account == account:
return credentials
@classmethod
def display_credentials(cls):
'''
method that returns the credentials list
'''
return cls.credentials_list
|
class Credentials:
"""
Class that generates new instances of credentials.
"""
credentials_list = []
def __init__(self, account, username, password):
self.account = account
self.username = username
self.password = password
def save_credentials(self):
"""
save_credentials method saves credentials objects into credentials_list
"""
Credentials.credentials_list.append(self)
def delete_credentials(self):
"""
delete_credentials method deletes a saved credential from the credentials_list
"""
Credentials.credentials_list.remove(self)
@classmethod
def find_by_account(cls, account):
"""
Method that takes in a account and returns a credentials that matches that account.
Args:
account: Phone account to search for
Returns :
Credentials of person that matches the account.
"""
for credentials in cls.credentials_list:
if credentials.account == account:
return credentials
@classmethod
def display_credentials(cls):
"""
method that returns the credentials list
"""
return cls.credentials_list
|
class Solution:
def brokenCalc(self, X: int, Y: int) -> int:
count = 0
while Y>X:
if Y%2==0:
Y //= 2
else:
Y += 1
count += 1
return count + X - Y
|
class Solution:
def broken_calc(self, X: int, Y: int) -> int:
count = 0
while Y > X:
if Y % 2 == 0:
y //= 2
else:
y += 1
count += 1
return count + X - Y
|
s = float(input('What is the salary of the functionary? $'))
if s > 1250.00:
t = s + s * 0.10
print(f'His salary increased by 10% and is now {t:.2f}')
else:
f = s + s * 0.15
print(f'His salary increased by 15% and is now {f:.2f}')
|
s = float(input('What is the salary of the functionary? $'))
if s > 1250.0:
t = s + s * 0.1
print(f'His salary increased by 10% and is now {t:.2f}')
else:
f = s + s * 0.15
print(f'His salary increased by 15% and is now {f:.2f}')
|
condition_table_true = ["lt", "gt", "eq"]
condition_table_false = ["ge", "le", "ne"]
trap_condition_table = {
1: "lgt",
2: "llt",
4: "eq",
5: "lge",
8: "gt",
12: "ge",
16: "lt",
20: "le",
31: "u"
}
spr_table = {
8: "lr",
9: "ctr"
}
def decodeI(value):
return (value >> 2) & 0xFFFFFF, (value >> 1) & 1, value & 1
def decodeB(value):
return (value >> 21) & 0x1F, (value >> 16) & 0x1F, (value >> 2) & 0x3FFF, (value >> 1) & 1, value & 1
def decodeD(value):
return (value >> 21) & 0x1F, (value >> 16) & 0x1F, value & 0xFFFF
def decodeX(value):
return (value >> 21) & 0x1F, (value >> 16) & 0x1F, (value >> 11) & 0x1F, (value >> 1) & 0x3FF, value & 1
def extend_sign(value, bits=16):
if value & 1 << (bits - 1):
value -= 1 << bits
return value
def ihex(value):
return "-" * (value < 0) + "0x" + hex(value).lstrip("-0x").rstrip("L").zfill(1).upper()
def decodeCond(BO, BI):
#TODO: Better condition code
if BO == 20: return ""
if BO & 1: return "?"
if BI > 2: return "?"
if BO == 4: return condition_table_false[BI]
if BO == 12: return condition_table_true[BI]
return "?"
def loadStore(value, regtype="r"):
D, A, d = decodeD(value)
d = extend_sign(d)
return "%s%i, %s(r%i)" %(regtype, D, ihex(d), A)
def loadStoreX(D, A, B, pad):
if pad: return "<invalid>"
return "r%i, %s, r%i" %(D, ("r%i" %A) if A else "0", B)
def add(D, A, B, Rc):
return "add%s" %("." * Rc), "r%i, r%i, r%i" %(D, A, B)
def addi(value, addr):
D, A, SIMM = decodeD(value)
SIMM = extend_sign(SIMM)
if A == 0:
return "li", "r%i, %s" %(D, ihex(SIMM))
return "addi", "r%i, r%i, %s" %(D, A, ihex(SIMM))
def addic(value, addr):
D, A, SIMM = decodeD(value)
SIMM = extend_sign(SIMM)
return "addic", "r%i, r%i, %s" %(D, A, ihex(SIMM))
def addic_(value, addr):
D, A, SIMM = decodeD(value)
SIMM = extend_sign(SIMM)
return "addic.", "r%i, r%i, %s" %(D, A, ihex(SIMM))
def addis(value, addr):
D, A, SIMM = decodeD(value)
SIMM = extend_sign(SIMM)
if A == 0:
return "lis", "r%i, %s" %(D, ihex(SIMM))
return "addis", "r%i, r%i, %s" %(D, A, ihex(SIMM))
def and_(S, A, B, Rc):
return "and%s" % ("." * Rc), "r%i, r%i, r%i" % (A, S, B)
def b(value, addr):
LI, AA, LK = decodeI(value)
LI = extend_sign(LI, 24) * 4
if AA:
dst = LI
else:
dst = addr + LI
return "b%s%s" %("l" * LK, "a" * AA), ihex(dst)
def bc(value, addr):
BO, BI, BD, AA, LK = decodeB(value)
LI = extend_sign(LK, 14) * 4
instr = "b" + decodeCond(BO, BI)
if LK: instr += "l"
if AA:
instr += "a"
dst = LI
else:
dst = addr + LI
return instr, ihex(dst)
def bcctr(BO, BI, pad, LK):
if pad: return "<invalid>"
instr = "b" + decodeCond(BO, BI) + "ctr"
if LK:
instr += "l"
return instr
def bclr(BO, BI, pad, LK):
if pad: return "<invalid>"
instr = "b" + decodeCond(BO, BI) + "lr"
if LK:
instr += "l"
return instr
def cmp(cr, A, B, pad):
if pad: return "<invalid>"
if cr & 3:
return "<invalid>"
return "cmp", "cr%i, r%i, r%i" %(cr >> 2, A, B)
def cmpi(value, addr):
cr, A, SIMM = decodeD(value)
SIMM = extend_sign(SIMM)
if cr & 3:
return "<invalid>"
return "cmpwi", "cr%i, r%i, %s" %(cr >> 2, A, ihex(SIMM))
def cmpl(cr, A, B, pad):
if pad: return "<invalid>"
if cr & 3:
return "<invalid>"
return "cmplw", "cr%i, r%i, r%i" %(cr >> 2, A, B)
def cmpli(value, addr):
cr, A, UIMM = decodeD(value)
if cr & 3:
return "<invalid>"
return "cmplwi", "cr%i, r%i, %s" %(cr >> 2, A, ihex(UIMM))
def cntlzw(S, A, pad, Rc):
if pad: return "<invalid>"
return "cntlzw%s" %("." * Rc), "r%i, r%i" %(A, S)
def dcbst(pad1, A, B, pad2):
if pad1 or pad2: return "<invalid>"
return "dcbst", "r%i, r%i" %(A, B)
def fmr(D, pad, B, Rc):
if pad: return "<invalid>"
return "fmr%s" %("." * Rc), "f%i, f%i" %(D, B)
def fneg(D, pad, B, Rc):
if pad: return "<invalid>"
return "fneg%s" %("." * Rc), "f%i, f%i" %(D, B)
def mfspr(D, sprLo, sprHi, pad):
if pad: return "<invalid>"
sprnum = (sprHi << 5) | sprLo
if sprnum not in spr_table:
spr = "?"
else:
spr = spr_table[sprnum]
return "mf%s" %spr, "r%i" %D
def mtspr(S, sprLo, sprHi, pad):
if pad: return "<invalid>"
sprnum = (sprHi << 5) | sprLo
if sprnum not in spr_table:
spr = ihex(sprnum)
else:
spr = spr_table[sprnum]
return "mt%s" %spr, "r%i" %S
def lbz(value, addr): return "lbz", loadStore(value)
def lfd(value, addr): return "lfd", loadStore(value, "f")
def lfs(value, addr): return "lfs", loadStore(value, "f")
def lmw(value, addr): return "lmw", loadStore(value)
def lwz(value, addr): return "lwz", loadStore(value)
def lwzu(value, addr): return "lwzu", loadStore(value)
def lwarx(D, A, B, pad): return "lwarx", loadStoreX(D, A, B, pad)
def lwzx(D, A, B, pad): return "lwzx", loadStoreX(D, A, B, pad)
def or_(S, A, B, Rc):
if S == B:
return "mr%s" %("." * Rc), "r%i, r%i" %(A, S)
return "or%s" %("." * Rc), "r%i, r%i, r%i" %(A, S, B)
def ori(value, addr):
S, A, UIMM = decodeD(value)
if UIMM == 0:
return "nop"
return "ori", "r%s, r%s, %s" %(A, S, ihex(UIMM))
def oris(value, addr):
S, A, UIMM = decodeD(value)
return "oris", "r%s, r%s, %s" %(A, S, ihex(UIMM))
def rlwinm(value, addr):
S, A, SH, M, Rc = decodeX(value)
MB = M >> 5
ME = M & 0x1F
dot = "." * Rc
if SH == 0 and MB == 0 and ME == 31:
return "nop"
if MB == 0 and ME == 31 - SH:
return "slwi%s" %dot, "r%i, r%i, %i" %(A, S, SH)
if ME == 31 and SH == 32 - MB:
return "srwi%s" %dot, "r%i, r%i, %i" %(A, S, MB)
if MB == 0 and ME < 31:
return "extlwi%s" %dot, "r%i, r%i, %i,%i" %(A, S, ME + 1, SH)
#extrwi
if MB == 0 and ME == 31:
if SH >= 16:
return "rotlwi%s" %dot, "r%i, r%i, %i" %(A, S, SH)
return "rotrwi%s" %dot, "r%i, r%i, %i" %(A, S, 32 - SH)
if SH == 0 and ME == 31:
return "clrlwi%s" %dot, "r%i, r%i, %i" %(A, S, MB)
if SH == 0 and MB == 0:
return "clrrwi%s" %dot, "r%i, r%i, %i" %(A, S, 31 - ME)
#clrlslwi
return "rlwinm%s" %dot, "r%i, r%i, r%i,r%i,r%i" %(A, S, SH, MB, ME)
def sc(value, addr):
if value & 0x3FFFFFF != 2:
return "<invalid>"
return "sc"
def stb(value, addr): return "stb", loadStore(value)
def stfd(value, addr): return "stfd", loadStore(value, "f")
def stfs(value, addr): return "stfs", loadStore(value, "f")
def stfsu(value, addr): return "stfsu", loadStore(value, "f")
def stmw(value, addr): return "stmw", loadStore(value)
def stw(value, addr): return "stw", loadStore(value)
def stwu(value, addr): return "stwu", loadStore(value)
def stbx(S, A, B, pad): return "stbx", loadStoreX(S, A, B, pad)
def stwx(S, A, B, pad): return "stwx", loadStoreX(S, A, B, pad)
def stwcx(S, A, B, pad): return "stwcx", loadStoreX(S, A, B, pad ^ 1)
def tw(TO, A, B, pad):
if pad: return "<invalid>"
if TO == 31 and A == 0 and B == 0:
return "trap"
if TO not in trap_condition_table:
condition = "?"
else:
condition = trap_condition_table[TO]
return "tw%s" %condition, "r%i, r%i" %(A, B)
opcode_table_ext1 = {
16: bclr,
528: bcctr
}
opcode_table_ext2 = {
0: cmp,
4: tw,
20: lwarx,
23: lwzx,
26: cntlzw,
28: and_,
32: cmpl,
54: dcbst,
150: stwcx,
151: stwx,
215: stbx,
266: add,
339: mfspr,
444: or_,
467: mtspr
}
opcode_table_float_ext1 = {
40: fneg,
72: fmr
}
def ext1(value, addr):
DS, A, B, XO, Rc = decodeX(value)
if not XO in opcode_table_ext1:
return "ext1 - %s" %bin(XO)
return opcode_table_ext1[XO](DS, A, B, Rc)
def ext2(value, addr):
DS, A, B, XO, Rc = decodeX(value)
if not XO in opcode_table_ext2:
return "ext2 - %s" %bin(XO)
return opcode_table_ext2[XO](DS, A, B, Rc)
def float_ext1(value, addr):
D, A, B, XO, Rc = decodeX(value)
if not XO in opcode_table_float_ext1:
return "float_ext1 - %s" %bin(XO)
return opcode_table_float_ext1[XO](D, A, B, Rc)
opcode_table = {
10: cmpli,
11: cmpi,
12: addic,
13: addic_,
14: addi,
15: addis,
16: bc,
17: sc,
18: b,
19: ext1,
21: rlwinm,
24: ori,
25: oris,
31: ext2,
32: lwz,
33: lwzu,
34: lbz,
36: stw,
37: stwu,
38: stb,
46: lmw,
47: stmw,
48: lfs,
50: lfd,
52: stfs,
53: stfsu,
54: stfd,
63: float_ext1
}
def disassemble(value, address):
opcode = value >> 26
if opcode not in opcode_table:
return "???"
instr = opcode_table[opcode](value, address)
if type(instr) == str:
return instr
return instr[0] + " " * (10 - len(instr[0])) + instr[1]
|
condition_table_true = ['lt', 'gt', 'eq']
condition_table_false = ['ge', 'le', 'ne']
trap_condition_table = {1: 'lgt', 2: 'llt', 4: 'eq', 5: 'lge', 8: 'gt', 12: 'ge', 16: 'lt', 20: 'le', 31: 'u'}
spr_table = {8: 'lr', 9: 'ctr'}
def decode_i(value):
return (value >> 2 & 16777215, value >> 1 & 1, value & 1)
def decode_b(value):
return (value >> 21 & 31, value >> 16 & 31, value >> 2 & 16383, value >> 1 & 1, value & 1)
def decode_d(value):
return (value >> 21 & 31, value >> 16 & 31, value & 65535)
def decode_x(value):
return (value >> 21 & 31, value >> 16 & 31, value >> 11 & 31, value >> 1 & 1023, value & 1)
def extend_sign(value, bits=16):
if value & 1 << bits - 1:
value -= 1 << bits
return value
def ihex(value):
return '-' * (value < 0) + '0x' + hex(value).lstrip('-0x').rstrip('L').zfill(1).upper()
def decode_cond(BO, BI):
if BO == 20:
return ''
if BO & 1:
return '?'
if BI > 2:
return '?'
if BO == 4:
return condition_table_false[BI]
if BO == 12:
return condition_table_true[BI]
return '?'
def load_store(value, regtype='r'):
(d, a, d) = decode_d(value)
d = extend_sign(d)
return '%s%i, %s(r%i)' % (regtype, D, ihex(d), A)
def load_store_x(D, A, B, pad):
if pad:
return '<invalid>'
return 'r%i, %s, r%i' % (D, 'r%i' % A if A else '0', B)
def add(D, A, B, Rc):
return ('add%s' % ('.' * Rc), 'r%i, r%i, r%i' % (D, A, B))
def addi(value, addr):
(d, a, simm) = decode_d(value)
simm = extend_sign(SIMM)
if A == 0:
return ('li', 'r%i, %s' % (D, ihex(SIMM)))
return ('addi', 'r%i, r%i, %s' % (D, A, ihex(SIMM)))
def addic(value, addr):
(d, a, simm) = decode_d(value)
simm = extend_sign(SIMM)
return ('addic', 'r%i, r%i, %s' % (D, A, ihex(SIMM)))
def addic_(value, addr):
(d, a, simm) = decode_d(value)
simm = extend_sign(SIMM)
return ('addic.', 'r%i, r%i, %s' % (D, A, ihex(SIMM)))
def addis(value, addr):
(d, a, simm) = decode_d(value)
simm = extend_sign(SIMM)
if A == 0:
return ('lis', 'r%i, %s' % (D, ihex(SIMM)))
return ('addis', 'r%i, r%i, %s' % (D, A, ihex(SIMM)))
def and_(S, A, B, Rc):
return ('and%s' % ('.' * Rc), 'r%i, r%i, r%i' % (A, S, B))
def b(value, addr):
(li, aa, lk) = decode_i(value)
li = extend_sign(LI, 24) * 4
if AA:
dst = LI
else:
dst = addr + LI
return ('b%s%s' % ('l' * LK, 'a' * AA), ihex(dst))
def bc(value, addr):
(bo, bi, bd, aa, lk) = decode_b(value)
li = extend_sign(LK, 14) * 4
instr = 'b' + decode_cond(BO, BI)
if LK:
instr += 'l'
if AA:
instr += 'a'
dst = LI
else:
dst = addr + LI
return (instr, ihex(dst))
def bcctr(BO, BI, pad, LK):
if pad:
return '<invalid>'
instr = 'b' + decode_cond(BO, BI) + 'ctr'
if LK:
instr += 'l'
return instr
def bclr(BO, BI, pad, LK):
if pad:
return '<invalid>'
instr = 'b' + decode_cond(BO, BI) + 'lr'
if LK:
instr += 'l'
return instr
def cmp(cr, A, B, pad):
if pad:
return '<invalid>'
if cr & 3:
return '<invalid>'
return ('cmp', 'cr%i, r%i, r%i' % (cr >> 2, A, B))
def cmpi(value, addr):
(cr, a, simm) = decode_d(value)
simm = extend_sign(SIMM)
if cr & 3:
return '<invalid>'
return ('cmpwi', 'cr%i, r%i, %s' % (cr >> 2, A, ihex(SIMM)))
def cmpl(cr, A, B, pad):
if pad:
return '<invalid>'
if cr & 3:
return '<invalid>'
return ('cmplw', 'cr%i, r%i, r%i' % (cr >> 2, A, B))
def cmpli(value, addr):
(cr, a, uimm) = decode_d(value)
if cr & 3:
return '<invalid>'
return ('cmplwi', 'cr%i, r%i, %s' % (cr >> 2, A, ihex(UIMM)))
def cntlzw(S, A, pad, Rc):
if pad:
return '<invalid>'
return ('cntlzw%s' % ('.' * Rc), 'r%i, r%i' % (A, S))
def dcbst(pad1, A, B, pad2):
if pad1 or pad2:
return '<invalid>'
return ('dcbst', 'r%i, r%i' % (A, B))
def fmr(D, pad, B, Rc):
if pad:
return '<invalid>'
return ('fmr%s' % ('.' * Rc), 'f%i, f%i' % (D, B))
def fneg(D, pad, B, Rc):
if pad:
return '<invalid>'
return ('fneg%s' % ('.' * Rc), 'f%i, f%i' % (D, B))
def mfspr(D, sprLo, sprHi, pad):
if pad:
return '<invalid>'
sprnum = sprHi << 5 | sprLo
if sprnum not in spr_table:
spr = '?'
else:
spr = spr_table[sprnum]
return ('mf%s' % spr, 'r%i' % D)
def mtspr(S, sprLo, sprHi, pad):
if pad:
return '<invalid>'
sprnum = sprHi << 5 | sprLo
if sprnum not in spr_table:
spr = ihex(sprnum)
else:
spr = spr_table[sprnum]
return ('mt%s' % spr, 'r%i' % S)
def lbz(value, addr):
return ('lbz', load_store(value))
def lfd(value, addr):
return ('lfd', load_store(value, 'f'))
def lfs(value, addr):
return ('lfs', load_store(value, 'f'))
def lmw(value, addr):
return ('lmw', load_store(value))
def lwz(value, addr):
return ('lwz', load_store(value))
def lwzu(value, addr):
return ('lwzu', load_store(value))
def lwarx(D, A, B, pad):
return ('lwarx', load_store_x(D, A, B, pad))
def lwzx(D, A, B, pad):
return ('lwzx', load_store_x(D, A, B, pad))
def or_(S, A, B, Rc):
if S == B:
return ('mr%s' % ('.' * Rc), 'r%i, r%i' % (A, S))
return ('or%s' % ('.' * Rc), 'r%i, r%i, r%i' % (A, S, B))
def ori(value, addr):
(s, a, uimm) = decode_d(value)
if UIMM == 0:
return 'nop'
return ('ori', 'r%s, r%s, %s' % (A, S, ihex(UIMM)))
def oris(value, addr):
(s, a, uimm) = decode_d(value)
return ('oris', 'r%s, r%s, %s' % (A, S, ihex(UIMM)))
def rlwinm(value, addr):
(s, a, sh, m, rc) = decode_x(value)
mb = M >> 5
me = M & 31
dot = '.' * Rc
if SH == 0 and MB == 0 and (ME == 31):
return 'nop'
if MB == 0 and ME == 31 - SH:
return ('slwi%s' % dot, 'r%i, r%i, %i' % (A, S, SH))
if ME == 31 and SH == 32 - MB:
return ('srwi%s' % dot, 'r%i, r%i, %i' % (A, S, MB))
if MB == 0 and ME < 31:
return ('extlwi%s' % dot, 'r%i, r%i, %i,%i' % (A, S, ME + 1, SH))
if MB == 0 and ME == 31:
if SH >= 16:
return ('rotlwi%s' % dot, 'r%i, r%i, %i' % (A, S, SH))
return ('rotrwi%s' % dot, 'r%i, r%i, %i' % (A, S, 32 - SH))
if SH == 0 and ME == 31:
return ('clrlwi%s' % dot, 'r%i, r%i, %i' % (A, S, MB))
if SH == 0 and MB == 0:
return ('clrrwi%s' % dot, 'r%i, r%i, %i' % (A, S, 31 - ME))
return ('rlwinm%s' % dot, 'r%i, r%i, r%i,r%i,r%i' % (A, S, SH, MB, ME))
def sc(value, addr):
if value & 67108863 != 2:
return '<invalid>'
return 'sc'
def stb(value, addr):
return ('stb', load_store(value))
def stfd(value, addr):
return ('stfd', load_store(value, 'f'))
def stfs(value, addr):
return ('stfs', load_store(value, 'f'))
def stfsu(value, addr):
return ('stfsu', load_store(value, 'f'))
def stmw(value, addr):
return ('stmw', load_store(value))
def stw(value, addr):
return ('stw', load_store(value))
def stwu(value, addr):
return ('stwu', load_store(value))
def stbx(S, A, B, pad):
return ('stbx', load_store_x(S, A, B, pad))
def stwx(S, A, B, pad):
return ('stwx', load_store_x(S, A, B, pad))
def stwcx(S, A, B, pad):
return ('stwcx', load_store_x(S, A, B, pad ^ 1))
def tw(TO, A, B, pad):
if pad:
return '<invalid>'
if TO == 31 and A == 0 and (B == 0):
return 'trap'
if TO not in trap_condition_table:
condition = '?'
else:
condition = trap_condition_table[TO]
return ('tw%s' % condition, 'r%i, r%i' % (A, B))
opcode_table_ext1 = {16: bclr, 528: bcctr}
opcode_table_ext2 = {0: cmp, 4: tw, 20: lwarx, 23: lwzx, 26: cntlzw, 28: and_, 32: cmpl, 54: dcbst, 150: stwcx, 151: stwx, 215: stbx, 266: add, 339: mfspr, 444: or_, 467: mtspr}
opcode_table_float_ext1 = {40: fneg, 72: fmr}
def ext1(value, addr):
(ds, a, b, xo, rc) = decode_x(value)
if not XO in opcode_table_ext1:
return 'ext1 - %s' % bin(XO)
return opcode_table_ext1[XO](DS, A, B, Rc)
def ext2(value, addr):
(ds, a, b, xo, rc) = decode_x(value)
if not XO in opcode_table_ext2:
return 'ext2 - %s' % bin(XO)
return opcode_table_ext2[XO](DS, A, B, Rc)
def float_ext1(value, addr):
(d, a, b, xo, rc) = decode_x(value)
if not XO in opcode_table_float_ext1:
return 'float_ext1 - %s' % bin(XO)
return opcode_table_float_ext1[XO](D, A, B, Rc)
opcode_table = {10: cmpli, 11: cmpi, 12: addic, 13: addic_, 14: addi, 15: addis, 16: bc, 17: sc, 18: b, 19: ext1, 21: rlwinm, 24: ori, 25: oris, 31: ext2, 32: lwz, 33: lwzu, 34: lbz, 36: stw, 37: stwu, 38: stb, 46: lmw, 47: stmw, 48: lfs, 50: lfd, 52: stfs, 53: stfsu, 54: stfd, 63: float_ext1}
def disassemble(value, address):
opcode = value >> 26
if opcode not in opcode_table:
return '???'
instr = opcode_table[opcode](value, address)
if type(instr) == str:
return instr
return instr[0] + ' ' * (10 - len(instr[0])) + instr[1]
|
__version__ = "2.2.3"
__title__ = "taxidTools"
__description__ = "A Python Toolkit for Taxonomy"
__author__ = "Gregoire Denay"
__author_email__ = 'gregoire.denay@cvua-rrw.de'
__licence__ = 'BSD License'
__url__ = "https://github.com/CVUA-RRW/taxidTools"
|
__version__ = '2.2.3'
__title__ = 'taxidTools'
__description__ = 'A Python Toolkit for Taxonomy'
__author__ = 'Gregoire Denay'
__author_email__ = 'gregoire.denay@cvua-rrw.de'
__licence__ = 'BSD License'
__url__ = 'https://github.com/CVUA-RRW/taxidTools'
|
#!/usr/bin/python3.3
S1 = 'abc'
S2 = 'xyz123'
z = zip(S1, S2)
print(list(z))
print(list(zip([1, 2, 3], [2, 3, 4, 5])))
print(list(map(abs, [-2, -1, 0, 1, 2])))
print(list(map(pow, [1, 2, 3], [2, 3, 4, 5])))
print(list(map(lambda x, y: x+y, open('script2.py'), open('script2.py'))))
print([x+y for (x, y) in zip(open('script2.py'), open('script2.py'))])
def mymap(func, *seqs):
res = []
for x in zip(*seqs):
res.append(func(*x))
return res
print(list(mymap(abs, [-2, -1, 0, 1, 2])))
print(list(mymap(pow, [1, 2, 3], [2, 3, 4, 5])))
def mymap(func, *seqs):
return [func(*x) for x in zip(*seqs)]
print(list(mymap(abs, [-2, -1, 0, 1, 2])))
print(list(mymap(pow, [1, 2, 3], [2, 3, 4, 5])))
def mymap(func, *seqs):
return (func(*x) for x in zip(*seqs))
print(list(mymap(abs, [-2, -1, 0, 1, 2])))
print(list(mymap(pow, [1, 2, 3], [2, 3, 4, 5])))
def mymap(func, *seqs):
for x in zip(*seqs):
yield func(*x)
print(list(mymap(abs, [-2, -1, 0, 1, 2])))
print(list(mymap(pow, [1, 2, 3], [2, 3, 4, 5])))
def myzip(*seq):
res = []
seqs = [list(S) for S in seq]
while all(seqs):
res.append(tuple(S.pop(0) for S in seqs))
return res
print(list(myzip([1, 2, 3], [2, 3, 4, 5])))
print([x+y for (x, y) in zip(open('script2.py'), open('script2.py'))])
def mymappad(*seq, pad=None):
res = []
seqs = [list(S) for S in seq]
while any(seqs):
res.append(tuple((S.pop(0) if S else pad) for S in seqs))
return res
print(mymappad(S1, S2, pad=99))
print(mymappad(S1, S2))
def myzip(*seq):
seqs = [list(S) for S in seq]
while all(seqs):
yield tuple(S.pop(0) for S in seqs)
print(list(myzip([1, 2, 3], [2, 3, 4, 5])))
print([x+y for (x, y) in myzip(open('script2.py'), open('script2.py'))])
def mymappad(*seq, pad=None):
seqs = [list(S) for S in seq]
while any(seqs):
yield tuple((S.pop(0) if S else pad) for S in seqs)
print(list(mymappad(S1, S2, pad=99)))
print(list(mymappad(S1, S2)))
def myzip(*seq):
minlen = min(len(S) for S in seq)
return [tuple(S[i] for S in seq) for i in range(minlen)]
print(list(myzip([1, 2, 3], [2, 3, 4, 5])))
def mymappad(*seq, pad=None):
maxlen = max(len(S) for S in seq)
return [tuple(S[i] if i < len(S) else pad for S in seq) for i in range(maxlen)]
print(list(mymappad(S1, S2, pad=99)))
print(list(mymappad(S1, S2)))
def myzip(*seq):
minlen = min(len(S) for S in seq)
return (tuple(S[i] for S in seq) for i in range(minlen))
print(list(myzip([1, 2, 3], [2, 3, 4, 5])))
def myzip(*seq):
iters = list(map(iter, seq))
i = 0
while iters:
i = i+1
print(i)
res = [next(i) for i in iters]
print(bool(iters))
yield tuple(res)
print('lala')
print(list(myzip([1, 2, 3], [2, 3, 4, 5])))
|
s1 = 'abc'
s2 = 'xyz123'
z = zip(S1, S2)
print(list(z))
print(list(zip([1, 2, 3], [2, 3, 4, 5])))
print(list(map(abs, [-2, -1, 0, 1, 2])))
print(list(map(pow, [1, 2, 3], [2, 3, 4, 5])))
print(list(map(lambda x, y: x + y, open('script2.py'), open('script2.py'))))
print([x + y for (x, y) in zip(open('script2.py'), open('script2.py'))])
def mymap(func, *seqs):
res = []
for x in zip(*seqs):
res.append(func(*x))
return res
print(list(mymap(abs, [-2, -1, 0, 1, 2])))
print(list(mymap(pow, [1, 2, 3], [2, 3, 4, 5])))
def mymap(func, *seqs):
return [func(*x) for x in zip(*seqs)]
print(list(mymap(abs, [-2, -1, 0, 1, 2])))
print(list(mymap(pow, [1, 2, 3], [2, 3, 4, 5])))
def mymap(func, *seqs):
return (func(*x) for x in zip(*seqs))
print(list(mymap(abs, [-2, -1, 0, 1, 2])))
print(list(mymap(pow, [1, 2, 3], [2, 3, 4, 5])))
def mymap(func, *seqs):
for x in zip(*seqs):
yield func(*x)
print(list(mymap(abs, [-2, -1, 0, 1, 2])))
print(list(mymap(pow, [1, 2, 3], [2, 3, 4, 5])))
def myzip(*seq):
res = []
seqs = [list(S) for s in seq]
while all(seqs):
res.append(tuple((S.pop(0) for s in seqs)))
return res
print(list(myzip([1, 2, 3], [2, 3, 4, 5])))
print([x + y for (x, y) in zip(open('script2.py'), open('script2.py'))])
def mymappad(*seq, pad=None):
res = []
seqs = [list(S) for s in seq]
while any(seqs):
res.append(tuple((S.pop(0) if S else pad for s in seqs)))
return res
print(mymappad(S1, S2, pad=99))
print(mymappad(S1, S2))
def myzip(*seq):
seqs = [list(S) for s in seq]
while all(seqs):
yield tuple((S.pop(0) for s in seqs))
print(list(myzip([1, 2, 3], [2, 3, 4, 5])))
print([x + y for (x, y) in myzip(open('script2.py'), open('script2.py'))])
def mymappad(*seq, pad=None):
seqs = [list(S) for s in seq]
while any(seqs):
yield tuple((S.pop(0) if S else pad for s in seqs))
print(list(mymappad(S1, S2, pad=99)))
print(list(mymappad(S1, S2)))
def myzip(*seq):
minlen = min((len(S) for s in seq))
return [tuple((S[i] for s in seq)) for i in range(minlen)]
print(list(myzip([1, 2, 3], [2, 3, 4, 5])))
def mymappad(*seq, pad=None):
maxlen = max((len(S) for s in seq))
return [tuple((S[i] if i < len(S) else pad for s in seq)) for i in range(maxlen)]
print(list(mymappad(S1, S2, pad=99)))
print(list(mymappad(S1, S2)))
def myzip(*seq):
minlen = min((len(S) for s in seq))
return (tuple((S[i] for s in seq)) for i in range(minlen))
print(list(myzip([1, 2, 3], [2, 3, 4, 5])))
def myzip(*seq):
iters = list(map(iter, seq))
i = 0
while iters:
i = i + 1
print(i)
res = [next(i) for i in iters]
print(bool(iters))
yield tuple(res)
print('lala')
print(list(myzip([1, 2, 3], [2, 3, 4, 5])))
|
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
ns = ''
for ch in s:
if ch.isalnum():
ns += ch.lower()
return ns == ns[::-1]
|
class Solution(object):
def is_palindrome(self, s):
"""
:type s: str
:rtype: bool
"""
ns = ''
for ch in s:
if ch.isalnum():
ns += ch.lower()
return ns == ns[::-1]
|
class LPGeneralException(Exception):
"""Raised when generic exceptions when using 'LPData' class"""
def __init__(self, msg):
self.msg = msg
class LPOptimizationFailedException(Exception):
"""Raised when optimization fails when using LPData class"""
pass
|
class Lpgeneralexception(Exception):
"""Raised when generic exceptions when using 'LPData' class"""
def __init__(self, msg):
self.msg = msg
class Lpoptimizationfailedexception(Exception):
"""Raised when optimization fails when using LPData class"""
pass
|
def make_singleton(class_):
def __new__(cls, *args, **kwargs):
raise Exception('class', cls.__name__, 'is a singleton')
class_.__new__ = __new__
|
def make_singleton(class_):
def __new__(cls, *args, **kwargs):
raise exception('class', cls.__name__, 'is a singleton')
class_.__new__ = __new__
|
def main():
a = int(input("Insira a idade do nadador: "))
if(a <= 5):
print("Categoria: Bebe")
elif(a > 5 and a <= 7):
print("Categoria: Infantil A")
elif(a >= 8 and a <= 10):
print("Categoria: Infantil B")
elif(a >= 11 and a <= 13):
print("Categoria: Juvenil A")
elif(a >= 14 and a <= 17):
print("Categoria: Juvenil B")
else:
print("Categoria: Senior")
main()
|
def main():
a = int(input('Insira a idade do nadador: '))
if a <= 5:
print('Categoria: Bebe')
elif a > 5 and a <= 7:
print('Categoria: Infantil A')
elif a >= 8 and a <= 10:
print('Categoria: Infantil B')
elif a >= 11 and a <= 13:
print('Categoria: Juvenil A')
elif a >= 14 and a <= 17:
print('Categoria: Juvenil B')
else:
print('Categoria: Senior')
main()
|
#Contains an (x,y) point, usually in projected coords.
class Point:
def __init__(self, x:float, y:float):
self.x = x
self.y = y
def __repr__(self):
return "Point(%f,%f)" % (self.x, self.y)
def __str__(self):
return "(%f,%f)" % (self.x, self.y)
#Contains a (lat/lng) location, usually as +/- rather than E/W
class Location:
def __init__(self, lat:float, lng:float):
self.lat = lat
self.lng = lng
def __repr__(self):
return "Location(%f,%f)" % (self.lat, self.lng)
def __str__(self):
return "(%f,%f)" % (self.lat, self.lng)
|
class Point:
def __init__(self, x: float, y: float):
self.x = x
self.y = y
def __repr__(self):
return 'Point(%f,%f)' % (self.x, self.y)
def __str__(self):
return '(%f,%f)' % (self.x, self.y)
class Location:
def __init__(self, lat: float, lng: float):
self.lat = lat
self.lng = lng
def __repr__(self):
return 'Location(%f,%f)' % (self.lat, self.lng)
def __str__(self):
return '(%f,%f)' % (self.lat, self.lng)
|
class Node:
pass
class BinaryNode(Node):
def __init__(self, des, src1, src2):
self.des=des
self.src1=src1
self.src2=src2
class AdduNode(BinaryNode):
def __str__(self):
return f'addu {self.des}, {self.src1}, {self.src2}'
class MuloNode(BinaryNode):
def __str__(self):
return f'mulo {self.des}, {self.src1}, {self.src2}'
class DivuNode(BinaryNode):
def __str__(self):
return f'divu {self.des}, {self.src1}, {self.src2}'
class SubuNode(BinaryNode):
def __str__(self):
return f'subu {self.des}, {self.src1}, {self.src2}'
class SeqNode(BinaryNode):
def __str__(self):
return f'seq {self.des}, {self.src1}, {self.src2}'
class SneNode(BinaryNode):
def __str__(self):
return f'sne {self.des}, {self.src1}, {self.src2}'
class SgeuNode(BinaryNode):
def __str__(self):
return f'sgeu {self.des}, {self.src1}, {self.src2}'
class SgtuNode(BinaryNode):
def __str__(self):
return f'sgtu {self.des}, {self.src1}, {self.src2}'
class SleuNode(BinaryNode):
def __str__(self):
return f'sleu {self.des}, {self.src1}, {self.src2}'
class SltuNode(BinaryNode):
def __str__(self):
return f'sltu {self.des}, {self.src1}, {self.src2}'
class BNode(Node):
def __init__(self, lab):
self.lab=lab
def __str__(self):
return f'b {self.lab}'
class BeqzNode(Node):
def __init__(self,src, lab):
self.src=src
self.lab=lab
def __str__(self):
return f'beqz {self.src}, {self.lab}'
class JNode(Node):
def __init__(self, lab):
self.lab=lab
def __str__(self):
return f'j {self.lab}'
class JrNode(Node):
def __init__(self, src):
self.src=src
def __str__(self):
return f'jr {self.src}'
class AddressNode(Node):
pass
class ConstAddrNode(AddressNode):
def __init__(self, const):
self.const=const
def __str__(self):
return self.const
class RegAddrNode(AddressNode):
def __init__(self, reg, const=None):
self.const=const
self.reg=reg
def __str__(self):
if self.const:
return f'{self.const}({self.reg})'
else:
return f'({self.reg})'
class SymbolAddrNode(AddressNode):
def __init__(self, symbol, const=None, reg=None):
self.symbol=symbol
self.const=const
self.reg=reg
def __str__(self):
if self.const and self.reg:
return f'{self.symbol} + {self.const}({self.reg})'
if self.const:
return f'{self.symbol} + {self.const}'
return self.symbol
class LoadAddrNode(Node):
def __init__(self, des, addr):
self.des=des
self.addr=addr
class LaNode(LoadAddrNode):
def __str__(self):
return f'la {self.des}, {self.addr}'
class LbuNode(LoadAddrNode):
def __str__(self):
return f'lbu {self.des}, {self.addr}'
class LhuNode(LoadAddrNode):
def __str__(self):
return f'lhu {self.des}, {self.addr}'
class LwNode(LoadAddrNode):
def __str__(self):
return f'lw {self.des}, {self.addr}'
class Ulhu(LoadAddrNode):
def __str__(self):
return f'ulhu {self.des}, {self.addr}'
class Ulw(LoadAddrNode):
def __str__(self):
return f'ulw {self.des}, {self.addr}'
class LoadConstNode(Node):
def __init__(self, des, const):
self.des=des
self.const=const
class LuiNode(LoadConstNode):
def __str__(self):
return f'lui {self.des}, {self.const}'
class LiNode(LoadConstNode):
def __str__(self):
return f'li {self.des}, {self.const}'
class Move(Node):
def __init__(self, src, des):
self.des=des
self.src=src
def __str__(self):
return f'move {self.des}, {self.src}'
class UnaryNode(Node):
def __init__(self, des, src):
self.des=des
self.src=src
class NotNode(UnaryNode):
def __str__(self):
return f'la {self.des}, {self.src}'
class SyscallNode(Node):
def __str__(self):
return 'syscall'
|
class Node:
pass
class Binarynode(Node):
def __init__(self, des, src1, src2):
self.des = des
self.src1 = src1
self.src2 = src2
class Addunode(BinaryNode):
def __str__(self):
return f'addu {self.des}, {self.src1}, {self.src2}'
class Mulonode(BinaryNode):
def __str__(self):
return f'mulo {self.des}, {self.src1}, {self.src2}'
class Divunode(BinaryNode):
def __str__(self):
return f'divu {self.des}, {self.src1}, {self.src2}'
class Subunode(BinaryNode):
def __str__(self):
return f'subu {self.des}, {self.src1}, {self.src2}'
class Seqnode(BinaryNode):
def __str__(self):
return f'seq {self.des}, {self.src1}, {self.src2}'
class Snenode(BinaryNode):
def __str__(self):
return f'sne {self.des}, {self.src1}, {self.src2}'
class Sgeunode(BinaryNode):
def __str__(self):
return f'sgeu {self.des}, {self.src1}, {self.src2}'
class Sgtunode(BinaryNode):
def __str__(self):
return f'sgtu {self.des}, {self.src1}, {self.src2}'
class Sleunode(BinaryNode):
def __str__(self):
return f'sleu {self.des}, {self.src1}, {self.src2}'
class Sltunode(BinaryNode):
def __str__(self):
return f'sltu {self.des}, {self.src1}, {self.src2}'
class Bnode(Node):
def __init__(self, lab):
self.lab = lab
def __str__(self):
return f'b {self.lab}'
class Beqznode(Node):
def __init__(self, src, lab):
self.src = src
self.lab = lab
def __str__(self):
return f'beqz {self.src}, {self.lab}'
class Jnode(Node):
def __init__(self, lab):
self.lab = lab
def __str__(self):
return f'j {self.lab}'
class Jrnode(Node):
def __init__(self, src):
self.src = src
def __str__(self):
return f'jr {self.src}'
class Addressnode(Node):
pass
class Constaddrnode(AddressNode):
def __init__(self, const):
self.const = const
def __str__(self):
return self.const
class Regaddrnode(AddressNode):
def __init__(self, reg, const=None):
self.const = const
self.reg = reg
def __str__(self):
if self.const:
return f'{self.const}({self.reg})'
else:
return f'({self.reg})'
class Symboladdrnode(AddressNode):
def __init__(self, symbol, const=None, reg=None):
self.symbol = symbol
self.const = const
self.reg = reg
def __str__(self):
if self.const and self.reg:
return f'{self.symbol} + {self.const}({self.reg})'
if self.const:
return f'{self.symbol} + {self.const}'
return self.symbol
class Loadaddrnode(Node):
def __init__(self, des, addr):
self.des = des
self.addr = addr
class Lanode(LoadAddrNode):
def __str__(self):
return f'la {self.des}, {self.addr}'
class Lbunode(LoadAddrNode):
def __str__(self):
return f'lbu {self.des}, {self.addr}'
class Lhunode(LoadAddrNode):
def __str__(self):
return f'lhu {self.des}, {self.addr}'
class Lwnode(LoadAddrNode):
def __str__(self):
return f'lw {self.des}, {self.addr}'
class Ulhu(LoadAddrNode):
def __str__(self):
return f'ulhu {self.des}, {self.addr}'
class Ulw(LoadAddrNode):
def __str__(self):
return f'ulw {self.des}, {self.addr}'
class Loadconstnode(Node):
def __init__(self, des, const):
self.des = des
self.const = const
class Luinode(LoadConstNode):
def __str__(self):
return f'lui {self.des}, {self.const}'
class Linode(LoadConstNode):
def __str__(self):
return f'li {self.des}, {self.const}'
class Move(Node):
def __init__(self, src, des):
self.des = des
self.src = src
def __str__(self):
return f'move {self.des}, {self.src}'
class Unarynode(Node):
def __init__(self, des, src):
self.des = des
self.src = src
class Notnode(UnaryNode):
def __str__(self):
return f'la {self.des}, {self.src}'
class Syscallnode(Node):
def __str__(self):
return 'syscall'
|
n, m = map(int, input().split())
connected = []
seeds = []
for i in range(0, n):
connected.append([])
for i in range(0, m):
a, b = map(int, input().split())
if (b not in connected[a-1]):
connected[a-1].append(b)
if (a not in connected[b-1]):
connected[b-1].append(a)
print(connected)
# for each pasture
for i in range(0, n):
# for each seed
for j in range(1, 4):
valid = True
# for each other pasture
for k in range(1, 4):
if k == j:
continue
if k in connected[j]:
valid = False
break
if valid:
seeds.append(k)
break
print(seeds)
|
(n, m) = map(int, input().split())
connected = []
seeds = []
for i in range(0, n):
connected.append([])
for i in range(0, m):
(a, b) = map(int, input().split())
if b not in connected[a - 1]:
connected[a - 1].append(b)
if a not in connected[b - 1]:
connected[b - 1].append(a)
print(connected)
for i in range(0, n):
for j in range(1, 4):
valid = True
for k in range(1, 4):
if k == j:
continue
if k in connected[j]:
valid = False
break
if valid:
seeds.append(k)
break
print(seeds)
|
class Rule:
def __init__(self, rule_id):
self.rule_id = rule_id
def __eq__(self, other):
return self.rule_id == other.rule_id
class RuleSet:
def __init__(self, **kwargs):
self.rules = {}
for k, v in kwargs.items():
self.rules[k] = Rule(v)
def __getattr__(self, attr_name):
return self.rules[attr_name]
def __add__(self, other):
result = self.__class__()
result.rules.update(self.rules)
result.rules.update(other.rules)
return result
|
class Rule:
def __init__(self, rule_id):
self.rule_id = rule_id
def __eq__(self, other):
return self.rule_id == other.rule_id
class Ruleset:
def __init__(self, **kwargs):
self.rules = {}
for (k, v) in kwargs.items():
self.rules[k] = rule(v)
def __getattr__(self, attr_name):
return self.rules[attr_name]
def __add__(self, other):
result = self.__class__()
result.rules.update(self.rules)
result.rules.update(other.rules)
return result
|
class Solution(object):
def validPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
l, r = 0, len(s)-1
count = 0
def get_result(l,r,s,count,forward=True):
while l < r:
if s[l] == s[r]:
l += 1; r -= 1
elif count < 1:
if not forward:
r -=1
else:
l += 1
count += 1
else:
return False
return True
result1 = get_result(l,r,s, count)
result2 = get_result(l,r,s,count,forward=False)
return result1 or result2
abc = Solution()
print (abc.validPalindrome("abca"))
|
class Solution(object):
def valid_palindrome(self, s):
"""
:type s: str
:rtype: bool
"""
(l, r) = (0, len(s) - 1)
count = 0
def get_result(l, r, s, count, forward=True):
while l < r:
if s[l] == s[r]:
l += 1
r -= 1
elif count < 1:
if not forward:
r -= 1
else:
l += 1
count += 1
else:
return False
return True
result1 = get_result(l, r, s, count)
result2 = get_result(l, r, s, count, forward=False)
return result1 or result2
abc = solution()
print(abc.validPalindrome('abca'))
|
#! /usr/bin/python
# -*- coding: iso-8859-15 -*-
def sc(n):
if n > 1:
r = sc(n - 1) + n ** 3
else:
r = 1
return r
a = int(input("Desde: "))
b = int(input("Hasta: "))
for i in range(a, b+1):
if sc(i):
print ("Numero primo: ",i)
|
def sc(n):
if n > 1:
r = sc(n - 1) + n ** 3
else:
r = 1
return r
a = int(input('Desde: '))
b = int(input('Hasta: '))
for i in range(a, b + 1):
if sc(i):
print('Numero primo: ', i)
|
sum(
1,
2, 3,
5,
)
sum(
1,
2, 3,
5)
|
sum(1, 2, 3, 5)
sum(1, 2, 3, 5)
|
class AccountError(Exception):
"""
Raised when the API can't locate any accounts for the user
"""
pass
|
class Accounterror(Exception):
"""
Raised when the API can't locate any accounts for the user
"""
pass
|
class BackendError(Exception):
pass
class FieldError(Exception):
pass
|
class Backenderror(Exception):
pass
class Fielderror(Exception):
pass
|
def read_spreadsheet():
file_name = "Data/day2.txt"
file = open(file_name, "r")
spreadsheet = []
for line in file:
line = list(map(int, line.split()))
spreadsheet.append(line)
return spreadsheet
def checksum(spreadsheet):
total = 0
for row in spreadsheet:
total += max(row) - min(row)
print(f"Part one: {total}")
def divisible_checksum(spreadsheet):
total = 0
for row in spreadsheet:
for i in range(len(row)-1):
for j in range(i+1, len(row)):
if row[i]%row[j] == 0:
total += row[i]//row[j]
if row[j]%row[i] == 0:
total += row[j]//row[i]
print(f"Part two: {total}")
if __name__ == "__main__":
spreadsheet = read_spreadsheet()
checksum(spreadsheet)
divisible_checksum(spreadsheet)
|
def read_spreadsheet():
file_name = 'Data/day2.txt'
file = open(file_name, 'r')
spreadsheet = []
for line in file:
line = list(map(int, line.split()))
spreadsheet.append(line)
return spreadsheet
def checksum(spreadsheet):
total = 0
for row in spreadsheet:
total += max(row) - min(row)
print(f'Part one: {total}')
def divisible_checksum(spreadsheet):
total = 0
for row in spreadsheet:
for i in range(len(row) - 1):
for j in range(i + 1, len(row)):
if row[i] % row[j] == 0:
total += row[i] // row[j]
if row[j] % row[i] == 0:
total += row[j] // row[i]
print(f'Part two: {total}')
if __name__ == '__main__':
spreadsheet = read_spreadsheet()
checksum(spreadsheet)
divisible_checksum(spreadsheet)
|
#!/usr/bin/env python3
# recherche empirique
aiguille = list()
for t in range(0, 43200):
h = t / 120
m = (t / 10) % 360
if abs(abs(h - m) - 90) < 0.05 or abs(abs(h - m) - 270) < 0.05:
if len(aiguille) > 0 and (t - aiguille[-1][0]) < 2:
del aiguille[-1]
hh, mm = int(h / 30), int(m / 6)
aiguille.append((t, f"{hh:02d}:{mm:02d}:{t%60:02d} {h:6.2f} {m:6.2f}"))
# calcul exact
exact = list()
for i in range(22):
h = (90 + 180 * i) / 11
m = (12 * h) % 360
hh, mm, ss = int(h / 30), int(m / 6), int(120 * h) % 60
fmt = f"{hh:02d}:{mm:02d}:{ss:02d} {h:6.2f} {m:6.2f}"
exact.append(fmt)
# affichage
for i, ((_, v), w) in enumerate(zip(aiguille, exact)):
print(f"{i+1:2} {v} {w}")
|
aiguille = list()
for t in range(0, 43200):
h = t / 120
m = t / 10 % 360
if abs(abs(h - m) - 90) < 0.05 or abs(abs(h - m) - 270) < 0.05:
if len(aiguille) > 0 and t - aiguille[-1][0] < 2:
del aiguille[-1]
(hh, mm) = (int(h / 30), int(m / 6))
aiguille.append((t, f'{hh:02d}:{mm:02d}:{t % 60:02d} {h:6.2f} {m:6.2f}'))
exact = list()
for i in range(22):
h = (90 + 180 * i) / 11
m = 12 * h % 360
(hh, mm, ss) = (int(h / 30), int(m / 6), int(120 * h) % 60)
fmt = f'{hh:02d}:{mm:02d}:{ss:02d} {h:6.2f} {m:6.2f}'
exact.append(fmt)
for (i, ((_, v), w)) in enumerate(zip(aiguille, exact)):
print(f'{i + 1:2} {v} {w}')
|
"""
Given a string S, find the longest palindromic substring in S.
Substring of string S:
S[i...j] where 0 <= i <= j < len(S)
Palindrome string:
A string which reads the same backwards. More formally, S is palindrome if reverse(S) = S.
Incase of conflict, return the substring which occurs first ( with the least starting index ).
Example :
Input : "aaaabaaa"
Output : "aaabaaa"
"""
class Solution:
# Method 01 :: Using string reverse function
def longestSubstring(self, s):
n = len(s)
if n < 2 or s == s[::-1]:
return s
longest_sq, start = 1, 0
for i in range(1, n):
odd = s[i-longest_sq -1 : i+1]
even = s[i -longest_sq : i+1]
if i-longest_sq -1 >= 0 and odd == odd[::-1]:
start = i - longest_sq -1
longest_sq += 2
continue
if i-longest_sq >= 0 and even == even[::-1]:
start = i -longest_sq
longest_sq += 1
return s[start: start+longest_sq]
# Method 02 :: Looping for every char to check if they are equal or not
def longestPalindrome(self, s):
n = len(s)
if n < 2 or s == s[::-1]:
return s
start, low, high, maxlen = 0,0,0,1
for i in range(1, n):
# working on odd len palindrome
low, high = i-1, i
while (low >= 0 and high < n) and (s[low] == s[high]):
if high -low +1 > maxlen:
start = low
maxlen = high - low + 1
high += 1
low -= 1
# working on even palindrome string
low, high = i-1, i+1
while (low >= 0 and high < n) and s[low] == s[high]:
if high - low + 1 > maxlen:
maxlen = high - low + 1
start = low
high += 1
low -= 1
return s[start: start+ maxlen]
s = Solution()
print(s.longestSubstring("aaaabaaa"))
print(s.longestPalindrome("abax"))
|
"""
Given a string S, find the longest palindromic substring in S.
Substring of string S:
S[i...j] where 0 <= i <= j < len(S)
Palindrome string:
A string which reads the same backwards. More formally, S is palindrome if reverse(S) = S.
Incase of conflict, return the substring which occurs first ( with the least starting index ).
Example :
Input : "aaaabaaa"
Output : "aaabaaa"
"""
class Solution:
def longest_substring(self, s):
n = len(s)
if n < 2 or s == s[::-1]:
return s
(longest_sq, start) = (1, 0)
for i in range(1, n):
odd = s[i - longest_sq - 1:i + 1]
even = s[i - longest_sq:i + 1]
if i - longest_sq - 1 >= 0 and odd == odd[::-1]:
start = i - longest_sq - 1
longest_sq += 2
continue
if i - longest_sq >= 0 and even == even[::-1]:
start = i - longest_sq
longest_sq += 1
return s[start:start + longest_sq]
def longest_palindrome(self, s):
n = len(s)
if n < 2 or s == s[::-1]:
return s
(start, low, high, maxlen) = (0, 0, 0, 1)
for i in range(1, n):
(low, high) = (i - 1, i)
while (low >= 0 and high < n) and s[low] == s[high]:
if high - low + 1 > maxlen:
start = low
maxlen = high - low + 1
high += 1
low -= 1
(low, high) = (i - 1, i + 1)
while (low >= 0 and high < n) and s[low] == s[high]:
if high - low + 1 > maxlen:
maxlen = high - low + 1
start = low
high += 1
low -= 1
return s[start:start + maxlen]
s = solution()
print(s.longestSubstring('aaaabaaa'))
print(s.longestPalindrome('abax'))
|
"""
Constants and methods used in testing
"""
class Colors():
WHITE = 'rgba(255, 255, 255, 1)'
RED_ERROR = 'rgba(220, 53, 69, 1)'
users = {
'valid_user': {'first_name':'Shinji',
'last_name': 'Ikari',
'user_name': 'sikari',
'address1': '123 Main St.',
'country': 'United States',
'state': 'California',
'zip': '12345',
'name_on_card': 'John Galt',
'number_on_card': '1111111111111',
'cvv': '111'},
'user_wo_username':{
'first_name':'Shinji',
'last_name': 'Ikari',
'address1': '123 Main St.',
'country': 'United States',
'state': 'California',
'zip': '12345',
'name_on_card': 'John Galt',
'number_on_card': '1111111111111',
'cvv': '111'
},
'user_invalid_cc':{
'first_name':'Shinji',
'last_name': 'Ikari',
'user_name': 'sikari',
'address1': '123 Main St.',
'country': 'United States',
'state': 'California',
'zip': '12345',
'name_on_card': 'John Galt',
'number_on_card': '4671100111123',
'cvv': '111'
},
}
|
"""
Constants and methods used in testing
"""
class Colors:
white = 'rgba(255, 255, 255, 1)'
red_error = 'rgba(220, 53, 69, 1)'
users = {'valid_user': {'first_name': 'Shinji', 'last_name': 'Ikari', 'user_name': 'sikari', 'address1': '123 Main St.', 'country': 'United States', 'state': 'California', 'zip': '12345', 'name_on_card': 'John Galt', 'number_on_card': '1111111111111', 'cvv': '111'}, 'user_wo_username': {'first_name': 'Shinji', 'last_name': 'Ikari', 'address1': '123 Main St.', 'country': 'United States', 'state': 'California', 'zip': '12345', 'name_on_card': 'John Galt', 'number_on_card': '1111111111111', 'cvv': '111'}, 'user_invalid_cc': {'first_name': 'Shinji', 'last_name': 'Ikari', 'user_name': 'sikari', 'address1': '123 Main St.', 'country': 'United States', 'state': 'California', 'zip': '12345', 'name_on_card': 'John Galt', 'number_on_card': '4671100111123', 'cvv': '111'}}
|
# Iterate through the array and maintain the min_so_far value. at each step profit = max(profit, arr[i]-min_so_far)
class Solution:
def maxProfit(self, prices: List[int]) -> int:
i = 0
max_profit = 0
min_so_far = 99999
for i in range(len(prices)):
max_profit = max(max_profit, prices[i]-min_so_far)
min_so_far = min(min_so_far, prices[i])
return max_profit
|
class Solution:
def max_profit(self, prices: List[int]) -> int:
i = 0
max_profit = 0
min_so_far = 99999
for i in range(len(prices)):
max_profit = max(max_profit, prices[i] - min_so_far)
min_so_far = min(min_so_far, prices[i])
return max_profit
|
def f(xs):
ys = 'string'
for x in xs:
g(ys)
def g(x):
return x.lower()
|
def f(xs):
ys = 'string'
for x in xs:
g(ys)
def g(x):
return x.lower()
|
def get_standard_config_dictionary(values):
run_dict = {}
run_dict['Configuration Name'] = values['standard_name_input']
run_dict['Model file'] = values['standard_model_input']
var_values = list(filter(''.__ne__, values['standard_value_input'].split('\n')))
run_dict['Parameter values'] = list(map(lambda x: x.strip(), var_values))
run_dict['Repetitions'] = values['standard_repetition_input']
run_dict['Ticks per run'] = values['standard_tick_input']
reporters = list(filter(''.__ne__, values['standard_reporter_input'].split('\n')))
run_dict['NetLogo reporters'] = list(map(lambda x: x.strip(), reporters))
setup_commands = list(filter(''.__ne__, values['standard_setup_input'].split('\n')))
run_dict['Setup commands'] = list(map(lambda x: x.strip(), setup_commands))
run_dict['Parallel executors'] = values['standard_process_input']
return run_dict
|
def get_standard_config_dictionary(values):
run_dict = {}
run_dict['Configuration Name'] = values['standard_name_input']
run_dict['Model file'] = values['standard_model_input']
var_values = list(filter(''.__ne__, values['standard_value_input'].split('\n')))
run_dict['Parameter values'] = list(map(lambda x: x.strip(), var_values))
run_dict['Repetitions'] = values['standard_repetition_input']
run_dict['Ticks per run'] = values['standard_tick_input']
reporters = list(filter(''.__ne__, values['standard_reporter_input'].split('\n')))
run_dict['NetLogo reporters'] = list(map(lambda x: x.strip(), reporters))
setup_commands = list(filter(''.__ne__, values['standard_setup_input'].split('\n')))
run_dict['Setup commands'] = list(map(lambda x: x.strip(), setup_commands))
run_dict['Parallel executors'] = values['standard_process_input']
return run_dict
|
A, B, C = input() .split()
A = float(A)
B = float(B)
C = float(C)
triangulo = float(A * C /2)
circulo = float(3.14159 * C**2)
trapezio = float(((A + B) * C) /2)
quadrado = float(B * B)
retangulo = float(A * B)
print("TRIANGULO: %0.3f" %triangulo)
print("CIRCULO: %0.3f" %circulo)
print("TRAPEZIO: %0.3f" %trapezio)
print("QUADRADO: %0.3f" %quadrado)
print("RETANGULO: %0.3f" %retangulo)
|
(a, b, c) = input().split()
a = float(A)
b = float(B)
c = float(C)
triangulo = float(A * C / 2)
circulo = float(3.14159 * C ** 2)
trapezio = float((A + B) * C / 2)
quadrado = float(B * B)
retangulo = float(A * B)
print('TRIANGULO: %0.3f' % triangulo)
print('CIRCULO: %0.3f' % circulo)
print('TRAPEZIO: %0.3f' % trapezio)
print('QUADRADO: %0.3f' % quadrado)
print('RETANGULO: %0.3f' % retangulo)
|
__all__ = [
'TargetApiError',
'TargetApiParamsError',
'TargetApiBadRequestError',
'TargetApiUnauthorizedError',
'TargetApiNotFoundError',
'TargetApiMethodNotAllowedError',
'TargetApiServerError',
'TargetApiServiceUnavailableError',
'TargetApiParameterNotImplementedError',
'TargetApiUnknownError'
]
class TargetApiError(Exception):
"""
Errors from Target API client
"""
def __init__(self, *args, **kwargs):
super(TargetApiError, self).__init__()
self.args = args
self.code = kwargs.pop('code', None)
self.msg = kwargs.pop('msg', None)
def __str__(self): # pragma: no cover
if self.code is not None or self.msg is not None:
return 'TargetAPI error: %(msg)s (%(code)s)' % self.__dict__
return Exception.__str__(self)
class TargetApiParamsError(TargetApiError):
"""
Error, when validate of request parameters is False
"""
def __init__(self, *args, **kwargs):
super(TargetApiParamsError, self).__init__()
self.msg = kwargs.pop('msg', 'Invalid parameters')
def __str__(self):
return 'TargetAPI error: %(msg)s' % self.__dict__
class TargetApiBadRequestError(TargetApiError):
"""
Server return 400 code - Bad request
"""
def __init__(self, *args, **kwargs):
super(TargetApiBadRequestError, self).__init__()
self.code = kwargs.pop('code', 400)
self.msg = kwargs.pop('msg', 'Bad request')
class TargetApiUnauthorizedError(TargetApiError):
"""
Server return 401 code - Unauthorized (Bad credentials)
"""
def __init__(self, *args, **kwargs):
super(TargetApiUnauthorizedError, self).__init__()
self.code = kwargs.pop('code', 401)
self.msg = kwargs.pop('msg', 'Unauthorized')
class TargetApiNotFoundError(TargetApiError):
"""
Server return 404 code - Not found
"""
def __init__(self, *args, **kwargs):
super(TargetApiNotFoundError, self).__init__()
self.code = kwargs.pop('code', 404)
self.msg = kwargs.pop('msg', 'Not found')
class TargetApiMethodNotAllowedError(TargetApiError):
"""
Server return 405 code - Method not allowed
"""
def __init__(self, *args, **kwargs):
super(TargetApiMethodNotAllowedError, self).__init__()
self.code = kwargs.pop('code', 405)
self.msg = kwargs.pop('msg', 'Method not allowed')
class TargetApiServerError(TargetApiError):
"""
Server return 500 code - Internal server error
"""
def __init__(self, *args, **kwargs):
super(TargetApiServerError, self).__init__()
self.code = kwargs.pop('code', 500)
self.msg = kwargs.pop('msg', 'Internal server error')
class TargetApiServiceUnavailableError(TargetApiError):
"""
Server return 503 code - Service is unavailable
"""
def __init__(self, *args, **kwargs):
super(TargetApiServiceUnavailableError, self).__init__()
self.code = kwargs.pop('code', 503)
self.msg = kwargs.pop('msg', 'Service unavailable')
class TargetApiParameterNotImplementedError(TargetApiError):
"""
Error, when some required parameter is not implemented
"""
def __init__(self, *args, **kwargs):
super(TargetApiParameterNotImplementedError, self).__init__()
self.parameter = kwargs.pop('parameter', '')
def __str__(self):
if self.parameter is not None:
return 'TargetAPI error: Parameter %(parameter)s not implemented' % self.__dict__
return 'TargetAPI error: Parameter not implemented'
class TargetApiUnknownError(TargetApiError):
"""
Unknown error
"""
def __init__(self, *args, **kwargs):
super(TargetApiUnknownError, self).__init__()
self.msg = kwargs.pop('msg', 'Unknown error')
|
__all__ = ['TargetApiError', 'TargetApiParamsError', 'TargetApiBadRequestError', 'TargetApiUnauthorizedError', 'TargetApiNotFoundError', 'TargetApiMethodNotAllowedError', 'TargetApiServerError', 'TargetApiServiceUnavailableError', 'TargetApiParameterNotImplementedError', 'TargetApiUnknownError']
class Targetapierror(Exception):
"""
Errors from Target API client
"""
def __init__(self, *args, **kwargs):
super(TargetApiError, self).__init__()
self.args = args
self.code = kwargs.pop('code', None)
self.msg = kwargs.pop('msg', None)
def __str__(self):
if self.code is not None or self.msg is not None:
return 'TargetAPI error: %(msg)s (%(code)s)' % self.__dict__
return Exception.__str__(self)
class Targetapiparamserror(TargetApiError):
"""
Error, when validate of request parameters is False
"""
def __init__(self, *args, **kwargs):
super(TargetApiParamsError, self).__init__()
self.msg = kwargs.pop('msg', 'Invalid parameters')
def __str__(self):
return 'TargetAPI error: %(msg)s' % self.__dict__
class Targetapibadrequesterror(TargetApiError):
"""
Server return 400 code - Bad request
"""
def __init__(self, *args, **kwargs):
super(TargetApiBadRequestError, self).__init__()
self.code = kwargs.pop('code', 400)
self.msg = kwargs.pop('msg', 'Bad request')
class Targetapiunauthorizederror(TargetApiError):
"""
Server return 401 code - Unauthorized (Bad credentials)
"""
def __init__(self, *args, **kwargs):
super(TargetApiUnauthorizedError, self).__init__()
self.code = kwargs.pop('code', 401)
self.msg = kwargs.pop('msg', 'Unauthorized')
class Targetapinotfounderror(TargetApiError):
"""
Server return 404 code - Not found
"""
def __init__(self, *args, **kwargs):
super(TargetApiNotFoundError, self).__init__()
self.code = kwargs.pop('code', 404)
self.msg = kwargs.pop('msg', 'Not found')
class Targetapimethodnotallowederror(TargetApiError):
"""
Server return 405 code - Method not allowed
"""
def __init__(self, *args, **kwargs):
super(TargetApiMethodNotAllowedError, self).__init__()
self.code = kwargs.pop('code', 405)
self.msg = kwargs.pop('msg', 'Method not allowed')
class Targetapiservererror(TargetApiError):
"""
Server return 500 code - Internal server error
"""
def __init__(self, *args, **kwargs):
super(TargetApiServerError, self).__init__()
self.code = kwargs.pop('code', 500)
self.msg = kwargs.pop('msg', 'Internal server error')
class Targetapiserviceunavailableerror(TargetApiError):
"""
Server return 503 code - Service is unavailable
"""
def __init__(self, *args, **kwargs):
super(TargetApiServiceUnavailableError, self).__init__()
self.code = kwargs.pop('code', 503)
self.msg = kwargs.pop('msg', 'Service unavailable')
class Targetapiparameternotimplementederror(TargetApiError):
"""
Error, when some required parameter is not implemented
"""
def __init__(self, *args, **kwargs):
super(TargetApiParameterNotImplementedError, self).__init__()
self.parameter = kwargs.pop('parameter', '')
def __str__(self):
if self.parameter is not None:
return 'TargetAPI error: Parameter %(parameter)s not implemented' % self.__dict__
return 'TargetAPI error: Parameter not implemented'
class Targetapiunknownerror(TargetApiError):
"""
Unknown error
"""
def __init__(self, *args, **kwargs):
super(TargetApiUnknownError, self).__init__()
self.msg = kwargs.pop('msg', 'Unknown error')
|
PAD = 0
UNK = 1
EOS = 2
BOS = 3
PAD_WORD = '<blank>'
UNK_WORD = '<unk>'
EOS_WORD = '<eos>'
BOS_WORD = '<bos>'
|
pad = 0
unk = 1
eos = 2
bos = 3
pad_word = '<blank>'
unk_word = '<unk>'
eos_word = '<eos>'
bos_word = '<bos>'
|
#!/usr/bin/env python3
class Solution(object):
def isNumber(self, s):
"""
:type s: str
:rtype: bool
"""
state = [{},
{'blank': 1, 'sign': 2, 'digit': 3, '.': 4},
{'digit': 3, '.': 4},
{'digit': 3, '.': 5, 'e': 6, 'blank': 9},
{'digit': 5},
{'digit': 5, 'e': 6, 'blank': 9},
{'sign': 7, 'digit': 8},
{'digit': 8},
{'digit': 8, 'blank': 9},
{'blank': 9}]
curr_state = 1
for c in s:
if c >= '0' and c <= '9':
c = 'digit'
if c == ' ':
c = 'blank'
if c in ['+', '-']:
c = 'sign'
if c not in state[curr_state].keys():
return False
curr_state = state[curr_state][c]
if curr_state not in [3, 5, 8, 9]:
return False
return True
if __name__ == "__main__":
s = Solution()
s1 = "2e10"
result = s.isNumber(s1)
print(result)
|
class Solution(object):
def is_number(self, s):
"""
:type s: str
:rtype: bool
"""
state = [{}, {'blank': 1, 'sign': 2, 'digit': 3, '.': 4}, {'digit': 3, '.': 4}, {'digit': 3, '.': 5, 'e': 6, 'blank': 9}, {'digit': 5}, {'digit': 5, 'e': 6, 'blank': 9}, {'sign': 7, 'digit': 8}, {'digit': 8}, {'digit': 8, 'blank': 9}, {'blank': 9}]
curr_state = 1
for c in s:
if c >= '0' and c <= '9':
c = 'digit'
if c == ' ':
c = 'blank'
if c in ['+', '-']:
c = 'sign'
if c not in state[curr_state].keys():
return False
curr_state = state[curr_state][c]
if curr_state not in [3, 5, 8, 9]:
return False
return True
if __name__ == '__main__':
s = solution()
s1 = '2e10'
result = s.isNumber(s1)
print(result)
|
class File:
def __init__(self, name: str, kind: str, content=None, base64=False):
self.content = content
self.name = name
self.type = kind
self.base64 = base64
def save(self, path):
with open(path, 'wb') as f:
f.write(self.content)
def open(self, path):
with open(path, 'rb') as f:
self.content = f.read()
|
class File:
def __init__(self, name: str, kind: str, content=None, base64=False):
self.content = content
self.name = name
self.type = kind
self.base64 = base64
def save(self, path):
with open(path, 'wb') as f:
f.write(self.content)
def open(self, path):
with open(path, 'rb') as f:
self.content = f.read()
|
# README! #
# You can add your own maps, just follow the format:
# mapX = ("Name shown to the user", PUT THE THREE QUOTATION MARKS (""") HERE
# MAP GOES HERE, you can use any characters, but you can only define the map's borders
# PUT THREE QUOTATION MARKS (""") HERE
# #################################### #
# You MUST put the maps in this order: map1 map2 map3 map4 map5 map6 map7 etc.
# Quotation marks like this
# V
map1 = ("Tall", """
############################################################
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
############################################################
""") # <-- use the quotation marks like this
map2 = ("Tall/thin", """
###################################
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
###################################
""") # <-- use the quotation marks like this
map3 = ("T h i c c square", """
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
""")
map4 = ("32x32 (because of characters' nature, which are taller than how large they are, this map will look rectangular", """
QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ
Q Q
Q Q
Q Q
Q Q
Q Q
Q Q
Q Q
Q Q
Q Q
Q Q
Q Q
Q Q
Q Q
Q Q
Q Q
Q Q
Q Q
Q Q
Q Q
Q Q
Q Q
Q Q
Q Q
Q Q
Q Q
Q Q
Q Q
Q Q
Q Q
Q Q
Q Q
Q Q
QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ
""")
|
map1 = ('Tall', '\n############################################################\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n############################################################\n')
map2 = ('Tall/thin', '\n###################################\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n###################################\n')
map3 = ('T h i c c square', '\n@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n@ @\n@ @\n@ @\n@ @\n@ @\n@ @\n@ @\n@ @\n@ @\n@ @\n@ @\n@ @\n@ @\n@ @\n@ @\n@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n')
map4 = ("32x32 (because of characters' nature, which are taller than how large they are, this map will look rectangular", '\nQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ\nQ Q\nQ Q\nQ Q\nQ Q\nQ Q\nQ Q\nQ Q\nQ Q\nQ Q\nQ Q\nQ Q\nQ Q\nQ Q\nQ Q\nQ Q\nQ Q\nQ Q\nQ Q\nQ Q\nQ Q\nQ Q\nQ Q\nQ Q\nQ Q\nQ Q\nQ Q\nQ Q\nQ Q\nQ Q\nQ Q\nQ Q\nQ Q\nQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ\n')
|
class Chain():
def __init__(self, val):
self.val = val
def add(self, b):
self.val += b
return self
def sub(self, b):
self.val -= b
return self
def mul(self, b):
self.val *= b
return self
print(Chain(5).add(5).sub(2).mul(10))
|
class Chain:
def __init__(self, val):
self.val = val
def add(self, b):
self.val += b
return self
def sub(self, b):
self.val -= b
return self
def mul(self, b):
self.val *= b
return self
print(chain(5).add(5).sub(2).mul(10))
|
#passed Test Set 1 in py
# def romanToInt(s):
# translations = {
# "I": 1,
# "V": 5,
# "X": 10,
# "L": 50,
# "C": 100,
# "D": 500,
# "M": 1000
# }
# number = 0
# s = s.replace("IV", "IIII").replace("IX", "VIIII")
# s = s.replace("XL", "XXXX").replace("XC", "LXXXX")
# s = s.replace("CD", "CCCC").replace("CM", "DCCCC")
# for char in s:
# number += translations[char]
# print(number)
def make_change(s):
# num = 0;
# temp = s
s = s.replace("01","2");
s = s.replace("12","3");
s = s.replace("23","4");
s = s.replace("34","5");
s = s.replace("45","6");
s = s.replace("56","7");
s = s.replace("67","8");
s = s.replace("78","9");
s = s.replace("89","0");
s = s.replace("90","1");
return s;
# if(temp == s):
# # return num;
# return s;
# else:
# return make_change(s);
t=int(input())
tt=1
while(tt<=t):
n=int(input())
s=input()
# temp = s
while(True):
temp = s
s = make_change(s)
if(temp == s):
break;
# ans = make_change(s)
print("Case #",tt,": ",s,sep='')
tt+=1
|
def make_change(s):
s = s.replace('01', '2')
s = s.replace('12', '3')
s = s.replace('23', '4')
s = s.replace('34', '5')
s = s.replace('45', '6')
s = s.replace('56', '7')
s = s.replace('67', '8')
s = s.replace('78', '9')
s = s.replace('89', '0')
s = s.replace('90', '1')
return s
t = int(input())
tt = 1
while tt <= t:
n = int(input())
s = input()
while True:
temp = s
s = make_change(s)
if temp == s:
break
print('Case #', tt, ': ', s, sep='')
tt += 1
|
EQUAL_ROWS_DATAFRAME_NAME = \
'dataframe_of_equal_rows'
NON_EQUAL_ROWS_DATAFRAME_NAME = \
'dataframe_of_non_equal_rows'
|
equal_rows_dataframe_name = 'dataframe_of_equal_rows'
non_equal_rows_dataframe_name = 'dataframe_of_non_equal_rows'
|
# HEAD
# Augmented Assignment Operators
# DESCRIPTION
# Describes basic usage of all the augmented operators available
# RESOURCES
#
foo = 40
# Addition augmented operator
foo += 1
print(foo)
# Subtraction augmented operator
foo -= 1
print(foo)
# Multiplication augmented operator
foo *= 1
print(foo)
# Division augmented operator
foo /= 2
print(foo)
# Modulus augmented operator
foo %= 3
print(foo)
# Modulus augmented operator
foo //= 3
print(foo)
# Example Usage
strOne = 'Testing'
listOne = [1, 2]
strOne += ' String' # concat for strings and lists
print(strOne)
listOne *= 2 # replication for strings and lists
print(listOne)
|
foo = 40
foo += 1
print(foo)
foo -= 1
print(foo)
foo *= 1
print(foo)
foo /= 2
print(foo)
foo %= 3
print(foo)
foo //= 3
print(foo)
str_one = 'Testing'
list_one = [1, 2]
str_one += ' String'
print(strOne)
list_one *= 2
print(listOne)
|
def test_client_can_get_avatars(client):
resp = client.get('/api/avatars')
assert resp.status_code == 200
def test_client_gets_correct_avatars_fields(client):
resp = client.get('/api/avatars')
assert 'offset' in resp.json
assert resp.json['offset'] is None
assert 'total' in resp.json
assert 'data' in resp.json
assert resp.json['total'] == len(resp.json['data'])
assert {
'avatar_id',
'category',
'uri',
'created_at',
'updated_at',
} == set(resp.json['data'][0].keys())
def test_client_filters_avatars_fields(client):
resp = client.get('/api/avatars?fields=category,created_at')
avatars = resp.json['data']
assert {
'category',
'created_at',
} == set(avatars[0].keys())
def test_client_offsets_avatars(client):
resp_1 = client.get('/api/avatars')
resp_2 = client.get('/api/avatars?offset=2')
assert len(resp_1.json['data']) \
== len(resp_2.json['data']) + min(2, len(resp_1.json['data']))
def test_client_limits_avatars(client):
resp_1 = client.get('/api/avatars?max_n_results=1')
resp_2 = client.get('/api/avatars?max_n_results=2')
assert len(resp_1.json['data']) <= 1
assert len(resp_2.json['data']) <= 2
def test_logged_off_client_cannot_create_avatar(client):
resp = client.post('/api/avatars',
data={
'uri': 'http://newavatars.com/img.png',
'category': 'dummy',
}
)
assert resp.status_code == 401
def test_logged_in_user_cannot_create_avatar(client_with_tok):
resp = client_with_tok.post('/api/avatars',
data={
'uri': 'http://newavatars.com/img.png',
'category': 'dummy',
}
)
assert resp.status_code == 401
def test_logged_in_mod_cannot_create_avatar(mod_with_tok):
resp = mod_with_tok.post('/api/avatars',
data={
'uri': 'http://newavatars.com/img.png',
'category': 'dummy',
}
)
assert resp.status_code == 401
def test_logged_in_admin_can_create_avatar(admin_with_tok):
resp = admin_with_tok.post('/api/avatars',
data={
'uri': 'http://newavatars.com/img.png',
'category': 'dummy',
}
)
assert resp.status_code == 200
def test_logged_in_admin_gets_correct_data_on_user_creation(admin_with_tok):
resp = admin_with_tok.post('/api/avatars',
data={
'uri': 'http://newavatars.com/img.png',
'category': 'dummy',
}
)
assert 'data' in resp.json
assert resp.json['data']['uri'] == 'http://newavatars.com/img.png'
assert resp.json['data']['category'] == 'dummy'
def test_client_can_get_avatar(client, avatar_id):
resp = client.get('/api/avatars/{}'.format(avatar_id))
assert resp.status_code == 200
assert 'data' in resp.json
def test_client_gets_correct_avatar_fields(client, avatar_id):
resp = client.get('/api/avatars/{}'.format(avatar_id))
assert 'data' in resp.json
assert {
'avatar_id',
'category',
'uri',
'created_at',
'updated_at',
} == set(resp.json['data'].keys())
def test_logged_off_client_cannot_edit_avatar(client, avatar_id):
resp = client.put('/api/avatars/{}'.format(avatar_id),
data={
'uri': 'http://newavatars.com/newimg.png',
}
)
assert resp.status_code == 401
def test_logged_in_user_cannot_edit_avatar(client_with_tok, avatar_id):
resp = client_with_tok.put('/api/avatars/{}'.format(avatar_id),
data={
'uri': 'http://newavatars.com/newimg.png',
}
)
assert resp.status_code == 401
def test_logged_in_mod_cannot_edit_avatar(mod_with_tok, avatar_id):
resp = mod_with_tok.put('/api/avatars/{}'.format(avatar_id),
data={
'uri': 'http://newavatars.com/newimg.png',
}
)
assert resp.status_code == 401
def test_logged_in_admin_can_edit_avatar(admin_with_tok, avatar_id):
resp = admin_with_tok.put('/api/avatars/{}'.format(avatar_id),
data={
'uri': 'http://newavatars.com/img.png',
'category': 'dummy',
}
)
assert resp.status_code == 200
def test_logged_in_admin_gets_correct_put_fields(admin_with_tok, avatar_id):
resp = admin_with_tok.put('/api/avatars/{}'.format(avatar_id),
data={
'category': 'newcategory',
}
)
assert 'data' in resp.json
assert {
'avatar_id',
'category',
'uri',
'created_at',
'updated_at',
} == set(resp.json['data'].keys())
def test_logged_in_admin_corretly_edits_avatar(admin_with_tok, avatar_id):
resp_1 = admin_with_tok.get('/api/avatars/{}'.format(avatar_id))
resp_2 = admin_with_tok.put('/api/avatars/{}'.format(avatar_id),
data={
'category': resp_1.json['data']['category'] + '_altered',
'uri': resp_1.json['data']['uri'] + '.png',
}
)
resp_3 = admin_with_tok.get('/api/avatars/{}'.format(avatar_id))
assert resp_1.status_code == 200
assert resp_2.status_code == 200
assert resp_3.status_code == 200
assert resp_3.json['data']['category'] \
== resp_1.json['data']['category'] + '_altered'
assert resp_3.json['data']['uri'] \
== resp_1.json['data']['uri'] + '.png'
def test_logged_off_client_cannot_delete_avatar(client, avatar_id):
resp = client.delete('/api/avatars/{}'.format(avatar_id))
assert resp.status_code == 401
def test_logged_in_user_cannot_delete_avatar(client_with_tok, avatar_id):
resp = client_with_tok.delete('/api/avatars/{}'.format(avatar_id))
assert resp.status_code == 401
def test_logged_in_mod_cannot_delete_avatar(mod_with_tok, avatar_id):
resp = mod_with_tok.delete('/api/avatars/{}'.format(avatar_id))
assert resp.status_code == 401
def test_logged_in_admin_can_delete_avatar(admin_with_tok, avatar_id):
resp = admin_with_tok.delete('/api/avatars/{}'.format(avatar_id))
assert resp.status_code == 204
def test_logged_in_admin_corretly_deletes_avatar(admin_with_tok, avatar_id):
resp_1 = admin_with_tok.get('/api/avatars/{}'.format(avatar_id))
resp_2 = admin_with_tok.delete('/api/avatars/{}'.format(avatar_id))
resp_3 = admin_with_tok.get('/api/avatars/{}'.format(avatar_id))
assert resp_1.status_code == 200
assert resp_2.status_code == 204
assert resp_3.status_code == 404
|
def test_client_can_get_avatars(client):
resp = client.get('/api/avatars')
assert resp.status_code == 200
def test_client_gets_correct_avatars_fields(client):
resp = client.get('/api/avatars')
assert 'offset' in resp.json
assert resp.json['offset'] is None
assert 'total' in resp.json
assert 'data' in resp.json
assert resp.json['total'] == len(resp.json['data'])
assert {'avatar_id', 'category', 'uri', 'created_at', 'updated_at'} == set(resp.json['data'][0].keys())
def test_client_filters_avatars_fields(client):
resp = client.get('/api/avatars?fields=category,created_at')
avatars = resp.json['data']
assert {'category', 'created_at'} == set(avatars[0].keys())
def test_client_offsets_avatars(client):
resp_1 = client.get('/api/avatars')
resp_2 = client.get('/api/avatars?offset=2')
assert len(resp_1.json['data']) == len(resp_2.json['data']) + min(2, len(resp_1.json['data']))
def test_client_limits_avatars(client):
resp_1 = client.get('/api/avatars?max_n_results=1')
resp_2 = client.get('/api/avatars?max_n_results=2')
assert len(resp_1.json['data']) <= 1
assert len(resp_2.json['data']) <= 2
def test_logged_off_client_cannot_create_avatar(client):
resp = client.post('/api/avatars', data={'uri': 'http://newavatars.com/img.png', 'category': 'dummy'})
assert resp.status_code == 401
def test_logged_in_user_cannot_create_avatar(client_with_tok):
resp = client_with_tok.post('/api/avatars', data={'uri': 'http://newavatars.com/img.png', 'category': 'dummy'})
assert resp.status_code == 401
def test_logged_in_mod_cannot_create_avatar(mod_with_tok):
resp = mod_with_tok.post('/api/avatars', data={'uri': 'http://newavatars.com/img.png', 'category': 'dummy'})
assert resp.status_code == 401
def test_logged_in_admin_can_create_avatar(admin_with_tok):
resp = admin_with_tok.post('/api/avatars', data={'uri': 'http://newavatars.com/img.png', 'category': 'dummy'})
assert resp.status_code == 200
def test_logged_in_admin_gets_correct_data_on_user_creation(admin_with_tok):
resp = admin_with_tok.post('/api/avatars', data={'uri': 'http://newavatars.com/img.png', 'category': 'dummy'})
assert 'data' in resp.json
assert resp.json['data']['uri'] == 'http://newavatars.com/img.png'
assert resp.json['data']['category'] == 'dummy'
def test_client_can_get_avatar(client, avatar_id):
resp = client.get('/api/avatars/{}'.format(avatar_id))
assert resp.status_code == 200
assert 'data' in resp.json
def test_client_gets_correct_avatar_fields(client, avatar_id):
resp = client.get('/api/avatars/{}'.format(avatar_id))
assert 'data' in resp.json
assert {'avatar_id', 'category', 'uri', 'created_at', 'updated_at'} == set(resp.json['data'].keys())
def test_logged_off_client_cannot_edit_avatar(client, avatar_id):
resp = client.put('/api/avatars/{}'.format(avatar_id), data={'uri': 'http://newavatars.com/newimg.png'})
assert resp.status_code == 401
def test_logged_in_user_cannot_edit_avatar(client_with_tok, avatar_id):
resp = client_with_tok.put('/api/avatars/{}'.format(avatar_id), data={'uri': 'http://newavatars.com/newimg.png'})
assert resp.status_code == 401
def test_logged_in_mod_cannot_edit_avatar(mod_with_tok, avatar_id):
resp = mod_with_tok.put('/api/avatars/{}'.format(avatar_id), data={'uri': 'http://newavatars.com/newimg.png'})
assert resp.status_code == 401
def test_logged_in_admin_can_edit_avatar(admin_with_tok, avatar_id):
resp = admin_with_tok.put('/api/avatars/{}'.format(avatar_id), data={'uri': 'http://newavatars.com/img.png', 'category': 'dummy'})
assert resp.status_code == 200
def test_logged_in_admin_gets_correct_put_fields(admin_with_tok, avatar_id):
resp = admin_with_tok.put('/api/avatars/{}'.format(avatar_id), data={'category': 'newcategory'})
assert 'data' in resp.json
assert {'avatar_id', 'category', 'uri', 'created_at', 'updated_at'} == set(resp.json['data'].keys())
def test_logged_in_admin_corretly_edits_avatar(admin_with_tok, avatar_id):
resp_1 = admin_with_tok.get('/api/avatars/{}'.format(avatar_id))
resp_2 = admin_with_tok.put('/api/avatars/{}'.format(avatar_id), data={'category': resp_1.json['data']['category'] + '_altered', 'uri': resp_1.json['data']['uri'] + '.png'})
resp_3 = admin_with_tok.get('/api/avatars/{}'.format(avatar_id))
assert resp_1.status_code == 200
assert resp_2.status_code == 200
assert resp_3.status_code == 200
assert resp_3.json['data']['category'] == resp_1.json['data']['category'] + '_altered'
assert resp_3.json['data']['uri'] == resp_1.json['data']['uri'] + '.png'
def test_logged_off_client_cannot_delete_avatar(client, avatar_id):
resp = client.delete('/api/avatars/{}'.format(avatar_id))
assert resp.status_code == 401
def test_logged_in_user_cannot_delete_avatar(client_with_tok, avatar_id):
resp = client_with_tok.delete('/api/avatars/{}'.format(avatar_id))
assert resp.status_code == 401
def test_logged_in_mod_cannot_delete_avatar(mod_with_tok, avatar_id):
resp = mod_with_tok.delete('/api/avatars/{}'.format(avatar_id))
assert resp.status_code == 401
def test_logged_in_admin_can_delete_avatar(admin_with_tok, avatar_id):
resp = admin_with_tok.delete('/api/avatars/{}'.format(avatar_id))
assert resp.status_code == 204
def test_logged_in_admin_corretly_deletes_avatar(admin_with_tok, avatar_id):
resp_1 = admin_with_tok.get('/api/avatars/{}'.format(avatar_id))
resp_2 = admin_with_tok.delete('/api/avatars/{}'.format(avatar_id))
resp_3 = admin_with_tok.get('/api/avatars/{}'.format(avatar_id))
assert resp_1.status_code == 200
assert resp_2.status_code == 204
assert resp_3.status_code == 404
|
"""
Question:
Write a program that accepts a comma separated sequence of words as input and prints the words in a comma-separated sequence
after sorting them alphabetically.
Suppose the following input is supplied to the program:
without,hello,bag,world
Then, the output should be:
bag,hello,without,world
"""
enter_string = input()
items = [x for x in enter_string.split(',')]
items.sort()
print(','.join(items))
"""
Input : lionel, christiano, diego, aguero
Output : aguero, christiano, diego,lionel
"""
|
"""
Question:
Write a program that accepts a comma separated sequence of words as input and prints the words in a comma-separated sequence
after sorting them alphabetically.
Suppose the following input is supplied to the program:
without,hello,bag,world
Then, the output should be:
bag,hello,without,world
"""
enter_string = input()
items = [x for x in enter_string.split(',')]
items.sort()
print(','.join(items))
'\nInput : lionel, christiano, diego, aguero\nOutput : aguero, christiano, diego,lionel\n\n'
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
def helper(root):
if root is None:
return 0,0
if root.left is None and root.right is None:
return 1,1
l1,m1 = helper(root.left)
l2,m2 = helper(root.right)
l = max(l1,l2) + 1
m = max(l1 + l2 + 1, m1 ,m2)
return l,m
l,m = helper(root)
if m:
return m -1
return m
|
class Solution:
def diameter_of_binary_tree(self, root: TreeNode) -> int:
def helper(root):
if root is None:
return (0, 0)
if root.left is None and root.right is None:
return (1, 1)
(l1, m1) = helper(root.left)
(l2, m2) = helper(root.right)
l = max(l1, l2) + 1
m = max(l1 + l2 + 1, m1, m2)
return (l, m)
(l, m) = helper(root)
if m:
return m - 1
return m
|
data_in: str = str()
balance: float = float()
deposit: float = float()
while True:
data_in = input()
if data_in == 'NoMoreMoney':
break
deposit = float(data_in)
if deposit < 0:
print('Invalid operation!')
break
print(f'Increase: {deposit:.2f}')
balance += deposit
print(f'Total: {balance:.2f}')
|
data_in: str = str()
balance: float = float()
deposit: float = float()
while True:
data_in = input()
if data_in == 'NoMoreMoney':
break
deposit = float(data_in)
if deposit < 0:
print('Invalid operation!')
break
print(f'Increase: {deposit:.2f}')
balance += deposit
print(f'Total: {balance:.2f}')
|
class Solution:
# # Track unsorted indexes using sets (Revisited), O(n*m) time, O(n) space
# def minDeletionSize(self, strs: List[str]) -> int:
# n, m = len(strs), len(strs[0])
# unsorted = set(range(n-1))
# res = 0
# for j in range(m):
# if any(strs[i][j] > strs[i+1][j] for i in unsorted):
# res += 1
# else:
# unsorted -= {i for i in unsorted if strs[i][j] < strs[i+1][j]}
# return res
# Track unsorted indexes using sets (Top Voted), O(n*m) time, O(n) space
def minDeletionSize(self, A: List[str]) -> int:
res, n, m = 0, len(A), len(A[0])
unsorted = set(range(n - 1))
for j in range(m):
if any(A[i][j] > A[i + 1][j] for i in unsorted):
res += 1
else:
unsorted -= {i for i in unsorted if A[i][j] < A[i + 1][j]}
return res
|
class Solution:
def min_deletion_size(self, A: List[str]) -> int:
(res, n, m) = (0, len(A), len(A[0]))
unsorted = set(range(n - 1))
for j in range(m):
if any((A[i][j] > A[i + 1][j] for i in unsorted)):
res += 1
else:
unsorted -= {i for i in unsorted if A[i][j] < A[i + 1][j]}
return res
|
# code
t = int(input())
for _ in range(t):
n = int(input())
temp = list(map(int, input().split()))
l = [temp[i:i+n] for i in range(0, len(temp), n)]
del temp
weight = 1
for i in range(n):
l.append(list(map(int, input().split(','))))
row = 0
col = 0
suml = 0
while True:
if row < n-1 and col < n-1:
a = min(l[row+1][col], l[row][col+1])
if a == l[row+1][col]:
row += 1
else:
col += 1
suml += a
if row == n-1 and col < n-1:
col += 1
a = l[row][col]
suml += a
if row < n-1 and col == n-1:
row += 1
a = l[row][col]
suml += a
if row == n-1 and col == n-1:
a = l[row][col]
suml += a
print(suml)
break
|
t = int(input())
for _ in range(t):
n = int(input())
temp = list(map(int, input().split()))
l = [temp[i:i + n] for i in range(0, len(temp), n)]
del temp
weight = 1
for i in range(n):
l.append(list(map(int, input().split(','))))
row = 0
col = 0
suml = 0
while True:
if row < n - 1 and col < n - 1:
a = min(l[row + 1][col], l[row][col + 1])
if a == l[row + 1][col]:
row += 1
else:
col += 1
suml += a
if row == n - 1 and col < n - 1:
col += 1
a = l[row][col]
suml += a
if row < n - 1 and col == n - 1:
row += 1
a = l[row][col]
suml += a
if row == n - 1 and col == n - 1:
a = l[row][col]
suml += a
print(suml)
break
|
def Efrase(frase):
nums = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')
if frase.count('.') == 1 and frase[len(frase) - 1] != '.' or frase == '.':
return False
elif frase.count('.') > 1:
return False
for j in range(0, 10):
if nums[j] in frase:
return False
return True
#entrada
while True:
try:
frase = str(input()).strip().split()
#processamento
fraseValida = ''
for i in range(0, len(frase)): #frase valida (eliminando palavras invalidas)
if Efrase(frase[i]):
fraseValida = fraseValida + ' ' + frase[i]
fraseValida = fraseValida.strip().split()
nPalavras = len(fraseValida)
m = ponto = 0
for i in range(0, nPalavras): #calculando o tamanho medio das palavras
m += len(fraseValida[i])
ponto += fraseValida[i].count('.')
m -= ponto
if nPalavras > 0:
m = m // nPalavras
else:
m = 0
#saida
if m <= 3:
print(250)
elif m <= 5:
print(500)
else:
print(1000)
except EOFError:
break
|
def efrase(frase):
nums = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')
if frase.count('.') == 1 and frase[len(frase) - 1] != '.' or frase == '.':
return False
elif frase.count('.') > 1:
return False
for j in range(0, 10):
if nums[j] in frase:
return False
return True
while True:
try:
frase = str(input()).strip().split()
frase_valida = ''
for i in range(0, len(frase)):
if efrase(frase[i]):
frase_valida = fraseValida + ' ' + frase[i]
frase_valida = fraseValida.strip().split()
n_palavras = len(fraseValida)
m = ponto = 0
for i in range(0, nPalavras):
m += len(fraseValida[i])
ponto += fraseValida[i].count('.')
m -= ponto
if nPalavras > 0:
m = m // nPalavras
else:
m = 0
if m <= 3:
print(250)
elif m <= 5:
print(500)
else:
print(1000)
except EOFError:
break
|
#!/usr/bin/env python
outlinks_file = open('link_graph_ly.txt', 'r')
inlinks_file = open('link_graph_ly2.txt', 'w')
inlinks = {} # url -> list of inlinks in url
for line in outlinks_file.readlines():
urls = line.split()
if (len(urls)) < 1:
continue
url = urls[0]
inlinks[url] = []
outlinks_file.seek(0)
for line in outlinks_file.readlines():
urls = line.split()
if (len(urls)) < 1:
continue
url = urls[0]
outlinks = urls[1:]
for ol in outlinks:
if ol in inlinks:
inlinks[ol].append(url)
# Write to file
for url in inlinks:
inlinks_file.write(url + ' ' + ' '.join(inlinks[url]) + '\n')
inlinks_file.flush()
inlinks_file.close()
|
outlinks_file = open('link_graph_ly.txt', 'r')
inlinks_file = open('link_graph_ly2.txt', 'w')
inlinks = {}
for line in outlinks_file.readlines():
urls = line.split()
if len(urls) < 1:
continue
url = urls[0]
inlinks[url] = []
outlinks_file.seek(0)
for line in outlinks_file.readlines():
urls = line.split()
if len(urls) < 1:
continue
url = urls[0]
outlinks = urls[1:]
for ol in outlinks:
if ol in inlinks:
inlinks[ol].append(url)
for url in inlinks:
inlinks_file.write(url + ' ' + ' '.join(inlinks[url]) + '\n')
inlinks_file.flush()
inlinks_file.close()
|
def init(cfg):
data = {'_logLevel': 'WARN', '_moduleLogLevel': 'WARN'}
if cfg['_stage'] == 'dev':
data.update({
'_logLevel': 'DEBUG',
'_moduleLogLevel': 'WARN',
'_logFormat': '%(levelname)s: %(message)s'
})
return data
|
def init(cfg):
data = {'_logLevel': 'WARN', '_moduleLogLevel': 'WARN'}
if cfg['_stage'] == 'dev':
data.update({'_logLevel': 'DEBUG', '_moduleLogLevel': 'WARN', '_logFormat': '%(levelname)s: %(message)s'})
return data
|
"""Common configs for plots"""
class Base():
font = {
'family': 'Times New Roman',
'size': 16,
}
class Legend(Base):
font = {**Base.font, 'weight': 'bold'}
class Tick(Base):
font = {**Base.font, 'size': 12}
|
"""Common configs for plots"""
class Base:
font = {'family': 'Times New Roman', 'size': 16}
class Legend(Base):
font = {**Base.font, 'weight': 'bold'}
class Tick(Base):
font = {**Base.font, 'size': 12}
|
"""read()"""
f = open("./test_file2", 'r', encoding = 'utf-8')
# read a file line-by-line using a for loop
for line in f:
print(line, end='')
# read individual lines of a file
f5 = f.readline()
f6 = f.readline()
f7 = f.readline()
print("f5\n", f5)
print("f6\n", f6)
print("f7\n", f7)
# list of remaining lines of the entire file.
f8 = f.readlines()
print("f8\n", f8)
|
"""read()"""
f = open('./test_file2', 'r', encoding='utf-8')
for line in f:
print(line, end='')
f5 = f.readline()
f6 = f.readline()
f7 = f.readline()
print('f5\n', f5)
print('f6\n', f6)
print('f7\n', f7)
f8 = f.readlines()
print('f8\n', f8)
|
user1_input = int(input("Please enter number 1 : Rock or 2 : Scissors or 3 : Papers."))
user2_input = int(input("Please enter number 1 : Rock or 2 : Scissors or 3 : Papers."))
if user1_input == 1:
user1_input = 'Rock'
elif user1_input == 2:
user1_input = 'Scissors'
else:
user1_input = 'Papers'
if user2_input == 1:
user2_input = 'Rock'
elif user2_input == 2:
user2_input = 'Scissors'
else:
user2_input = 'Papers'
while user1_input != user2_input:
if user1_input == 'Rock':
if user2_input == 'Papers':
print("User2 is the winner")
break
elif user2_input == 'Scissors':
print("User1 is the winner")
break
elif user1_input == 'Scissors':
if user2_input == 'Rock':
print("User2 is the winner.")
break
elif user2_input == 'Papers':
print("User1 is the winner.")
break
elif user1_input == 'Papers':
if user2_input == 'Scissors':
print("User2 is the winner.")
break
elif user2_input == 'Rock':
print("User1 is the winner.")
break
# Another Solution attempted on 14/2/2020
while True:
print("Please input your command")
print("1 : Play Rock, Scissors and Paper Game")
print("0 : Exit the Game\n")
command = int(input("\nEnter your command"))
if command == 0:
break
elif command == 1:
choices = []
for i in range(1, 3):
plays = ['Rock', 'Scissors', 'Players']
print(f'Enter play for user {i}\n')
print("1. Rock \n",
"2. Scissors \n",
"3. Paper\n",)
choice = int(input("\nPlease enter your choice"))
if choice == 1:
choices.append("Rock")
if choice == 2:
choices.append("Scissors")
if choice == 3:
choices.append("Paper")
if choices[0] == choices[1]:
print("===" * 10)
print("It is a draw")
print("===" * 10)
else:
if choices[0] == "Rock" and choices[1] == "Scissors":
print("\nPlayer 1 is the winner\n")
elif choices[0] == "Scissors" and choices[1] == "Paper":
print("\nPlayer 1 is the winner\n")
elif choices[0] == "Paper" and choices[1] == "Rock":
print("\nPlayer1 is the winner\n")
else:
print("\nPlayer 2 is the winner\n")
|
user1_input = int(input('Please enter number 1 : Rock or 2 : Scissors or 3 : Papers.'))
user2_input = int(input('Please enter number 1 : Rock or 2 : Scissors or 3 : Papers.'))
if user1_input == 1:
user1_input = 'Rock'
elif user1_input == 2:
user1_input = 'Scissors'
else:
user1_input = 'Papers'
if user2_input == 1:
user2_input = 'Rock'
elif user2_input == 2:
user2_input = 'Scissors'
else:
user2_input = 'Papers'
while user1_input != user2_input:
if user1_input == 'Rock':
if user2_input == 'Papers':
print('User2 is the winner')
break
elif user2_input == 'Scissors':
print('User1 is the winner')
break
elif user1_input == 'Scissors':
if user2_input == 'Rock':
print('User2 is the winner.')
break
elif user2_input == 'Papers':
print('User1 is the winner.')
break
elif user1_input == 'Papers':
if user2_input == 'Scissors':
print('User2 is the winner.')
break
elif user2_input == 'Rock':
print('User1 is the winner.')
break
while True:
print('Please input your command')
print('1 : Play Rock, Scissors and Paper Game')
print('0 : Exit the Game\n')
command = int(input('\nEnter your command'))
if command == 0:
break
elif command == 1:
choices = []
for i in range(1, 3):
plays = ['Rock', 'Scissors', 'Players']
print(f'Enter play for user {i}\n')
print('1. Rock \n', '2. Scissors \n', '3. Paper\n')
choice = int(input('\nPlease enter your choice'))
if choice == 1:
choices.append('Rock')
if choice == 2:
choices.append('Scissors')
if choice == 3:
choices.append('Paper')
if choices[0] == choices[1]:
print('===' * 10)
print('It is a draw')
print('===' * 10)
elif choices[0] == 'Rock' and choices[1] == 'Scissors':
print('\nPlayer 1 is the winner\n')
elif choices[0] == 'Scissors' and choices[1] == 'Paper':
print('\nPlayer 1 is the winner\n')
elif choices[0] == 'Paper' and choices[1] == 'Rock':
print('\nPlayer1 is the winner\n')
else:
print('\nPlayer 2 is the winner\n')
|
class AdvancedBoxScore:
def __init__(self, seconds_played, offensive_rating, defensive_rating,
teammate_assist_percentage, assist_to_turnover_ratio, assists_per_100_possessions,
offensive_rebound_percentage, defensive_rebound_percentage, turnovers_per_100_possessions,
effective_field_goal_percentage, true_shooting_percentage):
self.seconds_played = seconds_played
self.offensive_rating = offensive_rating
self.defensive_rating = defensive_rating
self.teammate_assist_percentage = teammate_assist_percentage
self.assist_to_turnover_ratio = assist_to_turnover_ratio
self.assists_per_100_possessions = assists_per_100_possessions
self.offensive_rebound_percentage = offensive_rebound_percentage
self.defensive_rebound_percentage = defensive_rebound_percentage
self.turnovers_per_100_possessions = turnovers_per_100_possessions
self.effective_field_goal_percentage = effective_field_goal_percentage
self.true_shooting_percentage = true_shooting_percentage
def __unicode__(self):
return '{0} | {1}'.format(self.get_additional_unicode(), self.get_base_unicode)
def get_base_unicode(self):
return 'seconds played: {seconds_played} | offensive rating: {offensive_rating} | ' \
'defensive rating: {defensive_rating} | teammate assist percentage: {teammate_assist_percentage} |' \
'assist to turnover ratio: {assist_to_turnover_ratio} | ' \
'assists per 100 possessions: {assists_per_100_possessions} | ' \
'offensive rebound percentage: {offensive_rebound_percentage} |' \
'defensive rebound percentage: {defensive_rebound_percentage} |' \
'turnovers per 100 possessions: {turnovers_per_100_possessions} |' \
'effective field goal percentage: {effective_field_goal_percentage} |' \
'true shooting percentage: {true_shooting_percentage}'\
.format(seconds_played=self.seconds_played, offensive_rating=self.offensive_rating,
defensive_rating=self.defensive_rating, teammate_assist_percentage=self.teammate_assist_percentage,
assist_to_turnover_ratio=self.assist_to_turnover_ratio,
assists_per_100_possessions=self.assists_per_100_possessions,
offensive_rebound_percentage=self.offensive_rebound_percentage,
defensive_rebound_percentage=self.defensive_rebound_percentage,
turnovers_per_100_possessions=self.turnovers_per_100_possessions,
effective_field_goal_percentage=self.effective_field_goal_percentage,
true_shooting_percentage=self.true_shooting_percentage)
def get_additional_unicode(self):
return NotImplementedError('Should be implemented in concrete class')
class AdvancedPlayerBoxScore(AdvancedBoxScore):
def __init__(self, player, seconds_played, offensive_rating, defensive_rating,
teammate_assist_percentage, assist_to_turnover_ratio, assists_per_100_possessions,
offensive_rebound_percentage, defensive_rebound_percentage, turnovers_per_100_possessions,
effective_field_goal_percentage, true_shooting_percentage, usage_percentage):
self.player = player
self.usage_percentage = usage_percentage
AdvancedBoxScore.__init__(self, seconds_played=seconds_played,
offensive_rating=offensive_rating, defensive_rating=defensive_rating,
teammate_assist_percentage=teammate_assist_percentage,
assist_to_turnover_ratio=assist_to_turnover_ratio,
assists_per_100_possessions=assists_per_100_possessions,
offensive_rebound_percentage=offensive_rebound_percentage,
defensive_rebound_percentage=defensive_rebound_percentage,
turnovers_per_100_possessions=turnovers_per_100_possessions,
effective_field_goal_percentage=effective_field_goal_percentage,
true_shooting_percentage=true_shooting_percentage)
def get_additional_unicode(self):
return 'player: {player} | usage percentage: {usage_percentage}'.format(player=self.player,
usage_percentage=self.usage_percentage)
class AdvancedTeamBoxScore(AdvancedBoxScore):
def __init__(self, team, seconds_played, offensive_rating, defensive_rating,
teammate_assist_percentage, assist_to_turnover_ratio, assists_per_100_possessions,
offensive_rebound_percentage, defensive_rebound_percentage, turnovers_per_100_possessions,
effective_field_goal_percentage, true_shooting_percentage):
self.team = team
AdvancedBoxScore.__init__(self, seconds_played=seconds_played,
offensive_rating=offensive_rating, defensive_rating=defensive_rating,
teammate_assist_percentage=teammate_assist_percentage,
assist_to_turnover_ratio=assist_to_turnover_ratio,
assists_per_100_possessions=assists_per_100_possessions,
offensive_rebound_percentage=offensive_rebound_percentage,
defensive_rebound_percentage=defensive_rebound_percentage,
turnovers_per_100_possessions=turnovers_per_100_possessions,
effective_field_goal_percentage=effective_field_goal_percentage,
true_shooting_percentage=true_shooting_percentage)
def get_additional_unicode(self):
return 'team: {team}'.format(team=self.team)
class TraditionalBoxScore:
def __init__(self, seconds_played, field_goals_made, field_goals_attempted,
three_point_field_goals_made, three_point_field_goals_attempted,
free_throws_made, free_throws_attempted, offensive_rebounds, defensive_rebounds, assists,
steals, blocks, turnovers, personal_fouls):
self.seconds_played = seconds_played
self.field_goals_made = field_goals_made
self.field_goals_attempted = field_goals_attempted
self.three_point_field_goals_made = three_point_field_goals_made
self.three_point_field_goals_attempted = three_point_field_goals_attempted
self.free_throws_made = free_throws_made
self.free_throws_attempted = free_throws_attempted
self.offensive_rebounds = offensive_rebounds
self.defensive_rebounds = defensive_rebounds
self.assists = assists
self.steals = steals
self.blocks = blocks
self.turnovers = turnovers
self.personal_fouls = personal_fouls
def __unicode__(self):
return '{0} | {1}'.format(self.get_additional_unicode(), self.get_base_unicode())
def get_base_unicode(self):
return 'seconds played: {seconds_played} | field goals made: {field_goals_made} |' \
'field goals attempted: {field_goals_attempted} | ' \
'three point field goals made: {three_point_field_goals_made} | ' \
'three point field goals attempted: {three_point_field_goals_attempted} | ' \
'free throws made: {free_throws_made} |' 'free throws attempted: {free_throws_attempted} | ' \
'offensive rebounds: {offensive rebounds} |' 'defensive rebounds: {defensive rebounds} | ' \
'assists: {assists} | steals: {steals} | blocks: {blocks} | turnovers: {turnovers} | ' \
'personal fouls: {personal_fouls}'.format(seconds_played=self.seconds_played,
field_goals_made=self.field_goals_made,
field_goals_attempted=self.field_goals_attempted,
three_point_field_goals_made=self.three_point_field_goals_made,
three_point_field_goals_attempted=self.three_point_field_goals_attempted,
free_throws_made=self.free_throws_made,
free_throws_attempted=self.free_throws_attempted,
offensive_rebounds=self.offensive_rebounds,
defensive_rebounds=self.defensive_rebounds,
assists=self.assists, steals=self.steals, blocks=self.blocks,
turnovers=self.turnovers, personal_fouls=self.personal_fouls)
def get_additional_unicode(self):
raise NotImplementedError('Implement in concrete classes')
class TraditionalPlayerBoxScore(TraditionalBoxScore):
def __init__(self, player, seconds_played, field_goals_made, field_goals_attempted,
three_point_field_goals_made, three_point_field_goals_attempted,
free_throws_made, free_throws_attempted, offensive_rebounds, defensive_rebounds, assists,
steals, blocks, turnovers, personal_fouls, plus_minus):
self.player = player
self.plus_minus = plus_minus
TraditionalBoxScore.__init__(self, seconds_played=seconds_played, field_goals_made=field_goals_made,
field_goals_attempted=field_goals_attempted,
three_point_field_goals_made=three_point_field_goals_made,
three_point_field_goals_attempted=three_point_field_goals_attempted,
free_throws_made=free_throws_made, free_throws_attempted=free_throws_attempted,
offensive_rebounds=offensive_rebounds, defensive_rebounds=defensive_rebounds,
assists=assists, steals=steals, blocks=blocks, turnovers=turnovers,
personal_fouls=personal_fouls)
def get_additional_unicode(self):
return 'player: {player} | plus minus: {plus_minus}'.format(player=self.player, plus_minus=self.plus_minus)
class TraditionalTeamBoxScore(TraditionalBoxScore):
def __init__(self, team, seconds_played, field_goals_made, field_goals_attempted, free_throws_attempted,
three_point_field_goals_made, three_point_field_goals_attempted,
free_throws_made, offensive_rebounds, defensive_rebounds, assists,
steals, blocks, turnovers, personal_fouls):
self.team = team
TraditionalBoxScore.__init__(self, seconds_played=seconds_played, field_goals_made=field_goals_made,
field_goals_attempted=field_goals_attempted,
three_point_field_goals_made=three_point_field_goals_made,
three_point_field_goals_attempted=three_point_field_goals_attempted,
free_throws_made=free_throws_made, free_throws_attempted=free_throws_attempted,
offensive_rebounds=offensive_rebounds, defensive_rebounds=defensive_rebounds,
assists=assists, steals=steals, blocks=blocks, turnovers=turnovers,
personal_fouls=personal_fouls)
def get_additional_unicode(self):
return 'team: {team}'.format(self.team)
class GameBoxScore:
def __init__(self, game_id, player_box_scores, team_box_scores):
self.game_id = game_id
self.player_box_scores = player_box_scores
self.team_box_scores = team_box_scores
|
class Advancedboxscore:
def __init__(self, seconds_played, offensive_rating, defensive_rating, teammate_assist_percentage, assist_to_turnover_ratio, assists_per_100_possessions, offensive_rebound_percentage, defensive_rebound_percentage, turnovers_per_100_possessions, effective_field_goal_percentage, true_shooting_percentage):
self.seconds_played = seconds_played
self.offensive_rating = offensive_rating
self.defensive_rating = defensive_rating
self.teammate_assist_percentage = teammate_assist_percentage
self.assist_to_turnover_ratio = assist_to_turnover_ratio
self.assists_per_100_possessions = assists_per_100_possessions
self.offensive_rebound_percentage = offensive_rebound_percentage
self.defensive_rebound_percentage = defensive_rebound_percentage
self.turnovers_per_100_possessions = turnovers_per_100_possessions
self.effective_field_goal_percentage = effective_field_goal_percentage
self.true_shooting_percentage = true_shooting_percentage
def __unicode__(self):
return '{0} | {1}'.format(self.get_additional_unicode(), self.get_base_unicode)
def get_base_unicode(self):
return 'seconds played: {seconds_played} | offensive rating: {offensive_rating} | defensive rating: {defensive_rating} | teammate assist percentage: {teammate_assist_percentage} |assist to turnover ratio: {assist_to_turnover_ratio} | assists per 100 possessions: {assists_per_100_possessions} | offensive rebound percentage: {offensive_rebound_percentage} |defensive rebound percentage: {defensive_rebound_percentage} |turnovers per 100 possessions: {turnovers_per_100_possessions} |effective field goal percentage: {effective_field_goal_percentage} |true shooting percentage: {true_shooting_percentage}'.format(seconds_played=self.seconds_played, offensive_rating=self.offensive_rating, defensive_rating=self.defensive_rating, teammate_assist_percentage=self.teammate_assist_percentage, assist_to_turnover_ratio=self.assist_to_turnover_ratio, assists_per_100_possessions=self.assists_per_100_possessions, offensive_rebound_percentage=self.offensive_rebound_percentage, defensive_rebound_percentage=self.defensive_rebound_percentage, turnovers_per_100_possessions=self.turnovers_per_100_possessions, effective_field_goal_percentage=self.effective_field_goal_percentage, true_shooting_percentage=self.true_shooting_percentage)
def get_additional_unicode(self):
return not_implemented_error('Should be implemented in concrete class')
class Advancedplayerboxscore(AdvancedBoxScore):
def __init__(self, player, seconds_played, offensive_rating, defensive_rating, teammate_assist_percentage, assist_to_turnover_ratio, assists_per_100_possessions, offensive_rebound_percentage, defensive_rebound_percentage, turnovers_per_100_possessions, effective_field_goal_percentage, true_shooting_percentage, usage_percentage):
self.player = player
self.usage_percentage = usage_percentage
AdvancedBoxScore.__init__(self, seconds_played=seconds_played, offensive_rating=offensive_rating, defensive_rating=defensive_rating, teammate_assist_percentage=teammate_assist_percentage, assist_to_turnover_ratio=assist_to_turnover_ratio, assists_per_100_possessions=assists_per_100_possessions, offensive_rebound_percentage=offensive_rebound_percentage, defensive_rebound_percentage=defensive_rebound_percentage, turnovers_per_100_possessions=turnovers_per_100_possessions, effective_field_goal_percentage=effective_field_goal_percentage, true_shooting_percentage=true_shooting_percentage)
def get_additional_unicode(self):
return 'player: {player} | usage percentage: {usage_percentage}'.format(player=self.player, usage_percentage=self.usage_percentage)
class Advancedteamboxscore(AdvancedBoxScore):
def __init__(self, team, seconds_played, offensive_rating, defensive_rating, teammate_assist_percentage, assist_to_turnover_ratio, assists_per_100_possessions, offensive_rebound_percentage, defensive_rebound_percentage, turnovers_per_100_possessions, effective_field_goal_percentage, true_shooting_percentage):
self.team = team
AdvancedBoxScore.__init__(self, seconds_played=seconds_played, offensive_rating=offensive_rating, defensive_rating=defensive_rating, teammate_assist_percentage=teammate_assist_percentage, assist_to_turnover_ratio=assist_to_turnover_ratio, assists_per_100_possessions=assists_per_100_possessions, offensive_rebound_percentage=offensive_rebound_percentage, defensive_rebound_percentage=defensive_rebound_percentage, turnovers_per_100_possessions=turnovers_per_100_possessions, effective_field_goal_percentage=effective_field_goal_percentage, true_shooting_percentage=true_shooting_percentage)
def get_additional_unicode(self):
return 'team: {team}'.format(team=self.team)
class Traditionalboxscore:
def __init__(self, seconds_played, field_goals_made, field_goals_attempted, three_point_field_goals_made, three_point_field_goals_attempted, free_throws_made, free_throws_attempted, offensive_rebounds, defensive_rebounds, assists, steals, blocks, turnovers, personal_fouls):
self.seconds_played = seconds_played
self.field_goals_made = field_goals_made
self.field_goals_attempted = field_goals_attempted
self.three_point_field_goals_made = three_point_field_goals_made
self.three_point_field_goals_attempted = three_point_field_goals_attempted
self.free_throws_made = free_throws_made
self.free_throws_attempted = free_throws_attempted
self.offensive_rebounds = offensive_rebounds
self.defensive_rebounds = defensive_rebounds
self.assists = assists
self.steals = steals
self.blocks = blocks
self.turnovers = turnovers
self.personal_fouls = personal_fouls
def __unicode__(self):
return '{0} | {1}'.format(self.get_additional_unicode(), self.get_base_unicode())
def get_base_unicode(self):
return 'seconds played: {seconds_played} | field goals made: {field_goals_made} |field goals attempted: {field_goals_attempted} | three point field goals made: {three_point_field_goals_made} | three point field goals attempted: {three_point_field_goals_attempted} | free throws made: {free_throws_made} |free throws attempted: {free_throws_attempted} | offensive rebounds: {offensive rebounds} |defensive rebounds: {defensive rebounds} | assists: {assists} | steals: {steals} | blocks: {blocks} | turnovers: {turnovers} | personal fouls: {personal_fouls}'.format(seconds_played=self.seconds_played, field_goals_made=self.field_goals_made, field_goals_attempted=self.field_goals_attempted, three_point_field_goals_made=self.three_point_field_goals_made, three_point_field_goals_attempted=self.three_point_field_goals_attempted, free_throws_made=self.free_throws_made, free_throws_attempted=self.free_throws_attempted, offensive_rebounds=self.offensive_rebounds, defensive_rebounds=self.defensive_rebounds, assists=self.assists, steals=self.steals, blocks=self.blocks, turnovers=self.turnovers, personal_fouls=self.personal_fouls)
def get_additional_unicode(self):
raise not_implemented_error('Implement in concrete classes')
class Traditionalplayerboxscore(TraditionalBoxScore):
def __init__(self, player, seconds_played, field_goals_made, field_goals_attempted, three_point_field_goals_made, three_point_field_goals_attempted, free_throws_made, free_throws_attempted, offensive_rebounds, defensive_rebounds, assists, steals, blocks, turnovers, personal_fouls, plus_minus):
self.player = player
self.plus_minus = plus_minus
TraditionalBoxScore.__init__(self, seconds_played=seconds_played, field_goals_made=field_goals_made, field_goals_attempted=field_goals_attempted, three_point_field_goals_made=three_point_field_goals_made, three_point_field_goals_attempted=three_point_field_goals_attempted, free_throws_made=free_throws_made, free_throws_attempted=free_throws_attempted, offensive_rebounds=offensive_rebounds, defensive_rebounds=defensive_rebounds, assists=assists, steals=steals, blocks=blocks, turnovers=turnovers, personal_fouls=personal_fouls)
def get_additional_unicode(self):
return 'player: {player} | plus minus: {plus_minus}'.format(player=self.player, plus_minus=self.plus_minus)
class Traditionalteamboxscore(TraditionalBoxScore):
def __init__(self, team, seconds_played, field_goals_made, field_goals_attempted, free_throws_attempted, three_point_field_goals_made, three_point_field_goals_attempted, free_throws_made, offensive_rebounds, defensive_rebounds, assists, steals, blocks, turnovers, personal_fouls):
self.team = team
TraditionalBoxScore.__init__(self, seconds_played=seconds_played, field_goals_made=field_goals_made, field_goals_attempted=field_goals_attempted, three_point_field_goals_made=three_point_field_goals_made, three_point_field_goals_attempted=three_point_field_goals_attempted, free_throws_made=free_throws_made, free_throws_attempted=free_throws_attempted, offensive_rebounds=offensive_rebounds, defensive_rebounds=defensive_rebounds, assists=assists, steals=steals, blocks=blocks, turnovers=turnovers, personal_fouls=personal_fouls)
def get_additional_unicode(self):
return 'team: {team}'.format(self.team)
class Gameboxscore:
def __init__(self, game_id, player_box_scores, team_box_scores):
self.game_id = game_id
self.player_box_scores = player_box_scores
self.team_box_scores = team_box_scores
|
def solution(A):
# write your code in Python 3.6
disks = []
for i,v in enumerate(A):
disks.append((i-v,1))
disks.append((i+v,0))
disks.sort(key=lambda x: (x[0], not x[1]))
active = 0
intersections = 0
for i,isBegin in disks:
if isBegin:
intersections += active
active += 1
else:
active -= 1
if intersections > 10**7:
return -1
return intersections
|
def solution(A):
disks = []
for (i, v) in enumerate(A):
disks.append((i - v, 1))
disks.append((i + v, 0))
disks.sort(key=lambda x: (x[0], not x[1]))
active = 0
intersections = 0
for (i, is_begin) in disks:
if isBegin:
intersections += active
active += 1
else:
active -= 1
if intersections > 10 ** 7:
return -1
return intersections
|
"""
Given an integer array, adjust each integers so that the difference of every adjcent integers are not greater than a
given number target.
If the array before adjustment is A, the array after adjustment is B, you should minimize the sum of |A[i]-B[i]|
Note
You can assume each number in the array is a positive integer and not greater than 100
Example
Given [1,4,2,3] and target=1, one of the solutions is [2,3,2,3], the adjustment cost is 2 and it's minimal. Return 2.
"""
__author__ = 'Danyang'
class Solution:
def MinAdjustmentCost(self, A, target):
"""
state dp
f[i][j] = min(f[i-1][k] + |a[i]-j|, for k j-l to j+l)
comments: similar to Vertibi algorithm (Hidden Markov Model)
:param A: An integer array.
:param target: An integer.
"""
S = 100
n = len(A)
f = [[1<<31 for _ in xrange(S+1)] for _ in xrange(n+1)]
for j in xrange(S+1):
f[0][j] = 0
for i in xrange(1, n+1):
for j in xrange(1, S+1):
for k in xrange(max(1, j-target), min(S, j+target)+1):
f[i][j] = min(f[i][j], f[i-1][k]+abs(A[i-1]-j))
mini = 1<<31
for j in xrange(1, S+1):
mini = min(mini, f[n][j])
return mini
if __name__ == "__main__":
assert Solution().MinAdjustmentCost([12, 3, 7, 4, 5, 13, 2, 8, 4, 7, 6, 5, 7], 2) == 19
|
"""
Given an integer array, adjust each integers so that the difference of every adjcent integers are not greater than a
given number target.
If the array before adjustment is A, the array after adjustment is B, you should minimize the sum of |A[i]-B[i]|
Note
You can assume each number in the array is a positive integer and not greater than 100
Example
Given [1,4,2,3] and target=1, one of the solutions is [2,3,2,3], the adjustment cost is 2 and it's minimal. Return 2.
"""
__author__ = 'Danyang'
class Solution:
def min_adjustment_cost(self, A, target):
"""
state dp
f[i][j] = min(f[i-1][k] + |a[i]-j|, for k j-l to j+l)
comments: similar to Vertibi algorithm (Hidden Markov Model)
:param A: An integer array.
:param target: An integer.
"""
s = 100
n = len(A)
f = [[1 << 31 for _ in xrange(S + 1)] for _ in xrange(n + 1)]
for j in xrange(S + 1):
f[0][j] = 0
for i in xrange(1, n + 1):
for j in xrange(1, S + 1):
for k in xrange(max(1, j - target), min(S, j + target) + 1):
f[i][j] = min(f[i][j], f[i - 1][k] + abs(A[i - 1] - j))
mini = 1 << 31
for j in xrange(1, S + 1):
mini = min(mini, f[n][j])
return mini
if __name__ == '__main__':
assert solution().MinAdjustmentCost([12, 3, 7, 4, 5, 13, 2, 8, 4, 7, 6, 5, 7], 2) == 19
|
def repeatedString(s, n):
total = s.count("a") * int(n/len(s))
total += s[:n % len(s)].count("a")
return total
s = "aba"
n = 10
n = int(n)
repeatedString(s, n)
|
def repeated_string(s, n):
total = s.count('a') * int(n / len(s))
total += s[:n % len(s)].count('a')
return total
s = 'aba'
n = 10
n = int(n)
repeated_string(s, n)
|
# ======================================================================
# Beverage Bandits
# Advent of Code 2018 Day 15 -- Eric Wastl -- https://adventofcode.com
#
# Python implementation by Dr. Dean Earl Wright III
# ======================================================================
# ======================================================================
# p e r s o n . p y
# ======================================================================
"People and persons for the Advent of Code 2018 Day 15 puzzle"
# ----------------------------------------------------------------------
# import
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
# constants
# ----------------------------------------------------------------------
ROW_MULT = 100
ADJACENT = [-100, -1, 1, 100]
# ----------------------------------------------------------------------
# location
# ----------------------------------------------------------------------
def row_col_to_loc(row, col):
return row * ROW_MULT + col
def loc_to_row_col(loc):
return divmod(loc, ROW_MULT)
def distance(loc1, loc2):
loc1row, loc1col = loc_to_row_col(loc1)
loc2row, loc2col = loc_to_row_col(loc2)
return abs(loc1row - loc2row) + abs(loc1col - loc2col)
def adjacent(loc1, loc2):
return distance(loc1, loc2) == 1
# ======================================================================
# Person
# ======================================================================
class Person(object): # pylint: disable=R0902, R0205
"Elf/Goblin for Beverage Bandits"
def __init__(self, letter='#', location=0, attack=3):
# 1. Set the initial values
self.letter = letter
self.location = location
self.hitpoints = 200
self.attack = attack
def distance(self, location):
return distance(self.location, location)
def attacks(self, other):
other.hitpoints = max(0, other.hitpoints - self.attack)
def adjacent(self):
return [self.location + a for a in ADJACENT]
# ======================================================================
# People
# ======================================================================
class People(object): # pylint: disable=R0902, R0205
"Multiple Elf/Goblin for Beverage Bandits"
def __init__(self, letter='#'):
# 1. Set the initial values
self.letter = letter
self.persons = {}
def __len__(self):
return len(self.persons)
def __getitem__(self, loc):
if loc in self.persons:
return self.persons[loc]
else:
raise AttributeError("No such location: %s" % loc)
def __setitem__(self, loc, person):
if self.letter != person.letter:
raise ValueError("Incompatable letters: %s != %s" % (self.letter, person.letter))
if loc != person.location:
raise ValueError("Incompatable locations: %s != %s" % (loc, person.location))
self.persons[loc] = person
def __delitem__(self, loc):
if loc in self.persons:
del self.persons[loc]
else:
raise AttributeError("No such location: %s" % loc)
def __iter__(self):
return iter(self.persons)
def __contains__(self, loc):
return loc in self.persons
def add(self, person):
if self.letter != person.letter:
raise ValueError("Incompatable letters: %s != %s" % (self.letter, person.letter))
if person.location in self.persons:
raise ValueError("Location %s already occuried" % (person.location))
self.persons[person.location] = person
def locations(self):
keys = list(self.persons.keys())
keys.sort()
return keys
def hitpoints(self):
return sum([x.hitpoints for x in self.persons.values()])
# ----------------------------------------------------------------------
# module initialization
# ----------------------------------------------------------------------
if __name__ == '__main__':
pass
# ======================================================================
# end p e r s o n . p y end
# ======================================================================
|
"""People and persons for the Advent of Code 2018 Day 15 puzzle"""
row_mult = 100
adjacent = [-100, -1, 1, 100]
def row_col_to_loc(row, col):
return row * ROW_MULT + col
def loc_to_row_col(loc):
return divmod(loc, ROW_MULT)
def distance(loc1, loc2):
(loc1row, loc1col) = loc_to_row_col(loc1)
(loc2row, loc2col) = loc_to_row_col(loc2)
return abs(loc1row - loc2row) + abs(loc1col - loc2col)
def adjacent(loc1, loc2):
return distance(loc1, loc2) == 1
class Person(object):
"""Elf/Goblin for Beverage Bandits"""
def __init__(self, letter='#', location=0, attack=3):
self.letter = letter
self.location = location
self.hitpoints = 200
self.attack = attack
def distance(self, location):
return distance(self.location, location)
def attacks(self, other):
other.hitpoints = max(0, other.hitpoints - self.attack)
def adjacent(self):
return [self.location + a for a in ADJACENT]
class People(object):
"""Multiple Elf/Goblin for Beverage Bandits"""
def __init__(self, letter='#'):
self.letter = letter
self.persons = {}
def __len__(self):
return len(self.persons)
def __getitem__(self, loc):
if loc in self.persons:
return self.persons[loc]
else:
raise attribute_error('No such location: %s' % loc)
def __setitem__(self, loc, person):
if self.letter != person.letter:
raise value_error('Incompatable letters: %s != %s' % (self.letter, person.letter))
if loc != person.location:
raise value_error('Incompatable locations: %s != %s' % (loc, person.location))
self.persons[loc] = person
def __delitem__(self, loc):
if loc in self.persons:
del self.persons[loc]
else:
raise attribute_error('No such location: %s' % loc)
def __iter__(self):
return iter(self.persons)
def __contains__(self, loc):
return loc in self.persons
def add(self, person):
if self.letter != person.letter:
raise value_error('Incompatable letters: %s != %s' % (self.letter, person.letter))
if person.location in self.persons:
raise value_error('Location %s already occuried' % person.location)
self.persons[person.location] = person
def locations(self):
keys = list(self.persons.keys())
keys.sort()
return keys
def hitpoints(self):
return sum([x.hitpoints for x in self.persons.values()])
if __name__ == '__main__':
pass
|
"""
here we produce visualization with excel
# one-time excel preparation
in cmder
xlwings addin install
open excel
enable Trust access to VBA
File > Options > Trust Center > Trust Center Settings > Macro Settings
# making the visualization workbook
in cmder
chdir this_directory
xlwings quickstart book_report
the result of this is in
sol_book_report\*
# studying the visualization
in cmder type excel
open with excel sol_book_report\book_report.xlsm
open with sublime book_report.py
"""
|
"""
here we produce visualization with excel
# one-time excel preparation
in cmder
xlwings addin install
open excel
enable Trust access to VBA
File > Options > Trust Center > Trust Center Settings > Macro Settings
# making the visualization workbook
in cmder
chdir this_directory
xlwings quickstart book_report
the result of this is in
sol_book_report\\*
# studying the visualization
in cmder type excel
open with excel sol_book_report\x08ook_report.xlsm
open with sublime book_report.py
"""
|
def Singleton(cls):
_instance = {}
def _singleton(*args, **kwargs):
if cls not in _instance:
_instance[cls] = cls(*args, *kwargs)
return _instance[cls]
return _singleton
@Singleton
class A(object):
def __init__(self, x):
self.x = x
if __name__ == '__main__':
a = A(12)
print(a.x)
|
def singleton(cls):
_instance = {}
def _singleton(*args, **kwargs):
if cls not in _instance:
_instance[cls] = cls(*args, *kwargs)
return _instance[cls]
return _singleton
@Singleton
class A(object):
def __init__(self, x):
self.x = x
if __name__ == '__main__':
a = a(12)
print(a.x)
|
"""501. Find Mode in Binary Search Tree"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def findMode(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
nums = []
if not root:
return None
self.dfs(root, nums)
d = {}
for num in nums:
if num not in d:
d[num] = 1
else:
d[num] += 1
res = []
mode = max(d.values())
for key in d:
if d[key] == mode:
res.append(key)
return res
def dfs(self, node, nums):
if not node:
return
self.dfs(node.left, nums)
nums.append(node.val)
self.dfs(node.right, nums)
|
"""501. Find Mode in Binary Search Tree"""
class Solution(object):
def find_mode(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
nums = []
if not root:
return None
self.dfs(root, nums)
d = {}
for num in nums:
if num not in d:
d[num] = 1
else:
d[num] += 1
res = []
mode = max(d.values())
for key in d:
if d[key] == mode:
res.append(key)
return res
def dfs(self, node, nums):
if not node:
return
self.dfs(node.left, nums)
nums.append(node.val)
self.dfs(node.right, nums)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.