content stringlengths 7 1.05M |
|---|
class SemesterNotFoundException(Exception):
# Invalid semester or module does not take place during the specified semester
def __init__(self, semester, *args):
super().__init__(args)
self.semester = semester
def __str__(self):
return f'No valid modules found for semester {self.semester}'
class YearNotFoundException(Exception):
# Invalid year
def __init__(self, year, *args):
super().__init__(args)
self.year = year
def __str__(self):
return f'No valid modules found for academic year {self.year}'
class CalendarOutOfRangeError(Exception):
# data for the year not present in database
def __init__(self, *args):
super().__init__(args)
def __str__(self):
return 'Current date does not fall within any given date boundaries'
|
class Solution:
def findMissingRanges(self, nums: List[int], lower: int, upper: int) -> List[str]:
"""Array.
Running time: O(n) where n == len(nums).
"""
res = []
nxt = lower
for i in range(len(nums)):
if nums[i] < nxt:
continue
if nums[i] == nxt:
nxt += 1
continue
self._append_range(nxt, nums[i] - 1, res)
nxt = nums[i] + 1
self._append_range(nxt, upper, res)
return res
def _append_range(self, lo, hi, res):
if lo == hi:
res.append(str(lo))
elif lo < hi:
res.append(str(lo) + '->' + str(hi))
|
# Working with strings
print("Hello world!")
# Combine strings
language = "Python"
print("I learning " + language)
# Convert to string
age = 23
print("I'm " + str(age) + " old.") |
class Vertex:
def __init__(self, node):
self.id = node
self.cons = {}
def add_con(self, con, weight):
self.cons[con] = weight
def get_cons(self):
return self.cons.keys()
def get_id(self):
return self.id
def get_weight(self, con):
return self.cons[con]
class Graph:
def __init__(self):
self.verticies = {}
def add_vertex(self, node):
self.verticies[node] = Vertex(node)
return self.verticies[node]
def add_edge(self, frm, to, weight):
if frm not in self.verticies:
self.add_edge(frm)
if to not in self.verticies:
self.add_edge(to)
self.verticies[frm].add_con(self.verticies[to], weight)
self.verticies[to].add_con(self.verticies[frm], weight)
def get_verticies(self):
return self.verticies.keys() |
def solve():
fib = [1, 2]
even = [2]
while sum(fib[-2:]) <= 4000000:
number = sum(fib[-2:])
if number % 2:
even.append(number)
fib.append(number)
return sum(even)
def main():
print(f"{solve()=}")
if __name__ == "__main__":
main()
|
# -*- mode: python -*-
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
DOCUMENTATION = '''
---
author: "Benno Joy (@bennojoy)"
module: include_vars
short_description: Load variables from files, dynamically within a task.
description:
- Loads variables from a YAML/JSON file dynamically during task runtime. It can work with conditionals, or use host specific variables to determine the path name to load from.
options:
file:
version_added: "2.2"
description:
- The file name from which variables should be loaded.
- If the path is relative, it will look for the file in vars/ subdirectory of a role or relative to playbook.
name:
version_added: "2.2"
description:
- The name of a variable into which assign the included vars, if omitted (null) they will be made top level vars.
default: null
free-form:
description:
- This module allows you to specify the 'file' option directly w/o any other options.
notes:
- The file is always required either as the explicit option or using the free-form.
version_added: "1.4"
'''
EXAMPLES = """
# Include vars of stuff.yml into the 'stuff' variable (2.2).
- include_vars:
file: stuff.yml
name: stuff
# Conditionally decide to load in variables into 'plans' when x is 0, otherwise do not. (2.2)
- include_vars: file=contingency_plan.yml name=plans
when: x == 0
# Load a variable file based on the OS type, or a default if not found.
- include_vars: "{{ item }}"
with_first_found:
- "{{ ansible_distribution }}.yml"
- "{{ ansible_os_family }}.yml"
- "default.yml"
# bare include (free-form)
- include_vars: myvars.yml
"""
|
n = int(input())
a = list(map(int, input().split()))
cnt = [0] * 1010
for num in a:
cnt[num] += 1
for i in range(1, 1000 + 1):
if cnt[i] > 1:
print('No')
quit()
print('Yes')
|
class Worker:
"""
Abstract class to define the basic structure of
a specif type of worker.
"""
def __init__(self):
"""
Initialize worker instance.
"""
raise NotImplementedError
def run(self):
"""
Logic to be executed on each iteration.
"""
raise NotImplementedError
def do_work(self):
"""
Performs a specific type of work.
"""
raise NotImplementedError
class TimedWorker(Worker):
def __init__(self, wait_time):
"""
Initialize timed worker class.
"""
self.wait_time = wait_time
def run(self, shutdown_event):
"""
Calls do_work method inside an infinite loop and
wait n seconds to receive a shutdown event before
calling do_work again.
"""
do_work = True
while not shutdown_event.is_set():
try:
if do_work:
self.do_work()
shutdown_event.wait(self.wait_time)
except KeyboardInterrupt:
do_work = False |
class Solution(object):
def reverse(self, x):
res = 0
ax = abs(x)
while ax != 0:
pop = ax % 10
ax = int(ax/10)
res = res * 10 + pop
if (x < 0):
res *= -1
return res
b = -123 % -10
a = Solution().reverse(-123) |
def bs_decode(binary: str, key: str) -> int:
sum = 0
last_idx = 0
for i, s in enumerate(binary):
if s == '0':
continue
elif s == '1':
sum += int(key[last_idx: i + 1])
last_idx = i + 1
else:
assert False
sum += int(key[last_idx:])
return sum
def binary_search(binary: str, key: str) -> int:
if len(binary) == len(key) - 1:
return bs_decode(binary, key)
else:
return binary_search(binary + '0', key) + binary_search(binary + '1', key)
def main():
S = input()
print(binary_search('', S))
if __name__ == "__main__":
main()
|
class ElementPositionBound(
ElementPositioning,
):
pass
|
counter = 0
#we go through two for loops
#first is for power
for i in range(1,50):
#and second is for number
for j in range(1,50):
#we turn j**i into string
#and if lenght of that string is equal to i (power)
if len(str(j**i)) == i:
#then counter increases by 1
counter += 1
#we print counter
print(counter) |
class UnknownDeviceError(Exception):
pass
class DenyError(Exception):
pass
class WrongP1P2Error(Exception):
pass
class WrongDataLengthError(Exception):
pass
class InsNotSupportedError(Exception):
pass
class ClaNotSupportedError(Exception):
pass
class WrongResponseLengthError(Exception):
pass
class DisplayAddressFailError(Exception):
pass
class DisplayAmountFailError(Exception):
pass
class WrongTxLengthError(Exception):
pass
class TxParsingFailError(Exception):
pass
class TxHashFail(Exception):
pass
class BadStateError(Exception):
pass
class SignatureFailError(Exception):
pass
class TxRejectSignError(Exception):
pass
class BIP44BadPurposeError(Exception):
pass
class BIP44BadCoinTypeError(Exception):
pass
class BIP44BadAccountNotHardenedError(Exception):
pass
class BIP44BadAccountError(Exception):
pass
class BIP44BadBadChangeError(Exception):
pass
class BIP44BadAddressError(Exception):
pass
class MagicParsingError(Exception):
pass
class DisplaySystemFeeFailError(Exception):
pass
class DisplayNetworkFeeFailError(Exception):
pass
class DisplayTotalFeeFailError(Exception):
pass
class DisplayTransferAmountError(Exception):
pass
class ConvertToAddressFailError(Exception):
pass
|
class SubscriberOne:
def __init__(self, name):
self.name = name
def update(self, message):
print('{} got message "{}"'.format(self.name, message))
class SubscriberTwo:
def __init__(self, name):
self.name = name
def receive(self, message):
print('{} got message "{}"'.format(self.name, message))
class Publisher:
def __init__(self):
self.subscribers = dict()
def register(self, who, callback=None):
if callback == None:
callback = getattr(who, 'update')
self.subscribers[who] = callback
def unregister(self, who):
del self.subscribers[who]
def dispatch(self, message):
for subscriber, callback in self.subscribers.items():
callback(message)
|
_help = "ping local machine" # help is always optional
name = "ping" # name must be defined if loading command using CommandModule
def ping():
print("Pong!")
|
#-*- coding:utf-8 -*-
class QuickFind(object):
def __init__(self,objnum):
self.id=[i for i in range(0,objnum)]
def union(self,p,q):
qid=self.id[q]
pid=self.id[p]
j=0
for v in self.id:
if pid==v:
self.id[j]=qid
j=j+1
def connected(self,q,p):
return self.id[q]==self.id[p]
class QuickUnion(object):
def __init__(self,objnum):
self.id=[i for i in range(0,objnum)]
def _root(self,obj):
i=obj
while i!=self.id[i]:
i=self.id[i]
return i
def union(self,p,q):
qroot=self._root(q)
proot=self._root(p)
self.id[proot]=qroot
def connected(self,q,p):
return self._root(q)==self._root(p)
class QuickUnionWithWeighted(object):
r'''
quick union with weighted tree
'''
def __init__(self,objnum):
self.id=[i for i in range(0,objnum)]
self.sz=[0 for i in range(0,objnum)]
def _root(self,obj):
i=obj
while i!=self.id[i]:
i=self.id[i]
return i
def union(self,p,q):
qroot=self._root(q)
proot=self._root(p)
if self.sz[q]>=self.sz[p]:
self.id[proot]=qroot
self.sz[qroot]=self.sz[qroot]+self.sz[proot]
else:
self.id[qroot]=proot
self.sz[proot]+=self.sz[qroot]
def connected(self,q,p):
return self._root(q)==self._root(p)
if __name__=='__main__':
#uf=QuickFind(10)
#uf=QuickUnion(20)
uf=QuickUnionWithWeighted(20)
uf.union(1,4)
uf.union(0,9)
print('1 connected 4',uf.connected(1,4))
print('0 connected 9',uf.connected(0,9))
print('4 connected 3',uf.connected(4,3))
print(uf.id)
print('union 4 to 3')
uf.union(4,3)
print(uf.id)
print('4 connected 3',uf.connected(4,3))
print('1 connected 3',uf.connected(3,1))
|
# parsetab_astmatch.py
# This file is automatically generated. Do not edit.
_tabversion = '3.2'
_lr_method = 'LALR'
_lr_signature = b'\x87\xfc\xcf\xdfD\xa2\x85\x13Hp\xa3\xe5Xz\xbcp'
_lr_action_items = {'SPECIAL':([0,2,4,5,6,7,8,9,10,11,12,13,15,16,17,18,19,],[-13,3,-13,-13,-13,-9,-8,-7,3,-6,3,3,3,-12,-13,-2,3,]),'OR':([0,2,4,5,6,7,8,9,10,11,12,13,15,16,17,18,19,],[-13,4,-13,-13,-13,-9,-8,-7,4,-6,4,4,4,-12,-13,-2,4,]),'NOT':([0,2,4,5,6,7,8,9,10,11,12,13,15,16,17,18,19,],[-13,5,-13,-13,-13,-9,-8,-7,5,-6,5,5,5,-12,-13,-2,5,]),'CODE':([0,2,4,5,6,7,8,9,10,11,12,13,15,16,17,18,19,],[-13,9,-13,-13,-13,-9,-8,-7,9,-6,9,9,9,-12,-13,-2,9,]),'LBK':([0,2,4,5,6,7,8,9,10,11,12,13,15,16,17,18,19,],[-13,6,-13,-13,-13,-9,-8,-7,6,-6,6,6,6,-12,-13,-2,6,]),'WORD':([3,],[11,]),'COMMA':([4,5,6,7,8,9,11,12,13,14,15,16,17,18,19,],[-13,-13,-5,-9,-8,-7,-6,-10,-11,17,-3,-12,-13,-2,-4,]),'$end':([0,1,2,4,5,7,8,9,11,12,13,16,18,],[-13,0,-1,-13,-13,-9,-8,-7,-6,-10,-11,-12,-2,]),'RBK':([4,5,6,7,8,9,11,12,13,14,15,16,17,18,19,],[-13,-13,-5,-9,-8,-7,-6,-10,-11,18,-3,-12,-13,-2,-4,]),'STAR':([0,2,4,5,6,7,8,9,10,11,12,13,15,16,17,18,19,],[-13,-13,-13,-13,-13,-9,-8,-7,16,-6,-10,-11,-13,-12,-13,-2,-13,]),}
_lr_action = { }
for _k, _v in _lr_action_items.items():
for _x,_y in zip(_v[0],_v[1]):
if not _x in _lr_action: _lr_action[_x] = { }
_lr_action[_x][_k] = _y
del _lr_action_items
_lr_goto_items = {'ast_match':([0,],[1,]),'ast_special':([2,10,12,13,15,19,],[8,8,8,8,8,8,]),'ast_exprlist':([6,],[14,]),'ast_expr':([0,2,4,5,6,10,12,13,15,17,19,],[2,10,12,13,15,10,10,10,10,19,10,]),'ast_set':([2,10,12,13,15,19,],[7,7,7,7,7,7,]),}
_lr_goto = { }
for _k, _v in _lr_goto_items.items():
for _x,_y in zip(_v[0],_v[1]):
if not _x in _lr_goto: _lr_goto[_x] = { }
_lr_goto[_x][_k] = _y
del _lr_goto_items
_lr_productions = [
("S' -> ast_match","S'",1,None,None,None),
('ast_match -> ast_expr','ast_match',1,'p_ast_match','c:\\dev\\fairmotion\\tools\\extjs_cc\\js_ast_match.py',46),
('ast_set -> LBK ast_exprlist RBK','ast_set',3,'p_ast_set','c:\\dev\\fairmotion\\tools\\extjs_cc\\js_ast_match.py',52),
('ast_exprlist -> ast_expr','ast_exprlist',1,'p_ast_exprlist','c:\\dev\\fairmotion\\tools\\extjs_cc\\js_ast_match.py',60),
('ast_exprlist -> ast_exprlist COMMA ast_expr','ast_exprlist',3,'p_ast_exprlist','c:\\dev\\fairmotion\\tools\\extjs_cc\\js_ast_match.py',61),
('ast_exprlist -> <empty>','ast_exprlist',0,'p_ast_exprlist','c:\\dev\\fairmotion\\tools\\extjs_cc\\js_ast_match.py',62),
('ast_special -> SPECIAL WORD','ast_special',2,'p_ast_noderef','c:\\dev\\fairmotion\\tools\\extjs_cc\\js_ast_match.py',76),
('ast_expr -> ast_expr CODE','ast_expr',2,'p_ast_expr','c:\\dev\\fairmotion\\tools\\extjs_cc\\js_ast_match.py',82),
('ast_expr -> ast_expr ast_special','ast_expr',2,'p_ast_expr','c:\\dev\\fairmotion\\tools\\extjs_cc\\js_ast_match.py',83),
('ast_expr -> ast_expr ast_set','ast_expr',2,'p_ast_expr','c:\\dev\\fairmotion\\tools\\extjs_cc\\js_ast_match.py',84),
('ast_expr -> ast_expr OR ast_expr','ast_expr',3,'p_ast_expr','c:\\dev\\fairmotion\\tools\\extjs_cc\\js_ast_match.py',85),
('ast_expr -> ast_expr NOT ast_expr','ast_expr',3,'p_ast_expr','c:\\dev\\fairmotion\\tools\\extjs_cc\\js_ast_match.py',86),
('ast_expr -> ast_expr ast_expr STAR','ast_expr',3,'p_ast_expr','c:\\dev\\fairmotion\\tools\\extjs_cc\\js_ast_match.py',87),
('ast_expr -> <empty>','ast_expr',0,'p_ast_expr','c:\\dev\\fairmotion\\tools\\extjs_cc\\js_ast_match.py',88),
]
|
def print_max(a, b):
if a > b:
print(a, 'is maximum')
elif a == b:
print(a, 'is equal to', b)
else:
print(b, 'is maximum')
# directly pass literal values
print_max(3, 4)
x = 5
y = 7
# pass variables as arguments
print_max(x, y) |
tags = [
{
"name": "droplet_tag",
"resources": {
"count": 10,
"last_tagged_uri": "https://api.digitalocean.com/v2/droplets/246753544",
"droplets": {
"count": 7,
"last_tagged_uri": "https://api.digitalocean.com/v2/droplets/246753544",
},
"images": {"count": 0},
"volumes": {"count": 0},
"volume_snapshots": {"count": 0},
"databases": {"count": 0},
},
},
{
"name": "image_tag",
"resources": {
"count": 6,
"last_tagged_uri": "https://api.digitalocean.com/v2/droplets/246753544",
"droplets": {
"count": 3,
"last_tagged_uri": "https://api.digitalocean.com/v2/droplets/246753544",
},
"images": {"count": 0},
"volumes": {
"count": 1,
"last_tagged_uri": "https://api.digitalocean.com/v2/volumes/0e811232-4ea5-11ec-b6b7-246753544456",
},
"volume_snapshots": {"count": 0},
"databases": {"count": 0},
},
},
{
"name": "volume_tag",
"resources": {
"count": 0,
"droplets": {"count": 0},
"images": {"count": 0},
"volumes": {"count": 0},
"volume_snapshots": {"count": 0},
"databases": {"count": 0},
},
},
{
"name": "snapshot_tag",
"resources": {
"count": 0,
"droplets": {"count": 0},
"images": {"count": 0},
"volumes": {"count": 0},
"volume_snapshots": {"count": 0},
"databases": {"count": 0},
},
},
{
"name": "database_tag",
"resources": {
"count": 1,
"last_tagged_uri": "https://api.digitalocean.com/v2/load_balancers/ce34912e-07e3-4bde-97ca-246753544f3e",
"droplets": {"count": 0},
"images": {"count": 0},
"volumes": {"count": 0},
"volume_snapshots": {"count": 0},
"databases": {"count": 0},
},
},
{
"name": "firewall_tag",
"resources": {
"count": 1,
"last_tagged_uri": "https://api.digitalocean.com/v2/load_balancers/ce34912e-07e3-4bde-97ca-246753544f3e",
"droplets": {"count": 0},
"images": {"count": 0},
"volumes": {"count": 0},
"volume_snapshots": {"count": 0},
"databases": {"count": 0},
},
},
]
|
# local imports
# project imports
# external imports
def mine(attributes, data):
sums = {}
counts = {}
averages = {}
for attribute in attributes:
sums[attribute] = float(0)
counts[attribute] = 0
for entry in data:
for attribute in attributes:
if entry[attribute] is not None:
sums[attribute] += entry[attribute]
counts[attribute] += 1
for attribute in attributes:
averages[attribute] = sums[attribute] / counts[attribute] if counts[attribute] > 0 else None
return averages
|
del_items(0x800A1318)
SetType(0x800A1318, "char StrDate[12]")
del_items(0x800A1324)
SetType(0x800A1324, "char StrTime[9]")
del_items(0x800A1330)
SetType(0x800A1330, "char *Words[118]")
del_items(0x800A1508)
SetType(0x800A1508, "struct MONTH_DAYS MonDays[12]")
|
def method (a, n):
p = 1
x = a
while n != 0:
if n % 2 == 1:
p *= x
n = n // 2
x *= x
return p
print(method(3, 5))
|
# Authors: Sylvain MARIE <sylvain.marie@se.com>
# + All contributors to <https://github.com/smarie/python-pytest-cases>
#
# License: 3-clause BSD, <https://github.com/smarie/python-pytest-cases/blob/master/LICENSE>
def test_pytest_cases_plugin_installed(request):
"""A simple test to make sure that the pytest-case plugin is actually installed. Otherwise some tests wont work"""
assert request.session._fixturemanager.getfixtureclosure.func.__module__ == 'pytest_cases.plugin'
|
rcparams = {
"svg.fonttype": "none",
"pdf.fonttype": 42,
"savefig.transparent": True,
"figure.figsize": (4, 4),
"axes.titlesize": 15,
"axes.titleweight": 500,
"axes.titlepad": 8.0,
"axes.labelsize": 14,
"axes.labelweight": 500,
"axes.linewidth": 1.2,
"axes.labelpad": 6.0,
"font.size": 11,
"font.family": "sans-serif",
"font.sans-serif": [
"Helvetica",
"Computer Modern Sans Serif",
"DejaVU Sans",
],
"font.weight": 500,
"xtick.labelsize": 12,
"xtick.minor.size": 1.375,
"xtick.major.size": 2.75,
"xtick.major.pad": 2,
"xtick.minor.pad": 2,
"ytick.labelsize": 12,
"ytick.minor.size": 1.375,
"ytick.major.size": 2.75,
"ytick.major.pad": 2,
"ytick.minor.pad": 2,
"legend.fontsize": 12,
"legend.handlelength": 1.4,
"legend.numpoints": 1,
"legend.scatterpoints": 3,
"legend.frameon": False,
"lines.linewidth": 1.7,
}
|
"""
Test raising an exception, to check how tdiff (formerly clogdiff) handles it
"""
cases = [
('Raise an exception - does traceback go to .log file?',
'python -c "raise Exception"')
]
|
# Escrêva um programa que leia um valor em metros e exiba ele convertido em centimetros e milimetros.
print('Conversor de metros para centimetros e milimetros.')
metro = float(input('Quantos metros? : '))
centimetros = metro*100
milimetros = centimetros*10
print('Você digitou o valor de "{} metros"'.format(metro))
print('Convertendo para centimetros{}'.format('.'*3))
print('O valor em centimetros é de "{:.0f} cm"'.format(centimetros))
print('Convertendo para milimetros{}'.format('.'*3))
print('O valor em milimetros é de "{:.0f} mm"'.format(milimetros)) |
input = """
b :- not c.
a :- b.
b :- a.
c :- b, not k.
e v e1.
e v e2.
e v e3.
e v e4.
e v e5.
:- not e, not a.
k v k1.
k v k2.
k v k3.
k v k4.
k v k5.
k v k6.
c v c1.
"""
output = """
{a, b, c1, e, k}
{a, b, c1, e1, e2, e3, e4, e5, k}
{c, e, k1, k2, k3, k4, k5, k6}
{c, e, k}
"""
|
def conta_alertas_acude(lista):
cont=0
for i in range(len(lista)):
if lista[i]<17:
if i== 0:
if abs(lista[i]-17)<10:
cont+=1
else:
if abs(lista[i]-lista[i-1])<10:
cont+=1
return cont
|
#
# Main function with the simple pattern check
#
def main():
# First, we need to let the user enter the string
print("String pattern check with python!")
print("Please enter a string to validate: ")
strInput = input()
if (not validateStringInput(strInput)):
print("Invalid string entered. Please enter a string longer than one character!")
exit(-1)
print("What pattern do you want to check, against? Use * for multiple joker characters and ? for single joker characters.")
strPattern = input()
if (not validatePattern(strPattern)):
print("Ambiguous pattern entered. If * is followed by ? or ? is followed by *, the pattern is ambiguous!")
exit(-1)
# Next, we validate the string and return the results.
print("Validating string '%s'..." % strInput)
isMatch = ValidateStringAgainstPattern(strInput, strPattern)
isMatchString = "MATCHES" if isMatch else "does NOT MATCH"
print("The string %s %s the pattern %s!" % (strInput, isMatchString, strPattern))
def validateStringInput(toValidate):
if (not isinstance(toValidate, str)):
return False
if (len(toValidate) <= 1):
return False
if (toValidate.isspace()):
return False
return True
def validatePattern(toValidate):
if (("*?" in toValidate) or ("?*" in toValidate)):
return False
return True
def ValidateStringAgainstPattern(str, strPattern):
# Validate, if the first character of both strings are equal or if the first character of
# the pattern is a single-character joker. If so, we have a match and can continue to the next item in both,
# String and Pattern if there are more characters to validate.
if ((str[0] == strPattern[0]) or (strPattern[0] == '?')):
strLen = len(str)
patternLen = len(strPattern)
if strLen > 1 and patternLen > 1:
return ValidateStringAgainstPattern(str[1:len(str)], strPattern[1:len(strPattern)])
elif strLen == 1 and patternLen == 1:
return True
else:
return False
elif (strPattern[0] == '*'):
# Joker sign for multiple characters - let's see if we find pattern matches after the Joker.
# If we cannot find any match after the joker, the string does not match.
while len(str) > 1:
# The last character in the pattern string is the *-joker, hence we're good.
if len(strPattern) <= 1:
return True
# If the last character is not the *-joker, then we need to see, if we can find any pattern match after the joker.
# If so, we're good and have a matching string, but if not, we don't. We try to find any possible match after the joker
# since the border from the joker to the next section after the joker is not easily determined (i.e. ACCCCB to match A*CB).
if ValidateStringAgainstPattern(str, strPattern[1:len(strPattern)]):
return True
else:
str = str[1:len(str)]
else:
return False
if __name__ == "__main__":
main() |
class TenantsV2(object):
def on_get(self, req, resp):
client = req.env['sl_client']
account = client['Account'].getObject()
tenants = [
{
'enabled': True,
'description': None,
'name': str(account['id']),
'id': str(account['id']),
},
]
resp.body = {'tenants': tenants, 'tenant_links': []}
|
list=[' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?',
'@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_',
'`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~']
"""
This is a list of 95 characters from 32 to the 126 index of the ASCII table. It will work as a lookup table for the method.
"""
def vigenere(start, text, key):
result = ""
for i in range(len(text)):
if text[i] not in list:
result+=text[i]
else:
if start == 1:
result+=list[(list.index(text[i])+list.index(key[i%len(key)]))%len(list)]
else:
result+=list[(list.index(text[i])-list.index(key[i%len(key)]))%len(list)]
return result
start=int(input("Would you like to:\n1- Encrypt\n2- Decrypt\n"))
text=input("Text: ")
key=input("Key: ")
print(vigenere(start, text,key))
"""
This will work on any of the ASCII characters on the list.
Any character that is not on the list will be left as it is.
So ideally, don't use accented letters or things like that.
Unlike the text being encrypted, all the characters on the key must be on the list.
"""
|
def eg():
print ("eggo")
eg()
|
# Este tipo de algoritmos es para acomodar millonadas de datos en diferentes lugares para que despues sea mas facil buscar
# m = tamaño de la tabla hash
# Lectura del archivo
f = open('lorem.txt','r')
palabras = [x for l in f.readlines() for x in l.split()]
f.close()
print("cantidad de palabras del texto: {}".format(len(palabras)))
# Aqui se convier
def convertirTextoEnNumero(texto):
salida = ""
for x in texto:
salida += str(ord(x))
return int(salida)
def hashM(texto, m):
i = convertirTextoEnNumero(texto)
return i%m
def agregar(texto, hashTable, m):
res = hashM(texto, m)
hashTable[res].append(texto)
def buscar(texto, hashTable, m):
h = hashM(texto, m)
for i in hashTable[h]:
if i == texto:
return True
return False
m = 10
hashTable = [[] for i in range(m)]
for palabra in palabras:
agregar(palabra, hashTable, m)
print("Existe la palabra 'lorem'?: {}".format(buscar("lorem", hashTable, m)))
print("Existe la palabra 'ipsum'?: {}".format(buscar("ipsum", hashTable, m)))
print("Existe la palabra 'pano'?: {}".format(buscar("pano", hashTable, m)))
print("Existe la palabra 'elpanito'?: {}".format(buscar("elpanito", hashTable, m))) |
def binary_search(arr, first, last, x):
res = -1;
if last >= first:
while first <= last:
half = (first + last) // 2
if arr[half] == x:
res = half
return res
elif x > arr[half]:
first = half + 1
else:
last = half - 1
return res
else:
return res
|
def trans(o,beg,end):
if end>=beg:
mid=beg+(end-beg)//2
if((mid==end or o[mid+1]==0)and(o[mid]==1)):
return mid+1
if o[mid]==1:
return trans(o,(mid+1),end)
return trans(o,beg,mid-1)
else:
return 0
o=[int(x) for x in input('Enter NUMS seprated by space: ').split()]
print('No. 1s=',trans(o,0,len(o)-1))
|
optGeneric_template = '''
nSteps {nSteps}
nStepsInfoInterval {nStepsInterval}
nStepsWriteInterval {nStepsWrite}
nStepsBackupInterval {nStepsBackupInterval}
outPutFilePath {outPutFilePath}
outPutFormat {outPutFormat}
boxSize {boxX} {boxY} {boxZ}
T {temperature}
h {steepestDecentScale}
nStepsSteepestDescent {nStepsSteepestDescent}
nStepsSteepestDescentProgressInterval {nStepsSteepestDescentProgressInterval}
maxObjectiveForce {maxObjectiveForce}
dt {timeStep}
frictionConstant {frictionConstant}
cutOffDst {cutOffDst}
VerletListDst {VerletListDst}
inputCoordPath {inputCoordFile}
inputTopologyPath {inputTopFile}'''
optGenericWithElec_template = optGeneric_template+'''
dielectricConstant {dielectricConstant}
debyeLength {debyeLength}
'''
optGenericWithSurface_template = optGenericWithElec_template+'''
epsilonSurf {epsilonSurf}
sigmaSurf {sigmaSurf}
surfacePosition {surfacePosition}
'''
optGenericClash_template = optGeneric_template+'''
lambda {lambd}
gamma {gamma}
'''
optGenericClashWithCompression_template = optGenericClash_template+'''
initialSphereRadius {initialSphereRadius}
minimalSphereRadius {minimalSphereRadius}
compressionVelocity {compressionVelocity}
'''
optAFM_template = optGenericWithSurface_template+'''
frictionConstantTip {frictionConstantTip}
initialTipSampleDst {initialTipSampleDst}
descentVelocity {descentVelocity}
minimalChipHeight {minimalChipHeight}
Mtip {Mtip}
Rtip {Rtip}
Kxytip {Kxytip}
Ktip {Ktip}
epsilonTip {epsilonTip}
sigmaTip {sigmaTip}
Atip {Atip}
Btip {Btip}
epsilonTipSurf {epsilonTipSurf}
sigmaTipSurf {sigmaTipSurf}
ATipSurf {ATipSurf}
BTipSurf {BTipSurf}
nStepsIndentMeasure {nStepsIndentMeasure}
outputIndentationMeasureFilePath {outputIndentationMeasureFilePath}
'''
optGenericUmbrella_template = optGenericWithElec_template+'''
umbrellaK {umbrellaK}
umbrellaInit {umbrellaInit}
umbrellaEnd {umbrellaEnd}
umbrellaWindowsNumber {umbrellaWindowsNumber}
umbrellaCopies {umbrellaCopies}
nStepsUmbrellaMeasure {nStepsUmbrellaMeasure}
outputUmbrellaMeasureFilePath {outputUmbrellaMeasureFilePath}
'''
def writeOptionsGeneric(path:str,
nSteps:int,
nStepsInterval:int,
nStepsWrite:int,
nStepsBackupInterval:int,
outPutFilePath:str,
outPutFormat:str,
boxX:float,boxY:float,boxZ:float,
temperature:float,
steepestDecentScale:float,
nStepsSteepestDescent:int,
nStepsSteepestDescentProgressInterval:int,
maxObjectiveForce:float,
timeStep:float,
frictionConstant:float,
cutOffDst:float,
VerletListDst:float,
dielectricConstant:float,
debyeLength:float,
inputCoordFile:str,
inputTopFile:str):
opt = optGenericWithElec_template.format(nSteps=nSteps,
nStepsInterval=nStepsInterval,
nStepsWrite=nStepsWrite,
nStepsBackupInterval=nStepsBackupInterval,
outPutFilePath=outPutFilePath,
outPutFormat=outPutFormat,
boxX=boxX,boxY=boxY,boxZ=boxZ,
temperature=temperature,
steepestDecentScale=steepestDecentScale,
nStepsSteepestDescent=nStepsSteepestDescent,
nStepsSteepestDescentProgressInterval=nStepsSteepestDescentProgressInterval,
maxObjectiveForce=maxObjectiveForce,
timeStep=timeStep,
frictionConstant=frictionConstant,
cutOffDst=cutOffDst,
VerletListDst=VerletListDst,
dielectricConstant=dielectricConstant,
debyeLength=debyeLength,
inputCoordFile=inputCoordFile,
inputTopFile=inputTopFile)
with open(path,"w") as f:
f.write(opt)
def writeOptionsGenericFromDict(path,optionsDict):
nSteps=optionsDict["nSteps"]
nStepsInterval=optionsDict["nStepsInterval"]
nStepsWrite=optionsDict["nStepsWrite"]
nStepsBackupInterval=optionsDict["nStepsBackupInterval"]
outPutFilePath=optionsDict["outPutFilePath"]
outPutFormat=optionsDict["outPutFormat"]
boxX=optionsDict["boxX"]
boxY=optionsDict["boxY"]
boxZ=optionsDict["boxZ"]
temperature=optionsDict["temperature"]
steepestDecentScale=optionsDict["steepestDecentScale"]
nStepsSteepestDescent=optionsDict["nStepsSteepestDescent"]
nStepsSteepestDescentProgressInterval=optionsDict["nStepsSteepestDescentProgressInterval"]
maxObjectiveForce=optionsDict["maxObjectiveForce"]
timeStep=optionsDict["timeStep"]
frictionConstant=optionsDict["frictionConstant"]
cutOffDst=optionsDict["cutOffDst"]
VerletListDst=optionsDict["VerletListDst"]
dielectricConstant=optionsDict["dielectricConstant"]
debyeLength=optionsDict["debyeLength"]
inputCoordFile=optionsDict["inputCoordFile"]
inputTopFile=optionsDict["inputTopFile"]
writeOptionsGeneric(path,
nSteps,
nStepsInterval,
nStepsWrite,
nStepsBackupInterval,
outPutFilePath,
outPutFormat,
boxX,boxY,boxZ,
temperature,
steepestDecentScale,
nStepsSteepestDescent,
nStepsSteepestDescentProgressInterval,
maxObjectiveForce,
timeStep,
frictionConstant,
cutOffDst,
VerletListDst,
dielectricConstant,
debyeLength,
inputCoordFile,
inputTopFile)
def writeOptionsGenericWithSurface(path:str,
nSteps:int,
nStepsInterval:int,
nStepsWrite:int,
nStepsBackupInterval:int,
outPutFilePath:str,
outPutFormat:str,
boxX:float,boxY:float,boxZ:float,
temperature:float,
steepestDecentScale:float,
nStepsSteepestDescent:int,
nStepsSteepestDescentProgressInterval:int,
maxObjectiveForce:float,
timeStep:float,
frictionConstant:float,
cutOffDst:float,
VerletListDst:float,
dielectricConstant:float,
debyeLength:float,
inputCoordFile:str,
inputTopFile:str,
epsilonSurf:float,
sigmaSurf:float,
surfacePosition:float):
opt = optGenericWithSurface_template.format(nSteps=nSteps,
nStepsInterval=nStepsInterval,
nStepsWrite=nStepsWrite,
nStepsBackupInterval=nStepsBackupInterval,
outPutFilePath=outPutFilePath,
outPutFormat=outPutFormat,
boxX=boxX,boxY=boxY,boxZ=boxZ,
temperature=temperature,
steepestDecentScale=steepestDecentScale,
nStepsSteepestDescent=nStepsSteepestDescent,
nStepsSteepestDescentProgressInterval=nStepsSteepestDescentProgressInterval,
maxObjectiveForce=maxObjectiveForce,
timeStep=timeStep,
frictionConstant=frictionConstant,
cutOffDst=cutOffDst,
VerletListDst=VerletListDst,
dielectricConstant=dielectricConstant,
debyeLength=debyeLength,
inputCoordFile=inputCoordFile,
inputTopFile=inputTopFile,
epsilonSurf=epsilonSurf,
sigmaSurf=sigmaSurf,
surfacePosition=surfacePosition)
with open(path,"w") as f:
f.write(opt)
def writeOptionsGenericWithSurfaceFromDict(path,optionsDict):
nSteps=optionsDict["nSteps"]
nStepsInterval=optionsDict["nStepsInterval"]
nStepsWrite=optionsDict["nStepsWrite"]
nStepsBackupInterval=optionsDict["nStepsBackupInterval"]
outPutFilePath=optionsDict["outPutFilePath"]
outPutFormat=optionsDict["outPutFormat"]
boxX=optionsDict["boxX"]
boxY=optionsDict["boxY"]
boxZ=optionsDict["boxZ"]
temperature=optionsDict["temperature"]
steepestDecentScale=optionsDict["steepestDecentScale"]
nStepsSteepestDescent=optionsDict["nStepsSteepestDescent"]
nStepsSteepestDescentProgressInterval=optionsDict["nStepsSteepestDescentProgressInterval"]
maxObjectiveForce=optionsDict["maxObjectiveForce"]
timeStep=optionsDict["timeStep"]
frictionConstant=optionsDict["frictionConstant"]
cutOffDst=optionsDict["cutOffDst"]
VerletListDst=optionsDict["VerletListDst"]
inputCoordFile=optionsDict["inputCoordFile"]
dielectricConstant=optionsDict["dielectricConstant"]
debyeLength=optionsDict["debyeLength"]
inputTopFile=optionsDict["inputTopFile"]
epsilonSurf=optionsDict["epsilonSurf"]
sigmaSurf=optionsDict["sigmaSurf"]
surfacePosition=optionsDict["surfacePosition"]
writeOptionsGenericWithSurface(path,
nSteps,
nStepsInterval,
nStepsWrite,
nStepsBackupInterval,
outPutFilePath,
outPutFormat,
boxX,boxY,boxZ,
temperature,
steepestDecentScale,
nStepsSteepestDescent,
nStepsSteepestDescentProgressInterval,
maxObjectiveForce,
timeStep,
frictionConstant,
cutOffDst,
VerletListDst,
dielectricConstant,
debyeLength,
inputCoordFile,
inputTopFile,
epsilonSurf,
sigmaSurf,
surfacePosition)
def writeOptionsGenericClash(path:str,
nSteps:int,
nStepsInterval:int,
nStepsWrite:int,
nStepsBackupInterval:int,
outPutFilePath:str,
outPutFormat:str,
boxX:float,boxY:float,boxZ:float,
temperature:float,
steepestDecentScale:float,
nStepsSteepestDescent:int,
nStepsSteepestDescentProgressInterval:int,
maxObjectiveForce:float,
timeStep:float,
frictionConstant:float,
cutOffDst:float,
VerletListDst:float,
inputCoordFile:str,
inputTopFile:str,
lambd:float,
gamma:float):
opt = optGenericClash_template.format(nSteps=nSteps,
nStepsInterval=nStepsInterval,
nStepsWrite=nStepsWrite,
nStepsBackupInterval=nStepsBackupInterval,
outPutFilePath=outPutFilePath,
outPutFormat=outPutFormat,
boxX=boxX,boxY=boxY,boxZ=boxZ,
temperature=temperature,
steepestDecentScale=steepestDecentScale,
nStepsSteepestDescent=nStepsSteepestDescent,
nStepsSteepestDescentProgressInterval=nStepsSteepestDescentProgressInterval,
maxObjectiveForce=maxObjectiveForce,
timeStep=timeStep,
frictionConstant=frictionConstant,
cutOffDst=cutOffDst,
VerletListDst=VerletListDst,
inputCoordFile=inputCoordFile,
inputTopFile=inputTopFile,
lambd=lambd,
gamma=gamma)
with open(path,"w") as f:
f.write(opt)
def writeOptionsGenericClashFromDict(path,optionsDict):
nSteps=optionsDict["nSteps"]
nStepsInterval=optionsDict["nStepsInterval"]
nStepsWrite=optionsDict["nStepsWrite"]
nStepsBackupInterval=optionsDict["nStepsBackupInterval"]
outPutFilePath=optionsDict["outPutFilePath"]
outPutFormat=optionsDict["outPutFormat"]
boxX=optionsDict["boxX"]
boxY=optionsDict["boxY"]
boxZ=optionsDict["boxZ"]
temperature=optionsDict["temperature"]
steepestDecentScale=optionsDict["steepestDecentScale"]
nStepsSteepestDescent=optionsDict["nStepsSteepestDescent"]
nStepsSteepestDescentProgressInterval=optionsDict["nStepsSteepestDescentProgressInterval"]
maxObjectiveForce=optionsDict["maxObjectiveForce"]
timeStep=optionsDict["timeStep"]
frictionConstant=optionsDict["frictionConstant"]
cutOffDst=optionsDict["cutOffDst"]
VerletListDst=optionsDict["VerletListDst"]
inputCoordFile=optionsDict["inputCoordFile"]
inputTopFile=optionsDict["inputTopFile"]
lambd=optionsDict["lambd"]
gamma=optionsDict["gamma"]
writeOptionsGenericClash(path,
nSteps,
nStepsInterval,
nStepsWrite,
nStepsBackupInterval,
outPutFilePath,
outPutFormat,
boxX,boxY,boxZ,
temperature,
steepestDecentScale,
nStepsSteepestDescent,
nStepsSteepestDescentProgressInterval,
maxObjectiveForce,
timeStep,
frictionConstant,
cutOffDst,
VerletListDst,
inputCoordFile,
inputTopFile,
lambd,
gamma)
def writeOptionsGenericClashWithCompression(path:str,
nSteps:int,
nStepsInterval:int,
nStepsWrite:int,
nStepsBackupInterval:int,
outPutFilePath:str,
outPutFormat:str,
boxX:float,boxY:float,boxZ:float,
temperature:float,
steepestDecentScale:float,
nStepsSteepestDescent:int,
nStepsSteepestDescentProgressInterval:int,
maxObjectiveForce:float,
timeStep:float,
frictionConstant:float,
cutOffDst:float,
VerletListDst:float,
inputCoordFile:str,
inputTopFile:str,
lambd:float,
gamma:float,
initialSphereRadius:float,
minimalSphereRadius:float,
compressionVelocity:float):
opt = optGenericClashWithCompression_template.format(nSteps=nSteps,
nStepsInterval=nStepsInterval,
nStepsWrite=nStepsWrite,
nStepsBackupInterval=nStepsBackupInterval,
outPutFilePath=outPutFilePath,
outPutFormat=outPutFormat,
boxX=boxX,boxY=boxY,boxZ=boxZ,
temperature=temperature,
steepestDecentScale=steepestDecentScale,
nStepsSteepestDescent=nStepsSteepestDescent,
nStepsSteepestDescentProgressInterval=nStepsSteepestDescentProgressInterval,
maxObjectiveForce=maxObjectiveForce,
timeStep=timeStep,
frictionConstant=frictionConstant,
cutOffDst=cutOffDst,
VerletListDst=VerletListDst,
inputCoordFile=inputCoordFile,
inputTopFile=inputTopFile,
lambd=lambd,
gamma=gamma,
initialSphereRadius=initialSphereRadius,
minimalSphereRadius=minimalSphereRadius,
compressionVelocity=compressionVelocity)
with open(path,"w") as f:
f.write(opt)
def writeOptionsGenericClashWithCompressionFromDict(path,optionsDict):
nSteps=optionsDict["nSteps"]
nStepsInterval=optionsDict["nStepsInterval"]
nStepsWrite=optionsDict["nStepsWrite"]
nStepsBackupInterval=optionsDict["nStepsBackupInterval"]
outPutFilePath=optionsDict["outPutFilePath"]
outPutFormat=optionsDict["outPutFormat"]
boxX=optionsDict["boxX"]
boxY=optionsDict["boxY"]
boxZ=optionsDict["boxZ"]
temperature=optionsDict["temperature"]
steepestDecentScale=optionsDict["steepestDecentScale"]
nStepsSteepestDescent=optionsDict["nStepsSteepestDescent"]
nStepsSteepestDescentProgressInterval=optionsDict["nStepsSteepestDescentProgressInterval"]
maxObjectiveForce=optionsDict["maxObjectiveForce"]
timeStep=optionsDict["timeStep"]
frictionConstant=optionsDict["frictionConstant"]
cutOffDst=optionsDict["cutOffDst"]
VerletListDst=optionsDict["VerletListDst"]
inputCoordFile=optionsDict["inputCoordFile"]
inputTopFile=optionsDict["inputTopFile"]
lambd=optionsDict["lambd"]
gamma=optionsDict["gamma"]
initialSphereRadius=optionsDict["initialSphereRadius"]
minimalSphereRadius=optionsDict["minimalSphereRadius"]
compressionVelocity=optionsDict["compressionVelocity"]
writeOptionsGenericClashWithCompression(path,
nSteps,
nStepsInterval,
nStepsWrite,
nStepsBackupInterval,
outPutFilePath,
outPutFormat,
boxX,boxY,boxZ,
temperature,
steepestDecentScale,
nStepsSteepestDescent,
nStepsSteepestDescentProgressInterval,
maxObjectiveForce,
timeStep,
frictionConstant,
cutOffDst,
VerletListDst,
inputCoordFile,
inputTopFile,
lambd,
gamma,
initialSphereRadius,
minimalSphereRadius,
compressionVelocity)
def writeOptionsAFM(path:str,
nSteps:int,
nStepsInterval:int,
nStepsWrite:int,
nStepsBackupInterval:int,
outPutFilePath:str,
outPutFormat:str,
boxX:float,boxY:float,boxZ:float,
temperature:float,
steepestDecentScale:float,
nStepsSteepestDescent:int,
nStepsSteepestDescentProgressInterval:int,
maxObjectiveForce:float,
timeStep:float,
frictionConstant:float,
frictionConstantTip:float,
cutOffDst:float,
VerletListDst:float,
dielectricConstant:float,
debyeLength:float,
inputCoordFile:str,
inputTopFile:str,
epsilonSurf:float,
sigmaSurf:float,
surfacePosition:float,
initialTipSampleDst:float,
descentVelocity:float,
minimalChipHeight:float,
Mtip:float,
Rtip:float,
Kxytip:float,
Ktip:float,
epsilonTip:float,
sigmaTip:float,
Atip:float,
Btip:float,
epsilonTipSurf:float,
sigmaTipSurf :float,
ATipSurf:float,
BTipSurf:float,
nStepsIndentMeasure:str,
outputIndentationMeasureFilePath:str):
opt = optAFM_template.format(nSteps=nSteps,
nStepsInterval=nStepsInterval,
nStepsWrite=nStepsWrite,
nStepsBackupInterval=nStepsBackupInterval,
outPutFilePath=outPutFilePath,
outPutFormat=outPutFormat,
boxX=boxX,boxY=boxY,boxZ=boxZ,
temperature=temperature,
steepestDecentScale=steepestDecentScale,
nStepsSteepestDescent=nStepsSteepestDescent,
nStepsSteepestDescentProgressInterval=nStepsSteepestDescentProgressInterval,
maxObjectiveForce=maxObjectiveForce,
timeStep=timeStep,
frictionConstant=frictionConstant,
frictionConstantTip=frictionConstantTip,
cutOffDst=cutOffDst,
VerletListDst=VerletListDst,
dielectricConstant=dielectricConstant,
debyeLength=debyeLength,
inputCoordFile=inputCoordFile,
inputTopFile=inputTopFile,
epsilonSurf=epsilonSurf,
sigmaSurf=sigmaSurf,
surfacePosition=surfacePosition,
initialTipSampleDst=initialTipSampleDst,
descentVelocity=descentVelocity,
minimalChipHeight=minimalChipHeight,
Mtip=Mtip,
Rtip=Rtip,
Kxytip=Kxytip,
Ktip=Ktip,
epsilonTip=epsilonTip,
sigmaTip=sigmaTip,
Atip=Atip,
Btip=Btip,
epsilonTipSurf=epsilonTipSurf,
sigmaTipSurf =sigmaTipSurf,
ATipSurf=ATipSurf,
BTipSurf=BTipSurf,
nStepsIndentMeasure=nStepsIndentMeasure,
outputIndentationMeasureFilePath=outputIndentationMeasureFilePath)
with open(path,"w") as f:
f.write(opt)
def writeOptionsAFMFromDict(path,optionsDict):
nSteps=optionsDict["nSteps"]
nStepsInterval=optionsDict["nStepsInterval"]
nStepsWrite=optionsDict["nStepsWrite"]
nStepsBackupInterval=optionsDict["nStepsBackupInterval"]
outPutFilePath=optionsDict["outPutFilePath"]
outPutFormat=optionsDict["outPutFormat"]
boxX=optionsDict["boxX"]
boxY=optionsDict["boxY"]
boxZ=optionsDict["boxZ"]
temperature=optionsDict["temperature"]
steepestDecentScale=optionsDict["steepestDecentScale"]
nStepsSteepestDescent=optionsDict["nStepsSteepestDescent"]
nStepsSteepestDescentProgressInterval=optionsDict["nStepsSteepestDescentProgressInterval"]
maxObjectiveForce=optionsDict["maxObjectiveForce"]
timeStep=optionsDict["timeStep"]
frictionConstant=optionsDict["frictionConstant"]
frictionConstantTip=optionsDict["frictionConstantTip"]
cutOffDst=optionsDict["cutOffDst"]
VerletListDst=optionsDict["VerletListDst"]
dielectricConstant=optionsDict["dielectricConstant"]
debyeLength=optionsDict["debyeLength"]
inputCoordFile=optionsDict["inputCoordFile"]
inputTopFile=optionsDict["inputTopFile"]
epsilonSurf=optionsDict["epsilonSurf"]
sigmaSurf=optionsDict["sigmaSurf"]
surfacePosition=optionsDict["surfacePosition"]
initialTipSampleDst=optionsDict["initialTipSampleDst"]
descentVelocity=optionsDict["descentVelocity"]
minimalChipHeight=optionsDict["minimalChipHeight"]
Mtip=optionsDict["Mtip"]
Rtip=optionsDict["Rtip"]
Kxytip=optionsDict["Kxytip"]
Ktip=optionsDict["Ktip"]
epsilonTip=optionsDict["epsilonTip"]
sigmaTip=optionsDict["sigmaTip"]
Atip=optionsDict["Atip"]
Btip=optionsDict["Btip"]
epsilonTipSurf=optionsDict["epsilonTipSurf"]
sigmaTipSurf =optionsDict["sigmaTipSurf"]
ATipSurf=optionsDict["ATipSurf"]
BTipSurf=optionsDict["BTipSurf"]
nStepsIndentMeasure=optionsDict["nStepsIndentMeasure"]
outputIndentationMeasureFilePath=optionsDict["outputIndentationMeasureFilePath"]
writeOptionsAFM(path,
nSteps,
nStepsInterval,
nStepsWrite,
nStepsBackupInterval,
outPutFilePath,
outPutFormat,
boxX,boxY,boxZ,
temperature,
steepestDecentScale,
nStepsSteepestDescent,
nStepsSteepestDescentProgressInterval,
maxObjectiveForce,
timeStep,
frictionConstant,
frictionConstantTip,
cutOffDst,
VerletListDst,
dielectricConstant,
debyeLength,
inputCoordFile,
inputTopFile,
epsilonSurf,
sigmaSurf,
surfacePosition,
initialTipSampleDst,
descentVelocity,
minimalChipHeight,
Mtip,
Rtip,
Kxytip,
Ktip,
epsilonTip,
sigmaTip,
Atip,
Btip,
epsilonTipSurf,
sigmaTipSurf,
ATipSurf,
BTipSurf,
nStepsIndentMeasure,
outputIndentationMeasureFilePath)
def writeOptionsGenericUmbrella(path:str,
nSteps:int,
nStepsInterval:int,
nStepsWrite:int,
nStepsBackupInterval:int,
outPutFilePath:str,
outPutFormat:str,
boxX:float,boxY:float,boxZ:float,
temperature:float,
steepestDecentScale:float,
nStepsSteepestDescent:int,
nStepsSteepestDescentProgressInterval:int,
maxObjectiveForce:float,
timeStep:float,
frictionConstant:float,
cutOffDst:float,
VerletListDst:float,
dielectricConstant:float,
debyeLength:float,
inputCoordFile:str,
inputTopFile:str,
umbrellaK:float,
umbrellaInit:float,
umbrellaEnd:float,
umbrellaWindowsNumber:int,
umbrellaCopies:int,
nStepsUmbrellaMeasure:int,
outputUmbrellaMeasureFilePath:str):
opt = optGenericUmbrella_template.format(nSteps=nSteps,
nStepsInterval=nStepsInterval,
nStepsWrite=nStepsWrite,
nStepsBackupInterval=nStepsBackupInterval,
outPutFilePath=outPutFilePath,
outPutFormat=outPutFormat,
boxX=boxX,boxY=boxY,boxZ=boxZ,
temperature=temperature,
steepestDecentScale=steepestDecentScale,
nStepsSteepestDescent=nStepsSteepestDescent,
nStepsSteepestDescentProgressInterval=nStepsSteepestDescentProgressInterval,
maxObjectiveForce=maxObjectiveForce,
timeStep=timeStep,
frictionConstant=frictionConstant,
cutOffDst=cutOffDst,
VerletListDst=VerletListDst,
dielectricConstant=dielectricConstant,
debyeLength=debyeLength,
inputCoordFile=inputCoordFile,
inputTopFile=inputTopFile,
umbrellaK=umbrellaK,
umbrellaInit=umbrellaInit,
umbrellaEnd=umbrellaEnd,
umbrellaWindowsNumber=umbrellaWindowsNumber,
umbrellaCopies=umbrellaCopies,
nStepsUmbrellaMeasure=nStepsUmbrellaMeasure,
outputUmbrellaMeasureFilePath=outputUmbrellaMeasureFilePath)
with open(path,"w") as f:
f.write(opt)
def writeOptionsGenericUmbrellaFromDict(path,optionsDict):
nSteps=optionsDict["nSteps"]
nStepsInterval=optionsDict["nStepsInterval"]
nStepsWrite=optionsDict["nStepsWrite"]
nStepsBackupInterval=optionsDict["nStepsBackupInterval"]
outPutFilePath=optionsDict["outPutFilePath"]
outPutFormat=optionsDict["outPutFormat"]
boxX=optionsDict["boxX"]
boxY=optionsDict["boxY"]
boxZ=optionsDict["boxZ"]
temperature=optionsDict["temperature"]
steepestDecentScale=optionsDict["steepestDecentScale"]
nStepsSteepestDescent=optionsDict["nStepsSteepestDescent"]
nStepsSteepestDescentProgressInterval=optionsDict["nStepsSteepestDescentProgressInterval"]
maxObjectiveForce=optionsDict["maxObjectiveForce"]
timeStep=optionsDict["timeStep"]
frictionConstant=optionsDict["frictionConstant"]
cutOffDst=optionsDict["cutOffDst"]
VerletListDst=optionsDict["VerletListDst"]
dielectricConstant=optionsDict["dielectricConstant"]
debyeLength=optionsDict["debyeLength"]
inputCoordFile=optionsDict["inputCoordFile"]
inputTopFile=optionsDict["inputTopFile"]
umbrellaK=optionsDict["umbrellaK"]
umbrellaInit=optionsDict["umbrellaInit"]
umbrellaEnd=optionsDict["umbrellaEnd"]
umbrellaWindowsNumber=optionsDict["umbrellaWindowsNumber"]
umbrellaCopies=optionsDict["umbrellaCopies"]
nStepsUmbrellaMeasure=optionsDict["nStepsUmbrellaMeasure"]
outputUmbrellaMeasureFilePath=optionsDict["outputUmbrellaMeasureFilePath"]
writeOptionsGenericUmbrella(path,
nSteps,
nStepsInterval,
nStepsWrite,
nStepsBackupInterval,
outPutFilePath,
outPutFormat,
boxX,boxY,boxZ,
temperature,
steepestDecentScale,
nStepsSteepestDescent,
nStepsSteepestDescentProgressInterval,
maxObjectiveForce,
timeStep,
frictionConstant,
cutOffDst,
VerletListDst,
dielectricConstant,
debyeLength,
inputCoordFile,
inputTopFile,
umbrellaK,
umbrellaInit,
umbrellaEnd,
umbrellaWindowsNumber,
umbrellaCopies,
nStepsUmbrellaMeasure,
outputUmbrellaMeasureFilePath)
################################################
#writeOptionsGeneric("optionsTestGeneric.dat",
# 1000,
# 1000,
# 1000,
# 1000,
# "kk",
# "asdf",
# 1.23,2.13,3.12,
# 1.0,
# 1.5,
# 55555,
# 4444,
# -1.0,
# 0.123456,
# 2.0,
# 100.0,
# 150.0,
# "asdf.coord",
# "asdf.top")
#
#writeOptionsGenericWithSurface("optionsTestGenericSurface.dat",
# 1000,
# 1000,
# 1000,
# 1000,
# "kk",
# "asdf",
# 1.23,2.13,3.12,
# 1.0,
# 1.5,
# 55555,
# 4444,
# -1.0,
# 0.123456,
# 2.0,
# 100.0,
# 150.0,
# "asdf.coord",
# "asdf.top",
# 1.0,
# 2.0,
# -300)
#
#writeOptionsGenericClash("optionsTestClash.dat",
# 1000,
# 1000,
# 1000,
# 1000,
# "kk",
# "asdf",
# 1.23,2.13,3.12,
# 1.0,
# 1.5,
# 55555,
# 4444,
# -1.0,
# 0.123456,
# 2.0,
# 100.0,
# 150.0,
# "asdf.coord",
# "asdf.top",
# 2.0,
# 4.0)
#
#writeOptionsGenericClashWithCompression("optionsTestClashWithCompression.dat",
# 1000,
# 1000,
# 1000,
# 1000,
# "kk",
# "asdf",
# 1.23,2.13,3.12,
# 1.0,
# 1.5,
# 55555,
# 4444,
# -1.0,
# 0.123456,
# 2.0,
# 100.0,
# 150.0,
# "asdf.coord",
# "asdf.top",
# 2.0,
# 4.0,
# 300,
# 400,
# 0.01001)
#
#writeOptionsAFM("optionsAFM.dat",
# 1000,
# 1000,
# 1000,
# 1000,
# "kk",
# "asdf",
# 1.23,2.13,3.12,
# 1.0,
# 1.5,
# 55555,
# 4444,
# -1.0,
# 0.123456,
# 2.0,
# 100.0,
# 150.0,
# "asdf.coord",
# "asdf.top",
# 1.0,
# 2.0,
# -300,
# 1.123,
# 0.001,
# 2.323,
# 1.02,
# 5.02,
# 5698,
# 456,
# 5897,
# 57,
# 142566,
# 146,
# 1486,
# 98765,
# 12453,
# 1289)
|
def row_as_json(sqlite_row):
"""Return a dict from a sqlite_row."""
return {
key: sqlite_row[key]
for key in sqlite_row.keys()
}
def list_as_json(sqlite_rows):
"""Return a list of dicts from a list of sqlite_rows."""
return [
row_as_json(row)
for row in sqlite_rows
]
|
N = int(input())
A = list(map(int, input().split()))
t = len(set(A))
if (len(A) - t) % 2 == 0:
print(t)
else:
print(t - 1)
|
#Tugas Cycom 0001
#converter suhu fahrenheit
print ('selamat datang di converter fahrenheit')
print('pilih jenis suhu yang ingin diubah ke dalam fahrenheit ')
print('1.celcius')
print('2.reamur')
print('3.kelvin')
while True:
# Take input from the user
choice = input("Masukan pilihan (1/2/3):") # input user dari pilihan di atas
if choice == '1': # if user pick number 1. the program will start here
Celc = float(input('tentukan angka celcius :'))
CtoFahr = (9/5 * Celc) + 32 # rumus konversi suhu
print(CtoFahr, 'fahrenheit')
if choice == '2':
Ream = float(input('tentukan angka reamur : '))
ReamToFahr = (9/4 * Ream) + 32
print(ReamToFahr, 'fahrenheit')
if choice == '3':
Kelv = float(input('tentukan angka kelvin : '))
KelvToFahr = float(Kelv - 273.15) * 9/5 + 32
print(KelvToFahr, 'fahrenheit')
else:
break # break mean end so after u input the numbers and got number output the script will end
#notes for cycom members
#kalo mau copas silahkan tapi ganti variable nya jadi suhu lain dulu
|
# coding: utf-8
# ... import symbolic tools
glt_function = load('pyccel.symbolic.gelato', 'glt_function', True, 3)
dx = load('pyccel.symbolic.gelato', 'dx', False, 1)
dy = load('pyccel.symbolic.gelato', 'dy', False, 1)
# ...
# ... weak formulation
laplace = lambda u,v: dx(u)*dx(v) + dy(u)*dy(v)
a = lambda x,y,u,v: laplace(u,v) + 0.1 * dx(u) * v
# ...
# ... computing the glt symbol and lambdify it
ga = glt_function(a, [4, 4], [2, 2])
g = lambdify(ga)
# ...
# glt symbol is supposed to be 'complex' in this example
# TODO fix it. for the moment the symbol is always 'double'
y = g(0.5, 0.5, 0.1, 0.3)
# ...
print(' a := ', a)
print(' glt symbol := ', ga)
print('')
print(' symbol (0.5, 0.5, 0.1, 0.3) = ', y)
|
AUTHOR_FEMALE = {
"Femina": [
"0009",
"0051",
"0054",
"0197",
"0220",
"0244",
"0294",
"0372",
"0509",
"1213",
"1355",
"1493",
"1572",
"1814",
"1828",
"2703",
"2766",
]
}
|
# For reference - not used directly yet
def swap_key_values():
objs = cmds.ls(sl=True)
a = objs[0]
b = objs[1]
atx = cmds.getAttr(a + '.tx')
aty = cmds.getAttr(a + '.ty')
atz = cmds.getAttr(a + '.tz')
arx = cmds.getAttr(a + '.rx')
ary = cmds.getAttr(a + '.ry')
arz = cmds.getAttr(a + '.rz')
btx = cmds.getAttr(b + '.tx')
bty = cmds.getAttr(b + '.ty')
btz = cmds.getAttr(b + '.tz')
brx = cmds.getAttr(b + '.rx')
bry = cmds.getAttr(b + '.ry')
brz = cmds.getAttr(b + '.rz')
cmds.setAttr(a + '.tx',btx)
cmds.setAttr(a + '.ty',bty)
cmds.setAttr(a + '.tz',btz)
cmds.setAttr(a + '.rx',brx)
cmds.setAttr(a + '.ry',bry)
cmds.setAttr(a + '.rz',brz)
cmds.setAttr(b + '.tx',atx)
cmds.setAttr(b + '.ty',aty)
cmds.setAttr(b + '.tz',atz)
cmds.setAttr(b + '.rx',arx)
cmds.setAttr(b + '.ry',ary)
cmds.setAttr(b + '.rz',arz)
print("Done key values swap") |
n1 = float(input('Nota N1: '))
n2 = float(input('Nota N2: '))
m = (n1 + n2) / 2
print("A média do aluno é {:.1f}".format(m))
input()
|
class CanvasPoint:
def __init__(self, z_index, color):
self.z_index = z_index
self.color = color
|
"""
Settings for unit test to connect to your JIRA instance
"""
SERVER='<JIRA instance URL>'
USER='drehtuer@drehtuer.de'
PASSWORD='<plain text password or None>'
TOKEN='<access token or None>'
"""
Settings for test cases
"""
# jira_helper/JiraHelper.query
TEST_QUERY_JQL='project=<your project>'
TEST_QUERY_FIELDS=['created', 'updated']
# jira_helper/JiraHelper.worklog
TEST_WORKLOG_ISSUE='<story>'
TEST_WORKLOG_TIME='2h'
TEST_WORKLOG_COMMENT='Test comment'
|
# Copyright 2020 Ian Rankin
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the "Software"), to deal in the Software
# without restriction, including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
# to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or
# substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
# FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
## @package Edge.py
# Written Ian Rankin October 2019
#
# Rather a directed edge, but called an edge for short.
# Contains the basic implementation for an edge.
# Particular designed to be extendable to allow different information to be
# stored.
#from rdml_graph.core import Node
## Rather a directed edge, but called an edge for short.
# Contains the basic implementation for an edge.
# Particular designed to be extendable to allow different information to be
# stored.
class Edge(object):
## constructor
# Pass the parent and child nodes directly (not indcies)
# @param parent - the parent Node of the edge
# @param child - the child Node of the edge
# @param cost - [opt] the cost of the edge.
def __init__(self, parent, child, cost = 1.0):
# should be handed the parent node directly.
self.p = parent
self.c = child
# don't reference directly rather reference the getCost function.
self.cost = cost
## @var p
# the parent Node of the edge
## @var c
# The child Node of the edge.
## @var cost
# The cost of the Edge (use getCost function).
## get function for cost.
# This shoud be called rather than directly referencing
# in case the function is overloaded.
def getCost(self):
return self.cost
## checks if connecting id's are the same and cost is the same (could potentially)
# have two different edges to the same two nodes.
def __eq__(self, other):
#return isinstance(other, Edge) and self.c.id == other.c.id and self.p.id == other.p.id \
# and self.cost() == other.cost()
if isinstance(other, Edge):
return self.c == other.c and self.p == other.p and self.cost() == other.cost()
else:
return False
def __str__(self):
s = 'e('
if hasattr(self.p, 'id'):
s += 'p.id='+str(self.p.id)
else:
s += 'p='+str(self.p)
if hasattr(self.c, 'id'):
s += ',c.id='+str(self.c.id)
else:
s += ',c='+str(self.c)
s += ',cost='+str(self.cost)+')'
return s
|
IMAGES_STORE = 'C:\\'
ITEM_PIPELINES = {'shoppon.spiders.planning.pipline.ImgPipeline': 1}
DOWNLOADER_MIDDLEWARES = {
'scrapy_splash.SplashCookiesMiddleware': 723,
'scrapy_splash.SplashMiddleware': 725,
'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810,
}
SPLASH_URL = 'http://192.168.3.42:8050'
DUPEFILTER_CLASS = 'scrapy_splash.SplashAwareDupeFilter'
HTTPCACHE_STORAGE = 'scrapy_splash.SplashAwareFSCacheStorage'
|
class Solution:
def flipAndInvertImage(self, matrix: list[list[int]]) -> list[list[int]]:
if not matrix or len(matrix) == 0:
return matrix
for row in matrix:
start, end = 0, len(row) - 1
while start < end:
if row[start] == row[end]:
row[start], row[end] = 1 - row[start], 1 - row[end]
start += 1
end -= 1
if start == end:
row[start] = 1 - row[start]
return matrix
if __name__ == "__main__":
solution = Solution()
print(solution.flipAndInvertImage([[1,1,0],[1,0,1],[0,0,0]]))
print(solution.flipAndInvertImage([[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]])) |
expressao = str(input('Insira a expressão : '))
pilha = []
for simbolo in expressao:
if simbolo == '(':
pilha.append('(')
elif simbolo == ')':
if len(pilha) > 0:
pilha.pop()
else:
pilha.append(')')
break
if len(pilha) == 0:
print('A expressão está correta')
else:
print('A expressão está errada !!!') |
class Colour:
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
END = '\033[0m'
GRAY = '\033[90m'
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
PURPLE = '\033[95m'
CYAN = '\033[96m'
WHITE = '\033[97m'
DARKGRAY = '\033[30m'
DARKRED = '\033[31m'
DARKGREEN = '\033[32m'
DARKYELLOW = '\033[33m'
DARKBLUE = '\033[34m'
DARKPURPLE = '\033[35m'
DARKCYAN = '\033[36m'
DARKWHITE = '\033[37m'
FULLDARKGRAY = '\033[40m'
FULLDARKRED = '\033[41m'
FULLDARKGREEN = '\033[42m'
FULLDARKYELLOW = '\033[43m'
FULLDARKBLUE = '\033[44m'
FULLDARKPURPLE = '\033[45m'
FULLDARKCYAN = '\033[46m'
FULLDARKWHITE = '\033[47m'
FULLGRAY = '\033[100m'
FULLRED = '\033[101m'
FULLGREEN = '\033[102m'
FULLYELLOW = '\033[103m'
FULLBLUE = '\033[104m'
FULLPURPLE = '\033[105m'
FULLCYAN = '\033[106m'
FULLWHITE = '\033[107m'
def print(mesage,colour=''):
print(colour + mesage + Colour.END)
|
# LC173
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class BSTIterator:
def __init__(self, root: TreeNode):
if not root:
False
self.stack = []
self.dfsLeft(root)
def dfsLeft(self, node):
while node:
self.stack.append(node)
node = node.left
def next(self) -> int:
"""
@return the next smallest number
"""
nextElem = self.stack.pop(-1)
if nextElem.right:
self.dfsLeft(nextElem.right)
return nextElem.val
def hasNext(self) -> bool:
"""
@return whether we have a next smallest number
"""
return len(self.stack) != 0
# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()
|
"""
We are given a list of (axis-aligned) rectangles. Each rectangle[i] = [x1, y1,
x2, y2] , where (x1, y1) are the coordinates of the bottom-left corner, and
(x2, y2) are the coordinates of the top-right corner of the ith rectangle.
Find the total area covered by all rectangles in the plane. Since the answer
may be too large, return it modulo 10^9 + 7.
Example 1:
Input: [[0,0,2,2],[1,0,2,3],[1,0,3,1]]
Output: 6
Explanation: As illustrated in the picture.
Example 2:
Input: [[0,0,1000000000,1000000000]]
Output: 49
Explanation: The answer is 10^18 modulo (10^9 + 7), which is (10^9)^2 = (-7)^2
= 49.
Note:
1 <= rectangles.length <= 200
rectanges[i].length = 4
0 <= rectangles[i][j] <= 10^9
The total area covered by all rectangles will never exceed 2^63 - 1 and
thus will fit in a 64-bit signed integer.
"""
class Solution:
def rectangleArea(self, rectangles):
"""
:type rectangles: List[List[int]]
:rtype: int
"""
MOD = 10 ** 9 + 7
xs = set()
for (x1, _, x2, _) in rectangles:
xs.add(x1)
xs.add(x2)
xs = sorted(list(xs))
area = 0
for x1, x2 in zip(xs, xs[1:]):
intervals = [(b, t) for l, b, r, t in rectangles if l <= x1 <= x2 <= r]
if not intervals:
continue
intervals.sort()
(st, en) = intervals[0]
for s, e in intervals[1:]:
if s > en:
# new
area += (x2 - x1) * (en - st)
st, en = s, e
else:
en = max(en, e)
area += (x2 - x1) * (en - st)
return area % MOD
sol = Solution().rectangleArea
tests = [
(([[0, 0, 2, 2], [1, 0, 2, 3], [1, 0, 3, 1]],), 6),
(([[0, 0, 1000000000, 1000000000]],), 49),
]
for inputs, expect in tests:
print(sol(*inputs), " ?= ", expect)
|
color_list = {
"black": (0,0,0),
"white": (255,255,255),
"gray": (103, 110, 122),
"sky_blue": (69, 224, 255),
"red": (255, 0, 0),
"green": (32, 212, 68),
"blue": (0, 0, 255),
"purple": (255, 0 ,255),
"tan": (235, 218, 108),
"orange": (200, 150, 0)
} |
# -*- coding: utf-8 -*-
"""
The :mod:`.visualizations` module has several functions that support celloracle.
"""
#from .interactive_simulation_and_plot import Oracle_extended, DEFAULT_PARAMETERS
#from .development_analysis import Oracle_development_module, subset_oracle_for_development_analysiis
__all__ = []
|
class CameraConfig:
def __init__(self, name, server_port, camera_num):
self.name = name
self.server_port = server_port
self.camera_num = camera_num
|
# Esse programa tem a função de testar alguns comandos relacionados
# a listas. Em geral, a ideia dele é implementarmos nomes de animais
# de estimação que possuímos e no final devemos nos perguntar se
# um nome está presente na nossa lista de pets
def addPets(myPets):
flag = True
numPets = int(input('Quantos Pets você tem? '))
i = 0
while i < numPets:
name = input('Coloque o(s) nome(s) do(s) seu(s) Pet(S): ')
myPets.append(name)
i += 1
return None
def doiOwn(listOfPets, name):
if name in listOfPets:
print(f'Você tem um pet chamado {name}')
elif name not in listOfPets:
# Aqui eu poderia usar logo um else:
# Mas eu queria deixar calara a ideia de usarmos o 'not in'
print(f'Você não tem um pet chamado {name}')
myPets = []
addPets(myPets)
suggestName = input('Qual nome você deseja verificar? ')
doiOwn(myPets, suggestName)
|
pregdata = {
7 : "You need to have an ultrasound to determine the location of the pregnancy sac, size and vitality (heartbeat) of the fetus.",
8 : "You need to have an ultrasound to determine the location of the pregnancy sac, size and vitality (heartbeat) of the fetus.",
9 : "You need to have an ultrasound to determine the location of the pregnancy sac, size and vitality (heartbeat) of the fetus.",
10 : "You need to take the following test :Blood count, fasting glucose, urine culture, blood type (and RH antibodies level if negative), rubella antibodies, VDRL, CMV, antibodies, toxoplasma and HBsAG and if necessary an HIV test.",
11 : "You need to take the following test :Blood count, fasting glucose, urine culture, blood type (and RH antibodies level if negative), rubella antibodies, VDRL, CMV, antibodies, toxoplasma and HBsAG and if necessary an HIV test.",
12 : "Placental structure (chorionic placenta) and early chromosomal genetic diagnostic testing has to be done.",
13 : "Placental structure (chorionic placenta) and early chromosomal genetic diagnostic testing has to be done.",
14 : "You need have an ultrasound, nuchal translucency or fetal development test performed." ,
15 : "Ultrasound screening exam needs to be done.",
16 : "Ultrasound screening exam needs to be done.",
17 : "Triple screen test, fetoprotein or amniocentesis and blood count has to be done.",
18 : "Triple screen test, fetoprotein or amniocentesis and blood count has to be done.",
19 : "Triple screen test, fetoprotein or amniocentesis and blood count has to be done.",
20 : "Triple screen test, fetoprotein or amniocentesis and blood count has to be done.",
21 : "Triple screen test, fetoprotein or amniocentesis and blood count has to be done.",
22 : "Late ultrasound anomaly scan has to be done.",
23 : "Late ultrasound anomaly scan has to be done.",
24 : "Late ultrasound anomaly scan has to be done.",
25 : "Late ultrasound anomaly scan has to be done.",
26 : "You need have glucose tolerance test, blood count and RH antibody levels for those with negative blood type.",
27 : "You need have glucose tolerance test, blood count and RH antibody levels for those with negative blood type.",
28 : "You need have a visit to the physician to discuss glucose test results and talk about receiving RH immune globulin if RH negative",
29 : "You need have a visit to the physician to discuss glucose test results and talk about receiving RH immune globulin if RH negative",
30 : "You need have a visit to the physician to discuss glucose test results and talk about receiving RH immune globulin if RH negative",
31 : "Review of fetal growth has to be now!",
32 : "Review of fetal growth has to be now!",
33 : "Follow-up visit has to be done.",
34 : "Weekly tracking of fetal growth weight needs to be done.",
35 : "Weekly tracking of fetal growth weight needs to be done.",
36 : "Weekly tracking of fetal growth weight needs to be done.",
37 : "Weekly tracking of fetal growth weight needs to be done.",
38 : "Weekly tracking of fetal growth weight needs to be done.",
39 : "Weekly tracking of fetal growth weight needs to be done.",
40 : "Follow-up with doctor, ultrasound, monitoring biophysical profile every 2-4 days should be done."
}
babydata = {
0 : "Baby's dose for BCG vaccine for the prevention of TB and bladder cancer, first dose of HEPB vaccine for the prevention of Hepatitis B and first dose for POLIOVIRUS vaccine for the prevention of polio is due.",
1 : "No vaccination is pending.",
2 : "No vaccination is pending.",
3 : "No vaccination is pending.",
4 : "Baby's second dose of HEPB vaccine for the prevention of Hepatitis B and second dose of POLIOVIRUS vaccine for the prevenion of polio is due.",
5 : "No vaccination is pending.",
6 : "Baby's first dose of DTP vaccine for the prevention of Dipther ia, Tetanus and Pertussis, first dose of Hib vaccine for the prevention of infections, first dose of PCV vaccine for the prevention of Pneumonia, first dose of RV vaccine for the prevention of Diarrhea is due.",
7 : "Baby's first dose of DTP vaccine for the prevention of Dipther ia, Tetanus and Pertussis, first dose of Hib vaccine for the prevention of infections, first dose of PCV vaccine for the prevention of Pneumonia, first dose of RV vaccine for the prevention of Diarrhea is due.",
8 : "Baby's third dose of POLIOVIRUS for the prevention of polio is due.",
9 : "Baby's third dose of POLIOVIRUS for the prevention of polio is due.",
10 :"Baby's second dose of DTP vaccine for the prevention of Dipther ia, Tetanus and Pertussis, second dose of Hib vaccine for the prevention of infections, second dose of PCV vaccine for the prevention of Pneumonia, second dose of RV vaccine for the prevention of Diarrhea is due.",
11 : "Baby's second dose of DTP vaccine for the prevention of Dipther ia, Tetanus and Pertussis, second dose of Hib vaccine for the prevention of infections, second dose of PCV vaccine for the prevention of Pneumonia, second dose of RV vaccine for the prevention of Diarrhea is due.",
12 : "Baby's third dose of HEPB vaccine for the prevention of Hepatitis B is due.",
13 : "Baby's third dose of HEPB vaccine for the prevention of Hepatitis B is due.",
14 : "Baby's third dose of DTP vaccine for the prevention of Dipther ia, Tetanus and Pertussis, third dose of Hib vaccine for the prevention of infections, third dose of PCV vaccine for the prevention of Pneumonia, third dose of RV vaccine for the prevention of Diarrhea is due.",
15 : "Baby's third dose of DTP vaccine for the prevention of Dipther ia, Tetanus and Pertussis, third dose of Hib vaccine for the prevention of infections, third dose of PCV vaccine for the prevention of Pneumonia, third dose of RV vaccine for the prevention of Diarrhea is due.",
16 : "Baby's third dose of DTP vaccine for the prevention of Dipther ia, Tetanus and Pertussis, third dose of Hib vaccine for the prevention of infections, third dose of PCV vaccine for the prevention of Pneumonia, third dose of RV vaccine for the prevention of Diarrhea is due.",
36 : "Baby's first dose of TYPHOID vaccine for the prevention of Typhoid fever and Diarrhea and first dose of MMR vaccine for the prevention of Mumps and Rubella is due.",
38 : "Baby's fourth dose of DTP vaccine for the prevention of Dipther ia, Tetanus and Pertussis, fourth dose of Hib vaccine for the prevention of infections, fourth dose of PCV vaccine for the prevention of Pneumonia is due.",
52 : "Baby's first dose of Varicella vaccine for the prevention of Chicken pox and HepA vaccine for the prevention of the Liver disease.",
55 : "Baby's second dose of MMR vaccine for the prevention of Measles, Mumps and Rubella and Varicella vaccine for the prevention of Chicken pox.",
58 : "Baby's second dose of HepA for the prevention of Liver disease is due.",
104 : "Baby's second dose of Typhoid vaccine for the prevention of Typhoid Fever and Diarrhea is due.",
364 : "Baby's Tdap vaccine for the prevention of the Dipther ia, tetanus, and pertuassis is due.",
468 : "Baby's dose of HPV vaccine for the prevention of cancer and warts is due.",
}
|
class Solution:
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
extra = 1
for i in range(len(digits)-1, -1, -1):
digits[i] += extra
extra = digits[i] // 10
digits[i] %= 10
if extra == 1:
digits.insert(0, 1)
return digits |
a = 999
b = 999999999999999
b = 111
c = 3333333
c = 0000000
d = ieuwoidjfds
|
def includeme(config):
config.add_static_view('static', 'static', cache_max_age=3600)
config.add_route('home', '/')
config.add_route('login', '/login')
config.add_route('auth', '/auth/{action}')
config.add_route('register', '/register')
config.add_route('courses', '/courses')
config.add_route('createcourse', '/createcourse')
config.add_route('createscore', '/createscore')
config.add_route('signscore', '/signscore/{id}')
config.add_route('profile', '/user/{name}')
config.scan()
|
class ISOLATION_LEVEL:
READ_COMMITTED = 'READ COMMITTED'
READ_UNCOMMITTED = 'READ UNCOMMITTED'
REPEATABLE_READ = 'REPEATABLE READ'
SERIALIZABLE = 'SERIALIZABLE'
AUTOCOMMIT = 'AUTOCOMMIT'
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
ADMIN = 1
USER = 2
ROLES = {ADMIN: (ADMIN, 'Administrator'), USER: (USER, 'User')}
administrators = {'Donovan du Plessis': 'donovan@verifaction.co.za'}
error_messages = {
400: 'Bad request',
403: 'Forbidden resource requested',
404: [
'Oops, page not found.', 'We\'re sorry', 'Uh Oh!', 'Nope, not here.'
],
500: 'Something went wrong',
}
|
"""
@author: karthikrao
Program to calculate cost of a floorplan given its Polish Expression.
"""
def get_cost_FP(exp, w, h):
"""
Parameters
----------
Parameters
----------
exp : list
Initial Polish Expression.
w : dict
Contains approx. width of each gate in the netlist.
h : dict
Contains approx. height of each gate in the netlist.
Returns
-------
cost : int
Gives an estimate of the cost (area) of the floorplan.
w1 : dict
Contains approx. width of each gate in the netlist.
h1 : dict
Contains approx. height of each gate in the netlist.
"""
i=-1
c=0
exp1 = exp.copy()
w1=w.copy()
h1=h.copy()
while len(exp1)>1:
i+=1
if exp1[i] == 'H' or exp1[i] == 'V':
new = 'tempnode'+str(c)
if exp1[i] == 'H':
h1[new] = h1[exp1[i-1]] + h1[exp1[i-2]]
w1[new] = max(w1[exp1[i-1]], w1[exp1[i-2]])
if exp1[i] == 'V':
h1[new] = max(h1[exp1[i-1]], h1[exp1[i-2]])
w1[new] = w1[exp1[i-1]] + w1[exp1[i-2]]
exp1 = exp1[:i-2] + [new] + exp1[i+1:]
i=-1
c+=1
cost = h1[exp1[0]]*w1[exp1[0]]
return cost, w1, h1 |
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if not needle: return 0
m, n = len(haystack), len(needle)
for i in range(m-n+1):
j = n +i
if haystack[i:j] == needle:
return i
return -1 |
for _ in range(int(input())):
s=input()
o,e,c1,c2=0,0,0,0
flag=0
for i in range(len(s)):
if i%2==0:
if s[i]=='1':
e+=1
elif s[i]=='?':
c1+=1
else:
if s[i]=='1':
o+=1
elif s[i]=='?':
c2+=1
if o+c2 > e + (9-i)//2:
print(i+1)
flag=1
break
if e+c1 > o + (10-i)//2:
print(i+1)
flag=1
break
if not flag:
print(10) |
# You have an empty stack. You will receive an integer – N. On the next N lines you will receive queries.
# Each query is one of these four types:
# • '1 {number}' – push the number (integer) into the stack
# • '2' – delete the number at the top of the stack
# • '3' – print the maximum number in the stack
# • '4' – print the minimum number in the stack
# It is guaranteed that each query is valid.
# After you go through all the queries, print the stack from the top to the bottom in the following format:
# "{n}, {n1}, {n2}, ... {nn}"
my_stack = []
for _ in range(int(input())):
query = input()
if query[0] == '1':
my_stack.append(query[2:])
elif my_stack:
if query == '2':
my_stack.pop()
elif query == '3':
print(max(my_stack))
elif query == '4':
print(min(my_stack))
print(f', '.join([my_stack.pop() for _ in range(len(my_stack))]))
|
"""
This sub-module contains input/output modifiers that can be applied to
arguments to ``needs`` and ``provides`` to let GraphKit know it should treat
them differently.
Copyright 2016, Yahoo Inc.
Licensed under the terms of the Apache License, Version 2.0. See the LICENSE
file associated with the project for terms.
"""
class optional(str):
"""
An optional need signifies that the function's argument may not receive a value.
Only input values in ``needs`` may be designated as optional using this modifier.
An ``operation`` will receive a value for an optional need only if if it is available
in the graph at the time of its invocation.
The ``operation``'s function should have a defaulted parameter with the same name
as the opetional, and the input value will be passed as a keyword argument,
if it is available.
Here is an example of an operation that uses an optional argument::
>>> from graphkit import operation, compose, optional
>>> # Function that adds either two or three numbers.
>>> def myadd(a, b, c=0):
... return a + b + c
>>> # Designate c as an optional argument.
>>> graph = compose('mygraph')(
... operation(name='myadd', needs=['a', 'b', optional('c')], provides='sum')(myadd)
... )
>>> graph
NetworkOperation(name='mygraph',
needs=[optional('a'), optional('b'), optional('c')],
provides=['sum'])
>>> # The graph works with and without 'c' provided as input.
>>> graph({'a': 5, 'b': 2, 'c': 4})['sum']
11
>>> graph({'a': 5, 'b': 2})
{'a': 5, 'b': 2, 'sum': 7}
"""
__slots__ = () # avoid __dict__ on instances
def __repr__(self):
return "optional('%s')" % self
class sideffect(str):
"""
A sideffect data-dependency participates in the graph but never given/asked in functions.
Both inputs & outputs in ``needs`` & ``provides`` may be designated as *sideffects*
using this modifier. *Sideffects* work as usual while solving the graph but
they do not interact with the ``operation``'s function; specifically:
- input sideffects are NOT fed into the function;
- output sideffects are NOT expected from the function.
.. info:
an ``operation`` with just a single *sideffect* output return no value at all,
but it would still be called for its side-effect only.
Their purpose is to describe operations that modify the internal state of
some of their arguments ("side-effects").
A typical use case is to signify columns required to produce new ones in
pandas dataframes::
>>> from graphkit import operation, compose, sideffect
>>> # Function appending a new dataframe column from two pre-existing ones.
>>> def addcolumns(df):
... df['sum'] = df['a'] + df['b']
>>> # Designate `a`, `b` & `sum` column names as an sideffect arguments.
>>> graph = compose('mygraph')(
... operation(
... name='addcolumns',
... needs=['df', sideffect('a'), sideffect('b')],
... provides=[sideffect('sum')])(addcolumns)
... )
>>> graph
NetworkOperation(name='mygraph', needs=[optional('df'), optional('sideffect(a)'), optional('sideffect(b)')], provides=['sideffect(sum)'])
>>> # The graph works with and without 'c' provided as input.
>>> df = pd.DataFrame({'a': [5], 'b': [2]}) # doctest: +SKIP
>>> graph({'df': df})['sum'] == 11 # doctest: +SKIP
True
Note that regular data in *needs* and *provides* do not match same-named *sideffects*.
That is, in the following operation, the ``prices`` input is different from
the ``sideffect(prices)`` output:
>>> def upd_prices(sales_df, prices):
... sales_df["Prices"] = prices
>>> operation(fn=upd_prices,
... name="upd_prices",
... needs=["sales_df", "price"],
... provides=[sideffect("price")])
operation(name='upd_prices', needs=['sales_df', 'price'], provides=['sideffect(price)'], fn=upd_prices)
.. note::
An ``operation`` with *sideffects* outputs only, have functions that return
no value at all (like the one above). Such operation would still be called for
their side-effects.
.. tip::
You may associate sideffects with other data to convey their relationships,
simply by including their names in the string - in the end, it's just a string -
but no enforcement will happen from *graphkit*.
>>> sideffect("price[sales_df]")
'sideffect(price[sales_df])'
"""
__slots__ = () # avoid __dict__ on instances
def __new__(cls, name):
return super(sideffect, cls).__new__(cls, "sideffect(%s)" % name)
|
def header_option():
return {'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': '*', 'Access-Control-Allow-Methods': '*'}
def check_session(header):
session = header.get('session') or header.get('Session')
if session:
return session
|
# Exercise 5.1: Write a program which repeatedly reads numbers until the
# user enters “done”. Once “done” is entered, print out the total, count,
# and average of the numbers. If the user enters anything other than a
# number, detect their mistake using try and except and print an error
# message and skip to the next number.
# Enter a number: 4
# Enter a number: 5
# Enter a number: bad data
# Invalid input
# Enter a number: 7
# Enter a number: done
# 16 3 5.333333333333333
# Python for Everybody: Exploring Data Using Python 3
# by Charles R. Severance
total = 0.0
count = 0
average = 0.0
while True:
input_number = input("Enter a number: ")
if input_number == "done":
break
number = None
try:
number = float(input_number)
except:
print("Invalid input")
continue
total += number
count += 1
average = total / count
print(total, count, average)
|
'''
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
'''
nums = range(999, 99, -1)
allProducts = [x * y for x in nums for y in nums]
palindromeProducts = [p for p in allProducts if str(p) == str(p)[::-1]]
answer = max(palindromeProducts)
print(answer)
|
## Python Crash Course
# Exercise 3.8: Seeing the World:
# Think of at least five places in the world you’d like to visit .
# • Store the locations in a list . Make sure the list is not in alphabetical order.
# • Print your list in its original order . Don’t worry about printing the list neatly, just print it as a raw Python list.
# • Use sorted() to print your list in alphabetical order without modifying the actual list.
# • Show that your list is still in its original order by printing it.
# • Use sorted() to print your list in reverse alphabetical order without changing the order of the original list.
# • Show that your list is still in its original order by printing it again.
# • Use reverse() to change the order of your list . Print the list to show that its order has changed.
# • Use reverse() to change the order of your list again . Print the list to show it’s back to its original order.
# • Use sort() to change your list so it’s stored in alphabetical order . Print the list to show that its order has been changed.
# • Use sort() to change your list so it’s stored in reverse alphabetical order . Print the list to show that its order has changed.
def main():
# Prepare list of places in the world to visit
placesToVisit = ['Paris', 'Seychelles', 'Maldives', 'Hawai', 'Yosemite']
# Print the raw list
print("\nI want to visit following places with Manasi in lifetime:")
print(placesToVisit)
# Print list in alphabetical order without modifying original list using sorted function
print("\nPrinting list in alphabetical oreder using 'sorted' function")
print(sorted(placesToVisit))
# Print the original list, ensure that sorted function that is used prior did not change the order in original list
print("\nPrinting original list to ensure that it is intact and in the way as it was defined:")
print(placesToVisit)
# Print the list in reverse alphabetical order without modifying original list
print("\nPrinting list in reverse alphabetical order using sorted function:")
print(sorted(placesToVisit, reverse=True))
# Print original list to ensure that it is as it was defined in the first place
print("\nPrinting original list to ensure that it is intact and in the way as it was defined:")
print(placesToVisit)
# Use reverse function to reverse the order of the list
print("\nPrinting the list in reverse order:")
placesToVisit.reverse()
print(placesToVisit)
# Use reverse function again so that list becones back to original as it was defined at the first place
print("\nReversing the list again to obtain original list:")
placesToVisit.reverse()
print(placesToVisit)
# Sort the original list alphabetically
print("\nSorting the list alphabetically:")
placesToVisit.sort()
print(placesToVisit)
# Sort the previously sorted list in reverse order
print("\nReversing the order of places in list that was sorted alphabetically:")
placesToVisit.sort(reverse=True)
print(placesToVisit)
if __name__ == '__main__':
main()
|
bool(re.search(r'\t', 'cat\tdog'))
bool(re.search(r'\c', 'cat\tdog'))
print(re.sub(r'(?m)^', r'foo ', '1\n2\n'))
print(re.sub(r'(?m)$', r' baz', '1\n2\n'))
re.sub(r'[^,]*', r'{\g<0>}', ',cat,tiger')
regex.sub(r'[^,]*+', r'{\g<0>}', ',cat,tiger')
re.sub(r'(?<![^,])[^,]*', r'{\g<0>}', ',cat,tiger')
re.sub(r'\A([^,]+,){3}([^,]+)', r'\1(\2)', '1,2,3,4,5,6,7', count=1)
re.sub(r'\A((?:[^,]+,){3})([^,]+)', r'\1(\2)', '1,2,3,4,5,6,7', count=1)
re.findall(r'([^,]+,){3}', '1,2,3,4,5,6,7')
re.findall(r'(?:[^,]+,){3}', '1,2,3,4,5,6,7')
re.findall(r'[[:word:]]+', 'fox:αλεπού,eagle:αετός', flags=re.A)
regex.findall(r'[[:word:]]+', 'fox:αλεπού,eagle:αετός', flags=re.A)
regex.findall(r'[[:word:]]+', 'fox:αλεπού,eagle:αετός', flags=regex.A)
|
def fib(n):
if (n==1 or n==0):
return n
print("we are trying to calculate fib(",n,") we will call fib(",n-1,") fib(",n-2,")")
return fib(n-1) + fib(n-2)
for i in range(1,10):
print (fib(i))
|
class Solution:
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
prev = None
while head:
next = head.next
head.next = prev
prev = head
head = next
return prev |
class BotDBException(Exception):
"""DB exception"""
class AlreadyHasItException(BotDBException):
"""The database already has such a record"""
class NoSuchUser(BotDBException):
"""No such user in database"""
class NoSuchChannel(BotDBException):
"""No such channel in database"""
class ActuatorsRuntimeException(Exception):
...
class ActuatorAlreadyConnected(ActuatorsRuntimeException):
"""Actuator already plugged on"""
class NoSuchActuatorInRAM(ActuatorsRuntimeException):
"""No such client in ram_storage"""
class NoSuchCommand(ActuatorsRuntimeException):
"""No such command for client"""
def __init__(self, cmd: str, *args):
super().__init__(*args)
self.cmd = cmd
|
# -*- coding: utf-8 -*-
"""
@Time : 2021/12/20 14:23
@Author : 物述有栖
@File : __init__.py.py
@DES :
"""
|
n1= int(input('Digite o primeiro numero '))
n2= int(input('digite o segundo numero '))
resultado = n1+n2
print ('O resultado de {} + {} = {}'.format(n1,n2,resultado)) |
class DatabaseSeeder:
seeds = [
#
]
|
YOUTUBE_API_KEY = [ ""]
YOUTUBE_KEY_NUMBER = 0
SPOTIFY_CLIENT_ID = ""
SPOTIFY_CLIENT_SECRET = ""
MONGO_ATLAS_USER = ""
MONGO_ATLAS_PASSWORD = "" |
# Time: O(n), where n=len(A)+len(B)
# Space: O(n)
class Solution:
def intervalIntersection(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]:
a = 0
b = 0
ans = []
while a<len(A) and b<len(B):
start = max(A[a][0], B[b][0])
end = min(A[a][1], B[b][1])
if start<=end:
ans.append([start, end])
if end==A[a][1]:
a+=1
else:
b+=1
return ans
|
# -*- coding: utf-8 -*-
def main():
employer_number = int(input())
worked_hours = int(input())
amount_per_hour = float(input())
salary = worked_hours * amount_per_hour
print('NUMBER =', employer_number)
print('SALARY = U$ %.2f' % salary)
if __name__ == '__main__':
main() |
# Self powers
# Answer: 9110846700
def self_powers(limit=1001):
total = 0
for x in range(1, limit):
total += x ** x
return str(total)[-10:]
if __name__ == "__main__":
print(self_powers())
|
## Python Crash Course
# Exercise 8.6: City Names:
# Write a function called city_country() that takes in the name of a city and its country.
# The function should return a string formatted like this: "Santiago, Chile"
# Call your function with at least three city-country pairs, and print the value that’s returned.
#
def city_country(city='',country=''):
print("\n")
print('"',city,",",country,'"')
if __name__ == '__main__':
city_country(city='Reykjavik',country="Sweeden")
city_country(city="Santiago",country="Chille")
city_country(city="Sydney",country="Australia")
|
l = []
cont = 0
while True:
n = int(input(f'Digite um valor na posiçao {cont}: '))
cont += 1
if n not in l:
l.append(n)
print('Valor adicionado com sucesso')
else:
print('valor dupllicado nao vou adicionaor: ')
n = str(input('Quer continuar: ')).upper()[0]
if n in 'Nn':
break
l.sort()
print(l)
|
# In this game basiclly I am going to let you input a bruch of
# words and put them into my text, that makes a funny story.
# A few ways to do this:
# youtuber = 'Chanling'
# print('subscribe to ' + youtuber)
# print('subscribe to {}'.format(youtuber))
# print(f'subscribe to {youtuber}')
color = input('Enter a color you love ')
plural_noun = input('Enter a plural noun ')
celebrity = input('Enter a celebrity ')
print('Roses are ' + color)
print(plural_noun + ' are blue')
print('I love ' + celebrity) |
{
"targets": [
{
"target_name": "<(module_name)",
"sources": [
"src/node-aes-ccm.cc",
"src/node-aes-gcm.cc",
"src/addon.cc"
],
'conditions': [
[
'OS=="win"',
{
'conditions': [
# "openssl_root" is the directory on Windows of the OpenSSL files
[
'target_arch=="x64"',
{
'variables': {
'openssl_root%': 'C:/OpenSSL-Win64'
},
#'libraries': [ '<(openssl_root)/lib/<!@(dir /B C:\OpenSSL-Win64\lib\libeay32.lib C:\OpenSSL-Win64\lib\libcrypto.lib)' ],
},
{
'variables': {
'openssl_root%': 'C:/OpenSSL-Win32'
},
#'libraries': [ '<(openssl_root)/lib/<!@(dir /B C:\OpenSSL-Win32\lib\libeay32.lib C:\OpenSSL-Win32\lib\libcrypto.lib)' ],
}
],
],
'defines': [
'uint=unsigned int',
],
'include_dirs': [
'<(openssl_root)/include',
'<!(node -e "require(\'nan\')")',
],
},
{ # OS!="win"
'include_dirs': [
# use node's bundled openssl headers on Unix platforms
'<(node_root_dir)/deps/openssl/openssl/include',
'<!(node -e "require(\'nan\')")',
],
}
],
],
},
{
"target_name": "action_after_build",
"type": "none",
"dependencies": [ "<(module_name)" ],
"copies": [
{
"files": [ "<(PRODUCT_DIR)/<(module_name).node" ],
"destination": "<(module_path)"
}
]
}
]
}
|
"""
https://leetcode.com/problems/restore-ip-addresses/
"""
def solve(s):
res = []
n = len(s)
if n > 12:
return []
def bt(ans, i):
if i == n and len(ans) == 4:
res.append(".".join(ans))
return
for j in range(i + 1, n + 1):
if len(ans) < 4:
candidate = s[i:j]
v = int(candidate)
if v <= 255 and str(v) == candidate:
bt(ans + [candidate], j)
bt([], 0)
return res
|
N = int(input())
w = input()
d = {'b': 1, 'c': 1, 'd': 2, 'w': 2, 't': 3, 'j': 3, 'f': 4, 'q': 4, 'l': 5, 'v': 5,
's': 6, 'x': 6, 'p': 7, 'm': 7, 'h': 8, 'k': 8, 'n': 9, 'g': 9, 'z': 0, 'r': 0}
result = []
for s in w.split():
t = ''.join(str(d[c]) for c in s.lower() if c in d).strip()
if t != '':
result.append(t)
print(*result)
|
class BotProcessorFactory(object):
'''
Factory class to give the appropriate processor based on action
'''
def __init__(self):
pass
def getProcessor(self,action):
'''
Returns an object of Processor
'''
pass
class BaseProcessor(object):
'''
BaseProcessor class to process actions
Input: Structured JSON data
returns response
'''
def process(self,input):
pass
|
n, x = map(int, input().split())
s = input()
d = []
for i in range(n):
d.append(input())
# [d1, d2, d3, ..., dN]
t = [int(m) for m in d]#int型に直す
ans = 0
for i in range(n):
if s[i] == "1":
if t[i] > x:
ans += x
else:
ans += t[i]
else:
ans += t[i]
print(ans) |
# 1950年2月17日为正月初一
D = {} #1 2 3 4 5 6 7 8 9 10 11 12
D[1950] = ['19500217', 29, 30, 30, 29, 30, 30, 29, 29, 30, 29, 30, 29]
D[1951] = ['19510206', 30, 29, 30, 30, 29, 30, 29, 30, 29, 30, 29, 30]
D[1963] = ['19630125', 30, 29, 30, [29, 29], 30, 29, 30, 29, 30, 30, 30, 29]
D[1989] = ['19890206', 30, 29, 29, 30, 29, 30, 29, 30, 29, 30, 30, 30]
D[1991] = ['19910215', 29, 30, 29, 29, 30, 29, 29, 30, 29, 30, 30, 30]
D[2017] = ['20170128', 29, 30, 29, 30, 29, [29, 30], 29, 30, 29, 30, 30, 30]
D[2018] = ['20180216', 29, 30, 29, 30, 29, 29, 30, 29, 30, 29, 30, 30]
D[2019] = ['20190205', 30, 29, 30, 29, 30, 29, 29, 30, 29, 29, 30, 30]
def is_leap_year(year):
if year % 4:
return False
if year % 100 == 0 and year % 400 != 0:
return False
return True
def get_days(year, month):
l = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if is_leap_year(year):
l[1] = 29
return l[month-1]
def next_day_solar(year, month, day):
if day == get_days(year, month):
if month == 12:
year += 1
month = 1
else:
month += 1
day = 1
else:
day += 1
return year, month, day
def next_day_lunar(year, month, day, rerun):
day_num = D[year][month]
if type(day_num) is type([1,2]):
if rerun:
if day == day_num[1]:
day = 1
month += 1
return month, day, True
else:
day += 1
return month, day, True
else:
if day == day_num[0]:
day = 1
return month, day, True
else:
day += 1
return month, day, False
else:
if day == D[year][month]:
month += 1
day = 1
else:
day += 1
return month, day, False
def compare_solar(date1, date2):
sign = 1
if date1 > date2:
date1, date2 = date2, date1
sign = -1
count = 0
year = int(date1[:4])
month = int(date1[4:6])
day = int(date1[6:])
year2 = int(date2[:4])
month2 = int(date2[4:6])
day2 = int(date2[6:])
while year != year2 or month != month2 or day != day2:
year, month, day = next_day_solar(year, month, day)
count += 1
return count * sign
def solar2lunar(date):
sy = int(date[0:4])
if date < D[sy][0]:
year = sy - 1
else:
year = sy
count = compare_solar(D[year][0], date)
lm, ld = 1, 1
while count > 0:
# 有闰月
if type(D[year][lm]) is type([1,2]):
tmp = sum(D[year][lm])
if count >= tmp:
count -= tmp
lm += 1
else:
if count >= D[year][lm][0]:
count -= D[year][lm][0]
ld += count
count = 0
else:
ld += count
count = 0
else:
if count >= D[year][lm]:
count -= D[year][lm]
lm += 1
else:
ld += count
count = 0
return lm, ld
def lunar2solar(date, leap_month=False):
ly = int(date[0:4])
lm = int(date[4:6])
ld = int(date[6:8])
sdate = D[ly][0]
sy = int(sdate[0:4])
sm = int(sdate[4:6])
sd = int(sdate[6:8])
m, d = 1, 1
rerun = False
while m!=lm or d!=ld:
m, d, rerun = next_day_lunar(ly, m, d, rerun)
sy, sm, sd = next_day_solar(sy, sm, sd)
for item in D[ly]:
if type(item) is type([1,2]) and leap_month:
m, d, rerun = next_day_lunar(ly, m, d, rerun)
sy, sm, sd = next_day_solar(sy, sm, sd)
while m!=lm or d!=ld:
m, d, rerun = next_day_lunar(ly, m, d, rerun)
sy, sm, sd = next_day_solar(sy, sm, sd)
return sy, sm, sd
if __name__ == '__main__':
print(compare_solar('19891012', '19891013'))
test_cases1 = ['20180102', '20181013', '19891013', '20170304', '20170802', '20171231']
for item in test_cases1:
m, d = solar2lunar(item)
print(item + ': 阴历' + str(m) + '月' + str(d) + '日')
test_cases2 = ['19910623', '20170630']
for item in test_cases2:
y, m, d = lunar2solar(item, False)
print('阴历'+item+'为阳历'+str(y)+'年'+str(m)+'月'+str(d)+'日') |
class Solution:
def plusOne(self, digits):
num = 0
for i in range(len(digits)):
num += digits[i]*(10**(len(digits)-1-i))
list = [int(i) for i in str(num+1)]
return list
"""
You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's.
Increment the large integer by one and return the resulting array of digits.
Example 1:
Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be [1,2,4].
Example 2:
Input: digits = [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
Incrementing by one gives 4321 + 1 = 4322.
Thus, the result should be [4,3,2,2].
Example 3:
Input: digits = [9]
Output: [1,0]
Explanation: The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be [1,0].
""" |
# Basic settings for test project
# Database settings. This assumes that the default user and empty
# password will work.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'django_pg_agefilter',
'USER': '',
'PASSWORD': '',
'HOST': 'localhost',
}
}
SECRET_KEY = 'secret'
INSTALLED_APPS = (
'tests.app',
)
SILENCED_SYSTEM_CHECKS = [
'1_7.W001',
]
|
"""
25.62%
参考答案的,自己没思路
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def largestValues(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
maxes = []
row = [root]
while any(row):
maxes.append(max(node.val for node in row))
row = [kid for node in row for kid in (node.left, node.right) if kid]
return maxes |
'''
Description:
selectionSort (Algorithm Description) - This sorting algorithm is an in-place comparison-based algorithm in which the list is divided into two parts, the sorted part at the left end and the unsorted part at the right end. The smallest element is selected from the unsorted array and swapped with the leftmost element, and that element becomes a part of the sorted array. This process continues moving unsorted array boundary by one element to the right.
Average Time Complexity: O(n^2)
Tip: This algorithm is not suitable for large data sets as its average and worst case complexities are of Ο(n2), where n is the number of items.
Status: Complete.
'''
def selectionSort(input_list):
n = len(input_list)
for i in range(0,n-1):
min_element = i
for j in range(i+1,n):
if input_list[j] < input_list[min_element]:
min_element = j
#swap the min with with the actual min
temp = input_list[i]
input_list[i] = input_list[min_element]
input_list[min_element] = temp
##DRIVER
if __name__ == '__main__':
my_list = [10,9,4,1,89,45,67,23,12,76]
selectionSort(my_list)
print(my_list) |
#Unchanged Magicians:
listOfMagicians = ['Dynamo','david blain','karan singh magic']
newListOfMagicians = []
def show_magicians(listOfMagicians):
for magician in listOfMagicians:
print(magician)
def make_great(listofnames):
for name in listofnames:
newListOfMagicians.append("The Great "+name)
show_magicians(listOfMagicians)
make_great(listOfMagicians)
show_magicians(newListOfMagicians) |
#
# author: redleaf
# email: redleaf@gapp.nthu.edu.tw
#
def solve1(A, B, C):
a, b, c, ans = 0, 0, 0, 0
while a < len(A) and b < len(B) and c < len(C):
if B[b] < A[a] and B[b] < C[c]:
ans += (len(A) - a) * (len(C) - c)
b += 1
elif A[a] < C[c]:
a += 1
else:
c += 1
return ans
if __name__ == '__main__':
na, nb, nc = map(int, input().split())
A = sorted(list(map(int, input().split())))
B = sorted(list(map(int, input().split())))
C = sorted(list(map(int, input().split())))
print(solve1(A, B, C)) |
def screen(int):
size = str(int)
return str(size+"%")
def vh(int):
size = str(int)
return str(size+"vh")
def vw(int):
size = str(int)
return str(size+"vw")
def px(int):
size = str(int)
return str(size+"px") |
def bubble_sort(data, size):
swap = False
for x in range(0, size-1):
if data[x] > data[x+1]:
data[x], data[x+1] = data[x+1], data[x]
swap = True
if swap:
bubble_sort(data, size-1)
if __name__ == '__main__':
data = [2, 9, 8, 0, 1, 3, 5, 4, 6, 7]
print(data)
bubble_sort(data, len(data))
print(data)
|
#coding=utf-8
#!encoding=utf-8
'''
Created on 2013-12-30
@author: ETHAN
'''
class AutomationTaskDBRouter(object):
'''
db router for automationtesting
'''
def db_for_read(self,model,**hints):
''' read data from db automationtask
'''
if model._meta.app_label=='automationtesting':
return 'automationtesting'
def db_for_write(self,model,**hints):
''' write data to db automationtask
'''
if model._meta.app_label=='automationtesting':
return 'automationtesting'
def allow_syncdb(self,db,model):
''' make sure doraemon.automationtask just in db dorameon_automationtask
'''
if db=='automationtesting':
return model._meta.app_label=="automationtesting"
elif model._meta.app_label=="automationtesting":
return False
def allwo_relation(self,obj1,obj2,**hints):
if obj1._meta.app_label == 'automationtesting' or obj2._meta.app_label == 'automationtesting':
return True
return None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.