content
stringlengths 7
1.05M
|
|---|
#https://leetcode.com/explore/interview/card/top-interview-questions-easy/127/strings/880/
#%%
input=-123
output=321
class Solution:
def reverse(self, x: int) -> int:
string=list(str(abs(x)))
string.reverse()
if x>=0:
temp=int(''.join(string))
if temp>2**31-1:
return 0
else:
return temp
if x<0:
temp=-int(''.join(string))
if temp<-2**31:
return 0
else:
return temp
Solution.reverse(123,input)
# %%
# ! good result 99%
|
#py_list_comp_1.py
print([str(x)+"!" for x in [y for y in range(10)]])
|
class Solution:
def dominantIndex(self, nums: List[int]) -> int:
max_index = 0
for index, num in enumerate(nums):
if num > nums[max_index]:
max_index = index
for index, num in enumerate(nums):
if index == max_index:
continue
if not nums[max_index] >= 2 * num:
return -1
return max_index
|
SCRIPT=r'''
import sys,time
fi=open(sys.argv[1])
time.sleep(8)
fo=open(sys.argv[2],'w')
fo.write(fi.read())
fi.close()
fo.close()
'''
|
# SPDX-FileCopyrightText: Copyright (c) 2021 Dan Halbert for Adafruit Industries LLC
# SPDX-FileCopyrightText: 2021 James Carr
#
# SPDX-License-Identifier: MIT
"""
`adafruit_simplemath`
================================================================================
Math utility functions
* Author(s): Dan Halbert, James Carr
Implementation Notes
--------------------
**Software and Dependencies:**
* Adafruit CircuitPython firmware for the supported boards:
https://github.com/adafruit/circuitpython/releases
"""
__version__ = "0.0.0-auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_SimpleMath.git"
def map_range(
x: float, in_min: float, in_max: float, out_min: float, out_max: float
) -> float:
"""
Maps a number from one range to another. Somewhat similar to the Arduino
:attr:`map()` function, but returns a floating point result, and
constrains the output value to be between :attr:`out_min` and
:attr:`out_max`. If :attr:`in_min` is greater than :attr:`in_max` or
:attr:`out_min` is greater than :attr:`out_max`, the corresponding range
is reversed, allowing, for example, mapping a range of 0-10 to 50-0.
See also :py:func:`map_unconstrained_range`
.. code-block::
from adafruit_simplemath import map_range
percent = 23
screen_width = 320 # or board.DISPLAY.width
x = map_range(percent, 0, 100, 0, screen_width - 1)
print("X position", percent, "% from the left of screen is", x)
:param float x: Value to convert
:param float in_min: Start value of input range.
:param float in_max: End value of input range.
:param float out_min: Start value of output range.
:param float out_max: End value of output range.
:return: Returns value mapped to new range.
:rtype: float
"""
mapped = map_unconstrained_range(x, in_min, in_max, out_min, out_max)
return constrain(mapped, out_min, out_max)
def map_unconstrained_range(
x: float, in_min: float, in_max: float, out_min: float, out_max: float
) -> float:
"""
Maps a number from one range to another. Somewhat similar to the Arduino
:attr:`map()` function, but returns a floating point result, and
does not constrain the output value to be between :attr:`out_min` and
:attr:`out_max`. If :attr:`in_min` is greater than :attr:`in_max` or
:attr:`out_min` is greater than :attr:`out_max`, the corresponding range
is reversed, allowing, for example, mapping a range of 0-10 to 50-0.
See also :py:func:`map_range`
.. code-block::
from adafruit_simplemath import map_unconstrained_range
celsius = -20
fahrenheit = map_unconstrained_range(celsius, 0, 100, 32, 212)
print(celsius, "degress Celsius =", fahrenheit, "degrees Fahrenheit")
:param float x: Value to convert
:param float in_min: Start value of input range.
:param float in_max: End value of input range.
:param float out_min: Start value of output range.
:param float out_max: End value of output range.
:return: Returns value mapped to new range.
:rtype: float
"""
in_range = in_max - in_min
in_delta = x - in_min
if in_range != 0:
mapped = in_delta / in_range
elif in_delta != 0:
mapped = in_delta
else:
mapped = 0.5
mapped *= out_max - out_min
mapped += out_min
return mapped
def constrain(x: float, out_min: float, out_max: float) -> float:
"""Constrains :attr:`x` to be within the inclusive range
[:attr:`out_min`, :attr:`out_max`]. Sometimes called :attr:`clip` or
:attr:`clamp` in other libraries. :attr:`out_min` should be less than or
equal to :attr:`out_max`.
If :attr:`x` is less than :attr:`out_min`, return :attr:`out_min`.
If :attr:`x` is greater than :attr:`out_max`, return :attr:`out_max`.
Otherwise just return :attr:`x`.
If :attr:`max_value` is less than :attr:`min_value`, they will be swapped.
:param float x: Value to constrain
:param float out_min: Lower bound of output range.
:param float out_max: Upper bound of output range.
:return: Returns value constrained to given range.
:rtype: float
"""
if out_min <= out_max:
return max(min(x, out_max), out_min)
return min(max(x, out_max), out_min)
|
def dot(n,m):
r=['+'+'---+'*n]
for _ in range(m):
r.append('|'+' o |'*n)
r.append('+'+'---+'*n)
return '\n'.join(r)
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def recoverTree(self, root: TreeNode) -> None:
# there are two nodes to find
self.nodes = []
self.inorder(root)
t1, t2 = None, None
for i in range(len(self.nodes) - 1):
if self.nodes[i + 1] < self.nodes[i]:
t1 = self.nodes[i + 1]
if t2 == None:
t2 = self.nodes[i]
else:
break
self.search(t1, t2, root, 2)
return root
def search(self, t1, t2, root, count):
if not root:
return
if root.val == t1 and count > 0:
root.val = t2
count -= 1
elif root.val == t2 and count > 0:
root.val = t1
count -= 1
if count == 0:
return
self.search(t1, t2, root.left, count)
self.search(t1, t2, root.right, count)
def inorder(self, root):
if not root:
return
self.inorder(root.left)
self.nodes.append(root.val)
self.inorder(root.right)
|
def biggest_cycle_before(limit):
num = longest = 1
for n in range(3, limit, 2):
if n % 5 == 0:
continue
p = 1
while (10 ** p) % n != 1:
p += 1
if p > longest:
num, longest = n, p
print(num)
if __name__ == "__main__":
biggest_cycle_before(10)
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
__version__ = "2.0.3"
__author__ = "Amir Zeldes"
__copyright__ = "Copyright 2015-2018, Amir Zeldes"
__license__ = "MIT License"
|
t = int(input())
answer = []
for a in range(t):
n = int(input())
count = [0 for i in range(26)]
for j in range(n):
line = list(input())
for k in line:
count[ord(k)-97] += 1
ans = True
for k in count:
if(k%n != 0):
ans = False
break
if(ans):
answer.append("YES")
else:
answer.append("NO")
for b in answer:
print(b)
|
class LogSystem:
def __init__(self):
self.time_position_dict = {"Year": 0, "Month": 1,
"Day": 2, "Hour": 3,
"Minute": 4, "Second": 5}
self.logs = {}
def put(self, id, timestamp):
self.logs[timestamp] = id
def retrieve(self, s, e, gra):
retrieve_logs = []
need_length = self.time_position_dict[gra] + 1
actual_s = self.decode_timestamp(s, need_length)
actual_e = self.decode_timestamp(e, need_length)
for timestamp in self.logs.keys():
log_time = self.decode_timestamp(timestamp, need_length)
if actual_s <= log_time and log_time <= actual_e:
retrieve_logs.append(self.logs[timestamp])
return retrieve_logs
def decode_timestamp(self, timestamp, length):
decoded_time = int("".join(timestamp.split(":")[0:length]))
return decoded_time
if __name__ == "__main__":
log_system = LogSystem()
log_system.put(1, "2017:01:01:23:59:59")
log_system.put(2, "2017:01:01:22:59:59")
log_system.put(3, "2016:01:01:00:00:00")
res = log_system.retrieve("2016:01:01:01:01:01","2017:01:01:23:00:00",
"Hour")
print(res)
|
n1 = int(input('Digite um número: '))
dob = n1*2
trip = n1*3
raiz = n1**(0.5)
print('O número digitado foi: {} \nO dobro é {} \nO triplo é {} \nSua raiz quadrade é {:.2f}'.format(n1, dob, trip, raiz))
|
a = 'AJisa'
a = a.upper()
print(a)
a = a.lower()
print(a)
n = "89*"
print(n.isnumeric())
print(n.isalpha())
|
# pylint: skip-file
class GitRebase(GitCLI):
''' Class to wrap the git merge line tools
'''
# pylint: disable=too-many-arguments
def __init__(self,
path,
branch,
rebase_branch,
ssh_key=None):
''' Constructor for GitPush '''
super(GitRebase, self).__init__(path, ssh_key=ssh_key)
self.path = path
self.branch = branch
self.rebase_branch = rebase_branch
self.debug = []
os.chdir(path)
def checkout_branch(self):
''' check out the desired branch '''
current_branch_results = self._get_current_branch()
if current_branch_results['results'] == self.branch:
return True
current_branch_results = self._checkout(self.branch)
self.debug.append(current_branch_results)
if current_branch_results['returncode'] == 0:
return True
return False
def remote_update(self):
''' update the git remotes '''
remote_update_results = self._remote_update()
self.debug.append(remote_update_results)
if remote_update_results['returncode'] == 0:
return True
return False
def need_rebase(self):
''' checks to see if rebase is needed '''
git_diff_results = self._diff(self.rebase_branch)
self.debug.append(git_diff_results)
if git_diff_results['results']:
return True
return False
def rebase(self):
'''perform a git push '''
if self.checkout_branch():
if self.remote_update():
if self.need_rebase():
rebase_results = self._rebase(self.rebase_branch)
rebase_results['debug'] = self.debug
return rebase_results
else:
return {'returncode': 0,
'results': {},
'no_rebase_needed': True
}
return {'returncode': 1,
'results': {},
'debug': self.debug
}
|
"""Common values used for testing.
"""
SYSTEM_RAM_GB_MAIN = 64
SYSTEM_RAM_GB_SMALL = 2
SYSTEM_RAM_GB_TOO_SMALL = 1
OSM_PBF_GB_US = 10.4
OSM_PBF_GB_CO = 0.2
# Scaled below the 2GB threshold...
OSM_PBF_GB_USWEST = 1.99
# Should always use flat file, even w/out SSD
OSM_PBF_GB_ALWAYS_FLAT_FILE = 30.1
|
#entrada
x, y = str(input()).split()
x = int(x)
y = int(y)
#saída
for i in range(1, y + 1):
if i % x == 0:
print(i)
else:
print(i, end=' ')
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2021, Cisco Systems
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r"""
---
module: tag
short_description: Manage Tag objects of Tag
description:
- Returns the Tags for given filter criteria.
- Creates Tag with specified Tag attributes.
- Updates a Tag specified by id.
- Deletes a Tag specified by id.
- Returns Tag specified by Id.
- Returns Tag count.
version_added: '1.0.0'
author: Rafael Campos (@racampos)
options:
additional_info_attributes:
description:
- AdditionalInfo.attributes query parameter.
type: str
additional_info_name_space:
description:
- AdditionalInfo.nameSpace query parameter.
type: str
field:
description:
- Available field names are 'name,id,parentId,type,additionalInfo.nameSpace,additionalInfo.attributes'.
type: str
level:
description:
- Level query parameter.
type: str
limit:
description:
- Limit query parameter.
type: str
name:
description:
- Tag name is mandatory when filter operation is used.
- TagDTO's name.
- Name query parameter.
type: str
offset:
description:
- Offset query parameter.
type: str
order:
description:
- Available values are asc and des.
type: str
size:
description:
- Size in kilobytes(KB).
type: str
sort_by:
description:
- Only supported attribute is name. SortyBy is mandatory when order is used.
type: str
system_tag:
description:
- SystemTag query parameter.
type: str
description:
description:
- TagDTO's description.
type: str
dynamicRules:
description:
- TagDTO's dynamicRules (list of objects).
type: list
elements: dict
suboptions:
memberType:
description:
- It is the Tag's memberType.
type: str
rules:
description:
- It is the Tag's rules.
type: dict
suboptions:
items:
description:
- It is the Tag's items.
type: list
name:
description:
- It is the Tag's name.
type: str
operation:
description:
- It is the Tag's operation.
type: str
value:
description:
- It is the Tag's value.
type: str
values:
description:
- It is the Tag's values.
type: list
id:
description:
- TagDTO's id.
- Tag ID.
- Required for states query and absent.
type: str
instanceTenantId:
description:
- TagDTO's instanceTenantId.
type: str
systemTag:
description:
- TagDTO's systemTag.
type: bool
attribute_name:
description:
- AttributeName query parameter.
type: str
name_space:
description:
- NameSpace query parameter.
type: str
count:
description:
- If true gets the number of objects.
- Required for state query.
type: bool
requirements:
- dnacentersdk
seealso:
# Reference by module name
- module: cisco.dnac.plugins.module_utils.definitions.tag
# Reference by Internet resource
- name: Tag reference
description: Complete reference of the Tag object model.
link: https://developer.cisco.com/docs/dna-center/api/1-3-3-x
# Reference by Internet resource
- name: Tag reference
description: SDK reference.
link: https://dnacentersdk.readthedocs.io/en/latest/api/api.html#v2-1-1-summary
"""
EXAMPLES = r"""
- name: get_tag
cisco.dnac.tag:
state: query # required
additional_info_attributes: SomeValue # string
additional_info_name_space: SomeValue # string
field: SomeValue # string
level: SomeValue # string
limit: SomeValue # string
name: SomeValue # string
offset: SomeValue # string
order: SomeValue # string
size: SomeValue # string
sort_by: SomeValue # string
system_tag: SomeValue # string
register: nm_get_tag
- name: create_tag
cisco.dnac.tag:
state: present # required
description: SomeValue # string
dynamicRules:
- memberType: SomeValue # string
rules:
values:
- SomeValue # string
items: None
operation: SomeValue # string
name: SomeValue # string
value: SomeValue # string
id: SomeValue # string
instanceTenantId: SomeValue # string
name: SomeValue # string
systemTag: True # boolean
- name: update_tag
cisco.dnac.tag:
state: present # required
description: SomeValue # string
dynamicRules:
- memberType: SomeValue # string
rules:
values:
- SomeValue # string
items: None
operation: SomeValue # string
name: SomeValue # string
value: SomeValue # string
id: SomeValue # string
instanceTenantId: SomeValue # string
name: SomeValue # string
systemTag: True # boolean
- name: delete_tag
cisco.dnac.tag:
state: absent # required
id: SomeValue # string, required
- name: get_tag_by_id
cisco.dnac.tag:
state: query # required
id: SomeValue # string, required
register: nm_get_tag_by_id
- name: get_tag_count
cisco.dnac.tag:
state: query # required
count: True # boolean, required
attribute_name: SomeValue # string
level: SomeValue # string
name: SomeValue # string
name_space: SomeValue # string
size: SomeValue # string
system_tag: SomeValue # string
register: nm_get_tag_count
"""
RETURN = r"""
dnac_response:
description: A dictionary with the response returned by the DNA Center Python SDK
returned: always
type: dict
sample: {"response": 29, "version": "1.0"}
sdk_function:
description: The DNA Center SDK function used to execute the task
returned: always
type: str
sample: tag.create_tag
missing_params:
description: Provided arguments do not comply with the schema of the DNA Center Python SDK function
returned: when the function request schema is not satisfied
type: list
sample:
"""
|
# Acorn 2.0: Cocoa Butter
# Booleans are treated as integers
# Allow hex
#Number meta class
class N():
def __init__(self,n):
try:
self.n = float(n)
if(self.n.is_integer()):
self.n = int(n)
except:
self.n = int(n,16)
def N(self):
return self.n
def __repr__(self):
return 'N(%s)' % self.n
#Boolean meta class
class B():
def __init__(self,b):
self.boolean = b
def B(self):
if(self.boolean == "true"):
return 1
elif(self.boolean == "false"):
return 0
elif(isinstance(self.boolean,B)):
return int((self.boolean).B())
elif(isinstance(self.boolean,N)):
return int(bool(self.boolean.N()))
elif(self.boolean == True):
return 1
else:
return 0
def __repr__(self):
return 'B(\'%s\')' % self.boolean
#String meta class
class S():
def __init__(self,s):
self.s = str(s)
def S(self):
return self.s
def __repr__(self):
return 'S(\'%s\')' % self.s
#Var meta class
class Var():
def __init__(self,x):
self.x = str(x)
def X(self):
return self.x
def __repr__(self):
return 'Var(\'%s\')' % self.x
#Null meta class
class Null():
def __init__(self):
self.n = "Null"
def null(self):
return self.n
def __repr__(self):
return 'Null()'
#Unary meta operations
class Unary():
def __init__(self,uop,e1):
self.op = str(uop)
self.e1 = e1
def expr1(self):
return self.e1
def uop(self):
return self.op
def __repr__(self):
return 'Unary(%s,%s)' % (self.op, self.e1)
#Binary meta operations
class Binary():
def __init__(self,bop,e1,e2):
self.op = str(bop)
self.e1 = e1
self.e2 = e2
def expr1(self):
return self.e1
def expr2(self):
return self.e2
def bop(self):
return self.op
def __repr__(self):
return 'Binary(%s,%s,%s)' % (self.op, self.e1, self.e2)
#Trinary meta operator
class If():
def __init__(self,e1,e2,e3):
self.e1 = e1
self.e2 = e2
self.e3 = e3
def expr1(self):
return self.e1
def expr2(self):
return self.e2
def expr3(self):
return self.e3
def __repr__(self):
return 'If(%s,%s,%s)' % (self.e1, self.e2, self.e3)
class Function():
def __init__(self,arguments,body):
self.e1 = arguments
self.e2 = body
def expr1(self):
return self.e1
def expr2(self):
return self.e2
def __repr__(self):
return 'Function(%s,%s)' % (self.e1, self.e2)
class Call():
def __init__(self,arguments,body):
self.e1 = arguments
self.e2 = body
def expr1(self):
return self.e1
def expr2(self):
return self.e2
def __repr__(self):
return 'Call(%s,%s)' % (self.e1, self.e2)
class Return():
def __init__(self,returns):
self.e1 = returns
def expr1(self):
return self.e1
def __repr__(self):
return 'Return(%s)' % (self.e1)
class Seq():
def __init__(self,e1,e2):
self.e1 = e1
self.e2 = e2
def expr1(self):
return self.e1
def expr2(self):
return self.e2
def __repr__(self):
return 'Seq(%s,%s)' % (self.e1, self.e2)
class Eq():
def __init__(self,e1,e2):
self.e1 = e1
self.e2 = e2
def expr1(self):
return self.e1
def expr2(self):
return self.e2
def __repr__(self):
return 'Eq(%s,%s)' % (self.e1, self.e2)
class Ne():
def __init__(self,e1,e2):
self.e1 = e1
self.e2 = e2
def expr1(self):
return self.e1
def expr2(self):
return self.e2
def __repr__(self):
return 'Ne(%s,%s)' % (self.e1, self.e2)
class Lt():
def __init__(self,e1,e2):
self.e1 = e1
self.e2 = e2
def expr1(self):
return self.e1
def expr2(self):
return self.e2
def __repr__(self):
return 'Lt(%s,%s)' % (self.e1, self.e2)
class Le():
def __init__(self,e1,e2):
self.e1 = e1
self.e2 = e2
def expr1(self):
return self.e1
def expr2(self):
return self.e2
def __repr__(self):
return 'Le(%s,%s)' % (self.e1, self.e2)
class Gt():
def __init__(self,e1,e2):
self.e1 = e1
self.e2 = e2
def expr1(self):
return self.e1
def expr2(self):
return self.e2
def __repr__(self):
return 'Gt(%s,%s)' % (self.e1, self.e2)
class Ge():
def __init__(self,e1,e2):
self.e1 = e1
self.e2 = e2
def expr1(self):
return self.e1
def expr2(self):
return self.e2
def __repr__(self):
return 'Ge(%s,%s)' % (self.e1, self.e2)
class And():
def __init__(self,e1,e2):
self.e1 = e1
self.e2 = e2
def expr1(self):
return self.e1
def expr2(self):
return self.e2
def __repr__(self):
return 'And(%s,%s)' % (self.e1, self.e2)
class Or():
def __init__(self,e1,e2):
self.e1 = e1
self.e2 = e2
def expr1(self):
return self.e1
def expr2(self):
return self.e2
def __repr__(self):
return 'Or(%s,%s)' % (self.e1, self.e2)
class BitwiseAnd():
def __init__(self,e1,e2):
self.e1 = e1
self.e2 = e2
def expr1(self):
return self.e1
def expr2(self):
return self.e2
def __repr__(self):
return 'Intersect(%s,%s)' % (self.e1, self.e2)
class BitwiseOr():
def __init__(self,e1,e2):
self.e1 = e1
self.e2 = e2
def expr1(self):
return self.e1
def expr2(self):
return self.e2
def __repr__(self):
return 'Union(%s,%s)' % (self.e1, self.e2)
class LeftShift():
def __init__(self,e1,e2):
self.e1 = e1
self.e2 = e2
def expr1(self):
return self.e1
def expr2(self):
return self.e2
def __repr__(self):
return 'LeftShift(%s,%s)' % (self.e1, self.e2)
class RightShift():
def __init__(self,e1,e2):
self.e1 = e1
self.e2 = e2
def expr1(self):
return self.e1
def expr2(self):
return self.e2
def __repr__(self):
return 'RightShift(%s,%s)' % (self.e1, self.e2)
class Malloc():
def __init__(self,m,x,v):
self.e1 = m
self.e2 = x
self.e3 = v
def expr1(self):
return self.e1
def expr2(self):
return self.e2
def expr3(self):
return self.e3
def __repr__(self):
return 'Malloc(%s,%s,%s)' % (self.e1, self.e2, self.e3)
class Array():
def __init__(self,e1):
self.e1 = e1
def expr1(self):
return self.e1
def __repr__(self):
return 'Array(%s)' % self.e1
class Index():
def __init__(self,array,index):
self.e1 = array
self.e2 = index
def expr1(self):
return self.e1
def expr2(self):
return self.e2
def __repr__(self):
return 'Index(%s,%s)' % (self.e1, self.e2)
class Assign():
def __init__(self,var,val):
self.e1 = var
self.e2 = val
def expr1(self):
return self.e1
def expr2(self):
return self.e2
def __repr__(self):
return 'Assign(%s,%s)' % (self.e1, self.e2)
class ForEach():
def __init__(self,i,start,end,scope,closure):
self.e1 = i
self.e2 = start
self.e3 = end
self.e4 = scope
self.e5 = closure
def expr1(self):
return self.e1
def expr2(self):
return self.e2
def expr3(self):
return self.e3
def expr4(self):
return self.e4
def expr5(self):
return self.e5
def __repr__(self):
return 'ForEach(%s,%s,%s,%s,%s)' % (self.e1, self.e2, self.e3, self.e4, self.e5)
class For():
def __init__(self,index,condition,count,scope):
self.e1 = index
self.e2 = condition
self.e3 = count
self.e4 = scope
def expr1(self):
return self.e1
def expr2(self):
return self.e2
def expr3(self):
return self.e3
def expr4(self):
return self.e4
def __repr__(self):
return 'For(%s,%s,%s,%s)' % (self.e1, self.e2, self.e3, self.e4)
class While():
def __init__(self,condition,scope):
self.e1 = condition
self.e2 = scope
def expr1(self):
return self.e1
def expr2(self):
return self.e2
def __repr__(self):
return 'While(%s,%s)' % (self.e1, self.e2)
#Side effects
class Print():
def __init__(self,expr):
self.expr1 = expr
def E(self):
return self.expr1
def __repr__(self):
return 'Print(%s)' % self.expr1
#Side effects
class Println():
def __init__(self,expr):
self.expr1 = expr
def E(self):
return self.expr1
class Input():
def __init__(self):
self.expr1 = None
def cast(self,n):
if(isfloat(n)):
return N(n)
if(n=="true" or n=="false"):
return B(n)
if(n=="null"):
return Null()
return S(n)
def __repr__(self):
return 'Input(%s)' % (self.expr1)
class Cast():
def __init__(self,value,type):
self.e1 = value
self.e2 = type
def cast(self,value,type):
if(isinstance(type,TInt)):
try:
n = N(int(value))
return n
except:
return False
elif(isinstance(type,TS)):
try:
s = S(str(value))
return s
except:
return False
elif(isinstance(type,TFloat)):
try:
f = N(float(value))
return f
except:
return False
elif(isinstance(type,TB)):
try:
b = B(bool(value))
return b
except:
return False
return False
def expr1(self):
return self.e1
def expr2(self):
return self.e2
def __repr__(self):
return 'Cast(%s,%s)' % (self.e1, self.e2)
class TInt():
def __init__(self):
self.e1 = None
def __repr__(self):
return 'Int'
class TFloat():
def __init__(self):
self.e1 = None
def __repr__(self):
return 'Float'
class TB():
def __init__(self):
self.e1 = None
def __repr__(self):
return 'Bool' % (self.e1)
class TS():
def __init__(self):
self.e1 = None
def __repr__(self):
return 'String'
#Helper functions
def isfloat(n):
try:
float(n)
return True
except:
return False
|
class Solution:
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
G = [0 for _ in range(n+1)]
G[0] = G[1] = 1
# 2...n
for i in range(2, n+1):
# 0...i
for j in range(1, i+1):
G[i] += G[j-1]*G[i-j]
return G[n]
|
input = """
dummy.
c(0,0).
d :- c(_,a_long__but_still_nice_constant), dummy.
"""
output = """
dummy.
c(0,0).
d :- c(_,a_long__but_still_nice_constant), dummy.
"""
|
COM = ['wink', 'double blink', 'close your eyes', 'jump']
def commands(binary_str):
handshake = []
for couple in zip(binary_str[::-1],COM):
if couple[0] == '1':
handshake.append(couple[1])
if binary_str[0] == '1':
handshake = handshake[::-1]
return handshake
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
if __name__ == "__main__":
u = set("abcdefghijklmnopqrstuvwxyz")
a = {"a", "b", "d", "i", "x"}
b = {"d", "e", "h", "i", "n", "u"}
c = {"e", "f", "m", "n"}
d = {"a", "c", "h", "k", "r", "s", "w", "x"}
bu = u.difference(b)
x = (a.difference(c)).intersection(bu)
print(f"x = {x}")
ba = u.difference(a)
y = (ba.intersection(d)).union(c.difference(b))
print(f"y = {y}")
|
#List of constants accessed in our main transit_tracker.py script
#URL for downloading data
URL = 'https://www.psrc.org/sites/default/files/2014-hhsurvey.zip'
#list of age ranges used to make labels
AGE_RANGE_LIST = list(range(0,12))
#List of education ranges used to make labels
EDU_RANGE_LIST = list(range(0,7))
#Tools used in Bokeh plotting
TOOLS = "pan,wheel_zoom,reset,poly_select,box_select,tap,box_zoom,save"
#List of zip codes used for PSRC data
USED_ZIPS_PSRC = ['98101', '98102', '98103', '98104', '98105', '98106', '98107',
'98108', '98109', '98112', '98115', '98116', '98117', '98118',
'98119', '98121', '98122', '98125', '98126', '98133', '98136',
'98144', '98146', '98177', '98178', '98195', '98199']
#list of length of used_zips for customJS code creation
N_PSRC = range(len(used_zips))
#Line width for Bokeh plotting PSRC data
WD = 2
#Line width for Bokeh plotting bus routes
WD2 = 2
|
# 字符串txt是否包含字符串ptn
txt = input('字符串txt:')
ptn = input('字符串ptn:')
if ptn in txt:
print('ptn包含于txt。')
else:
print('txt不包含ptn。')
|
class DestinationDirectoryError(Exception):
pass
def add_ssh_prefix(cmd: list[str], remote_host: str) -> list:
"""
Prefix a command with "ssh <remote_address>" for remote use
:param cmd: Command to be run remotely
:param remote_host: Remote machine address
:return: Command with prefix
"""
ssh_string = ["ssh", remote_host]
return ssh_string + cmd
def change_ownership_permission(
tar,
untar,
delete_destination_tar,
owner,
group,
permissions,
dest_tar_archive,
local_destination,
remote_host,
remote_destination=False,
):
"""
Create command change permissions at destination
Command depends on whether the tar archive, the destination directory
or both will remain at the destination.
"""
if tar:
if delete_destination_tar and not untar:
raise DestinationDirectoryError(
"Tar archive deleted, but not extracted. Aborting"
)
new_ownership = owner + ":" + group
chown_string = ["chown", "-R", new_ownership]
chmod_string = ["chmod", "-R", permissions]
if tar and untar and not delete_destination_tar:
change_archive = True
change_dest = True
elif tar and untar and delete_destination_tar:
change_archive = False
change_dest = True
elif tar and not untar:
change_archive = True
change_dest = False
elif not tar:
change_archive = False
change_dest = True
if change_archive and change_dest:
change_ownership_string = (
chown_string + [str(dest_tar_archive)] + [str(local_destination)]
)
change_permission_string = (
chmod_string + [str(dest_tar_archive)] + [str(local_destination)]
)
elif change_dest:
change_ownership_string = chown_string + [str(local_destination)]
change_permission_string = chmod_string + [str(local_destination)]
elif change_archive:
change_ownership_string = chown_string + [str(dest_tar_archive)]
change_permission_string = chmod_string + [str(dest_tar_archive)]
if remote_destination:
change_ownership_string = add_ssh_prefix(
change_ownership_string, remote_host
)
change_permission_string = add_ssh_prefix(
change_permission_string, remote_host
)
return change_ownership_string, change_permission_string
def delete_destination_tarball_string(
dest_tar_archive, remote_host, remote_destination=False
):
"""
Create command to delete tar archive after untar
"""
delete_dest_tarball_string = [
"rm",
"-v",
str(dest_tar_archive),
]
if remote_destination:
delete_dest_tarball_string = add_ssh_prefix(
delete_dest_tarball_string,
remote_host,
)
return delete_dest_tarball_string
|
SHARES = [
0.5, 0.6, 0.7, 0.8, 0.9,
0.91, 0.92, 0.93, 0.94,
0.95, 0.96, 0.97, 0.98,
0.99, 1.0
]
def pop(items):
return items[0], items[1:]
def get_quantiles(records, shares=SHARES):
if not shares:
return
counts = [count for _, count in records]
total = sum(counts)
accumulator = 0
shares = sorted(shares)
share, shares = pop(shares)
counts = sorted(counts, reverse=True)
for index, count in enumerate(counts):
accumulator += count
if accumulator / total >= share:
yield share, index
if not shares:
break
share, shares = pop(shares)
|
'''
Probem Task : A number is said to be Harshad if it's exactly divisible by
the sum of its digits. Create a function that determines whether a number
is a Harshad or not.
Problem Link : https://edabit.com/challenge/Rrauvu8afRbjqPM8L
'''
sum=0
def harshad(n):
global sum
if(n>0):
rem=n%10
sum=sum+rem
harshad(n//10)
if(n % sum ==0):
return "Harshad"
else:
return "Not Harshad"
n=int(input("Enter a number:"))
print(harshad(n))
|
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 2 09:34:42 2018
@author: Manu
TYPES OF VARIABLES
"""
#***********STRINGS*******************
#%%
#Use formate in order to crate a template
name= "Manuel"
city= "Avila (Spain)"
template = "I'm {}, I live in {}".format(name,city)
print(template)
#%%
#Operations with Strings
str1 = "i'm programming in PYTHON"
print(str1.upper())
print(str1.lower())
print(str1.capitalize())
str2 = "use split in order to separte words"
print(str2)
str2 = str2.split(" ")
print(str2)
#%%
#***************NUMBERS******************************
#types of numbers
num1 = 1
num2 = 2.0
print(num1,type(num1))
print (num2*65,type(num2))
#cast from int to float
print(int(num2))
print(float(num1))
#Operations
print(5+5)
print(5-5)
rest = 5%5
print(f"Rest of operation 5/5 is : {rest}",rest)
#%%
#*****************BOOLEANS*****************************
t= True
f = False
none = None
print(type(none))
print("The variable t is",t is True)
num1 = 5
num2 = 6
print(f"{num1} >= {num2} i ",num1 >=num2)
print(f"{num1} >= {num2} or {num1} <= {num2} is",num1 >=num2 or num1 <=num2)
#%%
|
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php or see LICENSE file.
# Copyright 2007-2008 Brisa Team <brisa-develop@garage.maemo.org>
""" Facilities for python properties generation.
"""
def gen_property_with_default(name, fget=None, fset=None, doc=""):
""" Generates a property of a name either with a default fget or a default
fset.
@param name: property name
@param fget: default fget
@param fset: default fset
@param doc: documentation for the property
@type name: string
@type fget: callable or None
@type fset: callable or None
@type doc: string
"""
if fget == None and fset == None:
raise NotImplementedError("fget or fset must be not null")
internal_name = '%s%s' % ("_prop_", name)
def getter(self):
if not internal_name in dir(self):
setattr(self, internal_name, "")
return getattr(self, internal_name)
def setter(self, value):
return setattr(self, internal_name, value)
if fget is None:
return property(getter, fset, doc=doc)
return property(fget, setter, doc=doc)
def gen_property_of_type(name, _type, doc=""):
""" Generates a type-forced property associated with a name. Provides type
checking on the setter (coherence between value to be set and the type
specified).
@param name: property name
@param _type: force type
@param doc: documentation for the property
@type name: string
@type _type: type
@type doc: string
"""
internal_name = '%s%s' % ("_prop_", name)
def getter(self):
return getattr(self, internal_name)
def setter(self, value):
if isinstance(value, _type):
return setattr(self, internal_name, value)
else:
raise TypeError(("invalid type '%s' for property %s:"
"%s is required.") %
(type(value).__name__, name, type(_type).__name__))
return property(getter, setter, doc=doc)
|
'''
Created: 2019-09-23 12:12:08
Author : YukiMuraRindon
Email : rinndonn@outlook.com
-----
Description:给定一个整数,写一个函数来判断它是否是 3 的幂次方。
'''
class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n == 1:
return True
elif n / 3 == 0 :
return False
else:
while n % 3 == 0:
n /= 3
if n == 1:
return True
return False
s=Solution()
print(s.isPowerOfThree(0))
|
def dechiffrer(message, cle_chiffrement):
int(cle_chiffrement)
resultat = ""
for lettre in message:
resultat = resultat + chr(ord(lettre) - cle_chiffrement)
return resultat
def chiffrer(message, cle_chiffrement):
return dechiffrer(message, -cle_chiffrement)
if __name__ == "__main__":
assert dechiffrer("Nsktwrfynvzj", 5) == "Informatique", "Erreur 1"
assert dechiffrer(chiffrer("azertyuiop", 3), 3) == "azertyuiop", "Erreur 2"
print("Tests validés.\n\n")
|
"""
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2
⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
"""
class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
votes = 0
for num in nums:
if votes == 0:
candidate = num
if num == candidate:
votes += 1
else:
votes -= 1
return candidate
def main():
sol = Solution()
print(sol.majorityElement([3, 2, 3]))
print(sol.majorityElement([2, 2, 1, 1, 1, 2, 2]))
if __name__ == '__main__':
main()
|
print('''Crie um programa que vai ler vários números e colocar em uma lista.
Depois disso, mostre:
A) Quantos números foram digitados.
B) A lista de valores, ordenada de forma descrescente.
C) Se o valor 5 foi digitado e está ou não na lista.''')
num = cont = 0
li = []
while True:
no = 1
keep = 'a'
cont += 1
num = int(input('Digite um número: '))
if cont == 1:
li.append(num)
else:
for n in enumerate(li):
if num <= li[n[0]]:
li.insert(n[0], num)
no = 0
break
if no == 1:
li.append(num)
while keep not in 'SsNn':
keep = input('Deseja continuar? [S/N]')
if keep not in 'SsNn':
print('Opção inválida.', end=' ')
if keep in 'Nn':
break
print(f'Você digitou {len(li)} números.')
li.sort(reverse=True)
print(f'A lista de valores ordenada de forma descrescente é {li}')
if 5 in li:
print('Sim, o 5 foi digitado e faz parte da lista!')
else:
print('Nãon o 5 não foi digitado e não faz parte da lista!')
|
a,b = 10,20
print(a+b) #Output: 30
print(a*b) #Output: 200
print(b/a) #Output: 2.0
print(b%a) #Output: 0
|
# -*- coding: utf-8 -*-
MSG_DATE_SEP = ">>>:"
END_MSG = "THEEND"
ALLOWED_KEYS = [
'q',
'e',
's',
'z',
'c',
'',
]
|
"""
Implement a function meetingPlanner that given the availability, slotsA and slotsB, of two people and a meeting duration dur, returns the earliest time slot that works for both of them and is of duration dur. If there is no common time slot that satisfies the duration requirement, return null.
Time is given in a Unix format called Epoch, which is a nonnegative integer holding the number of seconds that have elapsed since 00:00:00 UTC, Thursday, 1 January 1970.
Each person’s availability is represented by an array of pairs. Each pair is an epoch array of size two. The first epoch in a pair represents the start time of a slot. The second epoch is the end time of that slot. The input variable dur is a positive integer that represents the duration of a meeting in seconds. The output is also a pair represented by an epoch array of size two.
In your implementation assume that the time slots in a person’s availability are disjointed, i.e, time slots in a person’s availability don’t overlap. Further assume that the slots are sorted by slots’ start time.
Implement an efficient solution and analyze its time and space complexities.
Examples:
input: slotsA = [[10, 50], [60, 120], [140, 210]]
slotsB = [[0, 15], [60, 70]]
dur = 8
output: [60, 68]
input: slotsA = [[10, 50], [60, 120], [140, 210]]
slotsB = [[0, 15], [60, 70]]
dur = 12
output: null # since there is no common slot whose duration is 12
Constraints:
[time limit] 5000ms
[input] array.array.integer slotsA
1 ≤ slotsA.length ≤ 100
slotsA[i].length = 2
[input] array.array.integer slotsB
1 ≤ slotsB.length ≤ 100
slotsB[i].length = 2
[input] integer
[output] array.integer
Test Case #1
Input: [[7,12]], [[2,11]], 5,Expected: [],Actual: []
Test Case #2
Input: [[6,12]], [[2,11]], 5,Expected: [6,11],Actual: [6, 11]
Test Case #3
Input: [[1,10]], [[2,3],[5,7]], 2,Expected: [5,7],Actual: [5, 7]
Test Case #4
Input: [[0,5],[50,70],[120,125]], [[0,50]], 8,Expected: [],Actual: []
Test Case #5
Input: [[10,50],[60,120],[140,210]], [[0,15],[60,70]], 8,Expected: [60,68],Actual: [60, 68]
Test Case #6
Input: [[10,50],[60,120],[140,210]], [[0,15],[60,72]], 12,Expected: [60,72],Actual: [60, 72]
RUN CODE
"""
def meeting_planner(slotsA, slotsB, dur):
i = 0
j = 0
while (i < len(slotsA)) and (j < len(slotsB)):
start = max(slotsA[i][0], slotsB[j][0])
end = min(slotsA[i][1], slotsB[j][1])
if end - start >= dur:
return [start, start + dur]
if (slotsA[i][1] < slotsB[j][1]):
i += 1
else:
j += 1
return []
slotsA = [[10, 50], [60, 120], [140, 210]]
slotsB = [[0, 15], [60, 70]]
dur = 8
meeting_planner(slotsA, slotsB, dur)
|
# coding: utf-8
class Service:
pass
|
""" https://adventofcode.com/2018/day/11 """
def readFile():
with open(f"{__file__.rstrip('code.py')}input.txt", "r") as f:
return int(f.read())
def getPowerlevel(x, y, serial):
rackId = x + 10
powerLevel = (rackId * y + serial) * rackId
return (int(powerLevel / 100) % 10) - 5
def createGrid(serial):
grid = []
for j in range(1, 301):
row = []
for i in range(1, 301):
row.append(getPowerlevel(i, j, serial))
grid.append(row)
return grid
def getBiggestField(grid, size):
maxSum = 0
maxCoords = (-1, -1)
for j in range(300 - size + 1):
for i in range(300 - size + 1):
curSum = 0
for n in range(size):
for m in range(size):
curSum += grid[j + m][i + n]
if curSum > maxSum:
maxSum = curSum
maxCoords = (i + 1, j + 1)
return maxCoords, maxSum
def getSat(grid):
# generates and returns summed-area table
sat = {}
size = len(grid)
for j in range(size):
for i in range(size):
value = grid[j][i] + sat.get(str((i - 1, j)), 0)
value += sat.get(str((i, j - 1)), 0) - sat.get(str((i - 1, j - 1)), 0)
sat[str((i, j))] = value
return sat
def getBiggestFieldSAT(sat, size):
maxSum = 0
maxCoords = (-1, -1)
for j in range(300 - size):
for i in range(300 - size):
ip, jp = i + size, j + size
curSum = sat[str((i, j))] + sat[str((ip, jp))] - sat[str((ip, j))] - sat[str((i, jp))]
if curSum > maxSum:
maxSum = curSum
maxCoords = (i + 2, j + 2)
return maxCoords, maxSum
def part1(value):
grid = createGrid(value)
return getBiggestField(grid, 3)[0]
def part2(value):
grid = createGrid(value)
sat = getSat(grid)
maxSum = 0
size = -1
maxCoords = (-1, -1)
for i in range(300):
curCoords, curSum = getBiggestFieldSAT(sat, i)
if curSum > maxSum:
maxSum = curSum
size = i
maxCoords = curCoords
return (maxCoords[0], maxCoords[1], size)
if __name__ == "__main__":
value = readFile()
print(f"Part 1: {part1(value)}")
print(f"Part 2: {part2(value)}")
|
class View(dict):
"""A View contains the content displayed in the main window."""
def __init__(self, d=None):
"""
View constructor.
Keyword arguments:
d=None: Initial keys and values to initialize the view with.
Regardless of the value of d, keys 'songs', 'artists' and
'albums' are created with empty lists as default values.
"""
self['songs'], self['artists'], self['albums'] = [], [], []
if d is not None:
if isinstance(d, dict):
for k in d:
self[k] = d[k]
else:
raise TypeError('Initializing View with invalid argument')
def __setitem__(self, key, val):
"""Restrict values to lists only."""
if not isinstance(val, list):
raise TypeError('View can only hold lists as values.')
super().__setitem__(key, val)
def __len__(self):
"""Return the sum of each list's length."""
return sum(len(self[k]) for k in self)
def replace(self, other):
"""Replace the view's contents with some other dict."""
self = self.__init__(other)
def clear(self):
"""Clear elements without removing keys."""
for k in self.keys():
del self[k][:]
def is_empty(self):
"""Returns whether or not the view is empty."""
return all(not self[k] for k in self)
def copy(self):
"""Return a deep copy of the view's contents."""
return {k: self[k][:] for k in self}
|
def search(list, platform):
for i in range(len(list)):
if list[i] == platform:
return True
return False
fruit = ['banana', 'grape', 'apple', 'plam']
print(fruit)
frut = input('input to see if it exists: ')
if search(fruit, frut):
print("fruit is found")
else:
print("fruiit does not found")
|
# -*- coding: utf-8 -*-
def theaudiodb_albumdetails(data):
if data.get('album'):
item = data['album'][0]
albumdata = {}
albumdata['album'] = item['strAlbum']
if item.get('intYearReleased',''):
albumdata['year'] = item['intYearReleased']
if item.get('strStyle',''):
albumdata['styles'] = item['strStyle']
if item.get('strGenre',''):
albumdata['genre'] = item['strGenre']
if item.get('strLabel',''):
albumdata['label'] = item['strLabel']
if item.get('strReleaseFormat',''):
albumdata['type'] = item['strReleaseFormat']
if item.get('intScore',''):
albumdata['rating'] = str(int(float(item['intScore']) + 0.5))
if item.get('intScoreVotes',''):
albumdata['votes'] = item['intScoreVotes']
if item.get('strMood',''):
albumdata['moods'] = item['strMood']
if item.get('strTheme',''):
albumdata['themes'] = item['strTheme']
if item.get('strMusicBrainzID',''):
albumdata['mbreleasegroupid'] = item['strMusicBrainzID']
# api inconsistent
if item.get('strDescription',''):
albumdata['descriptionEN'] = item['strDescription']
elif item.get('strDescriptionEN',''):
albumdata['descriptionEN'] = item['strDescriptionEN']
if item.get('strDescriptionDE',''):
albumdata['descriptionDE'] = item['strDescriptionDE']
if item.get('strDescriptionFR',''):
albumdata['descriptionFR'] = item['strDescriptionFR']
if item.get('strDescriptionCN',''):
albumdata['descriptionCN'] = item['strDescriptionCN']
if item.get('strDescriptionIT',''):
albumdata['descriptionIT'] = item['strDescriptionIT']
if item.get('strDescriptionJP',''):
albumdata['descriptionJP'] = item['strDescriptionJP']
if item.get('strDescriptionRU',''):
albumdata['descriptionRU'] = item['strDescriptionRU']
if item.get('strDescriptionES',''):
albumdata['descriptionES'] = item['strDescriptionES']
if item.get('strDescriptionPT',''):
albumdata['descriptionPT'] = item['strDescriptionPT']
if item.get('strDescriptionSE',''):
albumdata['descriptionSE'] = item['strDescriptionSE']
if item.get('strDescriptionNL',''):
albumdata['descriptionNL'] = item['strDescriptionNL']
if item.get('strDescriptionHU',''):
albumdata['descriptionHU'] = item['strDescriptionHU']
if item.get('strDescriptionNO',''):
albumdata['descriptionNO'] = item['strDescriptionNO']
if item.get('strDescriptionIL',''):
albumdata['descriptionIL'] = item['strDescriptionIL']
if item.get('strDescriptionPL',''):
albumdata['descriptionPL'] = item['strDescriptionPL']
if item.get('strArtist',''):
albumdata['artist_description'] = item['strArtist']
artists = []
artistdata = {}
artistdata['artist'] = item['strArtist']
if item.get('strMusicBrainzArtistID',''):
artistdata['mbartistid'] = item['strMusicBrainzArtistID']
artists.append(artistdata)
albumdata['artist'] = artists
thumbs = []
extras = []
if item.get('strAlbumThumb',''):
thumbdata = {}
thumbdata['image'] = item['strAlbumThumb']
thumbdata['preview'] = item['strAlbumThumb'] + '/preview'
thumbdata['aspect'] = 'thumb'
thumbs.append(thumbdata)
if item.get('strAlbumThumbBack',''):
extradata = {}
extradata['image'] = item['strAlbumThumbBack']
extradata['preview'] = item['strAlbumThumbBack'] + '/preview'
extradata['aspect'] = 'back'
extras.append(extradata)
if item.get('strAlbumSpine',''):
extradata = {}
extradata['image'] = item['strAlbumSpine']
extradata['preview'] = item['strAlbumSpine'] + '/preview'
extradata['aspect'] = 'spine'
extras.append(extradata)
if item.get('strAlbumCDart',''):
extradata = {}
extradata['image'] = item['strAlbumCDart']
extradata['preview'] = item['strAlbumCDart'] + '/preview'
extradata['aspect'] = 'discart'
extras.append(extradata)
if item.get('strAlbum3DCase',''):
extradata = {}
extradata['image'] = item['strAlbum3DCase']
extradata['preview'] = item['strAlbum3DCase'] + '/preview'
extradata['aspect'] = '3dcase'
extras.append(extradata)
if item.get('strAlbum3DFlat',''):
extradata = {}
extradata['image'] = item['strAlbum3DFlat']
extradata['preview'] = item['strAlbum3DFlat'] + '/preview'
extradata['aspect'] = '3dflat'
extras.append(extradata)
if item.get('strAlbum3DFace',''):
extradata = {}
extradata['image'] = item['strAlbum3DFace']
extradata['preview'] = item['strAlbum3DFace'] + '/preview'
extradata['aspect'] = '3dface'
extras.append(extradata)
if thumbs:
albumdata['thumb'] = thumbs
if extras:
albumdata['extras'] = extras
return albumdata
|
"""
Zadanie jak powyżej. Funkcja powinna dostarczyć drogę króla w postaci tablicy zawierającej
kierunki (liczby od 0 do 7) poszczególnych ruchów króla do wybranego celu.
"""
def first_digit(number):
while number > 9:
number //= 10
return number
def king_recursion(T, w, k, visited=[]):
visited.append((w, k))
if ((w == len(T) - 1 and k == len(T) - 1) or (w == 0 and k == 0)
or (w == 0 and k == len(T) - 1) or (w == len(T) - 1 and k == 0)):
return True, visited
w_move = [0, -1, -1, -1, 0, 1, 1, 1]
k_move = [1, 1, 0, -1, -1, -1, 0, 1]
for i in range(8):
new_w = w + w_move[i]
new_k = k + k_move[i]
if new_w >= 0 and new_k >= 0 and new_w < len(T) and new_k < len(T):
if (new_w, new_k) not in visited:
first = first_digit(T[new_w][new_k])
if first > T[w][k] % 10:
if king_recursion(T, new_w, new_k, visited):
return True, visited
return False
T = [[30, 50, 49, 30, 49, 17, 39, 14],
[33, 10, 50, 36, 26, 24, 34, 25],
[19, 22, 9, 21, 47, 6, 19, 45],
[15, 10, 42, 27, 21, 3, 20, 4],
[7, 30, 6, 18, 13, 40, 46, 47],
[21, 46, 50, 16, 10, 22, 32, 36],
[11, 26, 43, 25, 24, 36, 24, 50],
[40, 38, 40, 17, 36, 13, 38, 36]]
w, k = 3, 4
print(king_recursion(T, w, k))
|
class State:
state = {}
@staticmethod
def init():
State.state = {
"lowres_frames": None,
"highres_frames": None,
"photopath": "",
"frame": 0,
"current_photo": None,
"share_code": "",
"preview_image_width": 0,
"photo_countdown": 0,
"reset_time": 0,
"upload_url": "",
"photo_url": "",
"api_key": ""
}
return State.state
@staticmethod
def set(value):
State.state[value[0]] = value[1]
return State.state
@staticmethod
def set_dict(value):
State.state = {**State.state, **value}
return State.state
@staticmethod
def get(key):
try:
return State.state.get(key)
except KeyError:
print("No key found")
return None
@staticmethod
def print():
print(State.state)
|
#!/usr/bin/env python3
"""Making a Box.
Create a function that creates a box based on dimension n.
Source:
https://edabit.com/challenge/dy3WWJr34gSGRPLee
"""
def make_box(n: int, character: str = '#') -> list:
"""Create a box on dimension n using character."""
box = []
for i in range(n):
if i in (0, n-1):
box.append(f'{character*n}')
else:
box.append(f'{character}{" "*(n-2)}{character}')
return box
def main():
"""Run sample make_box functions. Do not import."""
assert make_box(5) == [
"#####",
"# #",
"# #",
"# #",
"#####"
]
assert make_box(6) == [
"######",
"# #",
"# #",
"# #",
"# #",
"######"]
assert make_box(4) == [
"####",
"# #",
"# #",
"####"]
assert make_box(2) == [
"##",
"##"]
assert make_box(1) == [
"#"
]
print('Passed.')
if __name__ == "__main__":
main()
|
expected_output = {
'tracker_name': {
'tcp-10001': {
'status': 'UP',
'rtt_in_msec': 2,
'probe_id': 2
},
'udp-10001': {
'status': 'UP',
'rtt_in_msec': 1,
'probe_id': 3
}
}
}
|
"""
coax.exceptions
~~~~~~~~~~~~~~~
"""
class InterfaceError(Exception):
"""An interface error occurred."""
class ReceiveError(Exception):
"""A receive error occurred."""
class InterfaceTimeout(Exception):
"""The interface timed out."""
class ReceiveTimeout(Exception):
"""The receive operation timed out."""
class ProtocolError(Exception):
"""A protocol error occurred."""
|
def is_funny(string):
data = list(zip(string, reversed(string)))
for i in range(len(string)-1):
if abs(ord(data[i+1][0]) - ord(data[i][0])) != \
abs(ord(data[i+1][1]) - ord(data[i][1])):
return "Not Funny"
return "Funny"
N = int(input())
for i in range(N):
print(is_funny(input()))
|
#
# Common methods for the a2gtrad and a2advrad scripts.
#
#
#
# SOFTWARE HISTORY
#
# Date Ticket# Engineer Description
# ------------ ---------- ----------- --------------------------
# 08/13/2014 3393 nabowle Initial creation to contain common
# code for a2*radStub scripts.
# 03/15/2015 mjames@ucar Edited/added to awips package as RadarCommon
#
#
def get_datetime_str(record):
"""
Get the datetime string for a record.
Args:
record: the record to get data for.
Returns:
datetime string.
"""
return str(record.getDataTime())[0:19].replace(" ", "_") + ".0"
def get_data_type(azdat):
"""
Get the radar file type (radial or raster).
Args:
azdat: Boolean.
Returns:
Radial or raster.
"""
if azdat:
return "radial"
return "raster"
def get_hdf5_data(idra):
rdat = []
azdat = []
depVals = []
threshVals = []
if idra:
for item in idra:
if item.getName() == "Data":
rdat = item
elif item.getName() == "Angles":
azdat = item
# dattyp = "radial"
elif item.getName() == "DependentValues":
depVals = item.getShortData()
elif item.getName() == "Thresholds":
threshVals = item.getShortData()
return rdat, azdat, depVals, threshVals
def get_header(record, headerFormat, xLen, yLen, azdat, description):
# Encode dimensions, time, mapping, description, tilt, and VCP
mytime = get_datetime_str(record)
dattyp = get_data_type(azdat)
if headerFormat:
msg = str(xLen) + " " + str(yLen) + " " + mytime + " " + \
dattyp + " " + str(record.getLatitude()) + " " + \
str(record.getLongitude()) + " " + \
str(record.getElevation()) + " " + \
str(record.getElevationNumber()) + " " + \
description + " " + str(record.getTrueElevationAngle()) + " " + \
str(record.getVolumeCoveragePattern()) + "\n"
else:
msg = str(xLen) + " " + str(yLen) + " " + mytime + " " + \
dattyp + " " + description + " " + \
str(record.getTrueElevationAngle()) + " " + \
str(record.getVolumeCoveragePattern()) + "\n"
return msg
def encode_thresh_vals(threshVals):
spec = [".", "TH", "ND", "RF", "BI", "GC", "IC", "GR", "WS", "DS",
"RA", "HR", "BD", "HA", "UK"]
nnn = len(threshVals)
j = 0
msg = ""
while j < nnn:
lo = threshVals[j] % 256
hi = threshVals[j] / 256
msg += " "
j += 1
if hi < 0:
if lo > 14:
msg += "."
else:
msg += spec[lo]
continue
if hi % 16 >= 8:
msg += ">"
elif hi % 8 >= 4:
msg += "<"
if hi % 4 >= 2:
msg += "+"
elif hi % 2 >= 1:
msg += "-"
if hi >= 64:
msg += "%.2f" % (lo*0.01)
elif hi % 64 >= 32:
msg += "%.2f" % (lo*0.05)
elif hi % 32 >= 16:
msg += "%.1f" % (lo*0.1)
else:
msg += str(lo)
msg += "\n"
return msg
def encode_dep_vals(depVals):
nnn = len(depVals)
j = 0
msg = []
while j < nnn:
msg.append(str(depVals[j]))
j += 1
return msg
def encode_radial(azVals):
azValsLen = len(azVals)
j = 0
msg = []
while j < azValsLen:
msg.append(azVals[j])
j += 1
return msg
|
#!/usr/bin/env python
def mtx_pivot(mtx) -> list:
piv=[]
pivr=[[] for c in mtx[0]]
for r,row in enumerate(mtx):
for c,col in enumerate(row):
pivr[c]+=[col]
piv+=pivr
return piv
|
# #class
# # terms
# # i. features/attributes
# # ii. methods
# # i. a class with args
# # ii a class without args
# # task
# # crate a person class
# # features; age, sex, name, occupation, height
# class Person(object):
# """
# docstring for Person:
# """
# def __init__(self, name, age, occupation, height, sex):
# # super(Person, self).__init__()
# self.name = name
# self.age = age
# self.occupation = occupation
# self.height = height
# self.sex = sex
# def addSex(self, sex):
# self.sex = sex
# def addAge(self, age):
# self.age = int(age)
# def addOccupation(self, occupation):
# self.occupation = occupation
# def addHeight(self, height):
# self.height = float(height)
# def walk(self, steps):
# print(f'{self.name} just took {steps} steps.')
# person = Person('Tayo', 22, 'Farmer', 5.9, 'Male')
# # person.addSex('Male')
# # person.addHeight(5.8)
# # person.addOccupation('Farmer')
# person.addAge(30)
# age = person.age
# name = person.name
# height = person.height
# occupation = person.occupation
# sex = person.sex
# person.walk(100)
# print(f'I am {name} and {age} years old.\nI am a {occupation}.\
# \nI am {height} and I am {sex}.\nThank you!')
# tayo = Person
# # tayo()
# create a person class that can walk
# features; height, sex, age, name, occupation
# walk takes step ardument
# shout
# eat
# sleep
# sing
# import random
# class Person(object):
# """docstring for Person"""
# def __init__(self, name):
# # super(Person, self).__init__()
# self.name = name
# # self.engine_number = '000222233030'
# self.steps = 0
# print(self.name, 'has just been initialized.')
# def setAge(self, value):
# self.age = value
# def setSex(self, sex):
# self.sex = sex
# def setHeight(self, height):
# self.height = height
# def walk(self, steps):
# print(self.name, 'is took ', steps, 'steps.')
# r_number = random.randint(0, 100)
# self.steps += (steps * r_number)
# def eat(self, food):
# print('I am eating ', food)
# tayo = Person('Tayo')
# comfort = Person('Comfort')
# # set tayo's attributes
# tayo.setAge(12)
# # set comfort's attributes
# comfort.setAge(12)
# # Game start
# # tayo took 10 steps
# tayo.walk(10)
# # comfort took 30 steps
# comfort.walk(30)
# # tayo took 2 steps
# tayo.walk(2)
# # comfort took 10 steps
# comfort.walk(10)
# # at the end of the day
# # print the steps of each players
# print(f'{tayo.name} took {tayo.steps} steps\n {comfort.name} took {comfort.steps} ')
# if tayo.steps > comfort.steps:
# print(f'The winner is {tayo.name}')
# else:
# print(f'The winner is {comfort.name}')
# # tayo.setAge(20)
# # tayo.setSex('Male')
# # tayo.setHeight(5.9)
# # print(tayo.name, tayo.age)
# # tayo.walk(20)
# # tayo.eat('Rice')
# inheritance
# Parent
class Parent(object):
"""docstring for Parent"""
def __init__(self, name):
# super(Parent, self).__init__()
self.name = name
self.height = 6.0
# print()
def getHeight(self):
print(self.height)
class Child(Parent):
"""docstring for Child"""
def __init__(self, name):
super(Parent, self).__init__()
self.name = name
self.height = 6.2
def getHeight(self):
print(self.height)
child = Child('Tayo')
print(child.name)
child.getHeight()
print('------------------------------------')
parent = Parent('Tolu')
print(parent.name)
parent.getHeight()
|
"""
LC 6014
You are given a string s and an integer repeatLimit. Construct a new string repeatLimitedString using the characters of s such that no letter appears more than repeatLimit times in a row. You do not have to use all characters from s.
Return the lexicographically largest repeatLimitedString possible.
A string a is lexicographically larger than a string b if in the first position where a and b differ, string a has a letter that appears later in the alphabet than the corresponding letter in b. If the first min(a.length, b.length) characters do not differ, then the longer string is the lexicographically larger one.
Example 1:
Input: s = "cczazcc", repeatLimit = 3
Output: "zzcccac"
Explanation: We use all of the characters from s to construct the repeatLimitedString "zzcccac".
The letter 'a' appears at most 1 time in a row.
The letter 'c' appears at most 3 times in a row.
The letter 'z' appears at most 2 times in a row.
Hence, no letter appears more than repeatLimit times in a row and the string is a valid repeatLimitedString.
The string is the lexicographically largest repeatLimitedString possible so we return "zzcccac".
Note that the string "zzcccca" is lexicographically larger but the letter 'c' appears more than 3 times in a row, so it is not a valid repeatLimitedString.
Example 2:
Input: s = "aababab", repeatLimit = 2
Output: "bbabaa"
Explanation: We use only some of the characters from s to construct the repeatLimitedString "bbabaa".
The letter 'a' appears at most 2 times in a row.
The letter 'b' appears at most 2 times in a row.
Hence, no letter appears more than repeatLimit times in a row and the string is a valid repeatLimitedString.
The string is the lexicographically largest repeatLimitedString possible so we return "bbabaa".
Note that the string "bbabaaa" is lexicographically larger but the letter 'a' appears more than 2 times in a row, so it is not a valid repeatLimitedString.
"""
class Solution:
def repeatLimitedString(self, s: str, repeatLimit: int) -> str:
cnt = dict(Counter(s))
cs = sorted(cnt)
ans = []
# print(cnt, cs)
while cs:
self.use_letter(cnt, cs, ans, repeatLimit)
# print(ans)
return "".join(ans)
def use_letter(self, cnt, cs, ans, repeatLimit):
c = cs[-1]
while True:
app_n = min(repeatLimit, cnt[c])
ans.append(c * app_n)
cnt[c] -= app_n
if cnt[c] > 0 and len(cs) > 1:
backup = cs[-2]
ans.append(backup)
cnt[backup] -= 1
if cnt[backup] == 0:
cs.pop(len(cs) - 2)
else:
break
cs.pop()
"""
Time/Space O(N)
"""
|
def add_native_methods(clazz):
def floatToRawIntBits__float__(a0):
raise NotImplementedError()
def intBitsToFloat__int__(a0):
raise NotImplementedError()
clazz.floatToRawIntBits__float__ = staticmethod(floatToRawIntBits__float__)
clazz.intBitsToFloat__int__ = staticmethod(intBitsToFloat__int__)
|
# AUTOGENERATED! DO NOT EDIT! File to edit: 04_device.ipynb (unless otherwise specified).
__all__ = ['versions']
# Cell
def versions():
"Checks if GPU enabled and if so displays device details with cuda, pytorch, fastai versions"
print("GPU: ", torch.cuda.is_available())
if torch.cuda.is_available() == True:
print("Device = ", torch.device(torch.cuda.current_device()))
print("Cuda version - ", torch.version.cuda)
print("cuDNN version - ", torch.backends.cudnn.version())
print("PyTorch version - ", torch.__version__)
print("fastai version", fastai.__version__)
|
class PDB_container:
'''
Use to read a pdb file from a cocrystal structure and parse
it for further use
Note this class cannot write any files and we do not want any
files to be added by this class
This is good for IO management although the code might be hard to
understand
'''
def __init__(self):
'''
parse a pdb from file
'''
pass
def register_a_ligand(self):
pass
def Is_pure_protein(self):
pass
def Is_pure_nucleic(self):
pass
def Is_protein_nucleic_complex(self):
pass
def Bundle_ligand_result_dict(self):
pass
def Bundle_ligand_result_list(self):
pass
def list_ligand_ResId(self):
pass
def get_ligand_dict(self):
pass
class ligand_container:
pass
|
def method():
if True:
return 1
else:
return 2
def method2():
x = 2
if x:
y = 3
z = 1
|
# *****************************************************************************
# NICOS, the Networked Instrument Control System of the MLZ
# Copyright (c) 2009-2021 by the NICOS contributors (see AUTHORS)
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Module authors:
# Mark.Koennecke@psi.ch
#
# *****************************************************************************
name = 'SINQ Double Monochromator'
includes = ['stdsystem']
description = 'Test setup for the SINQ double monochromator'
devices = dict(
mth1 = device('nicos.devices.generic.VirtualMotor',
unit = 'degree',
description = 'First blade rotation',
abslimits = (-180, 180),
precision = 0.01
),
mth2 = device('nicos.devices.generic.VirtualMotor',
unit = 'degree',
description = 'Second blade rotation',
abslimits = (-180, 180),
precision = 0.01
),
mtx = device('nicos.devices.generic.VirtualMotor',
unit = 'mm',
description = 'Blade translation',
abslimits = (-1000, 1000),
precision = 0.01
),
wavelength = device('nicos_sinq.devices.doublemono.DoubleMonochromator',
description = 'SINQ Double Monochromator',
unit = 'A',
safe_position = 20.,
dvalue = 3.335,
distance = 100.,
abslimits = (2.4, 6.2),
mth1 = 'mth1',
mth2 = 'mth2',
mtx = 'mtx'
),
)
|
"""
https://leetcode.com/problems/reverse-integer
"""
# define an input for testing purposes
x = 1534236469
# actual code to submit
test = []
for i in str(x):
test += i
for z in range(len(test)):
if test[-1] == "0":
test.pop(-1)
else:
break
if test == []:
test.append("0")
if test[0] == "-":
test.append("-")
test.pop(0)
test.reverse()
solved = "".join(test)
# use print statement to check if it works
if int(solved) > -2147483648 and int(solved) < 2147483648:
print(int(solved))
else:
print(0)
# My Submission: https://leetcode.com/submissions/detail/433340125/
|
class Fluorescence:
def __init__(self, user_input, input_ceon):
self.user_input = user_input
self.input_ceons = [input_ceon]
self.number_trajectories = user_input.n_snapshots_ex
self.child_root = 'nasqm_fluorescence_'
self.job_suffix = 'fluorescence'
self.parent_restart_root = 'nasqm_qmexcited'
self.number_frames_in_parent = user_input.n_mcrd_frames_per_run_qmexcited * user_input.n_exc_runs
self.n_snapshots_per_trajectory = self.snaps_per_trajectory()
self.amber_restart = False
def __str__(self):
print_value = ""\
f"Traj_Data Info:\n"\
f"Class: Fluorescence:\n"\
f"Number input_ceons: {len(self.input_ceons)}\n"\
f"Number trajectories: {self.number_trajectories}\n"
return print_value
def snaps_per_trajectory(self):
n_frames = self.number_frames_in_parent
run_time = self.user_input.exc_run_time
time_delay = self.user_input.fluorescence_time_delay/1000
return int(n_frames * ( 1 - time_delay/run_time))
|
# André Roche - Project Euler Problem 5 24-Feb-18. More info @ https://projecteuler.net/problem=5
def gcd(a, b) :
if a == 0: return b
if b == 0: return a
if a < 0: a = -a
if b < 0: b = -b
while b != 0:
a, b = b, a%b
return a
result = 2
for i in range(2,21) :
result = i / gcd(result,i) * result
print (result)
|
#
# PySNMP MIB module COMPANY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/COMPANY-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:26:32 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, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, SingleValueConstraint, ValueSizeConstraint, ConstraintsIntersection, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsIntersection", "ConstraintsUnion")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
MibScalar, MibTable, MibTableRow, MibTableColumn, iso, Bits, TimeTicks, Counter64, IpAddress, MibIdentifier, Counter32, Gauge32, NotificationType, ObjectIdentity, enterprises, Unsigned32, Integer32, ModuleIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "iso", "Bits", "TimeTicks", "Counter64", "IpAddress", "MibIdentifier", "Counter32", "Gauge32", "NotificationType", "ObjectIdentity", "enterprises", "Unsigned32", "Integer32", "ModuleIdentity")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
allotCom = ModuleIdentity((1, 3, 6, 1, 4, 1, 2603))
if mibBuilder.loadTexts: allotCom.setLastUpdated('0103120000Z')
if mibBuilder.loadTexts: allotCom.setOrganization('Allot Communications')
if mibBuilder.loadTexts: allotCom.setContactInfo('Allot Communications postal: 5 Hanagar St. Industrial Zone Neve Neeman Hod Hasharon 45800 Israel phone: +972-(0)9-761-9200 fax: +972-(0)9-744-3626 email: support@allot.com')
if mibBuilder.loadTexts: allotCom.setDescription('This file defines the private Allot SNMP MIB extensions.')
neTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 2603, 2))
nePrimaryActive = NotificationType((1, 3, 6, 1, 4, 1, 2603, 2, 11))
if mibBuilder.loadTexts: nePrimaryActive.setStatus('current')
if mibBuilder.loadTexts: nePrimaryActive.setDescription('This trap is sent when the primary NE changes to Active mode')
nePrimaryBypass = NotificationType((1, 3, 6, 1, 4, 1, 2603, 2, 12))
if mibBuilder.loadTexts: nePrimaryBypass.setStatus('current')
if mibBuilder.loadTexts: nePrimaryBypass.setDescription('This trap is sent when the primary NE changes to Bypass mode')
neSecondaryActive = NotificationType((1, 3, 6, 1, 4, 1, 2603, 2, 13))
if mibBuilder.loadTexts: neSecondaryActive.setStatus('current')
if mibBuilder.loadTexts: neSecondaryActive.setDescription('This trap is sent when the secondary NE changes to Active mode')
neSecondaryStandBy = NotificationType((1, 3, 6, 1, 4, 1, 2603, 2, 14))
if mibBuilder.loadTexts: neSecondaryStandBy.setStatus('current')
if mibBuilder.loadTexts: neSecondaryStandBy.setDescription('This trap is sent when the secondary NE changes to StandBy mode')
neSecondaryBypass = NotificationType((1, 3, 6, 1, 4, 1, 2603, 2, 15))
if mibBuilder.loadTexts: neSecondaryBypass.setStatus('current')
if mibBuilder.loadTexts: neSecondaryBypass.setDescription('This trap is sent when the secondary NE changes to Bypass mode')
collTableOverFlow = NotificationType((1, 3, 6, 1, 4, 1, 2603, 2, 21))
if mibBuilder.loadTexts: collTableOverFlow.setStatus('current')
if mibBuilder.loadTexts: collTableOverFlow.setDescription('This trap is sent when acounting is not reading from the collector which causes the collector table to exceeds limits')
neAlertEvent = NotificationType((1, 3, 6, 1, 4, 1, 2603, 2, 22))
if mibBuilder.loadTexts: neAlertEvent.setStatus('current')
if mibBuilder.loadTexts: neAlertEvent.setDescription('This trap is sent when user defined event occurs')
neNotificationsGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 2603, 3)).setObjects(("COMPANY-MIB", "nePrimaryActive"), ("COMPANY-MIB", "nePrimaryBypass"), ("COMPANY-MIB", "neSecondaryActive"), ("COMPANY-MIB", "neSecondaryStandBy"), ("COMPANY-MIB", "neSecondaryBypass"), ("COMPANY-MIB", "collTableOverFlow"), ("COMPANY-MIB", "neAlertEvent"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
neNotificationsGroup = neNotificationsGroup.setStatus('current')
if mibBuilder.loadTexts: neNotificationsGroup.setDescription('The notifications which indicate specific changes of the NE state.')
mibBuilder.exportSymbols("COMPANY-MIB", nePrimaryBypass=nePrimaryBypass, nePrimaryActive=nePrimaryActive, neSecondaryBypass=neSecondaryBypass, PYSNMP_MODULE_ID=allotCom, neSecondaryActive=neSecondaryActive, allotCom=allotCom, collTableOverFlow=collTableOverFlow, neNotificationsGroup=neNotificationsGroup, neTraps=neTraps, neSecondaryStandBy=neSecondaryStandBy, neAlertEvent=neAlertEvent)
|
input_tokenizer = {}
input_tokenizer['en-bg'] = '-l en -a'
input_tokenizer['en-cs'] = '-l en -a'
input_tokenizer['en-de'] = '-l en -a'
input_tokenizer['en-el'] = '-l en -a'
input_tokenizer['en-hr'] = '-l en -a'
input_tokenizer['en-it'] = '-l en -a'
input_tokenizer['en-nl'] = '-l en -a'
input_tokenizer['en-pl'] = '-l en -a'
input_tokenizer['en-pt'] = '-l en -a'
input_tokenizer['en-ru'] = '-l en -a'
input_tokenizer['en-zh'] = '-l en -a'
|
# -*- coding: utf-8 -*-
#LoginForm
FORGOTTEN_PASS_BUTTON_TEXT = u"Passwort vergessen"
INVALID_LOGIN_TEXT = u"Benutzername / Kennwort ungültig"
LOGIN_ATTEMPTS_RESET_TEXT = u"Login Versuche zurücksetzen."
LOGIN_BUTTON_TEXT = u"Login"
LOGIN_HELP_TEXT = u"Von hier können Sie aus in Ihre Mitarbeiter-Account einloggen. Beide Benutzernamen, Passwörter und Kleinschreibung. Um die Software zu nutzen, müssen Sie ein Konto erstellen."
PASSWORD_LABEL_TEXT = u"Passwort"
LF_REGISTER_BUTTON_TEXT = u"Registrieren Neuer Mitarbeiter Konto"
SYSTEM_LOCKED_TEXT = u"System gesperrt"
TITLE_LABEL_LEFT_TEXT = u" Mitarbeiter \nTracker "
TITLE_LABEL_RIGHT_TEXT = u"\nBETA"
USERNAME_LABEL_TEXT = u"Benutzername"
|
"""
The TreeNode represents node in a Tree.
This module is perfect for Binary Tree but their implementation needs restructuring of the TreeNode
for other Tree types.
"""
class TreeNode(object):
"""
Node in a Tree has arguments
data,link[0]-leftlink,link[0]-right link
emptiness of a TreeNode is indicated by self.data==None
"""
### The Default Initializer
def __init__(self,data=None,link0=None,link1=None):
self.data=data
self.link=[]
self.link.append(link0)
self.link.append(link1)
### Data in the Tree Node is to be returned
def getData(self):
return self.data
### Compare Method needs to compare only the data.
### Since comparing the subTree Nodes depends on the Tree implementation
### B-Tree , B+ Tree , AVL, Binary Search Tree needs modifications in their compare method
### This TreeNode just need to care about the data present in it
###
### Compare Two Nodes
### -1 if self.data is less than that of arguments
### 0 if both are equal
### 1 if self.data is greater than that of argument
def compare(self,Node2):
if(self.data==None and Node2.data==None):
return True
if((self.data!=None and Node2.data==None) or (self.data!=None and Node2.data==None) ):
return False
if(self.data==Node2.data):
return True
else:
return False
NullNode=TreeNode()
|
#Task No. 3
def FindPath(graph,start,end,path=[]):
path = path + [start];
if (start == end):
return path
if (start not in graph):
return None
for node in graph[start]:
if node not in path:
path = FindPath(graph,node,end,path)
if path:
return path
return None
graph_1 = {1:[2,5],2:[1,3,5],3:[2,4],4:[3,5,6],5:[1,2,4],6:[4]}
print(FindPath(graph_1,6,1,[]))
|
class Node:
def __init__(self, value=None):
self.value = value
self.next = None
class linkedList:
def __init__(self):
self.head=None
self.tail=None
def __iter__ (self):
curNode = self.head
while curNode:
yield curNode
curNode=curNode.next
class Stack:
def __init__(self):
self.linkedList=linkedList()
def __str__(self):
if self.isEmpty():
return "Empty Stack"
else:
cal = [str(x.value) for x in self.linkedList]
return '\n'.join(cal)
def isEmpty(self):
if self.linkedList.head==None:
return True
else:
return False
def push(self,value):
node = Node(value)
node.next=self.linkedList.head
self.linkedList.head=node
def pop(self):
if self.isEmpty():
return "Empty Stack"
else:
nV=self.linkedList.head.value
self.linkedList.head = self.linkedList.head.next
return nV
def peek(self): #show the top element
if self.isEmpty():
return "Empty Stack"
else:
nV=self.linkedList.head.value
return nV
def deleteL(self):
self.linkedList.head=None
cStack = Stack()
print(cStack.isEmpty())
print(cStack.push(1))
print(cStack.push(2))
print(cStack.push(3))
print(cStack.push(4))
print(cStack)
print("0----")
print(cStack.pop())
print(cStack.peek())
|
#!/usr/bin/env python3
class Node:
def __init__(self, value, left=None, right=None) -> None:
self.value = value
self.left = left
self.right = right
def right_most_child_with_parent(self):
parent, curr = None, self
while curr.right:
parent = curr
curr = curr.right
return parent, curr
def second_largest(root):
if not root:
return None
prev, curr = root.right_most_child_with_parent()
if curr.left:
_, curr = curr.left.right_most_child_with_parent()
return curr.value
return prev.value if prev else prev
"""
7
/
4
/ \
3 5
"""
tree = Node(7, Node(4, Node(3), Node(5)))
assert second_largest(tree) == 5
"""
5
/ \
4 7
/ \
6 9
/
8
"""
tree = Node(5, Node(4), Node(7, Node(6), Node(9, Node(8))))
assert second_largest(tree) == 8
"""
5
"""
tree = Node(5)
assert second_largest(tree) == None
"""
5
\
7
\
10
/
9
/
8
"""
tree = Node(5, right=Node(7, right=Node(10, left=Node(9, left=Node(8)))))
assert second_largest(tree) == 9
|
#!/usr/bin/python
def is_member(item_to_check, list_to_check):
'''
Checks if an item is in a list
'''
for list_item in list_to_check:
if item_to_check == list_item:
return(True)
return(False)
|
"""Generics support via go_generics.
A Go template is similar to a go library, except that it has certain types that
can be replaced before usage. For example, one could define a templatized List
struct, whose elements are of type T, then instantiate that template for
T=segment, where "segment" is the concrete type.
"""
TemplateInfo = provider(
"Information about a go_generics template.",
fields = {
"unsafe": "whether the template requires unsafe code",
"types": "required types",
"opt_types": "optional types",
"consts": "required consts",
"opt_consts": "optional consts",
"deps": "package dependencies",
"template": "merged template source file",
},
)
def _go_template_impl(ctx):
srcs = ctx.files.srcs
template = ctx.actions.declare_file(ctx.label.name + "_template.go")
args = ["-o=%s" % template.path] + [f.path for f in srcs]
ctx.actions.run(
inputs = srcs,
outputs = [template],
mnemonic = "GoGenericsTemplate",
progress_message = "Building Go template %s" % ctx.label,
arguments = args,
executable = ctx.executable._tool,
)
return [TemplateInfo(
types = ctx.attr.types,
opt_types = ctx.attr.opt_types,
consts = ctx.attr.consts,
opt_consts = ctx.attr.opt_consts,
deps = ctx.attr.deps,
template = template,
)]
go_template = rule(
implementation = _go_template_impl,
attrs = {
"srcs": attr.label_list(doc = "the list of source files that comprise the template", mandatory = True, allow_files = True),
"deps": attr.label_list(doc = "the standard dependency list", allow_files = True, cfg = "target"),
"types": attr.string_list(doc = "the list of generic types in the template that are required to be specified"),
"opt_types": attr.string_list(doc = "the list of generic types in the template that can but aren't required to be specified"),
"consts": attr.string_list(doc = "the list of constants in the template that are required to be specified"),
"opt_consts": attr.string_list(doc = "the list of constants in the template that can but aren't required to be specified"),
"_tool": attr.label(executable = True, cfg = "host", default = Label("//tools/go_generics/go_merge")),
},
)
def _go_template_instance_impl(ctx):
info = ctx.attr.template[TemplateInfo]
output = ctx.outputs.out
# Check that all required types are defined.
for t in info.types:
if t not in ctx.attr.types:
fail("Missing value for type %s in %s" % (t, ctx.attr.template.label))
# Check that all defined types are expected by the template.
for t in ctx.attr.types:
if (t not in info.types) and (t not in info.opt_types):
fail("Type %s is not a parameter to %s" % (t, ctx.attr.template.label))
# Check that all required consts are defined.
for t in info.consts:
if t not in ctx.attr.consts:
fail("Missing value for constant %s in %s" % (t, ctx.attr.template.label))
# Check that all defined consts are expected by the template.
for t in ctx.attr.consts:
if (t not in info.consts) and (t not in info.opt_consts):
fail("Const %s is not a parameter to %s" % (t, ctx.attr.template.label))
# Build the argument list.
args = ["-i=%s" % info.template.path, "-o=%s" % output.path]
if ctx.attr.package:
args.append("-p=%s" % ctx.attr.package)
if len(ctx.attr.prefix) > 0:
args.append("-prefix=%s" % ctx.attr.prefix)
if len(ctx.attr.suffix) > 0:
args.append("-suffix=%s" % ctx.attr.suffix)
args += [("-t=%s=%s" % (p[0], p[1])) for p in ctx.attr.types.items()]
args += [("-c=%s=%s" % (p[0], p[1])) for p in ctx.attr.consts.items()]
args += [("-import=%s=%s" % (p[0], p[1])) for p in ctx.attr.imports.items()]
if ctx.attr.anon:
args.append("-anon")
ctx.actions.run(
inputs = [info.template],
outputs = [output],
mnemonic = "GoGenericsInstance",
progress_message = "Building Go template instance %s" % ctx.label,
arguments = args,
executable = ctx.executable._tool,
)
return [DefaultInfo(
files = depset([output]),
)]
go_template_instance = rule(
implementation = _go_template_instance_impl,
attrs = {
"template": attr.label(doc = "the label of the template to be instantiated", mandatory = True),
"prefix": attr.string(doc = "a prefix to be added to globals in the template"),
"suffix": attr.string(doc = "a suffix to be added to globals in the template"),
"types": attr.string_dict(doc = "the map from generic type names to concrete ones"),
"consts": attr.string_dict(doc = "the map from constant names to their values"),
"imports": attr.string_dict(doc = "the map from imports used in types/consts to their import paths"),
"anon": attr.bool(doc = "whether anoymous fields should be processed", mandatory = False, default = False),
"package": attr.string(doc = "the package for the generated source file", mandatory = False),
"out": attr.output(doc = "output file", mandatory = True),
"_tool": attr.label(executable = True, cfg = "host", default = Label("//tools/go_generics")),
},
)
|
def includeme(config):
# config.add_static_view('static', 'static', cache_max_age=3600)
config.add_route('home', '/')
config.add_route('hitori_boards', r'/hitori_boards')
config.add_route('hitori_board', r'/hitori_boards/{board_id:\d+}')
config.add_route('hitori_board_solve', r'/hitori_boards/{board_id:\d+}/solve')
config.add_route('hitori_board_clone', r'/hitori_boards/{board_id:\d+}/clone')
config.add_route('hitori_solves', r'/hitori_solves')
config.add_route('hitori_solve', r'/hitori_solves/{solve_id:\d+}')
config.add_route('hitori_cell_value', r'/hitori_cells/{cell_id:\d+}/value')
|
vetor = []
i = 1
while(i <= 100):
valor = int(input())
vetor.append(valor)
i = i + 1
print(max(vetor))
print(vetor.index(max(vetor)) + 1)
|
def test_length_ko_1_adb(style_checker):
"""Check length-ko-1.adb
"""
style_checker.set_year(2006)
p = style_checker.run_style_checker('gnat', 'length-ko-1.adb')
style_checker.assertNotEqual(p.status, 0, p.image)
style_checker.assertRunOutputEqual(p, """\
length-ko-1.adb:50:80: (style) this line is too long
""")
def test_length_ko_2_c(style_checker):
"""Check length-ko-2.c
"""
style_checker.set_year(2006)
p = style_checker.run_style_checker('gnat', 'length-ko-2.c')
style_checker.assertEqual(p.status, 0, p.image)
style_checker.assertRunOutputEmpty(p)
def test_misc_ok_1_c(style_checker):
"""Check misc-ok-1.c
"""
style_checker.set_year(2006)
p = style_checker.run_style_checker('gnat', 'misc-ok-1.c')
style_checker.assertEqual(p.status, 0, p.image)
style_checker.assertRunOutputEmpty(p)
|
"""Constants for dice-ml package."""
class BackEndTypes:
Sklearn = 'sklearn'
Tensorflow1 = 'TF1'
Tensorflow2 = 'TF2'
Pytorch = 'PYT'
class SamplingStrategy:
Random = 'random'
Genetic = 'genetic'
KdTree = 'kdtree'
|
"""Faça um programa que leia nome e média de um aluno, guardando também a situação em um dicionário.
No final, mostre o conteúdo da estrutura na tela."""
aluno = {}
nome = str(input('Nome: '))
aluno['Nome'] = nome
media = float(input(f'Média de {nome}: '))
aluno['Média'] = media
if media >= 7:
aluno['Situação'] = 'Aprovado(a)'
elif media >= 5:
aluno['Situação'] = 'Em recuperação'
else:
aluno['Situação'] = 'Reprovado(a)'
print('--' * 20)
for k, v in aluno.items():
print(f'{k} é igual a {v}')
|
class BasePairType:
def __init__( self, nt1, nt2, Kd, match_lowercase = False ):
'''
Two sequence characters that get matched to base pair, e.g., 'C' and 'G';
and the dissociation constant K_d (in M) associated with initial pair formation.
match_lowercase means match 'x' to 'x', 'y' to 'y', etc.
TODO: also store chemical modification info.
'''
self.nt1 = nt1
self.nt2 = nt2
self.Kd = Kd
self.match_lowercase = ( nt1 == '*' and nt2 == '*' and match_lowercase )
self.flipped = self # needs up be updated later.
def is_match( self, s1, s2 ):
if self.match_lowercase: return ( s1.islower() and s2.islower() and s1 == s2 )
return ( s1 == self.nt1 and s2 == self.nt2 )
def get_tag( self ):
if self.match_lowercase: return 'matchlowercase'
return self.nt1+self.nt2
def setup_base_pair_type( params, nt1, nt2, Kd, match_lowercase = False ):
if not hasattr( params, 'base_pair_types' ): params.base_pair_types = []
bpt1 = BasePairType( nt1, nt2, Kd, match_lowercase = match_lowercase )
params.base_pair_types.append( bpt1 )
if not match_lowercase:
bpt2 = BasePairType( nt2, nt1, Kd, match_lowercase = match_lowercase )
bpt1.flipped = bpt2
bpt2.flipped = bpt1
params.base_pair_types.append( bpt2 )
def get_base_pair_type_for_tag( params, tag ):
if not hasattr( params, 'base_pair_types' ): return None
for base_pair_type in params.base_pair_types:
if (tag == 'matchlowercase' and base_pair_type.match_lowercase) or \
(tag == base_pair_type.nt1 + base_pair_type.nt2 ):
return base_pair_type
#print( 'Could not figure out base_pair_type for ', tag )
return None
def get_base_pair_types_for_tag( params, tag ):
if not hasattr( params, 'base_pair_types' ): return None
if tag == 'WC':
WC_nts = [('C','G'),('G','C'),('A','U'),('U','A')] # ,('G','U'),('U','G')]
base_pair_types = []
for base_pair_type in params.base_pair_types:
if (base_pair_type.nt1,base_pair_type.nt2) in WC_nts:
base_pair_types.append( base_pair_type )
return base_pair_types
else:
return [ get_base_pair_type_for_tag( params, tag ) ]
return None
def initialize_base_pair_types( self ):
self.base_pair_types = []
|
# 상 우 하 좌
dx = [0, 1, 0, -1]
dy = [-1, 0, 1, 0]
mat = [
[0, 0, 1, 0],
[0, 0, 0, 1],
[0, 0, 0, 0],
[0, 1, 0, 0]
]
queue = []
for y in range(4):
for x in range(4):
if mat[y][x] == 1:
queue.append((y, x))
result = 0
while queue:
ny, nx = queue.pop(0)
for i in range(4):
ty, tx = ny + dy[i], nx + dx[i]
if 0 <= ty < 4 and 0 <= tx < 4 and mat[ty][tx] == 0:
mat[ty][tx] = mat[ny][nx] + 1
queue.append((ty, tx))
result = max(result, mat[ty][tx])
print(mat)
print(result)
|
def getdefaultencoding(space):
"""Return the current default string encoding used by the Unicode
implementation."""
return space.wrap(space.sys.defaultencoding)
def setdefaultencoding(space, w_encoding):
"""Set the current default string encoding used by the Unicode
implementation."""
encoding = space.str_w(w_encoding)
mod = space.getbuiltinmodule("_codecs")
w_lookup = space.getattr(mod, space.wrap("lookup"))
# check whether the encoding is there
space.call_function(w_lookup, w_encoding)
space.sys.w_default_encoder = None
space.sys.defaultencoding = encoding
def get_w_default_encoder(space):
w_encoding = space.wrap(space.sys.defaultencoding)
mod = space.getbuiltinmodule("_codecs")
w_lookup = space.getattr(mod, space.wrap("lookup"))
w_functuple = space.call_function(w_lookup, w_encoding)
w_encoder = space.getitem(w_functuple, space.wrap(0))
space.sys.w_default_encoder = w_encoder # cache it
return w_encoder
|
class StructLayoutAttribute(Attribute, _Attribute):
"""
Lets you control the physical layout of the data fields of a class or structure.
StructLayoutAttribute(layoutKind: LayoutKind)
StructLayoutAttribute(layoutKind: Int16)
"""
def __init__(self, *args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self, layoutKind):
"""
__new__(cls: type,layoutKind: LayoutKind)
__new__(cls: type,layoutKind: Int16)
"""
pass
Value = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Gets the System.Runtime.InteropServices.LayoutKind value that specifies how the class or structure is arranged.
Get: Value(self: StructLayoutAttribute) -> LayoutKind
"""
CharSet = None
Pack = None
Size = None
|
#lista de cores para menu:
#cor da letra
limpa = '\033[m'
Lbranco = '\033[30m'
Lvermelho = '\033[31m'
Lverde = '\033[32m'
Lamarelo = '\033[33m'
Lazul = '\033[34m'
Lroxo = '\033[35m'
Lazulclaro = '\033[36'
Lcinza = '\033[37'
#Fundo
Fbranco = '\033[40m'
Fvermelho = '\033[41m'
Fverde = '\033[42m'
Famarelo = '\033[43m'
Fazul = '\033[44m'
Froxo = '\033[45m'
Fazulclaro = '\033[46m'
Fcinza = '\033[46m'
|
def get_user_id(user_or_id):
if type(user_or_id) is str or type(user_or_id) is int:
return str(user_or_id)
elif hasattr(user_or_id, '__getitem__') and 'user_id' in user_or_id:
return str(user_or_id['user_id'])
elif hasattr(user_or_id, 'user_id'):
return str(user_or_id.user_id)
return None
def truncate_list_length(lst, length, *, add_per_element=0):
total_length = 0
for i, elem in enumerate(lst):
total_length += len(elem) + add_per_element
if total_length > length:
return lst[0:i]
return lst
def mention_users(users, max_count, max_length, *, join="\n", prefix=" - "):
trunc_users = users[0:max_count]
trunc_message = '_...and {} more._'
max_trunc_len = len(str(len(users)))
max_message_len = len(trunc_message.format(' ' * max_trunc_len))
final_max_len = max(0, max_length-max_message_len)
user_strs = truncate_list_length(
[f"{prefix}<@{get_user_id(user)}>" for user in trunc_users],
final_max_len,
add_per_element=len(join)
)
trunc_count = (len(users) - len(trunc_users)) + (len(trunc_users) - len(user_strs))
out_msg = join.join(user_strs) + (trunc_message and join + trunc_message.format(trunc_count) or '')
if (len(out_msg) > max_length) and final_max_len >= 3:
return '...'
elif len(out_msg) > max_length:
return ''
else:
return out_msg
def id_from_mention(mention):
try:
return int(mention.replace('<', '').replace('!', '').replace('>', '').replace('@', ''))
except:
return False
|
load("@io_bazel_rules_docker//container:container.bzl", _container_push = "container_push")
def container_push(*args, **kwargs):
"""Creates a script to push a container image to a Docker registry. The
target name must be specified when invoking the push script."""
if "registry" in kwargs:
fail(
"Cannot set 'registry' attribute on container_push",
attr = "registry",
)
if "repository" in kwargs:
fail(
"Cannot set 'repository' attribute on container_push",
attr = "repository",
)
kwargs["registry"] = "IGNORE"
kwargs["repository"] = "IGNORE"
_container_push(*args, **kwargs)
|
#!/usr/bin/env python
class bresenham:
def __init__(self, start, end):
self.start = list(start)
self.end = list(end)
self.path = []
self.steep = abs(self.end[1]-self.start[1]) > abs(self.end[0]-self.start[0])
if self.steep:
# print 'Steep'
self.start = self.swap(self.start[0],self.start[1])
self.end = self.swap(self.end[0],self.end[1])
if self.start[0] > self.end[0]:
# print 'flippin and floppin'
_x0 = int(self.start[0])
_x1 = int(self.end[0])
self.start[0] = _x1
self.end[0] = _x0
_y0 = int(self.start[1])
_y1 = int(self.end[1])
self.start[1] = _y1
self.end[1] = _y0
dx = self.end[0] - self.start[0]
dy = abs(self.end[1] - self.start[1])
error = 0
derr = dy/float(dx)
ystep = 0
y = self.start[1]
if self.start[1] < self.end[1]: ystep = 1
else: ystep = -1
for x in range(self.start[0],self.end[0]+1):
if self.steep:
self.path.append((y,x))
else:
self.path.append((x,y))
error += derr
if error >= 0.5:
y += ystep
error -= 1.0
def swap(self,n1,n2):
return [n2,n1]
"""
l = bresenham([8,1],[6,4])
print l.path
map = []
for x in range(0,15):
yc = []
for y in range(0,15):
yc.append('#')
map.append(yc)
for pos in l.path:
map[pos[0]][pos[1]] = '.'
for y in range(0,15):
for x in range(0,15):
print map[x][y],
print
"""
|
#
# PySNMP MIB module PROXY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PROXY-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:33:35 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, SingleValueConstraint, ValueSizeConstraint, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "SingleValueConstraint", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsIntersection")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
Unsigned32, Counter32, ModuleIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, Gauge32, Integer32, iso, Counter64, ObjectIdentity, MibIdentifier, IpAddress, NotificationType, TimeTicks, Bits, experimental = mibBuilder.importSymbols("SNMPv2-SMI", "Unsigned32", "Counter32", "ModuleIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Gauge32", "Integer32", "iso", "Counter64", "ObjectIdentity", "MibIdentifier", "IpAddress", "NotificationType", "TimeTicks", "Bits", "experimental")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
nsfnet = MibIdentifier((1, 3, 6, 1, 3, 25))
proxy = ModuleIdentity((1, 3, 6, 1, 3, 25, 17))
proxy.setRevisions(('1998-08-26 00:00',))
if mibBuilder.loadTexts: proxy.setLastUpdated('9809010000Z')
if mibBuilder.loadTexts: proxy.setOrganization('National Laboratory for Applied Network Research')
proxySystem = MibIdentifier((1, 3, 6, 1, 3, 25, 17, 1))
proxyConfig = MibIdentifier((1, 3, 6, 1, 3, 25, 17, 2))
proxyPerf = MibIdentifier((1, 3, 6, 1, 3, 25, 17, 3))
proxyMemUsage = MibScalar((1, 3, 6, 1, 3, 25, 17, 1, 1), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: proxyMemUsage.setStatus('current')
proxyStorage = MibScalar((1, 3, 6, 1, 3, 25, 17, 1, 2), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: proxyStorage.setStatus('current')
proxyCpuUsage = MibScalar((1, 3, 6, 1, 3, 25, 17, 1, 3), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: proxyCpuUsage.setStatus('current')
proxyUpTime = MibScalar((1, 3, 6, 1, 3, 25, 17, 1, 4), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: proxyUpTime.setStatus('current')
proxyAdmin = MibScalar((1, 3, 6, 1, 3, 25, 17, 2, 1), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: proxyAdmin.setStatus('current')
proxySoftware = MibScalar((1, 3, 6, 1, 3, 25, 17, 2, 2), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: proxySoftware.setStatus('current')
proxyVersion = MibScalar((1, 3, 6, 1, 3, 25, 17, 2, 3), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: proxyVersion.setStatus('current')
proxySysPerf = MibIdentifier((1, 3, 6, 1, 3, 25, 17, 3, 1))
proxyProtoPerf = MibIdentifier((1, 3, 6, 1, 3, 25, 17, 3, 2))
proxyCpuLoad = MibScalar((1, 3, 6, 1, 3, 25, 17, 3, 1, 1), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: proxyCpuLoad.setStatus('current')
proxyNumObjects = MibScalar((1, 3, 6, 1, 3, 25, 17, 3, 1, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: proxyNumObjects.setStatus('current')
proxyProtoClient = MibIdentifier((1, 3, 6, 1, 3, 25, 17, 3, 2, 1))
proxyProtoServer = MibIdentifier((1, 3, 6, 1, 3, 25, 17, 3, 2, 2))
proxyClientHttpRequests = MibScalar((1, 3, 6, 1, 3, 25, 17, 3, 2, 1, 1), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: proxyClientHttpRequests.setStatus('current')
proxyClientHttpHits = MibScalar((1, 3, 6, 1, 3, 25, 17, 3, 2, 1, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: proxyClientHttpHits.setStatus('current')
proxyClientHttpErrors = MibScalar((1, 3, 6, 1, 3, 25, 17, 3, 2, 1, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: proxyClientHttpErrors.setStatus('current')
proxyClientHttpInKbs = MibScalar((1, 3, 6, 1, 3, 25, 17, 3, 2, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: proxyClientHttpInKbs.setStatus('current')
proxyClientHttpOutKbs = MibScalar((1, 3, 6, 1, 3, 25, 17, 3, 2, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: proxyClientHttpOutKbs.setStatus('current')
proxyServerHttpRequests = MibScalar((1, 3, 6, 1, 3, 25, 17, 3, 2, 2, 1), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: proxyServerHttpRequests.setStatus('current')
proxyServerHttpErrors = MibScalar((1, 3, 6, 1, 3, 25, 17, 3, 2, 2, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: proxyServerHttpErrors.setStatus('current')
proxyServerHttpInKbs = MibScalar((1, 3, 6, 1, 3, 25, 17, 3, 2, 2, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: proxyServerHttpInKbs.setStatus('current')
proxyServerHttpOutKbs = MibScalar((1, 3, 6, 1, 3, 25, 17, 3, 2, 2, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: proxyServerHttpOutKbs.setStatus('current')
proxyMedianSvcTable = MibTable((1, 3, 6, 1, 3, 25, 17, 3, 3), )
if mibBuilder.loadTexts: proxyMedianSvcTable.setStatus('current')
proxyMedianSvcEntry = MibTableRow((1, 3, 6, 1, 3, 25, 17, 3, 3, 1), ).setIndexNames((0, "PROXY-MIB", "proxyMedianTime"))
if mibBuilder.loadTexts: proxyMedianSvcEntry.setStatus('current')
proxyMedianTime = MibTableColumn((1, 3, 6, 1, 3, 25, 17, 3, 3, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: proxyMedianTime.setStatus('current')
proxyHTTPAllSvcTime = MibTableColumn((1, 3, 6, 1, 3, 25, 17, 3, 3, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: proxyHTTPAllSvcTime.setStatus('current')
proxyHTTPMissSvcTime = MibTableColumn((1, 3, 6, 1, 3, 25, 17, 3, 3, 1, 3), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: proxyHTTPMissSvcTime.setStatus('current')
proxyHTTPHitSvcTime = MibTableColumn((1, 3, 6, 1, 3, 25, 17, 3, 3, 1, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: proxyHTTPHitSvcTime.setStatus('current')
proxyHTTPNhSvcTime = MibTableColumn((1, 3, 6, 1, 3, 25, 17, 3, 3, 1, 5), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: proxyHTTPNhSvcTime.setStatus('current')
proxyDnsSvcTime = MibTableColumn((1, 3, 6, 1, 3, 25, 17, 3, 3, 1, 6), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: proxyDnsSvcTime.setStatus('current')
mibBuilder.exportSymbols("PROXY-MIB", proxyStorage=proxyStorage, proxyMemUsage=proxyMemUsage, proxyServerHttpInKbs=proxyServerHttpInKbs, proxySystem=proxySystem, proxyAdmin=proxyAdmin, nsfnet=nsfnet, proxyHTTPHitSvcTime=proxyHTTPHitSvcTime, proxyUpTime=proxyUpTime, proxySoftware=proxySoftware, proxyClientHttpRequests=proxyClientHttpRequests, proxyServerHttpOutKbs=proxyServerHttpOutKbs, proxy=proxy, proxyPerf=proxyPerf, proxyProtoServer=proxyProtoServer, proxyProtoPerf=proxyProtoPerf, proxyNumObjects=proxyNumObjects, proxyDnsSvcTime=proxyDnsSvcTime, proxyMedianSvcEntry=proxyMedianSvcEntry, proxyHTTPAllSvcTime=proxyHTTPAllSvcTime, proxyConfig=proxyConfig, proxyMedianSvcTable=proxyMedianSvcTable, proxySysPerf=proxySysPerf, PYSNMP_MODULE_ID=proxy, proxyMedianTime=proxyMedianTime, proxyHTTPMissSvcTime=proxyHTTPMissSvcTime, proxyClientHttpOutKbs=proxyClientHttpOutKbs, proxyClientHttpInKbs=proxyClientHttpInKbs, proxyClientHttpErrors=proxyClientHttpErrors, proxyProtoClient=proxyProtoClient, proxyServerHttpErrors=proxyServerHttpErrors, proxyCpuLoad=proxyCpuLoad, proxyCpuUsage=proxyCpuUsage, proxyClientHttpHits=proxyClientHttpHits, proxyServerHttpRequests=proxyServerHttpRequests, proxyVersion=proxyVersion, proxyHTTPNhSvcTime=proxyHTTPNhSvcTime)
|
def removcaract(cnpj):
documento = []
for x in cnpj:
if x.isnumeric():
documento.append(x)
documento = ''.join(documento)
return documento
|
#!/usr/bin/env python
"""
_DQMCat_
"""
__all__ = []
|
class Solution:
def smallestDivisor(self, nums: List[int], threshold: int) -> int:
def condition(divisor) -> bool:
return sum((num - 1) // divisor + 1 for num in nums) <= threshold
lo, hi = 1, max(nums)
while lo < hi:
mid = lo + (hi - lo) // 2
if condition(mid):
hi = mid
else:
lo = mid + 1
return lo
|
# import numpy as np
# import matplotlib.pyplot as plt
#
# def f(t):
# return np.exp(-t) * np.cos(2*np.pi*t)
#
# t1 = np.arange(0.0, 5.0, 0.1)
# t2 = np.arange(0.0, 5.0, 0.02)
#
# plt.figure("2suplot")
# plt.subplot(211)
# plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
#
# plt.subplot(212)
# plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
# plt.show()
# plt.figure("2suplot222")
# plt.subplot(211)
# plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
#
# plt.subplot(212)
# plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
# plt.show()
if __name__ == '__main__':
print('程序自身在运行')
else:
print('我来自另一模块')
|
__author__ = 'maartenbreddels'
matplotlib = """import pylab
import numpy as np
import os
import json
import sys
name = "{name}" if len(sys.argv) == 1 else sys.argv[1]
filename_grid = name + "_grid.npy"
filename_grid_vector = name + "_grid_vector.npy"
filename_grid_selection = name + "_grid_selection.npy"
filename_meta = name + "_meta.json"
has_selection = os.path.exists(filename_grid_selection)
has_vectors = os.path.exists(filename_grid_vector)
meta = json.load(file(filename_meta))
grid = np.load(filename_grid)
xmin, xmax, ymin, ymax = meta["extent"]
if has_selection:
grid_selection = np.load(filename_grid_selection)
pylab.imshow(grid, extent=meta["extent"], origin="lower", cmap="binary")
pylab.imshow(grid_selection, alpha=0.4, extent=meta["extent"], origin="lower")
else:
pylab.imshow(grid, extent=meta["extent"], origin="lower")
if has_vectors:
vx, vy, vz = np.load(filename_grid_vector)
N = vx.shape[0]
dx = (xmax-xmin)/float(N)
dy = (ymax-ymin)/float(N)
x = np.linspace(xmin+dx/2, xmax-dx/2, N)
y = np.linspace(ymin+dy/2, ymax-dy/2, N)
x2d, y2d = np.meshgrid(x, y)
pylab.quiver(x2d, y2d, vx, vy, color="white")
pylab.show()
"""
|
"""This program finds the total number of possible combinations that can be used to
climb statirs . EG : for 3 stairs ,combination and output will be 1,1,1 , 1,2 , 2,1 i.e 3 . """
def counting_stairs(stair_number):
result = stair_number
# This function uses Recursion.
if(stair_number <=1):
result = 1
else:
result = (counting_stairs(stair_number-1) + counting_stairs(stair_number-2))
return result
if __name__ == '__main__':
count_stair = int(input("Enter total number of stairs: "))
print(f"Total Number of possible Combinations = {counting_stairs(count_stair)}")
"""Output
Total Number of possible Combinations = 8
Enter total number of stairs: 5
Time Complexity : O(2^n)
Space Complexity :O(1)
Created by Shubham Patel on 16-12-2020 on WoC
"""
|
def parse_eval_info(cur_eval_video_info):
length_eval_info = len(cur_eval_video_info)
cur_epoch = int(cur_eval_video_info[0].split(' ')[2].split('-')[1])
cur_video_auc = float(cur_eval_video_info[-1].split(' ')[-3].split('-')[1].split(',')[0])
return cur_epoch, cur_video_auc
file = '/home/mry/Desktop/seed-23197-time-31-Aug-at-07-35-19.log'
fr = open(file, 'r')
a = fr.readlines()
real_result_files_line = a[232:]
train_log_length_first = 11
train_log_length_common = 9
eval_log_length_list = [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
total_nme_print_length = 1
deliema_line_length = 1
final_block_line_list = []
per_num_length_first = (train_log_length_first + total_nme_print_length + deliema_line_length + sum(eval_log_length_list))
per_num_length_common = (train_log_length_common + total_nme_print_length + deliema_line_length + sum(eval_log_length_list))
epoch_num = 1 + (len(real_result_files_line)-per_num_length_first) // per_num_length_common
log_eval_info_list = []
model_count = 0
for epoch in range(epoch_num):
if epoch % 10 ==0:
start = per_num_length_first*model_count + per_num_length_common*(epoch-model_count)
end = start + per_num_length_first
all_info_of_curepoch = real_result_files_line[start : end]
#all_info_of_curepoch = real_result_files_line[epoch * per_num_length_first:epoch * per_num_length_first + per_num_length_first]
eval_info = all_info_of_curepoch[train_log_length_first:]
model_count += 1
else:
start = per_num_length_first*model_count + per_num_length_common*(epoch-model_count)
end = start + per_num_length_common
all_info_of_curepoch = real_result_files_line[start : end]
eval_info = all_info_of_curepoch[train_log_length_common:]
cur_epoch_dict = {}
cur_auc_list = []
video_info_dict = {}
vd_epoch = -1
for eval_video_id in range(len(eval_log_length_list)):
cur_eval_video_info = eval_info[eval_video_id*eval_log_length_list[eval_video_id]:(eval_video_id+1)*eval_log_length_list[eval_video_id]]
cur_epoch, cur_auc = parse_eval_info(cur_eval_video_info)
cur_auc_list.append(cur_auc)
vd_epoch = cur_epoch
cur_nme_list = [float(i) for i in eval_info[-2].strip().split(':')[1].split(',')]
video_info_dict['NME_total'] = cur_nme_list
video_info_dict['AUC0.08error'] = cur_auc_list
cur_epoch_dict[vd_epoch] = video_info_dict
log_eval_info_list.append(cur_epoch_dict)
pass
|
class ExitMixin():
def do_exit(self, _):
'''
Exit the shell.
'''
print(self._exit_msg)
return True
def do_EOF(self, params):
print()
return self.do_exit(params)
|
class Solution:
def calculateSum(self, N, A, B):
A_count = N//A
B_count = N//B
result = A*A_count*(1+A_count)//2 + B*B_count*(1+B_count)//2
a = min(A,B)
b = max(A,B)
while a > 0:
b, a= a, b%a
lcm = (A*B)//b
AB_count = (N - N%lcm)//lcm
return result - lcm*AB_count*(1+AB_count)//2
if __name__ == '__main__':
t = int(input())
for _ in range(t):
N,A,B = map(int,input().strip().split())
ob = Solution()
ans = ob.calculateSum(N, A, B)
print(ans)
|
def findDecision(obj): #obj[0]: Passanger, obj[1]: Weather, obj[2]: Time, obj[3]: Coupon, obj[4]: Coupon_validity, obj[5]: Gender, obj[6]: Age, obj[7]: Children, obj[8]: Education, obj[9]: Occupation, obj[10]: Income, obj[11]: Bar, obj[12]: Coffeehouse, obj[13]: Restaurant20to50, obj[14]: Direction_same, obj[15]: Distance
# {"feature": "Education", "instances": 85, "metric_value": 0.9774, "depth": 1}
if obj[8]<=2:
# {"feature": "Age", "instances": 68, "metric_value": 0.9944, "depth": 2}
if obj[6]<=5:
# {"feature": "Passanger", "instances": 60, "metric_value": 1.0, "depth": 3}
if obj[0]<=2:
# {"feature": "Occupation", "instances": 45, "metric_value": 0.9825, "depth": 4}
if obj[9]<=17:
# {"feature": "Bar", "instances": 42, "metric_value": 0.9587, "depth": 5}
if obj[11]<=3.0:
# {"feature": "Time", "instances": 40, "metric_value": 0.9341, "depth": 6}
if obj[2]<=3:
# {"feature": "Coupon_validity", "instances": 32, "metric_value": 0.8571, "depth": 7}
if obj[4]<=0:
# {"feature": "Coupon", "instances": 17, "metric_value": 0.9774, "depth": 8}
if obj[3]<=2:
# {"feature": "Children", "instances": 10, "metric_value": 0.7219, "depth": 9}
if obj[7]<=0:
return 'False'
elif obj[7]>0:
# {"feature": "Weather", "instances": 4, "metric_value": 1.0, "depth": 10}
if obj[1]<=0:
return 'False'
elif obj[1]>0:
return 'True'
else: return 'True'
else: return 'False'
elif obj[3]>2:
# {"feature": "Weather", "instances": 7, "metric_value": 0.8631, "depth": 9}
if obj[1]<=0:
# {"feature": "Coffeehouse", "instances": 5, "metric_value": 0.971, "depth": 10}
if obj[12]<=1.0:
# {"feature": "Income", "instances": 4, "metric_value": 0.8113, "depth": 11}
if obj[10]>2:
return 'True'
elif obj[10]<=2:
# {"feature": "Direction_same", "instances": 2, "metric_value": 1.0, "depth": 12}
if obj[14]<=0:
return 'False'
elif obj[14]>0:
return 'True'
else: return 'True'
else: return 'False'
elif obj[12]>1.0:
return 'False'
else: return 'False'
elif obj[1]>0:
return 'True'
else: return 'True'
else: return 'True'
elif obj[4]>0:
# {"feature": "Income", "instances": 15, "metric_value": 0.5665, "depth": 8}
if obj[10]<=5:
return 'False'
elif obj[10]>5:
# {"feature": "Coupon", "instances": 6, "metric_value": 0.9183, "depth": 9}
if obj[3]>2:
return 'False'
elif obj[3]<=2:
return 'True'
else: return 'True'
else: return 'False'
else: return 'False'
elif obj[2]>3:
# {"feature": "Restaurant20to50", "instances": 8, "metric_value": 0.9544, "depth": 7}
if obj[13]<=1.0:
# {"feature": "Coffeehouse", "instances": 5, "metric_value": 0.971, "depth": 8}
if obj[12]<=1.0:
return 'False'
elif obj[12]>1.0:
return 'True'
else: return 'True'
elif obj[13]>1.0:
return 'True'
else: return 'True'
else: return 'True'
elif obj[11]>3.0:
return 'True'
else: return 'True'
elif obj[9]>17:
return 'True'
else: return 'True'
elif obj[0]>2:
# {"feature": "Occupation", "instances": 15, "metric_value": 0.8366, "depth": 4}
if obj[9]<=10:
# {"feature": "Income", "instances": 13, "metric_value": 0.6194, "depth": 5}
if obj[10]>0:
return 'True'
elif obj[10]<=0:
# {"feature": "Coupon_validity", "instances": 3, "metric_value": 0.9183, "depth": 6}
if obj[4]>0:
return 'False'
elif obj[4]<=0:
return 'True'
else: return 'True'
else: return 'False'
elif obj[9]>10:
return 'False'
else: return 'False'
else: return 'True'
elif obj[6]>5:
# {"feature": "Time", "instances": 8, "metric_value": 0.5436, "depth": 3}
if obj[2]<=1:
return 'True'
elif obj[2]>1:
return 'False'
else: return 'False'
else: return 'True'
elif obj[8]>2:
# {"feature": "Occupation", "instances": 17, "metric_value": 0.7871, "depth": 2}
if obj[9]<=20:
# {"feature": "Coupon_validity", "instances": 16, "metric_value": 0.6962, "depth": 3}
if obj[4]<=0:
return 'True'
elif obj[4]>0:
# {"feature": "Time", "instances": 8, "metric_value": 0.9544, "depth": 4}
if obj[2]<=1:
# {"feature": "Coffeehouse", "instances": 5, "metric_value": 0.971, "depth": 5}
if obj[12]>1.0:
# {"feature": "Passanger", "instances": 3, "metric_value": 0.9183, "depth": 6}
if obj[0]<=1:
return 'True'
elif obj[0]>1:
return 'False'
else: return 'False'
elif obj[12]<=1.0:
return 'False'
else: return 'False'
elif obj[2]>1:
return 'True'
else: return 'True'
else: return 'True'
elif obj[9]>20:
return 'False'
else: return 'False'
else: return 'True'
|
class Cup:
def __init__(self,size,quantity):
self.size = size
self.quantity = quantity
def status(self):
return self.size-self.quantity
def fill(self, quantity):
if self.quantity<=self.status():
self.quantity+=quantity
cup = Cup(100, 50)
print(cup.status())
cup.fill(40)
cup.fill(20)
print(cup.status())
|
__author__ = 'croxis'
def convertToPatches(model):
"""Sets up a model for autotesselation."""
for node in model.find_all_matches("**/+GeomNode"):
geom_node = node.node()
num_geoms = geom_node.get_num_geoms()
for i in range(num_geoms):
geom_node.modify_geom(i).make_patches_in_place()
|
class BinaryConfusionMatrix:
def __init__(self, pos_tag="SPAM", neg_tag="OK"):
self.pos_tag = pos_tag
self.neg_tag = neg_tag
self.tp = 0
self.tn = 0
self.fp = 0
self.fn = 0
def as_dict(self):
return {"tp": self.tp, "tn": self.tn, "fp": self.fp, "fn": self.fn}
def _is_correct_values(self, value1, value2):
correct_values = [self.pos_tag, self.neg_tag]
return value1 in correct_values and value2 in correct_values
def update(self, truth, prediction):
if not self._is_correct_values(truth, prediction):
raise ValueError()
if truth == self.pos_tag:
if prediction == self.pos_tag:
self.tp += 1
else:
self.fn += 1
else:
if prediction == self.neg_tag:
self.tn += 1
else:
self.fp += 1
def compute_from_dicts(self, truth_dict, pred_dict):
for filename, truth in truth_dict.items():
self.update(truth, pred_dict[filename])
def quality_score(self, tp, tn, fp, fn):
return (tp + tn) / (tp + tn + 10 * fp + fn)
|
def karp_rabin(text, word, n, m):
MOD = 257
A = random.randint(2, MOD - 1)
Am = pow(A, m, MOD)
def generate(t):
return sum(ord(c) * pow(A, i, MOD) for i, c in enumerate(t[::-1])) % MOD
text += '$'
hash_text, hash_word = generate(text[1:m + 1]), generate(word[1:])
for i in range(1, n - m + 2):
if hash_text == hash_word and text[i:i + m] == word[1:]:
yield i
hash_text = (A * hash_text + ord(text[i + m]) - Am * ord(text[i])) % MOD
|
class Programa:
def __init__(self, nome, ano):
self._nome = nome.title()
self.ano = ano
self._likes = 0
@property
def likes(self):
return self._likes
def dar_like(self):
self._likes += 1
@property
def nome(self):
return self._nome
@nome.setter
def nome(self, novo_nome):
self._nome = novo_nome.title()
def __str__(self):
return f"{self.nome} - {self.ano} - {self.likes} Likes"
class Filme(Programa):
def __init__(self, nome, ano, duracao):
super().__init__(nome, ano)
self.duracao = duracao
def __str__(self):
return f"{self.nome} - {self.ano} - {self.duracao} min - {self.likes} Likes"
class Serie(Programa):
def __init__(self, nome, ano, temporadas):
super().__init__(nome, ano)
self.temporadas = temporadas
def __str__(self):
return f"{self.nome} - {self.ano} - {self.temporadas} temporadas - {self.likes} Likes"
class Playlist:
def __init__(self, nome, programas):
self.nome = nome
self._programas = programas
def __getitem__(self, item):
return self._programas[item]
@property
def listagem(self):
return self._programas
def __len__(self):
return len(self._programas)
vingadores = Filme("Vingadores - Guerra infinita", 2018, 160)
atlanta = Serie("Atlanta", 2018, 2)
tmep = Filme("Todo mundo em pânico", 1999, 100)
demolidor = Serie("Demolidor", 2016, 2)
vingadores.dar_like()
tmep.dar_like()
tmep.dar_like()
tmep.dar_like()
tmep.dar_like()
demolidor.dar_like()
demolidor.dar_like()
atlanta.dar_like()
atlanta.dar_like()
atlanta.dar_like()
filmes_e_series = [vingadores, atlanta, tmep]
playlist_fim_de_semana = Playlist("fim de semana", filmes_e_series)
print(f"Tamanho do Playlist: {len(playlist_fim_de_semana)}")
print(playlist_fim_de_semana[0])
for programa in playlist_fim_de_semana.listagem:
print(programa)
|
n = 1000000
# n = 100
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
primes = []
for i in range(2,n+1):
if prime[i]:
primes.append(i)
count = 0
ans = 0
for index,elem in enumerate(primes):
sum = 0
temp = 0
for i in range(index,len(primes)):
sum += primes[i]
temp +=1
if sum > n:
break
if prime[sum]:
if count < temp:
ans = sum
count = temp
print(ans,count)
|
STARLARK_BINARY_PATH = {
"java": "external/io_bazel/src/main/java/net/starlark/java/cmd/Starlark",
"go": "external/net_starlark_go/cmd/starlark/*/starlark",
"rust": "external/starlark-rust/target/debug/starlark-repl",
}
STARLARK_TESTDATA_PATH = "test_suite/"
|
#
# @lc app=leetcode id=868 lang=python3
#
# [868] Binary Gap
#
# @lc code=start
class Solution:
def binaryGap(self, N: int) -> int:
s = bin(N)
res = 0
i = float('inf')
for j, n in enumerate(s[2:]):
if n == '1':
res = max(res, j - i)
i = j
return res
# @lc code=end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.