content
stringlengths 7
1.05M
|
|---|
"""import numpy as np
import matplotlib.pyplot as plt
class Grid:
def __init__(self, height, weight, start):
self.height = height
self.weight = weight
self.i = start[0]
self.j = start[1]
def set(self, rewards, actions):
self.rewards = rewards
self.actions = actions
def set_state(self, s):
self.i = s[0]
self.j = s[1]
def current_state(self):
return (self.i, self.j)
def is_terminal(self, s):
return s not in self.actions
def move(self, action):
if action in self.actions[(self.i, self.j)]:
if action == 'U':
self.i -= 1
if action == "D":
self.i += 1
if action == "R":
self.j += 1
if action == "L":
self.j -= 1
return self.rewards.get((self.i, self.j), 0)
def undo_move(self, action):
if action == 'U':
self.i += 1
if action == 'D':
self.i -= 1
if action == 'R':
self.j -= 1
if action == 'L':
self.j += 1
assert(self.current_state in self.all_states)
def game_over(self):
return (self.i, self.j) not in self.actions
def all_states(self):
return set(self.actions.keys()) | set(self.rewards.keys())
def standard_grid():
g = Grid(3, 4, (0,2))
rewards = {(0,3) : 1, (1,3) : -1}
actions = {
(0, 0): ('D', 'R'),
(0, 1): ('L', 'R'),
(0, 2): ('L', 'D', 'R'),
(1, 0): ('U', 'D'),
(1, 2): ('U', 'D', 'R'),
(2, 0): ('U', 'R'),
(2, 1): ('L', 'R'),
(2, 2): ('L', 'R', 'U'),
(2, 3): ('L', 'U'),
}
g.set(rewards, actions)
return g
def negative_grid(step_cost = -0.1):
g = standard_grid()
g.rewards.update({
(0, 0): step_cost,
(0, 1): step_cost,
(0, 2): step_cost,
(1, 0): step_cost,
(1, 2): step_cost,
(2, 0): step_cost,
(2, 1): step_cost,
(2, 2): step_cost,
(2, 3): step_cost,
})
return g
"""
class Grid: #Environment
def __init__(self, width, height, start):
self.height = height
self.width = width
self.i = start[0]
self.j = start[1]
def set(self, rewards , actions):
self.rewards = rewards
self.actions = actions
def set_state(self, s):
self.i = s[0]
self.j = s[1]
def current_state(self):
return (self.i, self.j)
def game_over(self):
return (self.i, self.j) not in self.actions
def is_terminal(self, s):
return s not in self.actions
def move(self, action):
if action in self.actions[(self.i, self.j)]:
if action == 'U':
self.i -= 1
if action == 'D':
self.i += 1
if action == 'R':
self.j += 1
if action == 'L':
self.j -= 1
return self.rewards.get((self.i, self.j), 0)
def undo_move(self, action):
if action == 'U':
self.i += 1
if action == 'D':
self.i -= 1
if action == 'R':
self.j -= 1
if action == 'L':
self.j += 1
assert(self.current_state in self.all_states)
def all_states(self):
return set(self.actions.keys()) | set(self.rewards.keys())
def standard_grid():
g = Grid(3, 4, (2,0))
rewards = {(0,3) : 1, (1,3) : -1}
actions = {
(0, 0): ('D', 'R'),
(0, 1): ('L', 'R'),
(0, 2): ('L', 'D', 'R'),
(1, 0): ('U', 'D'),
(1, 2): ('U', 'D', 'R'),
(2, 0): ('U', 'R'),
(2, 1): ('L', 'R'),
(2, 2): ('L', 'R', 'U'),
(2, 3): ('L', 'U'),
}
g.set(rewards, actions)
return g
def negative_grid(step_cost = -0.1):
g = standard_grid()
g.rewards.update({
(0, 0): step_cost,
(0, 1): step_cost,
(0, 2): step_cost,
(1, 0): step_cost,
(1, 2): step_cost,
(2, 0): step_cost,
(2, 1): step_cost,
(2, 2): step_cost,
(2, 3): step_cost,
})
return g
|
'''
Represents the different HTTP status codes
returned from the API to indicate errors.
http://docs.veritranspay.co.id/sandbox/status_code.html
'''
# 20x - successful submission to api
SUCCESS = 200 # NOTE: this is returned when manually cancelled too!
CHALLENGE = 201
PENDING = 201 # NOTE: returned when payment type is VirtualAccount, Cimb, Bri Epay, KlikBCA, Klikpay BCA,
EXPIRED = 202 # NOTE: returned when payment type is GoPay
# 30x
MOVED_PERMANENTLY = 300
# 40x
VALIDATION_ERROR = 400
ACCESS_DENIED = 401
# note: documented as 'Access Denied' but this is more descriptive
# and that would also create two 'Access Denied'
UNAVAILABLE_PAYMENT_TYPE = 402
DUPLICATE_ORDER_ID = 406
ACCOUNT_INACTIVE = 410
TOKEN_ERROR = 411
# 50x
SERVER_ERROR = 500
FEATURE_UNAVAILABLE = 501
BANK_CONNECTION_PROBLEM = 502
SERVER_ERROR_OTHER = 503
FRAUD_DETECTION_UNAVAILABLE = 504
|
N = 4
board = [input() for _ in range(4)]
for i in range(N):
for j in range(N):
cand = []
if j + 2 < N:
cand.append([board[i][j+k] for k in range(3)])
if i + 2 < N:
cand.append([board[i+k][j] for k in range(3)])
if i + 2 < N and j + 2 < N:
cand.append([board[i+k][j+k] for k in range(3)])
if i + 2 < N and j - 2 >= 0:
cand.append([board[i+k][j-k] for k in range(3)])
for row in cand:
for k in range(3):
if all(c == 'x' if i != k else c == '.' for i, c in enumerate(row)):
print("YES")
quit()
print("NO")
|
LOG_FILE = 'temperature.log'
ZONE_ID = 'ZoneId'
MAX_TEMP = 'MaximumTemperature'
TRIGGERED = 'Triggered'
INCORRECT_CREDENTIALS = 'Incorrect Credentials.'
INCORRECT_ARGUEMENTS = 'Incorrect arguments provided - IP username password'
TEMPERATURE_API = 'http://{}/axis-cgi/temperature_alarm/getzonestatus.cgi?'
DATE_TIME_FORMAT = '%Y-%m-%d %H:%M:%S'
|
def coroutine(seq):
count = 0
while count < 200:
count += yield
seq.append(count)
seq = []
c = coroutine(seq)
next(c)
___assertEqual(seq, [])
c.send(10)
___assertEqual(seq, [10])
c.send(10)
___assertEqual(seq, [10, 20])
|
def active_message(domain, uidb64, token):
return f"아래 링크를 클릭하시면 인증이 완료되며, 바로 로그인하실 수 있습니다.\n\n링크 : https://{domain}/activate/{uidb64}/{token}\n\n감사합니다."
def reset_message(domain, uidb64, token):
return f"아래 링크를 클릭하시면 비밀번호 변경을 진행하실 수 있습니다.\n\n링크 : https://{domain}/reset/{uidb64}/{token}\n\n감사합니다."
|
# Make sure you follow the order of reaction
# output should be H2O,CO2,CH4
def burner(c,h,o):
water = co2 = methane = 0
if h >= 2 and o >= 1:
if 2 * o >= h:
water = h // 2
o -= water
h -= 2*water
else:
water = o
o -= water
h -= 2 * water
if o >= 2 and c >= 1:
if 2 * c >= o:
co2 = o // 2
c -= co2
o -= co2*2
else:
co2 = c
c -= co2
o -= co2 * 2
if c >= 1 and h >= 4:
if c * 4 >= h:
methane = h // 4
else:
methane = c
return water, co2, methane
|
class Solution:
def convertToBase7(self, num: int) -> str:
if num == 0:
return "0"
num, neg = (num, False) if num > 0 else (-num, True)
res = []
while num:
num, r = divmod(num, 7)
res.append(r)
if neg:
res.append("-")
return "".join(map(str, reversed(res)))
|
fin = open("Crime.csv")
for line in fin:
word = line.split()
def crime():
print(" Crime Type | Crime ID | Crime Count")
if (word == "ASSAULT" and word =="ROBBERY" and word == "THEFT OF VEHICLE" and word == "BREAK AND ENTER"):
print (word)
lst = []
for i in word:
lst.append(i)
crime
|
n = 1
par = impar = 0
while n != 0:
n = int(input('Digite um número: '))
if n != 0:
if n % 2 == 0:
par += 1
else:
impar += 1
print(f'Tem {par} número(s) par(es) e {impar} número(s) ímpar(es).')
|
def reduce_polymer(orig, to_remove=None, max_len=-1):
polymer = []
for i in range(len(orig)):
# We save a lot of processing time for Part 2
# if we cut off the string building once the
# array is too long
if max_len > 0 and len(polymer) >= max_len: return None
# The test character for Part 2 is 'removed'
# by just not adding it to the polymer array
if to_remove and orig[i].lower() == to_remove: continue
polymer.append(orig[i])
end_pair = polymer[len(polymer)-2:]
while len(polymer) > 1 and end_pair[0] != end_pair[1] and end_pair[0].lower() == end_pair[1].lower():
# If the end pair meets the criteria of being a matched upper and lower case
# then remove it from the end of the array. Repeat until the end pair is not removed
polymer = polymer[:-2]
end_pair = polymer[len(polymer)-2:]
return polymer
input = open('input/input05.txt').read()
print('Solution 5.1:', len(reduce_polymer(input)))
distinct_char = set(input.lower())
min_len = len(input)
char_to_remove = ''
for c in distinct_char:
poly = reduce_polymer(input, c, min_len)
if poly is not None and len(poly) < min_len:
min_len = len(poly)
char_to_remove = c
print('Most troublesome character is', char_to_remove)
print('Solution 5.2:', min_len)
|
# coding: utf-8
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache LICENSE, Version 2.0 (the
"LICENSE"); you may not use this file except in compliance
with the LICENSE. You may obtain a copy of the LICENSE at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the LICENSE is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the LICENSE for the
specific language governing permissions and limitations
under the LICENSE.
"""
class AuthCache:
_cache_dict = {}
@classmethod
def get_auth(cls, ak_with_name):
return cls._cache_dict.get(ak_with_name) if ak_with_name else None
@classmethod
def put_auth(cls, ak_with_name, _id):
cls._cache_dict[ak_with_name] = _id
|
na, nb = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a = set(a)
b = set(b)
t = len(a & b)
t2 = len(a.union(b))
print(t/t2)
|
#
# PySNMP MIB module MPLS-LC-FR-STD-MIB (http://pysnmp.sf.net)
# ASN.1 source http://mibs.snmplabs.com:80/asn1/MPLS-LC-FR-STD-MIB
# Produced by pysmi-0.0.7 at Sun Feb 14 00:21:02 2016
# On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose
# Using Python version 3.5.0 (default, Jan 5 2016, 17:11:52)
#
( ObjectIdentifier, Integer, OctetString, ) = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString")
( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
( ConstraintsUnion, ValueRangeConstraint, ConstraintsIntersection, ValueSizeConstraint, SingleValueConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueRangeConstraint", "ConstraintsIntersection", "ValueSizeConstraint", "SingleValueConstraint")
( DLCI, ) = mibBuilder.importSymbols("FRAME-RELAY-DTE-MIB", "DLCI")
( mplsInterfaceIndex, ) = mibBuilder.importSymbols("MPLS-LSR-STD-MIB", "mplsInterfaceIndex")
( mplsStdMIB, ) = mibBuilder.importSymbols("MPLS-TC-STD-MIB", "mplsStdMIB")
( ObjectGroup, ModuleCompliance, NotificationGroup, ) = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "ModuleCompliance", "NotificationGroup")
( TimeTicks, ObjectIdentity, NotificationType, Gauge32, ModuleIdentity, Counter64, Unsigned32, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, Integer32, iso, Counter32, Bits, ) = mibBuilder.importSymbols("SNMPv2-SMI", "TimeTicks", "ObjectIdentity", "NotificationType", "Gauge32", "ModuleIdentity", "Counter64", "Unsigned32", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "Integer32", "iso", "Counter32", "Bits")
( TextualConvention, StorageType, DisplayString, RowStatus, ) = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "StorageType", "DisplayString", "RowStatus")
mplsLcFrStdMIB = ModuleIdentity((1, 3, 6, 1, 2, 1, 10, 166, 10)).setRevisions(("2006-01-12 00:00",))
if mibBuilder.loadTexts: mplsLcFrStdMIB.setLastUpdated('200601120000Z')
if mibBuilder.loadTexts: mplsLcFrStdMIB.setOrganization('Multiprotocol Label Switching (MPLS) Working Group')
if mibBuilder.loadTexts: mplsLcFrStdMIB.setContactInfo(' Thomas D. Nadeau\n Cisco Systems, Inc.\n Email: tnadeau@cisco.com\n\n Subrahmanya Hegde\n Email: subrah@cisco.com\n\n General comments should be sent to mpls@uu.net\n ')
if mibBuilder.loadTexts: mplsLcFrStdMIB.setDescription('This MIB module contains managed object definitions for\n MPLS Label-Controlled Frame-Relay interfaces as defined\n in (RFC3034).\n\n Copyright (C) The Internet Society (2006). This\n version of this MIB module is part of RFC 4368; see\n the RFC itself for full legal notices.')
mplsLcFrStdNotifications = MibIdentifier((1, 3, 6, 1, 2, 1, 10, 166, 10, 0))
mplsLcFrStdObjects = MibIdentifier((1, 3, 6, 1, 2, 1, 10, 166, 10, 1))
mplsLcFrStdConformance = MibIdentifier((1, 3, 6, 1, 2, 1, 10, 166, 10, 2))
mplsLcFrStdInterfaceConfTable = MibTable((1, 3, 6, 1, 2, 1, 10, 166, 10, 1, 1), )
if mibBuilder.loadTexts: mplsLcFrStdInterfaceConfTable.setDescription("This table specifies per-interface MPLS LC-FR\n capability and associated information. In particular,\n this table sparsely extends the MPLS-LSR-STD-MIB's\n mplsInterfaceConfTable.")
mplsLcFrStdInterfaceConfEntry = MibTableRow((1, 3, 6, 1, 2, 1, 10, 166, 10, 1, 1, 1), ).setIndexNames((0, "MPLS-LSR-STD-MIB", "mplsInterfaceIndex"))
if mibBuilder.loadTexts: mplsLcFrStdInterfaceConfEntry.setDescription('An entry in this table is created by an LSR for\n every interface capable of supporting MPLS LC-FR.\n Each entry in this table will exist only if a\n corresponding entry in ifTable and mplsInterfaceConfTable\n exists. If the associated entries in ifTable and\n mplsInterfaceConfTable are deleted, the corresponding\n entry in this table must also be deleted shortly\n thereafter.')
mplsLcFrStdTrafficMinDlci = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 10, 1, 1, 1, 1), DLCI()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: mplsLcFrStdTrafficMinDlci.setDescription('This is the minimum DLCI value over which this\n LSR is willing to accept traffic on this\n interface.')
mplsLcFrStdTrafficMaxDlci = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 10, 1, 1, 1, 2), DLCI()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: mplsLcFrStdTrafficMaxDlci.setDescription('This is the max DLCI value over which this\n LSR is willing to accept traffic on this\n interface.')
mplsLcFrStdCtrlMinDlci = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 10, 1, 1, 1, 3), DLCI()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: mplsLcFrStdCtrlMinDlci.setDescription('This is the min DLCI value over which this\n LSR is willing to accept control traffic\n on this interface.')
mplsLcFrStdCtrlMaxDlci = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 10, 1, 1, 1, 4), DLCI()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: mplsLcFrStdCtrlMaxDlci.setDescription('This is the max DLCI value over which this\n LSR is willing to accept control traffic\n on this interface.')
mplsLcFrStdInterfaceConfRowStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 10, 1, 1, 1, 5), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: mplsLcFrStdInterfaceConfRowStatus.setDescription('This object is used to create and\n delete entries in this table. When configuring\n entries in this table, the corresponding ifEntry and\n mplsInterfaceConfEntry MUST exist beforehand. If a manager\n attempts to create an entry for a corresponding\n mplsInterfaceConfEntry that does not support LC-FR,\n the agent MUST return an inconsistentValue error.\n If this table is implemented read-only, then the\n agent must set this object to active(1) when this\n row is made active. If this table is implemented\n writable, then an agent MUST not allow modification\n to its objects once this value is set to active(1),\n except to mplsLcFrStdInterfaceConfRowStatus and\n mplsLcFrStdInterfaceConfStorageType.')
mplsLcFrStdInterfaceConfStorageType = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 10, 1, 1, 1, 6), StorageType().clone('nonVolatile')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: mplsLcFrStdInterfaceConfStorageType.setDescription("The storage type for this conceptual row.\n Conceptual rows having the value 'permanent(4)'\n need not allow write-access to any columnar\n objects in the row.")
mplsLcFrStdCompliances = MibIdentifier((1, 3, 6, 1, 2, 1, 10, 166, 10, 2, 1))
mplsLcFrStdGroups = MibIdentifier((1, 3, 6, 1, 2, 1, 10, 166, 10, 2, 2))
mplsLcFrStdModuleFullCompliance = ModuleCompliance((1, 3, 6, 1, 2, 1, 10, 166, 10, 2, 1, 1)).setObjects(*(("MPLS-LC-FR-STD-MIB", "mplsLcFrStdIfGroup"),))
if mibBuilder.loadTexts: mplsLcFrStdModuleFullCompliance.setDescription('Compliance statement for agents that provide\n full support for MPLS-LC-FR-STD-MIB. Such\n devices can be monitored and also be configured\n using this MIB module.')
mplsLcFrStdModuleReadOnlyCompliance = ModuleCompliance((1, 3, 6, 1, 2, 1, 10, 166, 10, 2, 1, 2)).setObjects(*(("MPLS-LC-FR-STD-MIB", "mplsLcFrStdIfGroup"),))
if mibBuilder.loadTexts: mplsLcFrStdModuleReadOnlyCompliance.setDescription('Compliance requirement for implementations that only\n provide read-only support for MPLS-LC-FR-STD-MIB.\n Such devices can be monitored but cannot be configured\n using this MIB module.\n ')
mplsLcFrStdIfGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 10, 166, 10, 2, 2, 1)).setObjects(*(("MPLS-LC-FR-STD-MIB", "mplsLcFrStdTrafficMinDlci"), ("MPLS-LC-FR-STD-MIB", "mplsLcFrStdTrafficMaxDlci"), ("MPLS-LC-FR-STD-MIB", "mplsLcFrStdCtrlMinDlci"), ("MPLS-LC-FR-STD-MIB", "mplsLcFrStdCtrlMaxDlci"), ("MPLS-LC-FR-STD-MIB", "mplsLcFrStdInterfaceConfRowStatus"), ("MPLS-LC-FR-STD-MIB", "mplsLcFrStdInterfaceConfStorageType"),))
if mibBuilder.loadTexts: mplsLcFrStdIfGroup.setDescription('Collection of objects needed for MPLS LC-FR\n interface configuration.')
mibBuilder.exportSymbols("MPLS-LC-FR-STD-MIB", mplsLcFrStdInterfaceConfStorageType=mplsLcFrStdInterfaceConfStorageType, mplsLcFrStdConformance=mplsLcFrStdConformance, mplsLcFrStdModuleReadOnlyCompliance=mplsLcFrStdModuleReadOnlyCompliance, mplsLcFrStdMIB=mplsLcFrStdMIB, PYSNMP_MODULE_ID=mplsLcFrStdMIB, mplsLcFrStdTrafficMinDlci=mplsLcFrStdTrafficMinDlci, mplsLcFrStdCtrlMaxDlci=mplsLcFrStdCtrlMaxDlci, mplsLcFrStdIfGroup=mplsLcFrStdIfGroup, mplsLcFrStdGroups=mplsLcFrStdGroups, mplsLcFrStdInterfaceConfTable=mplsLcFrStdInterfaceConfTable, mplsLcFrStdTrafficMaxDlci=mplsLcFrStdTrafficMaxDlci, mplsLcFrStdCompliances=mplsLcFrStdCompliances, mplsLcFrStdModuleFullCompliance=mplsLcFrStdModuleFullCompliance, mplsLcFrStdCtrlMinDlci=mplsLcFrStdCtrlMinDlci, mplsLcFrStdNotifications=mplsLcFrStdNotifications, mplsLcFrStdObjects=mplsLcFrStdObjects, mplsLcFrStdInterfaceConfRowStatus=mplsLcFrStdInterfaceConfRowStatus, mplsLcFrStdInterfaceConfEntry=mplsLcFrStdInterfaceConfEntry)
|
# O(n^2) overall
def get_longest_increasing_subsequence(nums):
l = len(nums)
# reverse adjacency list O(n^2)
reverse_adjacency = {i:set() for i in range(l)}
for i,n in enumerate(nums):
for j,e in enumerate(nums[i+1:], i +1):
if n < e:
reverse_adjacency[j].add(i)
# dynamic programming O(V+E)
p = ['-']*l
max_len = [0]*l
best_max = (0,0) # (len, index)
for i in range(l):
if len(reverse_adjacency[i]) != 0:
maxz = float('-inf')
for c in reverse_adjacency[i]:
if max_len[c] > maxz:
max_i = c
max_ = 1 + max_len[max_i]
else:
max_i = '-'
max_ = 1
p[i] = max_i
max_len[i] = max_
if max_ > best_max[0]:
best_max = (max_, i)
path = [best_max[1]]
while path[-1] != '-':
path.append(p[path[-1]])
return path, best_max[0]
|
"""
Variables for configuration of zoom meetings using SCA Room Assign Tool
"""
N = 1
SESSION_PATH = "session_info.obj"
CHROME_PATH = "C:/ChromeDriver/chromedriver.exe"
existing_meeting_id = None # either a valid meeting ID or None, e.g. "860 1959 8282"
username = ""
password = ""
room_names = ["Calligraphy", "Costume", "Cooking", "Performance", "Construction", "Other", "Chatroom 1",
"Chatroom 2"]
meeting_docs = """Bot started. """
meeting_params = {
"room_names": room_names,
"SESSION_PATH": SESSION_PATH,
"CHROME_PATH": CHROME_PATH,
"username": username,
"password": password,
"meeting_docs": meeting_docs}
|
# This is how we print something
print("Hello!")
# Let's use python3 hello.py to run the program
# We can set variables
my_variable = 5
print(my_variable)
# We can make a list
my_list = [1, 2, 3]
print(my_list)
|
def perm_coord(
self,
perm_coord_list=[0, 1, 2],
):
"""Permute coordinates of Mesh Solution in place
Parameters
----------
self : MeshSolution
a MeshSolution object
perm_coord_list : list
list of the coordinates to be permuted
"""
# swap mesh solution
for sol in self.solution:
# swap modal shapes
meshsol_field = sol.field
meshsol_field = meshsol_field.T[perm_coord_list].T
sol.field = meshsol_field
# swap mesh VTK
meshsol_mesh = self.get_mesh()
self.mesh = [meshsol_mesh.perm_coord(perm_coord_list=perm_coord_list)]
|
class DisjointSets:
"""
Disjoint-set union data structure in which each element contributes an
arbitrary measure.
"""
__slots__ = ('_parents', '_ranks', '_measures')
def __init__(self, measures):
"""
Constructs DisjointSets with a fixed number of elements, each initially
in a singleton. That is, it is as if a makeset operation is performed
for each element and corresponding measure (element, measure) in
enumerate(measures).
"""
self._measures = list(measures)
length = len(self._measures)
self._parents = list(range(length))
self._ranks = [0] * length
def _find_set(self, element):
"""Finds the representative of the set contaiing the given element."""
# Find the ancestor.
while element != self._parents[elements]:
element = self._parents[element]
# Compress the path.
def sieve(bound):
"""Yields primes up to at least `bound` with a Sieve of Eratosthenes."""
yield 2
table = [True] * (bound + 1) # True means possibly prime.
for factor in range(3, math.floor(math.sqrt(bound)) + 1, 2):
if table[factor]:
for multiple in range(factor * factor, bound + 1, factor * 2):
table[multiple] = False
for odd in range(3, bound + 1, 2):
if table[odd]:
yield odd
PRIMES = tuple(sieve(100_000))
assert PRIMES, 'as implemented, the algorithms need a non-empty PRIMES table'
def prime_factor_indices(product):
"""
Yields the `PRIMES` table index of each unique prime factor of `product`,
in ascending order.
"""
for index, prime in enumerate(PRIMES):
if product % prime == 0:
yield index
product //= prime
while product % prime:
product //= prime
if product == 1:
return
index = bisect.bisect_left(PRIMES, product)
assert PRIMES[index] == product, 'product should be reduced to one prime'
yield index
class Solution:
@staticmethod
def largestComponentSize(A: List[int]) -> int:
pass # FIXME: implement this
|
class Solution:
def sortedSquares(self, A: List[int]) -> List[int]:
A = [i*i for i in A]
return sorted(A)
|
class Variable(object):
def __init__(self, _id , offset):
self._id = _id
self.offset = offset
def __str__(self):
s = str(self._id)
if self.offset:
s = s + "/%d" % self.offset
return s
class VariableLimited(object):
def __init__(self, _id , offset, size):
self._id = _id
self.offset = offset
self.size = size
def __str__(self):
s = str(self._id)
if self.offset:
s = s + "/%d" % self.offset
return s + ":%d" % self.size
def VariableLimitedListInit():
return list()
def VariableLimitedListNext(a, l):
l.append(a)
return l
|
vm = float(input("Digite um volume em metros cubicos: "))
lc = 1000 * vm
print("O volume digitado é de {} metros cubicos, esse valor convertido é em volume {:.2f} litros " .format(vm,lc))
|
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# [mysql数据库配置信息]
db_mysql_host = "127.0.0.1"
db_mysql_port = 3306
db_mysql_user = 'root'
db_mysql_password = '123456'
db_mysql_database = 'matrix'
db_mysql_charset = 'utf8'
|
# -*- coding: utf-8 -*-
# texttaglib's package version information
__author__ = "Le Tuan Anh"
__email__ = "tuananh.ke@gmail.com"
__copyright__ = "Copyright (c) 2018, texttaglib, Le Tuan Anh"
__credits__ = []
__license__ = "MIT License"
__description__ = "Python library for managing and annotating text corpuses in different formats (ELAN, TIG, TTL, et cetera)"
__url__ = "https://github.com/letuananh/texttaglib"
__maintainer__ = "Le Tuan Anh"
__version_major__ = "0.1.1"
__version__ = "{}".format(__version_major__)
__version_long__ = "{}".format(__version_major__)
__status__ = "5 - Production/Stable"
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# https://github.com/michielkauwatjoe/Meta
class CubicBezier:
def __init__(self, bezierId=None, points=None, parent=None, isClosed=False):
u"""
Stores points of the cubic Bézier curve.
"""
self.bezierId = bezierId
self.points = points
self.parent = parent
self.isClosed = isClosed
|
numero = int(input('Digite um numero: '))
menor = numero -1
maior = numero + 1
print(f'Analisando o numero {numero}, seu antecessor {menor} e o sucessor é {maior}')
|
# General things:
RIGHT = 1
LEFT = 2
TOP = 3
BOTTOM = 4
# Names of layers
class Layers:
game_actors = 4
main = 3
sticky_background = 2
background = 1
background_color = 0
# Message names: (MSGNs)
class MSGN:
COLLISION_SIDES = 0
VELOCITY = 1
STATE = 100
LOOKDIRECTION = 101
STATESTACK = 102
# Warios states:
class WarioStates:
UPRIGHT_STAY = 0
UPRIGHT_MOVE = 1
CROUCH_STAY = 2
CROUCH_MOVE = 3
JUMP_STAY = 4
JUMP_MOVE = 5
FALL_STAY = 6
FALL_MOVE = 7
GOTO_SLEEP = 8
WAKE_UP = 9
SLEEP = 10
TURN = 11
SFIST_ONGROUND = 12
SFIST_JUMP = 13
SFIST_FALL = 14
BUMP_BACK = 15
# Spearhead-states:
class ShStates:
STAY = 0
MOVE = 1
ANGRY = 2
BLINK = 3
SLEEP = 4
TURN = 5
UPSIDE_DOWN = 6
|
# -*- coding: utf-8 -*-
account = {
'email': 'YOUR EMAIL',
'password': 'YOUR PASSWORD'
}
op = "Login"
form_id = "packt_user_login_form"
frequency = 8
|
tabby_dog="\tI'm tabbed in";
persian_dog="I'm split\non s line."
backslash_dog="i'm \\ a \\ dog"
fat_dog="I'll do a list:\t* dog food \t* Fishies \t* Catnip\n\t* Grass"
print(tabby_dog)
print(persian_dog)
print(backslash_dog)
print(fat_dog)
|
# Change these to your instagram login credentials.
username = "Username"
password = "Password"
|
#!chuck_extends project/urls.py
#!chuck_appends URLS
urlpatterns += patterns('',
url(r'^', include('filer.server.urls')),
url(r'^', include('cms.urls')),
)
#!end
|
class Pessoa:
olhos = 2
def __init__(self, *filhos, nome = None, idade = 35):#---->Aqui são parâmetros(None,35)para os valores(nome, idade).
self.idade = idade #----> Existem também os atributos de dados(que podem ser chamados também atributos de obje-
self.nome = nome #to) que são definidos pelo Método 'init'.Para criar o atributo de objeto, colocamos
self.filhos = list(filhos) #'self' mais o ponto e seguido do nome do atributo.O que vem depois do sinal de igual
# é o valor do atributo(aqui no:self.ATRIBUTO = VALOR)
def cumprimentar(self): #--->'cumprimentar' aqui, é chamado de Método(que definimos chamando a função 'def'), que
return f'Ola {id(self)}' #é uma espécie de atributo da classe Pessoa.
@staticmethod
def metodo_estatico():
return 42
@classmethod
def nome_e_atributos_de_classe(cls):
return f'{cls} - olhos {cls.olhos}'
if __name__ == '__main__':
renzo = Pessoa(nome='renzo') #--->Os filhos do objeto 'luciano' é um atributo complexo.Então para sermos bem especí-
luciano= Pessoa(renzo, nome='Luciano') #ficos, já onde tinhamos a criação do objeto(p = Pessoa('luciano'),agora em
print(Pessoa.cumprimentar(luciano)) #vez de 'p', vamos chamar o objeto de 'luciano' e entre parênteses onde tinha-
print(id(luciano)) #mos o parâmetro 'luciano', vamos colocar primeiro o valor 'nome' seguido do parâmetro 'luciano'.
print(luciano.cumprimentar())
print(luciano.nome)
print(luciano.idade)
for filho in luciano.filhos: #O que está escrito no for, se lê assim: Para cada filho dos filhos de luciano, im-
print(filho.nome) #prima o nome do filho.
luciano.sobrenome = 'Ramalho'
del luciano.filhos
luciano.olhos = 1
del luciano.olhos
print(luciano.__dict__)
print(renzo.__dict__)
Pessoa.olhos = 3
print(Pessoa.olhos)
print(luciano.olhos)
print(renzo.olhos)
print(id(Pessoa.olhos), id(luciano.nome), id(renzo.nome))
print(Pessoa.metodo_estatico(), luciano.metodo_estatico())
print(Pessoa.nome_e_atributos_de_classe(), luciano.nome_e_atributos_de_classe())
|
# Easy horntail gem
sm.spawnMob(8810202, 95, 260, False)
sm.spawnMob(8810203, 95, 260, False)
sm.spawnMob(8810204, 95, 260, False)
sm.spawnMob(8810205, 95, 260, False)
sm.spawnMob(8810206, 95, 260, False)
sm.spawnMob(8810207, 95, 260, False)
sm.spawnMob(8810208, 95, 260, False)
sm.spawnMob(8810209, 95, 260, False)
sm.spawnMob(8810214, 95, 260, False)
sm.removeReactor()
|
#https://codeforces.com/contest/1343/problem/C
for _ in range(int(input())):
n = int(input())
l = input().split()
new = []
sn=[]
nn=[]
ans=0
for i in l:
if i[0]!='-':
sn.append(int(i))
if(nn!=[]):
new.append(nn)
nn=[]
else:
nn.append(int(i))
if(sn!=[]):
new.append(sn)
sn=[]
new.append(nn)
new.append(sn)
new = [ele for ele in new if ele != []]
for i in new:
ans+=max(i)
print(ans)
# new = []
# ele=0
# t,p=0,0
# if l[0]>0:
# t=1
# for i in range(n):
# if l[i]>0 :
# p=1
# elif l[i]<0:
# p=0
# if(t!=p):
# new.append(ele)
# ele=0
# if(p==0 and (l[i]<0 or ele>l[i])):
# ele=l[i]
# t=p
# elif(p==1 and (l[i]>0 or ele>l[i])):
# ele=l[i]
# t=p
# print(new)
|
def in_bounds(matrix, i, j):
rows = len(matrix)
cols = len(matrix[0])
if i < 0 or i >= rows or j < 0 or j >= cols:
return False
return True
def read_matrix():
matrix = []
while row := input():
matrix.append([int(num) for num in list(row)])
return matrix
def pretty_print(matrix):
for i in range(len(matrix)):
for j in range(len(matrix[i])):
print(matrix[i][j], end=' ')
print()
|
#in=5
#in=10
#in=11
#in=20
#in=22
#in=30
#in=33
#in=40
#in=44
#in=50
#in=55
#golden=6050
n = input_int()
out = 0
while (n > 0):
x = input_int()
y = input_int()
out = out + x * y
n = n - 1
print(out)
|
for _ in range(int(input())):
n=int(input())
if n%2==0:
check=0
while n%2==0:
n=n//2
check+=1
if n<=1:
if check%2:
print("Bob")
else:
print("Alice")
else:
print("Alice")
else:
print("Bob")
|
class Solution:
def isOneEditDistance(self, s, t):
l1, l2, cnt, i, j = len(s), len(t), 0, 0, 0
while i < l1 and j < l2:
if s[i] != t[j]:
cnt += 1
if l1 < l2:
i -= 1
elif l1 > l2:
j -= 1
i += 1
j += 1
l = abs(l1 - l2)
return (cnt == 1 and l <= 1) or (cnt == 0 and l == 1)
|
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class NasSourceThrottlingParams(object):
"""Implementation of the 'NasSourceThrottlingParams' model.
Specifies the NAS specific source throttling parameters during source
registration or during backup of the source.
Attributes:
max_parallel_metadata_fetch_full_percentage (int): Specifies the
percentage value of maximum concurrent metadata to be fetched
during full backup of the source.
max_parallel_metadata_fetch_incremental_percentage (int): Specifies
the IPMI IP of the node (if physical cluster).
max_parallel_read_write_full_percentage (int): Specifies the
percentage value of maximum concurrent IO during full backup
max_parallel_read_write_incremental_percentage (int): Specifies the
percentage value of maximum concurrent IO during incremental
backup of the source.
"""
# Create a mapping from Model property names to API property names
_names = {
"max_parallel_metadata_fetch_full_percentage":'maxParallelMetadataFetchFullPercentage',
"max_parallel_metadata_fetch_incremental_percentage":'maxParallelMetadataFetchIncrementalPercentage',
"max_parallel_read_write_full_percentage":'maxParallelReadWriteFullPercentage',
"max_parallel_read_write_incremental_percentage":'maxParallelReadWriteIncrementalPercentage'
}
def __init__(self,
max_parallel_metadata_fetch_full_percentage=None,
max_parallel_metadata_fetch_incremental_percentage=None,
max_parallel_read_write_full_percentage=None,
max_parallel_read_write_incremental_percentage=None):
"""Constructor for the NasSourceThrottlingParams class"""
# Initialize members of the class
self.max_parallel_metadata_fetch_full_percentage = max_parallel_metadata_fetch_full_percentage
self.max_parallel_metadata_fetch_incremental_percentage = max_parallel_metadata_fetch_incremental_percentage
self.max_parallel_read_write_full_percentage = max_parallel_read_write_full_percentage
self.max_parallel_read_write_incremental_percentage = max_parallel_read_write_incremental_percentage
@classmethod
def from_dictionary(cls,
dictionary):
"""Creates an instance of this model from a dictionary
Args:
dictionary (dictionary): A dictionary representation of the object as
obtained from the deserialization of the server's response. The keys
MUST match property names in the API description.
Returns:
object: An instance of this structure class.
"""
if dictionary is None:
return None
# Extract variables from the dictionary
max_parallel_metadata_fetch_full_percentage = dictionary.get('maxParallelMetadataFetchFullPercentage')
max_parallel_metadata_fetch_incremental_percentage = dictionary.get('maxParallelMetadataFetchIncrementalPercentage')
max_parallel_read_write_full_percentage = dictionary.get('maxParallelReadWriteFullPercentage')
max_parallel_read_write_incremental_percentage = dictionary.get('maxParallelReadWriteIncrementalPercentage')
# Return an object of this model
return cls(max_parallel_metadata_fetch_full_percentage,
max_parallel_metadata_fetch_incremental_percentage,
max_parallel_read_write_full_percentage,
max_parallel_read_write_incremental_percentage)
|
#辞書型
print("辞書型")
profile = {
"name": "tani",
"email": "kazunori-t@cyberbra.in"
}
print(profile["name"])
# 新しく要素を追加
profile["gender"] = "male"
# 新しく要素を追加した辞書型(profile)を出力
print(profile)
print(profile["gender"])
|
# parsetab.py
# This file is automatically generated. Do not edit.
# pylint: disable=W,C,R
_tabversion = "3.10"
_lr_method = "LALR"
_lr_signature = "A AFTER_TOMORROW AM AT BEFORE_YESTERDAY COLON DATE_END DAY MINUS MONTH NUMBER OF ON PAST_PHRASE PHRASE PLUS PM THE TIME TODAY TOMORROW WORD_NUMBER YEAR YESTERDAY\n date_object :\n date_object : date_list\n date_list : date_list date\n date_list : date\n date_list : date_past\n date_list : in\n date_list : adder\n date_list : remover\n date_list : date_yesterday\n date_list : date_2moro\n date_list : date_day\n date_list : date_end\n date_list : date_or\n date_list : date_before_yesterday\n date_list : date_after_tomorrow\n date_list : date_twice\n date_list : timestamp\n date_list : timestamp_adpt\n \n timestamp : NUMBER COLON NUMBER\n timestamp : NUMBER COLON NUMBER COLON NUMBER\n \n timestamp_adpt : timestamp AM\n timestamp_adpt : timestamp PM\n timestamp_adpt : AT timestamp\n timestamp_adpt : AT timestamp PM\n timestamp_adpt : AT timestamp AM\n \n date : NUMBER\n date : WORD_NUMBER\n date : AT NUMBER\n date : AT WORD_NUMBER\n date : TIME\n date : NUMBER TIME\n date : NUMBER AM\n date : NUMBER PM\n date : AT NUMBER AM\n date : AT NUMBER PM\n date : WORD_NUMBER TIME\n date : PHRASE TIME\n date : TIME PHRASE\n date : NUMBER TIME PHRASE\n date : WORD_NUMBER TIME PHRASE\n date : PHRASE TIME PHRASE\n \n date_twice : date date\n date_twice : date_day date\n \n in : PHRASE NUMBER TIME\n in : PHRASE WORD_NUMBER TIME\n \n adder : PLUS NUMBER TIME\n adder : PLUS WORD_NUMBER TIME\n \n remover : MINUS NUMBER TIME\n remover : MINUS WORD_NUMBER TIME\n \n date_past : NUMBER TIME PAST_PHRASE\n date_past : WORD_NUMBER TIME PAST_PHRASE\n \n date_yesterday : YESTERDAY\n date_yesterday : YESTERDAY AT NUMBER\n date_yesterday : YESTERDAY AT WORD_NUMBER\n \n date_2moro : TOMORROW\n date_2moro : TOMORROW AT NUMBER\n date_2moro : TOMORROW AT WORD_NUMBER\n \n date_day : DAY\n date_day : ON DAY\n date_day : PHRASE DAY\n date_day : PAST_PHRASE DAY\n \n date_or : PAST_PHRASE TIME\n \n date_before_yesterday : BEFORE_YESTERDAY\n date_before_yesterday : THE BEFORE_YESTERDAY\n date_before_yesterday : THE TIME BEFORE_YESTERDAY\n \n date_after_tomorrow : AFTER_TOMORROW\n date_after_tomorrow : THE TIME AFTER_TOMORROW\n \n date_end : NUMBER DATE_END\n date_end : THE NUMBER DATE_END\n date_end : MONTH NUMBER DATE_END\n date_end : NUMBER DATE_END OF MONTH\n date_end : ON THE NUMBER DATE_END\n date_end : MONTH THE NUMBER DATE_END\n date_end : THE NUMBER DATE_END OF MONTH\n "
_lr_action_items = {
"$end": (
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
21,
26,
27,
28,
32,
33,
34,
35,
36,
39,
40,
41,
42,
43,
44,
45,
46,
48,
49,
50,
51,
52,
53,
56,
57,
58,
65,
68,
72,
73,
74,
75,
76,
78,
79,
80,
81,
82,
83,
84,
85,
86,
87,
88,
89,
90,
91,
92,
93,
94,
95,
97,
98,
99,
100,
102,
104,
106,
107,
108,
],
[
-1,
0,
-2,
-4,
-5,
-6,
-7,
-8,
-9,
-10,
-11,
-12,
-13,
-14,
-15,
-16,
-17,
-18,
-26,
-27,
-30,
-52,
-55,
-58,
-63,
-66,
-3,
-26,
-27,
-42,
-43,
-21,
-22,
-31,
-32,
-33,
-68,
-36,
-28,
-29,
-23,
-38,
-37,
-60,
-61,
-62,
-59,
-64,
-31,
-36,
-28,
-39,
-50,
-19,
-40,
-51,
-34,
-35,
-24,
-25,
-41,
-44,
-45,
-46,
-47,
-48,
-49,
-53,
-54,
-56,
-57,
-69,
-65,
-67,
-70,
-71,
-72,
-73,
-20,
-74,
],
),
"NUMBER": (
[
0,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
24,
25,
26,
27,
28,
30,
31,
32,
33,
34,
35,
36,
37,
39,
40,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51,
52,
53,
56,
57,
58,
63,
64,
65,
66,
68,
71,
72,
73,
74,
75,
76,
78,
79,
80,
81,
82,
83,
84,
85,
86,
87,
88,
89,
90,
91,
92,
93,
94,
95,
97,
98,
99,
100,
102,
103,
104,
106,
107,
108,
],
[
18,
35,
35,
-5,
-6,
-7,
-8,
-9,
-10,
35,
-12,
-13,
-14,
-15,
-16,
-17,
-18,
-26,
-27,
49,
-30,
54,
59,
61,
-52,
-55,
-58,
67,
70,
-63,
-66,
-3,
-26,
-27,
74,
-42,
-43,
-21,
-22,
-31,
-32,
-33,
-68,
78,
-36,
-28,
-29,
-23,
-38,
-37,
-60,
-61,
-62,
92,
94,
-59,
96,
-64,
101,
-31,
-36,
-28,
-39,
-50,
-19,
-40,
-51,
-34,
-35,
-24,
-25,
-41,
-44,
-45,
-46,
-47,
-48,
-49,
-53,
-54,
-56,
-57,
-69,
-65,
-67,
-70,
-71,
107,
-72,
-73,
-20,
-74,
],
),
"WORD_NUMBER": (
[
0,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
24,
25,
26,
27,
28,
32,
33,
34,
35,
36,
37,
39,
40,
41,
42,
43,
44,
45,
46,
48,
49,
50,
51,
52,
53,
56,
57,
58,
63,
64,
65,
68,
72,
73,
74,
75,
76,
78,
79,
80,
81,
82,
83,
84,
85,
86,
87,
88,
89,
90,
91,
92,
93,
94,
95,
97,
98,
99,
100,
102,
104,
106,
107,
108,
],
[
19,
36,
36,
-5,
-6,
-7,
-8,
-9,
-10,
36,
-12,
-13,
-14,
-15,
-16,
-17,
-18,
-26,
-27,
50,
-30,
55,
60,
62,
-52,
-55,
-58,
-63,
-66,
-3,
-26,
-27,
50,
-42,
-43,
-21,
-22,
-31,
-32,
-33,
-68,
-36,
-28,
-29,
-23,
-38,
-37,
-60,
-61,
-62,
93,
95,
-59,
-64,
-31,
-36,
-28,
-39,
-50,
-19,
-40,
-51,
-34,
-35,
-24,
-25,
-41,
-44,
-45,
-46,
-47,
-48,
-49,
-53,
-54,
-56,
-57,
-69,
-65,
-67,
-70,
-71,
-72,
-73,
-20,
-74,
],
),
"AT": (
[
0,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
21,
26,
27,
28,
32,
33,
34,
35,
36,
39,
40,
41,
42,
43,
44,
45,
46,
48,
49,
50,
51,
52,
53,
56,
57,
58,
65,
68,
72,
73,
74,
75,
76,
78,
79,
80,
81,
82,
83,
84,
85,
86,
87,
88,
89,
90,
91,
92,
93,
94,
95,
97,
98,
99,
100,
102,
104,
106,
107,
108,
],
[
20,
37,
37,
-5,
-6,
-7,
-8,
-9,
-10,
37,
-12,
-13,
-14,
-15,
-16,
-17,
-18,
-26,
-27,
-30,
63,
64,
-58,
-63,
-66,
-3,
-26,
-27,
-42,
-43,
-21,
-22,
-31,
-32,
-33,
-68,
-36,
-28,
-29,
-23,
-38,
-37,
-60,
-61,
-62,
-59,
-64,
-31,
-36,
-28,
-39,
-50,
-19,
-40,
-51,
-34,
-35,
-24,
-25,
-41,
-44,
-45,
-46,
-47,
-48,
-49,
-53,
-54,
-56,
-57,
-69,
-65,
-67,
-70,
-71,
-72,
-73,
-20,
-74,
],
),
"TIME": (
[
0,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
21,
22,
23,
26,
27,
28,
30,
32,
33,
34,
35,
36,
38,
39,
40,
41,
42,
43,
44,
45,
46,
48,
49,
50,
51,
52,
53,
54,
55,
56,
57,
58,
59,
60,
61,
62,
65,
68,
72,
73,
74,
75,
76,
78,
79,
80,
81,
82,
83,
84,
85,
86,
87,
88,
89,
90,
91,
92,
93,
94,
95,
97,
98,
99,
100,
102,
104,
106,
107,
108,
],
[
21,
21,
21,
-5,
-6,
-7,
-8,
-9,
-10,
21,
-12,
-13,
-14,
-15,
-16,
-17,
-18,
43,
48,
-30,
53,
58,
-52,
-55,
-58,
69,
-63,
-66,
-3,
72,
73,
53,
-42,
-43,
-21,
-22,
-31,
-32,
-33,
-68,
-36,
-28,
-29,
-23,
-38,
-37,
86,
87,
-60,
-61,
-62,
88,
89,
90,
91,
-59,
-64,
-31,
-36,
-28,
-39,
-50,
-19,
-40,
-51,
-34,
-35,
-24,
-25,
-41,
-44,
-45,
-46,
-47,
-48,
-49,
-53,
-54,
-56,
-57,
-69,
-65,
-67,
-70,
-71,
-72,
-73,
-20,
-74,
],
),
"PHRASE": (
[
0,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
21,
26,
27,
28,
32,
33,
34,
35,
36,
39,
40,
41,
42,
43,
44,
45,
46,
48,
49,
50,
51,
52,
53,
56,
57,
58,
65,
68,
72,
73,
74,
75,
76,
78,
79,
80,
81,
82,
83,
84,
85,
86,
87,
88,
89,
90,
91,
92,
93,
94,
95,
97,
98,
99,
100,
102,
104,
106,
107,
108,
],
[
22,
38,
38,
-5,
-6,
-7,
-8,
-9,
-10,
38,
-12,
-13,
-14,
-15,
-16,
-17,
-18,
-26,
-27,
52,
-52,
-55,
-58,
-63,
-66,
-3,
-26,
-27,
-42,
-43,
-21,
-22,
75,
-32,
-33,
-68,
79,
-28,
-29,
-23,
-38,
85,
-60,
-61,
-62,
-59,
-64,
75,
79,
-28,
-39,
-50,
-19,
-40,
-51,
-34,
-35,
-24,
-25,
-41,
-44,
-45,
-46,
-47,
-48,
-49,
-53,
-54,
-56,
-57,
-69,
-65,
-67,
-70,
-71,
-72,
-73,
-20,
-74,
],
),
"PLUS": (
[
0,
],
[
24,
],
),
"MINUS": (
[
0,
],
[
25,
],
),
"YESTERDAY": (
[
0,
],
[
26,
],
),
"TOMORROW": (
[
0,
],
[
27,
],
),
"DAY": (
[
0,
22,
23,
29,
],
[
28,
56,
57,
65,
],
),
"ON": (
[
0,
],
[
29,
],
),
"PAST_PHRASE": (
[
0,
43,
48,
],
[
23,
76,
80,
],
),
"THE": (
[
0,
29,
31,
],
[
30,
66,
71,
],
),
"MONTH": (
[
0,
77,
105,
],
[
31,
102,
108,
],
),
"BEFORE_YESTERDAY": (
[
0,
30,
69,
],
[
32,
68,
98,
],
),
"AFTER_TOMORROW": (
[
0,
69,
],
[
33,
99,
],
),
"AM": (
[
16,
18,
35,
49,
51,
74,
78,
107,
],
[
41,
44,
44,
81,
84,
81,
-19,
-20,
],
),
"PM": (
[
16,
18,
35,
49,
51,
74,
78,
107,
],
[
42,
45,
45,
82,
83,
82,
-19,
-20,
],
),
"DATE_END": (
[
18,
67,
70,
96,
101,
],
[
46,
97,
100,
104,
106,
],
),
"COLON": (
[
18,
49,
78,
],
[
47,
47,
103,
],
),
"OF": (
[
46,
97,
],
[
77,
105,
],
),
}
_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 = {
"date_object": (
[
0,
],
[
1,
],
),
"date_list": (
[
0,
],
[
2,
],
),
"date": (
[
0,
2,
3,
10,
],
[
3,
34,
39,
40,
],
),
"date_past": (
[
0,
],
[
4,
],
),
"in": (
[
0,
],
[
5,
],
),
"adder": (
[
0,
],
[
6,
],
),
"remover": (
[
0,
],
[
7,
],
),
"date_yesterday": (
[
0,
],
[
8,
],
),
"date_2moro": (
[
0,
],
[
9,
],
),
"date_day": (
[
0,
],
[
10,
],
),
"date_end": (
[
0,
],
[
11,
],
),
"date_or": (
[
0,
],
[
12,
],
),
"date_before_yesterday": (
[
0,
],
[
13,
],
),
"date_after_tomorrow": (
[
0,
],
[
14,
],
),
"date_twice": (
[
0,
],
[
15,
],
),
"timestamp": (
[
0,
20,
],
[
16,
51,
],
),
"timestamp_adpt": (
[
0,
],
[
17,
],
),
}
_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' -> date_object", "S'", 1, None, None, None),
("date_object -> <empty>", "date_object", 0, "p_date_object", "__init__.py", 422),
("date_object -> date_list", "date_object", 1, "p_date_object", "__init__.py", 423),
("date_list -> date_list date", "date_list", 2, "p_date_list", "__init__.py", 433),
("date_list -> date", "date_list", 1, "p_date", "__init__.py", 439),
("date_list -> date_past", "date_list", 1, "p_date", "__init__.py", 440),
("date_list -> in", "date_list", 1, "p_date", "__init__.py", 441),
("date_list -> adder", "date_list", 1, "p_date", "__init__.py", 442),
("date_list -> remover", "date_list", 1, "p_date", "__init__.py", 443),
("date_list -> date_yesterday", "date_list", 1, "p_date", "__init__.py", 444),
("date_list -> date_2moro", "date_list", 1, "p_date", "__init__.py", 445),
("date_list -> date_day", "date_list", 1, "p_date", "__init__.py", 446),
("date_list -> date_end", "date_list", 1, "p_date", "__init__.py", 447),
("date_list -> date_or", "date_list", 1, "p_date", "__init__.py", 448),
(
"date_list -> date_before_yesterday",
"date_list",
1,
"p_date",
"__init__.py",
449,
),
("date_list -> date_after_tomorrow", "date_list", 1, "p_date", "__init__.py", 450),
("date_list -> date_twice", "date_list", 1, "p_date", "__init__.py", 451),
("date_list -> timestamp", "date_list", 1, "p_date", "__init__.py", 452),
("date_list -> timestamp_adpt", "date_list", 1, "p_date", "__init__.py", 453),
(
"timestamp -> NUMBER COLON NUMBER",
"timestamp",
3,
"p_timestamp",
"__init__.py",
473,
),
(
"timestamp -> NUMBER COLON NUMBER COLON NUMBER",
"timestamp",
5,
"p_timestamp",
"__init__.py",
474,
),
(
"timestamp_adpt -> timestamp AM",
"timestamp_adpt",
2,
"p_timestamp_adapter",
"__init__.py",
497,
),
(
"timestamp_adpt -> timestamp PM",
"timestamp_adpt",
2,
"p_timestamp_adapter",
"__init__.py",
498,
),
(
"timestamp_adpt -> AT timestamp",
"timestamp_adpt",
2,
"p_timestamp_adapter",
"__init__.py",
499,
),
(
"timestamp_adpt -> AT timestamp PM",
"timestamp_adpt",
3,
"p_timestamp_adapter",
"__init__.py",
500,
),
(
"timestamp_adpt -> AT timestamp AM",
"timestamp_adpt",
3,
"p_timestamp_adapter",
"__init__.py",
501,
),
("date -> NUMBER", "date", 1, "p_single_date", "__init__.py", 516),
("date -> WORD_NUMBER", "date", 1, "p_single_date", "__init__.py", 517),
("date -> AT NUMBER", "date", 2, "p_single_date", "__init__.py", 518),
("date -> AT WORD_NUMBER", "date", 2, "p_single_date", "__init__.py", 519),
("date -> TIME", "date", 1, "p_single_date", "__init__.py", 520),
("date -> NUMBER TIME", "date", 2, "p_single_date", "__init__.py", 521),
("date -> NUMBER AM", "date", 2, "p_single_date", "__init__.py", 522),
("date -> NUMBER PM", "date", 2, "p_single_date", "__init__.py", 523),
("date -> AT NUMBER AM", "date", 3, "p_single_date", "__init__.py", 524),
("date -> AT NUMBER PM", "date", 3, "p_single_date", "__init__.py", 525),
("date -> WORD_NUMBER TIME", "date", 2, "p_single_date", "__init__.py", 526),
("date -> PHRASE TIME", "date", 2, "p_single_date", "__init__.py", 527),
("date -> TIME PHRASE", "date", 2, "p_single_date", "__init__.py", 528),
("date -> NUMBER TIME PHRASE", "date", 3, "p_single_date", "__init__.py", 529),
("date -> WORD_NUMBER TIME PHRASE", "date", 3, "p_single_date", "__init__.py", 530),
("date -> PHRASE TIME PHRASE", "date", 3, "p_single_date", "__init__.py", 531),
("date_twice -> date date", "date_twice", 2, "p_twice", "__init__.py", 610),
("date_twice -> date_day date", "date_twice", 2, "p_twice", "__init__.py", 611),
("in -> PHRASE NUMBER TIME", "in", 3, "p_single_date_in", "__init__.py", 641),
("in -> PHRASE WORD_NUMBER TIME", "in", 3, "p_single_date_in", "__init__.py", 642),
("adder -> PLUS NUMBER TIME", "adder", 3, "p_single_date_plus", "__init__.py", 655),
(
"adder -> PLUS WORD_NUMBER TIME",
"adder",
3,
"p_single_date_plus",
"__init__.py",
656,
),
(
"remover -> MINUS NUMBER TIME",
"remover",
3,
"p_single_date_minus",
"__init__.py",
669,
),
(
"remover -> MINUS WORD_NUMBER TIME",
"remover",
3,
"p_single_date_minus",
"__init__.py",
670,
),
(
"date_past -> NUMBER TIME PAST_PHRASE",
"date_past",
3,
"p_single_date_past",
"__init__.py",
684,
),
(
"date_past -> WORD_NUMBER TIME PAST_PHRASE",
"date_past",
3,
"p_single_date_past",
"__init__.py",
685,
),
(
"date_yesterday -> YESTERDAY",
"date_yesterday",
1,
"p_single_date_yesterday",
"__init__.py",
693,
),
(
"date_yesterday -> YESTERDAY AT NUMBER",
"date_yesterday",
3,
"p_single_date_yesterday",
"__init__.py",
694,
),
(
"date_yesterday -> YESTERDAY AT WORD_NUMBER",
"date_yesterday",
3,
"p_single_date_yesterday",
"__init__.py",
695,
),
(
"date_2moro -> TOMORROW",
"date_2moro",
1,
"p_single_date_2moro",
"__init__.py",
712,
),
(
"date_2moro -> TOMORROW AT NUMBER",
"date_2moro",
3,
"p_single_date_2moro",
"__init__.py",
713,
),
(
"date_2moro -> TOMORROW AT WORD_NUMBER",
"date_2moro",
3,
"p_single_date_2moro",
"__init__.py",
714,
),
("date_day -> DAY", "date_day", 1, "p_single_date_day", "__init__.py", 731),
("date_day -> ON DAY", "date_day", 2, "p_single_date_day", "__init__.py", 732),
("date_day -> PHRASE DAY", "date_day", 2, "p_single_date_day", "__init__.py", 733),
(
"date_day -> PAST_PHRASE DAY",
"date_day",
2,
"p_single_date_day",
"__init__.py",
734,
),
(
"date_or -> PAST_PHRASE TIME",
"date_or",
2,
"p_this_or_next_period",
"__init__.py",
765,
),
(
"date_before_yesterday -> BEFORE_YESTERDAY",
"date_before_yesterday",
1,
"p_before_yesterday",
"__init__.py",
786,
),
(
"date_before_yesterday -> THE BEFORE_YESTERDAY",
"date_before_yesterday",
2,
"p_before_yesterday",
"__init__.py",
787,
),
(
"date_before_yesterday -> THE TIME BEFORE_YESTERDAY",
"date_before_yesterday",
3,
"p_before_yesterday",
"__init__.py",
788,
),
(
"date_after_tomorrow -> AFTER_TOMORROW",
"date_after_tomorrow",
1,
"p_after_tomorrow",
"__init__.py",
798,
),
(
"date_after_tomorrow -> THE TIME AFTER_TOMORROW",
"date_after_tomorrow",
3,
"p_after_tomorrow",
"__init__.py",
799,
),
(
"date_end -> NUMBER DATE_END",
"date_end",
2,
"p_single_date_end",
"__init__.py",
809,
),
(
"date_end -> THE NUMBER DATE_END",
"date_end",
3,
"p_single_date_end",
"__init__.py",
810,
),
(
"date_end -> MONTH NUMBER DATE_END",
"date_end",
3,
"p_single_date_end",
"__init__.py",
811,
),
(
"date_end -> NUMBER DATE_END OF MONTH",
"date_end",
4,
"p_single_date_end",
"__init__.py",
812,
),
(
"date_end -> ON THE NUMBER DATE_END",
"date_end",
4,
"p_single_date_end",
"__init__.py",
813,
),
(
"date_end -> MONTH THE NUMBER DATE_END",
"date_end",
4,
"p_single_date_end",
"__init__.py",
814,
),
(
"date_end -> THE NUMBER DATE_END OF MONTH",
"date_end",
5,
"p_single_date_end",
"__init__.py",
815,
),
]
|
def fakulteta(n):
if n == 0:
return 1
else:
return n * fakulteta(n - 1)
def vsota_stevk_fakultete(n):
seznam = [int(d) for d in str(fakulteta(n))]
vsota = 0
for i in range(0, len(seznam)):
vsota = vsota + seznam[i]
return(vsota)
print(vsota_stevk_fakultete(100))
|
class Motor:
def __init__(self):
self.velocidade = 0
def acelerar(self):
self.velocidade += 1
def frear(self):
self.velocidade -= 2
self.velocidade = max(0, self.velocidade)
NORTE = 'Norte'
SUL = 'Sul'
LESTE = 'Leste'
OESTE = 'Oeste'
class Direcao:
rotacao_a_direita_dct={NORTE:LESTE, LESTE:SUL, SUL:OESTE, OESTE:NORTE}
rotacao_a_esquerda_dct={NORTE:OESTE, OESTE:SUL, SUL:LESTE, LESTE:NORTE}
def __init__(self):
self.valor = NORTE
def girar_a_direta(self):
self.valor = self.rotacao_a_direita_dct[self.valor]
def girar_a_esquerda(self):
self.valor = self.rotacao_a_esquerda_dct[self.valor]
|
# 1.
# import math
# # a,b,c = map(float,input('Enter a,b,c:').split(','))
# a,b,c = eval(input('Enter a,b,c:'))
# sum=b*b-4*a*c
# if sum >0:
# r1=(-b+math.sqrt(sum))/2*a
# r2=(-b-math.sqrt(sum))/2*a
# print('The roots are %.2f and %.2f'%(r1,r2))
# elif sum == 0:
# r1=r2=(-b+math.sqrt(sum))/2*a
# print('The root is %.2f'%r1)
# else:
# print('The equation has no real roots')
# 2.
# import random
# num1 = random.randint(0,100)
# num2 = random.randint(0,100)
# print(num1,num2)
# sum == num1+num2
# sum1 = input('请输入结果:')
# if sum1 == sum:
# print('结果为真')
# else:
# print('结果为假')
# 3.
# today = int(input('Enter today is day:'))
# num1 = int(input('Enter the number of days elapsed since today: '))
# week = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
# week1=(today+num1)%7
# print("Today is %s and the future day is %s"%(week[today],week[week1]))
# 4.1
# num1,num2,num3 = eval(input('输入三个数:'))
# if num1 > num2 :
# if num1 > num3:
# if num2 > num3:
# print(num3,num2,num1)
# else:
# print(num2,num3,num1)
# else:
# print(num2,num1,num3)
# else:
# if num1 > num3:
# print(num3,num1,num2)
# elif num2 > num3:
# print(num1,num3,num2)
# else:
# print(num1,num2,num3)
# 5.
# w1,p1 = eval(input('Enter weight and price for package 1:'))
# w2,p2 = eval(input('Enter weight and price for package 2:'))
# if p1%w1 < p2% w2:
# print('Package 1 has the better price.')
# else:
# print('Package 2 has the better price.')
# 6.
# m,y = eval (input('请输入月份,年份:'))
# if m in (1,3,5,7,8,10,12):
# print('%s年%s月的天数为31天'%(y,m))
# elif m in (4, 6 ,9,11):
# print('%s年%s月的天数为30天'%(y,m))
# if m == 2:
# if y % 4 == 0 and y % 100 != 0 or y % 400 == 0:
# print('%s年2月的天数为29天'%y)
# else:
# print('%s年2月的天数为28天'%y)
# 7.
# import numpy as np
# np1 = input('请猜测硬币是正面或是反面:')
# np2 = np.random.choice(['正面' ,'反面'])
# print(np2)
# if np1 == np2:
# print('恭喜你,答对了!😊')
# else:
# print('很遗憾,错了呢!😔')
# 8.
# import random
# user = int(input('请选择:scissor(0),rock(1),paper(2):'))
# computer = random.randint(0,2) #用于生成一个指定范围内的整数
# if user == 0 and computer == 1:
# print('The computer is rock,You are scissor. You lost.')
# elif user == 0 and computer == 2:
# print('The computer is paper,You are scissor. You won.')
# elif user == 0 and computer == 0:
# print('The computer is scissor,You are scissor. It is a draw. ')
# elif user == 1 and computer == 0:
# print('The computer is scissor,You are rock.You won. ')
# elif user == 1 and computer == 2:
# print('The computer is paper,You are rock.You lost. ')
# elif user == 1 and computer == 1:
# print('The computer is rock,You are rock.It is a draw. ')
# elif user == 2 and computer == 0:
# print('The computer is scissor,You are paper.You lost. ')
# elif user == 2 and computer == 1:
# print('The computer is rock,You are paper.You won. ')
# elif user == 2 and computer == 2:
# print('The computer is paper,You are paper.It is a draw.')
9#
# y = int(input('Enter year:'))
# m = int(input('Ether month:1-12:'))
# q = int(input('Ether the day of the month:1-31:'))
# a = ['Saturday' ,'Sunday','Monday','Tuesday','Wednesday','Thurday','Firday']
# if m == 1:
# m = 13
# y = y-1
# elif m == 2:
# m = 14
# y = y-1
# h = (q + ((26 * (m + 1) // 10)) + (y % 100) + ((y % 100) // 4) + ((y // 100) // 4) + (5 * y // 100)) % 7
# # '//'只输出整数,即只输出小数点前的:'/'输出完整运算结果,即会输出小数点后的:
# D=a[h]
# print('Day of the week is %s'%D)
#10.
# import numpy as np
# np1 = np.random.choice(['Ace',2,3,4,5,6,7,8,9,10,'Jack','Queen','King'])
# np2 = np.random.choice(['梅花' , '红桃' ,'黑桃' ,'方块'])
# print('The card you picked is the %s of %s'%(np1,np2))
# 11.
# num = input('Enter a three-digit integer:')
# if num == num [::-1]:
# print('%s is a palindrome'%num)
# else:
# print('%s is not a palindrome'%num)
# 12.
# a,b,c = eval(input('Enter three edges :'))
# if a+b>c and a-b<c:
# d=a+b+c
# print('The perimter is:%.0f'%d)
# 1.
#2.
money = 10000
sum = 0
for i in range(14):
money = money + money * 0.05
if i == 9:
print('十年后的大学的学费是:%.2f'%money)
else:
print('十年后的大学四年的总学费是:%.2f'%sum)
# 4.
# count = 0
# for i in range(100,1001):
# if i >= 100 and i <= 1000:
# if i % 5 == 0 and i % 6 == 0:
# count += 1
# print(i,"\t",end=' ')
# if count % 10 == 0:
# print(" ")
# 5.
# n=1
# while n * n < 1200:
# n=n+1
# print(n)
# while n * n * n >1200:
# n=n-1
# print(n)
|
# -*- coding: utf-8 -*-
"""
.. _Docutils Configuration: http://docutils.sourceforge.net/docs/user/config.html
.. _registry-intro:
Configuration registry
======================
Registry store configurations by the way of its interface.
Default global registry is available at ``rstview.registry.rstview_registry``
and is global for the whole project and apps, you don't need to fill it again
for a same Django instance.
A configuration is a dictionnary of parameters for reStructuredText parser:
.. sourcecode:: python
{
'default': {
'initial_header_level': 1,
'language_code': "en",
},
}
Configuration name is used to retrieve parameters from the registry interface.
See `Docutils Configuration`_ for a full references of available parser
parameters.
"""
class RstviewConfigAlreadyRegistered(Exception):
pass
class RstviewConfigNotRegistered(Exception):
pass
class RstConfigSite(object):
"""
Rstview configurations registry
Keyword Arguments:
initial (dict): Optional initial dictionnary of configuration. Default
to an empty dict.
"""
def __init__(self, *args, **kwargs):
self._registry = kwargs.get('initial', {})
def reset(self):
"""
Reset registry to an empty Dict.
"""
self._registry = {}
def get_registry(self):
"""
Return current registry
Returns:
dict: Currrent registry.
"""
return self._registry
def get_names(self):
"""
Return registred configuration names.
Returns:
list: List of registred names, sorted with default ``sorted()``
behavior.
"""
return sorted(self._registry.keys())
def has_name(self, name):
"""
Find if given name is a registred configuration name.
Returns:
bool: ``True`` if name exists in current registry, else ``False``.
"""
return name in self._registry
def get_parameters(self, name):
"""
Get parameters from given configuration name.
Arguments:
name (string): Configuration name.
Returns:
string or tuple: Configuration parameters.
"""
if not self.has_name(name):
msg = 'Given name "{}" is not registered as a configuration.'
raise RstviewConfigNotRegistered(msg.format(name))
return self._registry[name]
def register(self, name, value):
"""
Register a configuration for given name.
Arguments:
name (string): Configuration name.
value (string or tuple): Configuration parameters to define.
Raises:
``RstviewConfigAlreadyRegistered`` if name is allready registered in
configurations.
"""
if self.has_name(name):
msg = 'Given name "{}" is already registered as a configuration.'
raise RstviewConfigAlreadyRegistered(msg.format(name))
self._registry[name] = value
def unregister(self, name):
"""
Unregister a configuration from its name.
Arguments:
name (string): Url name.
Raises:
``RstviewConfigNotRegistered`` if given url name is not registred yet.
"""
if not self.has_name(name):
msg = 'Given name "{}" is not registered as a configuration.'
raise RstviewConfigNotRegistered(msg.format(name))
del self._registry[name]
def update(self, configs):
"""
Update many configuration.
This works like the ``Dict.update({..})`` method.
Arguments:
configs (dict): A dict of configurations.
"""
self._registry.update(configs)
#: Default rstview configurations registry for a Django instance.
rstview_registry = RstConfigSite()
|
# ** potência ou pow(4,3)
# // divisão inteira
nom = input('Comment vous vous appellez? ')
print('Cest un plaisir de vous conaitre {:20}!'.format(nom))
print('Cest un plaisir de vous conaitre {:>20}!'.format(nom))
print('Cest un plaisir de vous conaitre {:^20}!'.format(nom))
print('Cest un plaisir de vous conaitre {:=^20}!'.format(nom))
|
# (C) Datadog, Inc. 2010-2017
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
PORT = 11211
SERVICE_CHECK = 'memcache.can_connect'
|
PI = 3.1415 # Globale Variable
def kreisumfang(radius):
kreisumfang = 2 * PI * radius
return kreisumfang
def zylinder(radius, hoehe):
return hoehe * kreisumfang(radius)
print(zylinder(50, 20))
|
"""
A python package to update stuff.
This code is released under the terms of the MIT license. See the LICENSE
file for more details.
"""
|
def help_normalize_variations(variations: list[dict]) -> list[dict]:
list_normalized = []
obj_normalized = {}
list_obj_normalized = []
last_color = ""
count = 0
for element in variations:
if last_color == element.color or last_color == "":
list_normalized.append(
{
"size": element.size,
"quantity": element.quantity,
}
)
obj_normalized["color_name"] = element.color
obj_normalized["sizes_product"] = [*list_normalized]
last_color = element.color
if count == len(variations) - 1:
list_obj_normalized.append(obj_normalized)
else:
list_obj_normalized.append(obj_normalized)
obj_normalized = {}
last_color = ""
list_normalized = []
list_normalized.append(
{
"size": element.size,
"quantity": element.quantity,
}
)
count += 1
return list_obj_normalized
|
#!/usr/bin/env python
def construct_fip_id(subscription_id, group_name, lb_name, fip_name):
"""Build the future FrontEndId based on components name.
"""
return ('/subscriptions/{}'
'/resourceGroups/{}'
'/providers/Microsoft.Network'
'/loadBalancers/{}'
'/frontendIPConfigurations/{}').format(
subscription_id, group_name, lb_name, fip_name
)
def construct_bap_id(subscription_id, group_name, lb_name, address_pool_name):
"""Build the future BackEndId based on components name.
"""
return ('/subscriptions/{}'
'/resourceGroups/{}'
'/providers/Microsoft.Network'
'/loadBalancers/{}'
'/backendAddressPools/{}').format(
subscription_id, group_name, lb_name, address_pool_name
)
def construct_probe_id(subscription_id, group_name, lb_name, probe_name):
"""Build the future ProbeId based on components name.
"""
return ('/subscriptions/{}'
'/resourceGroups/{}'
'/providers/Microsoft.Network'
'/loadBalancers/{}'
'/probes/{}').format(
subscription_id, group_name, lb_name, probe_name
)
def update_nic_paramaters(address_pool_id, location, nic_info, params):
"""Update the NIC parameters structure.
"""
nic_params = params['nicParams']
nic_params['location'] = location
nic_params['ip_configurations'][0]['name'] = nic_info.ip_configurations[0].name
nic_params['ip_configurations'][0]['subnet']['id'] = nic_info.ip_configurations[0].subnet.id
nic_params['ip_configurations'][0]['load_balancer_backend_address_pools'] = [{
"id": address_pool_id
}]
return nic_params
#nic_params['ip_configurations'][0]['load_balancer_inbound_nat_rules'][0]['id'] = natrule_id
def create_vm_parameters(nic_id, is_nic_primary, location, vm_info, params):
"""Create the VM parameters structure.
"""
vm_params = params['vmParams']
vm_params['location'] = location
vm_params['network_profile']['network_interfaces'][0]['id'] = nic_id
vm_params['network_profile']['network_interfaces'][0]['primary'] = is_nic_primary
return vm_params
|
class aSumPrint:
def run(self, context): #include context
a_sum = context["aSum"] #to extract from shared dictionary
print(f'a_sum = {a_sum}')
def __call__(self, context):
self.run(context) #to run the function
|
"""
Beautiful Arrangement
Suppose you have n integers labeled 1 through n. A permutation of those n integers perm (1-indexed) is considered a beautiful arrangement if for every i (1 <= i <= n), either of the following is true:
perm[i] is divisible by i.
i is divisible by perm[i].
Given an integer n, return the number of the beautiful arrangements that you can construct.
Example 1:
Input: n = 2
Output: 2
Explanation:
The first beautiful arrangement is [1,2]:
- perm[1] = 1 is divisible by i = 1
- perm[2] = 2 is divisible by i = 2
The second beautiful arrangement is [2,1]:
- perm[1] = 2 is divisible by i = 1
- i = 2 is divisible by perm[2] = 1
Example 2:
Input: n = 1
Output: 1
Constraints:
1 <= n <= 15
"""
# approach: recursion with early exit
# memory: O(B), where B is the number of beautiful arrangements
# runtime: O(B), where n is the number of beautiful arrangements
class Solution:
def countArrangement(self, n: int) -> int:
# initialize
self.count = 0
self.nums = list(range(1, n + 1))
self.permute(0)
return self.count
def permute(self, j: int) -> None:
# we reached the end of a valid permutation
if j == len(self.nums):
self.count += 1
# otherwise keep iterating, swapping, and recursing
for i in range(j, len(self.nums)):
# first iteration swaps the same element, serving as a branch for subsequent swaps
self.swap(i, j)
# recurse and progress if the current permutation is valid
if (self.nums[j] % (j + 1) == 0) or ((j + 1) % self.nums[j] == 0):
self.permute(j + 1)
# backtrack
self.swap(i, j)
def swap(self, i: int, j: int) -> None:
t = self.nums[i]
self.nums[i] = self.nums[j]
self.nums[j] = t
|
#set following variables
types_of_people = 10
x = f"There are {types_of_people} types of people."
binary = "binary"
do_not = "don't"
y = f"Those who know {binary} and those who {do_not}."
#print variables "x" and "y" to create sentences
print(x)
print(y)
#print f-strings, notated with "f" in initial position.
#Using f-strings allow you to print literal strings AND variables notated in {}
print(f"I said: {x}")
print(f"I also said: '{y}'")
hilarious = False
#Empty curly braces set so for following print with formatting
joke_evaluation = "Isn't that joke so funny?! {}"
#Since we did not use the format (print (f...)) here, we used curly braces as
#a replacement field. Anything placed in {} are evaluating code, like normal.
print(joke_evaluation.format(hilarious))
w = "This is the left side of ..."
e = "a string with a right side"
#printing variables with "+" operator
print (w + e)
|
comida = ["tacos", "pozole", "pan de muerto", "pastel", "spaghetti", "gorditas"]
print("Acceder a los elementos de la lista individualmente")
print(comida[0])
print(comida[2])
print(comida[5])
print("Mostrar todos los elementos")
print(comida)
print()
print("Eliminar algun elemento")
del comida[3]
comida.pop()
print(comida)
print()
print("Agregar elementos en distintos puntos de la lista")
print("Al inicio burritos")
comida.insert(0,"burritos")
print("Al medio sopa")
comida.insert(2, "sopa")
print("Al final con .append tostadas")
comida.append("tostadas")
print("Asi quedaria ahora")
print(comida)
print()
print("Ahora a jugar con el orden de la lista")
print("Orden original")
print(comida,"\n")
print("Ordenados alfabeticamente sin alterar la lista original")
print(sorted(comida), "\n")
print("No se modifico la original")
print(comida,"\n")
print("Ordenados alfabeticamente de manera inversa sin alterar la lista original")
print(sorted(comida,reverse=True),"\n")
print("No se modifico la original")
print(comida,"\n")
print("Invertir la lista original")
comida.reverse()
print(comida,"\n")
print("Regresar la lista que acabamos de invertir a como estaba")
comida.reverse()
print(comida,"\n")
print("Ordenar la lista alfabeticamente modificando la lista")
comida.sort()
print(comida,"\n")
print("Ordenar la lista alfabeticamente de forma invertida modificando la lista")
comida.sort(reverse=True)
print(comida)
print()
print("Al final mostrar la longitud de esta lista que es de:",len(comida))
|
class Solution:
def depthSum(self, nestedList: List[NestedInteger]) -> int:
def helper(current, depth):
res = 0
for item in current:
if item.isInteger():
res += item.getInteger() * depth
else:
res += helper(item.getList(), depth + 1)
return res
return helper(nestedList, 1)
|
"""
Constants that are used throughout Zen.
"""
# Graph directedness
DIRECTED = 'directed'
UNDIRECTED = 'undirected'
# Direction constants
BOTH_DIR = 'both_dir'
IN_DIR = 'in_dir'
OUT_DIR = 'out_dir'
# Constants for specifying how weights should be merged.
# These values are accepted by the DiGraph.skeleton function.
AVG_OF_WEIGHTS = 0
MAX_OF_WEIGHTS = 1
MIN_OF_WEIGHTS = 2
# Constants for specifying how data should be merged.
# These values are accepted by the DiGraph.skeleton function.
NO_NONE_LIST_OF_DATA = 0
LIST_OF_DATA = 1
|
argv = ['']
def exit(n):
pass
exit(0)
stdout = open("/dev/null")
stderr = open("/dev/null")
stdin = open("/dev/null")
|
class Eval:
"""
Eval
"""
def __init__(self):
self.predict_num = 0
self.correct_num = 0
self.gold_num = 0
self.precision = 0
self.recall = 0
self.fscore = 0
def clear(self):
"""
:return:
"""
self.predict_num = 0
self.correct_num = 0
self.gold_num = 0
self.precision = 0
self.recall = 0
self.fscore = 0
def getFscore(self):
"""
:return:
"""
if self.predict_num == 0:
self.precision = 0
else:
self.precision = (self.correct_num / self.predict_num) * 100
if self.gold_num == 0:
self.recall = 0
else:
self.recall = (self.correct_num / self.gold_num) * 100
if self.precision + self.recall == 0:
self.fscore = 0
else:
self.fscore = 2 * (self.precision * self.recall) / (self.precision + self.recall)
return self.precision, self.recall, self.fscore
def acc(self):
"""
:return:
"""
return self.correct_num / self.gold_num
|
"""
1부터 N까지 모든 자연수의 합을 구하시오
S(N) = N + S(N-1)
"""
def get_sum(num):
if num == 1:
return 1
else:
return num + get_sum(num-1)
res = get_sum(10)
print(res)
|
x = int(input())
n = int(input())
a = []
for y in range(n):
a.append(input().split())
for y in range(n):
if x >= int(a[y][0]) and x <= int(a[y][1]):
print(a[y][2])
|
print("Sartu zenbakiak...")
a=int(input("Sartu lehenengoa: "))
b=int(input("sartu bigarrena: "))
def baino_haundiagoa(a, b):
if a > b:
return("Lehenengo zenbakia haundiagoa da.")
elif a < b:
return("Bigarren zenbakia haundiagoa da.")
else:
return("Zenbaki berdina sartu dezu.")
print(baino_haundiagoa(a, b))
|
'''
@author: Kittl
'''
def exportSubstations(dpf, exportProfile, tables, colHeads):
# Get the index in the list of worksheets
if exportProfile is 2:
cmpStr = "Substation"
elif exportProfile is 3:
cmpStr = ""
idxWs = [idx for idx,val in enumerate(tables[exportProfile-1]) if val == cmpStr]
if not idxWs:
dpf.PrintPlain('')
dpf.PrintInfo('There is no worksheet '+( cmpStr if not cmpStr == "" else "for substations" )+' defined. Skip this one!')
return (None, None)
elif len(idxWs) > 1:
dpf.PrintError('There is more than one table with the name '+cmpStr+' defined. Cancel this script.')
exit(1)
else:
idxWs = idxWs[0]
dpf.PrintPlain('')
dpf.PrintPlain('###################################')
dpf.PrintPlain('# Starting to export substations. #')
dpf.PrintPlain('###################################')
colHead = list();
for cHead in colHeads[exportProfile-1][idxWs]:
colHead.append(str(cHead.name))
expMat = list()
expMat.append(colHead)
substats = dpf.GetCalcRelevantObjects('*.ElmSubstat')
for substat in substats:
if exportProfile is 2:
expMat.append([
substat.loc_name, # id
substat.pArea.loc_name if substat.pArea is not None else "", # subnet
substat.pZone.loc_name if substat.pZone is not None else "" # voltLvl
])
else:
dpf.PrintError("This export profile isn't implemented yet.")
exit(1)
return (idxWs, expMat)
|
array=list(map(int,input().split()))
print('Your Array :',array)
for i in range(0,len(array)-1):
if(array[i+1]<array[i]):
temp=array[i+1]
j=i
while(temp<array[j] and j>=0):
array[j+1]=array[j]
j-=1
array[j+1]=temp
print('Sorted Array : ',array)
|
ENDINGS = ['.', '!', '?', ';']
def count_sentences(text):
text = text.strip()
if len(text) == 0:
return 0
split_result = None
for ending in ENDINGS:
separator = f'{ending} '
if split_result is None:
split_result = text.split(separator)
else:
split_result = [y for x in split_result for y in x.split(separator)]
last_is_sentence = text[-1] in ENDINGS
return len(split_result) - 1 + last_is_sentence
|
# %% [1013. Partition Array Into Three Parts With Equal Sum](https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/)
# 問題:3つのグループの和が等しくなるように2箇所で区切れるかを返せ
# 解法:和の1/3に等しい回数を数える
class Solution:
def canThreePartsEqualSum(self, A: List[int]) -> bool:
s = sum(A)
c, cs, s3 = 0, 0, s // 3
for a in A:
if (cs := cs + a) == s3:
c, cs = c + 1, 0
return c >= 3
|
def cheeseshop(kind, *arguments, **keywords):
print("-- Do you have any", kind, "?")
print("-- I'm sorry, we're all out of", kind)
for arg in arguments:
print(arg)
print("-" * 40)
for kw in keywords:
print(kw, ":", keywords[kw])
cheeseshop("Limburger", "It's very runny, sir.",
"It's really very, VERY runny, sir.",
shopkeeper="Michael Palin",
client="John Cleese",
sketch="Cheese Shop Sketch")
def list_example(*mylist):
for i in mylist:
print(i, end=", ")
print()
list_example("a ", 'b ', 'c ')
def dict_example(**mydict):
for i in mydict:
print(i, ":", mydict[i])
print()
dict_example(name="dsfds", value="valuedsfasdf")
def make_incrementor(n):
""" This is documentation
in python
"""
return lambda x: x + n
print()
func = make_incrementor(20)
print(func(1))
print(func(2))
print(func(3))
people = ['Dr. Christopher Brooks', 'Dr. Kevyn Collins-Thompson', 'Dr. VG Vinod Vydiswaran', 'Dr. Daniel Romero']
def split_title_and_name(person):
split = person.split(" ")
return split[0] + " " + split[-1]
print(list(map(split_title_and_name, people)))
|
# Under MIT License, see LICENSE.txt
__author__ = 'RoboCupULaval'
class TaskController:
"""Class added by composition to any task,
to keep track of the Task state
and logic flow.
This state-control class is separated
from the Task class so the Decorators
have a chance at compile-time security.
@author Ying"""
def __init__(self):
self.done = False
self.success = True
self.started = False
def set_task(self,task):
"""Sets the task reference
@param task Task to monitor"""
self.task = task
def safe_start(self,task):
"""Starts the monitored class"""
self.started = True
task.start()
def safe_end(self,task):
"""Ends the monitored task"""
self.done = False
self.started = False
task.end()
def finish_with_success(self):
"""Ends the monitored class, with success"""
self.success = True
self.done = True
def finish_with_failure(self):
"""Ends the monitored class, with failure"""
self.success = False
self.done = True
def succeeded(self):
"""Indicates whether the task finished successfully
@return True if it did, false if it didn't """
return self.success
def failed(self):
"""Indicates whether the task finished with failure
@return True if it did, false if it didn't"""
return not self.success
def finished(self):
"""Indicates whether the task finished
@return True if it did, false if it didn't """
return self.done
def started(self):
"""Indicates whether the class has started or not
@return True if it has, false if it hasn't"""
return self.started
def reset_task(self):
"""Marks the class as just started."""
self.done = False
|
'''
Get an undefined numbers of values and put them in a list.
In the end, show all the unique values in ascendent order.
'''
values = []
while True:
number = int(input('Choose a number: '))
if number not in values:
print(f'\033[32mAdd the number {number} to the list.\033[m')
values.append(number)
else:
print(f'\033[31mThe number {number} already exists in the list. Not added.\033[m')
again = input('Do you want to continue? [Y/N]').upper()
if again == 'N':
break
values.sort()
print(f'You choose the values {values}')
|
class Context(dict):
"""Model the execution context for a Resource.
"""
def __init__(self, request):
"""Takes a Request object.
"""
self.website = None # set in dynamic_resource.py
self.body = request.body
self.headers = request.headers
self.cookie = request.headers.cookie
self.path = request.line.uri.path
self.qs = request.line.uri.querystring
self.request = request
self.socket = None
self.channel = None
self.context = self
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
for method in ['OPTIONS', 'GET', 'HEAD', 'POST', 'PUT', 'DELETE',
'TRACE', 'CONNECT']:
self[method] = (method == request.line.method)
setattr(self, method, self[method])
def __getattr__(self, name):
try:
return self[name]
except KeyError:
raise AttributeError("")
def __setattr__(self, name, value):
self[name] = value
|
VOWELS = { c for c in "aeouiAEOUI" }
def swap_vowel_case_char(c :str) -> str:
return c.swapcase() if c in VOWELS else c
def swap_vowel_case(st: str) -> str:
return "".join(swap_vowel_case_char(c) for c in st)
|
# Marcelo Campos de Medeiros
# ADS UNIFIP
# REVISÃO DE PYTHON
# AULA 13 LAÇO DE REPETIÇÃO FOR ---> GUSTAVO GUANABARA
'''
Faça um Programa que leia o peso de cinco pessoas. No final mostre qual
foi maior e o menor peso lidos.
'''
print('='*30)
print('{:§^30}'.format(' PESO '))
print('='*30)
print()
#contadores os dois recebem 0 pq 1° laço ontem o maior == menor
maior = 0
menor = 0
# variáveis peso de cinco pessoas
for p in range(1, 6):
peso = float(input(f'Qual é o peso da {p}° pessoa: '))
#condição pq 1° laço p1 vai ter o maior e o menor peso (maior == menor)
if p == 1:
maior = peso
menor = peso
else:
# se 2°(...) laço peso > maior então maior = peso
if peso > maior:
maior = peso
# ou se 2°(...) laço peso > menor então menor = peso
if peso < menor:
menor = peso
print('='*40)
print(f'O maior peso foi de {maior:.2f}Kg.\n'
f'O menor peso foi de {menor:.2f}Kg.')
|
"""Base classes for pipelines and pipeline blocks."""
class Block(object):
"""Base class for all blocks.
Notes
-----
Blocks should take their parameters in ``__init__`` and provide at least
the ``process`` method for taking in data and returning some result.
"""
def __init__(self, name=None, hooks=None):
self._name = name
if name is None:
self._name = self.__class__.__name__
self._hooks = hooks
if hooks is None:
self._hooks = []
def __call__(self, *args, **kwargs):
return self.process(*args, **kwargs)
def process(self, data):
"""Process input data and produce a result.
Subclasses must implement this method, otherwise it shouldn't really be
a ``Block``.
"""
raise NotImplementedError
def clear(self):
"""Clear the state of the block.
Some blocks don't keep stateful attributes, so ``clear`` does nothing
by default.
"""
pass
@property
def name(self):
return self._name
@property
def hooks(self):
return self._hooks
def __repr__(self):
return "%s.%s()" % (
self.__class__.__module__,
self.__class__.__name__
)
class Pipeline(Block):
"""Feedforward arrangement of blocks for processing data.
A :class:`Pipeline` contains a set of :class:`Block` objects which operate
on data to produce a final output.
To create a pipeline, the following two rules are needed: blocks in a list
processed in series, and blocks in a tuple are processed in parallel.
Blocks that are arranged to take multiple inputs should expect to take the
corresponding number of inputs in the order they are given. It is up to the
user constructing the pipeline to make sure that the arrangement of blocks
makes sense.
Parameters
----------
blocks : container
The blocks in the pipline, with lists processed in series and tuples
processed in parallel.
Attributes
----------
named_blocks : dict
Dictionary of blocks in the pipeline. Keys are the names given to the
blocks in the pipeline and values are the block objects.
"""
def __init__(self, blocks, name=None):
super(Pipeline, self).__init__(name=name)
self.blocks = blocks
self.named_blocks = {}
# traverse the block structure to fill named_blocks
self._call_block('name', self.blocks)
def process(self, data):
"""
Calls the ``process`` method of each block in the pipeline, passing the
outputs around as specified in the block structure.
Parameters
----------
data : object
The input to the first block(s) in the pipeline. The type/format
doesn't matter, as long as the blocks you define accept it.
Returns
-------
out : object
The data output by the ``process`` method of the last block(s) in
the pipeline.
"""
out = self._call_block('process', self.blocks, data)
return out
def clear(self):
"""
Calls the ``clear`` method on each block in the pipeline. The effect
depends on the blocks themselves.
"""
self._call_block('clear', self.blocks)
def _call_block(self, fname, block, data=None):
if isinstance(block, list):
out = self._call_list(fname, block, data)
elif isinstance(block, tuple):
out = self._call_tuple(fname, block, data)
else:
if fname == 'name':
self.named_blocks[block.name] = block
return
f = getattr(block, fname)
if data is not None:
out = f(data)
else:
out = f()
if hasattr(block, 'hooks') and fname == 'process':
for hook in block.hooks:
hook(out)
return out
def _call_list(self, fname, block, data=None):
out = data
for b in block:
out = self._call_block(fname, b, out)
return out
def _call_tuple(self, fname, block, data=None):
out = []
for b in block:
out.append(self._call_block(fname, b, data))
if fname == 'process':
return out
else:
return None
|
PuzzleInput = "PuzzleInput.txt"
f = open(PuzzleInput)
txt = f.readlines()
sums = []
k=0
for j in range(len(txt)):
for i in range(25):
for k in range(25):
if i == k:
continue
else:
sums.append(int(txt[i])+int(txt[k]))
if int(txt[25]) in sums:
txt.pop(0)
sums = []
else:
print(int(txt[25]),"is not a sum of 2 of the previous 25 numbers")
break
|
if __name__ == '__main__':
# Creating a tuple
x = ()
x = (1, )
print(type(x))
x = (1)
print(type(x))
x = (1, 2, 3, "Apple", True, 4.0)
x = ((1, 2, 3), (4, 5, 6))
#Accessing Tuple
x = (1, 2, 3, "Apple", True, (7, 7, 7), 4.0)
print(x[3])
print(x[-2])
print(x[1:2])
print(x[1:3])
print(x[::2])
_, _, _, _, _, _, x7 = x
print(x7)
print(x[5][1])
# Modify tuple
x[0] = 2
x = (1, 2, 3)
# Tuple Operation
print((1, 2) + (3, 4, 5))
print((1, 2) * 3)
print(len(1, 2, 3))
print("Apple" in ("Hong Kong", "Taiwan"))
print(4 not in (3, 7, 9))
x = (1,2,3,1)
print(x.count(1))
print(x.index(1))
for num in x:
print(num, end=" ")
|
#
# @lc app=leetcode id=108 lang=python3
#
# [108] Convert Sorted Array to Binary Search Tree
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
def helper(left, right):
if left > right:
return None
# always choose left middle node as a root
p = (left + right) // 2
# preorder traversal: node -> left -> right
root = TreeNode(nums[p])
root.left = helper(left, p - 1)
root.right = helper(p + 1, right)
return root
return helper(0, len(nums) - 1)
# @lc code=end
|
class DecorationRepository:
def __init__(self):
self.decorations = []
@staticmethod
def get_obj_by_type(objects, obj_type):
result = [obj for obj in objects if obj.__class__.__name__ == obj_type]
return result
def add(self, decoration):
self.decorations.append(decoration)
def remove(self, decoration):
if decoration not in self.decorations:
return False
self.decorations.remove(decoration)
return True
def find_by_type(self, decoration_type: str):
decorations = self.get_obj_by_type(self.decorations,decoration_type)
if decorations:
return decorations[0]
return "None"
|
class Envelope:
"""
Envelope to add metadata to a message.
This is an internal type and is not part of the public API.
:param message: the message to send
:type message: any
:param reply_to: the future to reply to if there is a response
:type reply_to: :class:`pykka.Future`
"""
# Using slots speeds up envelope creation with ~20%
__slots__ = ["message", "reply_to"]
def __init__(self, message, reply_to=None):
self.message = message
self.reply_to = reply_to
def __repr__(self):
return f"Envelope(message={self.message!r}, reply_to={self.reply_to!r})"
|
#Rost,B. and Sander,C. (1994) Conservation and prediction of solvent accessibility in
#protein families. Proteins, 20, 216–226.
macc = {}
macc['A'] = 106
macc['C'] = 135
macc['D'] = 163
macc['E'] = 194
macc['F'] = 197
macc['G'] = 84
macc['H'] = 184
macc['I'] = 169
macc['K'] = 205
macc['L'] = 164
macc['M'] = 188
macc['N'] = 157
macc['P'] = 136
macc['Q'] = 198
macc['R'] = 248
macc['S'] = 130
macc['T'] = 142
macc['V'] = 142
macc['W'] = 227
macc['Y'] = 222
|
class Libro:
def __init__(self, titulo, autor, isbn, genero ):
self.autor = autor
self.titulo = titulo
self.isbn = isbn
self.genero = genero
def descripcion(self):
print("El nombre del libro es " + self.titulo + " y es del género " + self.genero)
print("Su autor es " + self.autor)
print("Su ISBN es " + self.isbn )
print("Elija el nombre del libro a buscar:")
tit = input()
print("¿Quién es el autor del libro?")
aut = input()
print("¿De qué género es?")
gen = input()
print("¿Cuál es el isbn?")
isbn = input()
libro = Libro(tit, aut, isbn, gen)
libro.descripcion
|
class NotValidAttributeException(Exception):
def __init__(self, message, errors):
super(NotValidAttributeException, self).__init__(message)
self.errors = errors
class NoReportFoundException(Exception):
def __init__(self, message, errors):
super(NoReportFoundException, self).__init__(message)
self.errors = errors
class ElementCannotBeFoundException(Exception):
def __init__(self, message, errors):
super(ElementCannotBeFoundException, self).__init__(message)
self.errors = errors
class TemplatePathNotFoundException(Exception):
def __init__(self, message, errors):
super(TemplatePathNotFoundException, self).__init__(message)
self.errors = errors
class NoINITemplateGivenException(Exception):
def __init__(self, message, errors):
super(NoINITemplateGivenException, self).__init__(message)
self.errors = errors
class TemplateINIFileDoesNotExistException(Exception):
def __init__(self, message, errors):
super(TemplateINIFileDoesNotExistException, self).__init__(message)
self.errors = errors
class TemplateFileIsNotAnINIFileException(Exception):
def __init__(self, message, errors):
super(TemplateFileIsNotAnINIFileException, self).__init__(message)
self.errors = errors
class OutputFileAlreadyExistsException(Exception):
def __init__(self, message, errors):
super(OutputFileAlreadyExistsException, self).__init__(message)
self.errors = errors
class InvalidOutputFilePathException(Exception):
def __init__(self, message, errors):
super(InvalidOutputFilePathException, self).__init__(message)
self.errors = errors
class BatchFileDoesNotExistException(Exception):
def __init__(self, message, errors):
super(BatchFileDoesNotExistException, self).__init__(message)
self.errors = errors
class NoBatchFileWithConcurrentEnabled(Exception):
def __init__(self, message, errors):
super(NoBatchFileWithConcurrentEnabled, self).__init__(message)
self.errors = errors
class InvalidDynamicInputStringException(Exception):
def __init__(self, message, errors):
super(InvalidDynamicInputStringException, self).__init__(message)
self.errors = errors
class DynamicVariableNotFoundInTemplateException(Exception):
def __init__(self, message, errors):
super(DynamicVariableNotFoundInTemplateException, self).__init__(message)
self.errors = errors
class DynamicTemplateAlreadyExistsException(Exception):
def __init__(self, message, errors):
super(DynamicTemplateAlreadyExistsException, self).__init__(message)
self.errors = errors
|
# Desenvolva um programa que leia o primeiro termos e a razão de uma PA.
# No final, mostre os 10 primeiros termos dessa progressão.
# an = a1 + (n - 1) . r
# Onde,
# an : termo que queremos calcular
# a1: primeiro termo da P.A.
# n: posição do termo que queremos descobrir
# r: razão*/
print("===============================")
print(" Os dez primeiros termos são")
print("===============================")
a1 = int(input("Digite o primeiro termo: "))
an = int(input("Digite a quantidade de termos: "))
p = int(input("Digite a posição do termo que queremos descobri: "))
r = int(input("Digite a razão da P.A.: "))
for c in range(1 , an + 1):
termos = a1 + (c - 1) * r
find = a1 + (p - 1) * r
print('{}'.format(termos), end= ' ')
print("\nO {}º termo da P.A. é {}".format(p, find))
|
n = int (input('Enter a number for prime number series : '))
for i in range(2,n):
for j in range(2,i):
if i % j == 0:
print(i,"is not a prime number because",j,"*",i//j,"=",i)
break
else:
print(i,"is a prime number")
|
# -*- coding: utf-8 -*-
#################################################################################
# Author : Webkul Software Pvt. Ltd. (<https://webkul.com/>)
# Copyright(c): 2015-Present Webkul Software Pvt. Ltd.
# All Rights Reserved.
#
#
#
# This program is copyright property of the author mentioned above.
# You can`t redistribute it and/or modify it.
#
#
# You should have received a copy of the License along with this program.
# If not, see <https://store.webkul.com/license.html/>
#################################################################################
{
"name" : "SEO-URL Redirect/Rewrite",
"summary" : "SEO-URL Redirect/Rewrite module helps to redirect or redirect a URL to another URL to avoid page not found error.",
"category" : "Website",
"version" : "1.2",
"sequence" : 1,
"author" : "Webkul Software Pvt. Ltd.",
"license" : "Other proprietary",
"website" : "https://store.webkul.com/Odoo-SEO-URL-Redirect-Rewrite.html",
"description" : """SEO
Search Engine Optimization
URL
SEO URL
Redirect/Rewrite
Rewrite
Redirect
SEO-URL Redirect/Rewrite
Odoo SEO-URL Redirect/Rewrite
URL Redirect/Rewrite
URL Rewrite
URL Redirect
""",
"live_test_url" : "http://odoodemo.webkul.com/?module=seo_url_redirect",
"depends" : [
'website_sale',
'website_webkul_addons',
'wk_wizard_messages',
],
"data" : [
'views/templates.xml',
'views/product_template_views.xml',
'views/product_views.xml',
'views/rewrite_view.xml',
'data/data_seo.xml',
'data/seo_server_actions.xml',
'views/website_views.xml',
'views/rewrite_menu.xml',
'views/res_config_views.xml',
'views/webkul_addons_config_inherit_view.xml',
],
"images" : ['static/description/Banner.png'],
"application" : True,
"installable" : True,
"auto_install" : False,
"price" : 45,
"currency" : "EUR",
"pre_init_hook" : "pre_init_check",
"post_init_hook" : "_update_seo_url",
}
|
"""
Implement an algorithm to delete a node in the middle (ie., any node but the first and last node,
not necessarily the exact middle) of a singly linked list, given only access to that node.
Input: the node c from the linked list a -> b -> c -> d -> e -> f
Result: nothing is returned, but the new linked list looks like a -> b -> d -> e -> f
"""
class Node:
def __init__(self, cargo=None, _next=None):
self.cargo = cargo
self.next = _next
def __str__(self):
return str(self.cargo)
def print_forward(node):
while node:
print(node.cargo)
node = node.next
def delete(node):
"""
Simply copy the data from the next node over to the current node.
"""
if not node or not node.next:
return False
node.cargo = node.next.cargo
node.next = node.next.next
return True
f = Node('f')
e = Node('e', _next=f)
d = Node('d', _next=e)
c = Node('c', _next=d)
b = Node('b', _next=c)
a = Node('a', _next=b)
print('-' * 40)
print_forward(a)
print('-' * 40)
delete(c)
print_forward(a)
|
class Solution:
def threeSumClosest(self, num, target):
num = sorted(num)
best_sum = num[0] + num[1] + num[2]
for i in range(len(num)):
j = i + 1
k = len(num) - 1
while j < k:
current_sum = num[i] + num[j] + num[k]
if current_sum == target:
return current_sum
if abs(current_sum - target) < abs(best_sum - target):
best_sum = current_sum
if current_sum > target:
k -= 1
else:
j += 1
return best_sum
|
'''
__iter__
如果一个类想被用于for ... in循环,类似list或tuple那样,就必须实现一个__iter__()方法
__getitem__
使实例可以像list一样通过下标获取元素
'''
class demo02:
def __init__(self):
self.a, self.b = 0, 1 # 初始化两个计数器a,b
def __iter__(self):
return self # 实例本身就是迭代对象,故返回自己
def __next__(self):
if self.a != 0:
self.a = self.a + 2
if(self.a > 100):
raise StopIteration()
return self.a
def __getitem__(self, item):
list1 = range(0,101,2)
return list1[item]
for x in demo02():
print(x)
print(demo02()[3])
|
# -*- coding: utf-8 -*-
"""
@author: krakowiakpawel9@gmail.com
@site: e-smartdata.org
"""
empty_tuple = tuple()
print(empty_tuple)
# %%
amazon = ('Amazon', 'USA', 'Technology', 1)
google = ('Google', 'USA', 'Technology', 2)
# %%
name_google = google[0]
# %%
data = (amazon, google)
print(data)
# %%
a = ('Pawel', 'Krakowiak')
print(a)
# %%
imie = 'Pawel'
nazwisko = 'Krakowiak'
# %%
imie, nazwisko, id_user = ('Pawel', 'Krakowiak', '001')
# %%
amazon_name, country, sector, rank = amazon
# %%
stocks = 'Amazon', 'Apple', 'IBM'
print(type(stocks))
# %%
nested = 'Europa', 'Polska', ('Warszawa', 'Krakow', 'Wroclaw')
print(nested)
# %%
a = 12
b = 14
c = b
b = a
a = c
print(a, b)
# %%
x, y = 10, 15
x, y = y, x
print(x, y)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#======================================================================
# Code for solving day 8 of AoC 2018
#======================================================================
VERBOSE = True
#------------------------------------------------------------------
#------------------------------------------------------------------
def load_input(filename):
with open(filename,'r') as f:
content = f.read()
return content.strip()
#------------------------------------------------------------------
#------------------------------------------------------------------
def part_one():
print("Performing part one.")
my_input = load_input("puzzle_input_day_8.txt")
print("Answer for part one: %d")
#------------------------------------------------------------------
#------------------------------------------------------------------
def part_two():
print("Performing part two.")
my_input = load_input("puzzle_input_day_8.txt")
print("Answer for part two: %d")
#------------------------------------------------------------------
#------------------------------------------------------------------
print('Answers for day 8:')
part_one()
part_two()
#======================================================================
|
flag=[0]*35
box = [
253, 194, 15, 13, 82,
129, 244, 80, 193, 233,
36, 54, 199, 69, 219,
74, 136, 6, 190, 144,
68, 57, 156, 153, 240,
65, 95, 135, 61, 179,
159, 183, 182, 130, 107]
target = [
174, 178, 102, 127, 22,
245, 143, 226, 245, 131,
65, 105, 135, 48, 94,
21, 185, 188, 225, 211,
116, 11, 178, 184, 248,
18, 47, 205, 79, 38,
235, 244, 149, 196, 185]
state = target
for i in range(0, 35, 5):
# state[i] = flag[i] ^ box[i]
# state[i + 1] = flag[(i + 1)] ^ box[(i + 1)]
# state[i + 2] = ((state[i] ^ state[(i + 1)] ^ flag[(i + 2)]) - box[(i + 2)]) & 255
# state[i + 3] = flag[(i + 3)] ^ box[(i + 3)]
# state[i + 4] = flag[(i + 4)] ^ state[(i + 3)]
flag[i+4]=state[i+4]^state[i+3]
flag[i+3]=state[i+3]^box[i+3]
flag[i+2]=((state[i+2]+box[i+2])&255)^state[i+1]^state[i]
flag[i+1]=state[i+1]^box[i+1]
flag[i]=state[i]^box[i]
print(bytes(flag))
|
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
i = 0
while 2**i <n:
i+=1
if 2**i==n:
return True
return False
|
widget_defaults = dict(
font="FiraCode Nerd Font",
fontsize = 21,
padding = 2,
background=colors[2]
)
extension_defaults = widget_defaults.copy()
def init_widgets_list():
prompt = "{0}@{1}: ".format(os.environ["USER"], socket.gethostname())
widgets_list = [
widget.Sep(
linewidth = 0,
padding = 6,
foreground = colors[2],
background = colors[0]
),
widget.Image(
filename = "~/.config/qtile/icons/tux.png",
scale = "False",
mouse_callbacks = {'Button1': lambda: qtile.cmd_spawn(myTerm)},
background = colors[0]
),
widget.Sep(
linewidth = 0,
padding = 6,
foreground = colors[2],
background = colors[0]
),
widget.TextBox(
text = '|',
background = colors[0],
foreground = '#808080',
fontsize = 20
),
widget.Sep(
linewidth = 0,
padding = 6,
foreground = colors[2],
background = colors[0]
),
widget.GroupBox(
font = "FiraCode Nerd Font",
fontsize = 18,
margin_y = 3,
margin_x = 0,
padding_y = 5,
padding_x = 3,
borderwidth = 3,
active = "#ff71ce",
inactive = colors[2],
rounded = False,
highlight_color = colors[0],
highlight_method = "line",
this_current_screen_border = colors[6],
this_screen_border = colors [4],
other_current_screen_border = colors[6],
other_screen_border = colors[4],
foreground = colors[2],
background = colors[0]
),
widget.Prompt(
prompt = prompt,
font = "Ubuntu Mono",
padding = 10,
foreground = colors[3],
background = colors[1],
fontsize = 16
),
widget.Sep(
linewidth = 0,
padding = 40,
foreground = colors[2],
background = colors[0]
),
widget.WindowName(
foreground = colors[6],
background = colors[0],
padding = 0
),
widget.Sep(
linewidth = 0,
padding = 6,
foreground = colors[0],
background = colors[0]
),
widget.TextBox(
text = '',
background = colors[0],
foreground = colors[5],
padding = -1,
fontsize = 70
),
widget.CheckUpdates(
update_interval = 1800,
distro = "Arch_checkupdates",
display_format = "⟳{updates} Updates",
foreground = colors[2],
mouse_callbacks = {'Button1': lambda: qtile.cmd_spawn(myTerm + ' -e sudo pacman -Syu')},
background = colors[5]
),
widget.TextBox(
text = '',
background = colors[5],
foreground = colors[4],
padding = -1,
fontsize = 70
),
widget.CPU(
format = 'cpu: {load_percent}% {freq_current}GHz',
foreground = colors[2],
background = colors[4]
),
widget.TextBox(
text = '',
background = colors[4],
foreground = colors[5],
padding = -1,
fontsize = 70
),
widget.TextBox(
text = " 🌡",
padding = 2,
foreground = colors[2],
background = colors[5],
fontsize = 16
),
widget.ThermalSensor(
foreground = colors[2],
background = colors[5],
threshold = 90,
padding = 5,
tag_sensor = "Package id 0"
),
widget.TextBox(
text='',
background = colors[5],
foreground = colors[4],
padding = -1,
fontsize = 70
),
widget.NvidiaSensors(
foreground = colors[2],
background = colors[4],
format = 'GPU {temp}°C'
),
widget.TextBox(
text = '',
background = colors[4],
foreground = colors[5],
padding = -1,
fontsize = 70
),
widget.TextBox(
text = " 🖬",
foreground = colors[2],
background = colors[5],
padding = 0,
fontsize = 16
),
widget.Memory(
foreground = colors[2],
background = colors[5],
mouse_callbacks = {'Button1': lambda: qtile.cmd_spawn(myTerm + ' -e htop')},
padding = 5
),
widget.TextBox(
text='',
background = colors[5],
foreground = colors[4],
padding = -1,
fontsize = 70
),
widget.Net(
interface = "wlan0",# interface_name
format = '{down} ↓↑ {up}',
foreground = colors[2],
background = colors[4],
padding = 5
),
widget.TextBox(
text = '',
background = colors[4],
foreground = colors[5],
padding = -1,
fontsize = 70
),
widget.TextBox(
text = "Vol:",
foreground = colors[2],
background = colors[5],
padding = 0,
),
widget.Volume(
foreground = colors[2],
background = colors[5],
padding = 5
),
widget.TextBox(
text = '',
background = colors[5],
foreground = colors[4],
padding = -1,
fontsize = 70
),
widget.CurrentLayoutIcon(
custom_icon_paths = [os.path.expanduser("~/.config/qtile/icons")],
foreground = colors[0],
background = colors[4],
padding = 0,
scale = 0.7
),
widget.CurrentLayout(
foreground = colors[2],
background = colors[4],
padding = 5
),
widget.TextBox(
text = '',
background = colors[4],
foreground = colors[5],
padding = -1,
fontsize = 70
),
widget.Clock(
foreground = colors[2],
background = colors[5],
format = "%A, %B %d - %H:%M:%S",
mouse_callbacks = {'Button1': lambda: qtile.cmd_spawn(myTerm + f" --hold -e cal {current_year}")}
),
widget.Sep(
linewidth = 0,
padding = 10,
foreground = colors[0],
background = colors[5]
),
widget.TextBox(
text = '',
background = colors[5],
foreground = colors[4],
padding = -1,
fontsize = 70
),
widget.Systray(
background=colors[4],
icon_size=21,
padding = 4
),
widget.Sep(
linewidth = 0,
padding = 10,
foreground = colors[0],
background = colors[4]
),
]
return widgets_list
|
def feast(beast, dish):
x = len(beast)
y = len(dish)
if beast[0] == dish[0]:
if beast[x-1] == dish[y-1]:
return True
else:
return False
else:
return False
def feast1(beast, dish):
return beast[0]==dish[0] and dish[-1]==beast[-1]
|
# encoding: utf-8
"""
location.py
Created by Thomas Mangin on 2014-06-22.
Copyright (c) 2014-2017 Exa Networks. All rights reserved.
License: 3-clause BSD. (See the COPYRIGHT file)
"""
# ===================================================================== Location
# file location
class Location(object):
def __init__(self, index_line=0, index_column=0, line=''):
self.line = line
self.index_line = index_line
self.index_column = index_column
def clear(self):
self.index_line = 0
self.index_column = 0
self.line = ''
class Error(Exception):
tabsize = 3
syntax = ''
def __init__(self, location, message, syntax=''):
self.line = location.line.replace('\t', ' ' * self.tabsize)
self.index_line = location.index_line
self.index_column = location.index_column + (self.tabsize - 1) * location.line[: location.index_column].count(
'\t'
)
self.message = '\n\n'.join(
(
'problem parsing configuration file line %d position %d'
% (location.index_line, location.index_column + 1),
'error message: %s' % message.replace('\t', ' ' * self.tabsize),
'%s%s' % (self.line, '-' * self.index_column + '^'),
)
)
# allow to give the right syntax in using Raised
if syntax:
self.message += '\n\n' + syntax
Exception.__init__(self)
def __repr__(self):
return self.message
|
"""
https://edabit.com/challenge/FGzWE8vNyxtTrw3Qg
Number of Separate Regions
The function is given a rectangular matrix consisting of zeros and ones. Count the number of different regions and return the result. A separate region is a collection of ones interconnected horizontally and vertically. A region can have holes in it.
Examples
num_regions([
[1, 1, 1, 1, 0],
[1, 1, 0, 1, 0],
[1, 1, 0, 0, 0],
[0, 0, 0, 0, 0]
]) ➞ 1
num_regions([
[1, 1, 1, 1, 0],
[1, 0, 0, 1, 0],
[1, 1, 1, 1, 0],
[0, 0, 0, 0, 1]
]) ➞ 2
# The region on the upper left looks like a doughnut.
num_regions([
[1, 1, 0, 0, 0],
[1, 1, 0, 0, 0],
[0, 0, 1, 0, 1],
[0, 0, 0, 1, 1]
]) ➞ 3
"""
def num_regions(grid):
result = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j]:
result +=1
set_grid = [(i,j)]
while set_grid:
x, y = set_grid.pop()
grid[x][y] = 0
for (s,t) in [(x,y+1), (x,y-1), (x+1,y),(x-1,y)]:
if 0 <= s < len(grid) and 0 <= t < len(grid[0]):
if grid[s][t]: set_grid.append((s,t))
return result
num_regions([
[1, 1, 1, 1, 0],
[1, 0, 0, 1, 0],
[1, 1, 1, 1, 0],
[0, 0, 0, 0, 1]
]) #➞ 2
|
# Every non-negative integer N has a binary representation, for example, 8 can be represented as “1000” in binary and 7 as “0111” in binary.
# The complement of a binary representation is the number in binary that we get when we change every 1 to a 0 and every 0 to a 1. For example, the binary complement of “1010” is “0101”.
# For a given positive number N in base-10, return the complement of its binary representation as a base-10 integer.
# Example 1:
# Input: 8
# Output: 7
# Explanation: 8 is 1000 in binary, its complement is 0111 in binary, which is 7 in base-10.
# Example 2:
# Input: 10
# Output: 5
# Explanation: 10 is 1010 in binary, its complement is 0101 in binary, which is 5 in base-10.
def getComplement(num):
'''
Time: O(b) where b is the number of bits used to represent a number.
Space: O(1)
'''
# first we need to get the all_set bits
bit_count = 0
d = num
while d > 0:
bit_count += 1
d = d >> 1
all_set_bits = pow(2, bit_count) - 1
return all_set_bits ^ num
if __name__ == '__main__':
num1 = 8
num2 = 10
r1 = getComplement(num1)
r2 = getComplement(num2)
print(r1, r2)
assert r1 == 7
assert r2 == 5
|
#Dictionary is key value pairs.
d1 = {}
print(type(d1))
d2 ={ "Jiggu":"Burger", "Rohan":"Fish", "Ravi":"Roti"}
#print(d2["Jiggu"]) case sensitive,tell about there syn...
#we can make dictionary inside a dictionary
d3 = {"Jiggu":"Burger", "Rohan":"Fish", "Ravi":"Roti",
"Pagal":{"B":"Oats","L": "Rice","D":"Chicken"}}
'''
d3["Ankit"] = "Junk Food"
d3[3453] = "Kabab"
del d3[3453]
'''
print(d3.get("Jiggu"))
|
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def isValidBST(root):
arr = []
def inOrderTraversal(root):
if not root: return
if root.left: inOrderTraversal(root.left)
arr.append(root.val)
if root.right: inOrderTraversal(root.right)
inOrderTraversal(root)
for i in range(1, len(arr)):
if arr[i] <= arr[i-1]:
return False
return True
# 2
# 1 3
root = TreeNode(2)
root.left = TreeNode(1)
root.right = TreeNode(3)
print(isValidBST(root)) # True
# 5
# 1 4
# x x 3 6
root = TreeNode(5)
root.left = TreeNode(1)
root.right = TreeNode(4)
root.right.left = TreeNode(3)
root.right.right = TreeNode(6)
print(isValidBST(root)) # False
# 10
# 5 15
# x x 6 20
root = TreeNode(10)
root.left = TreeNode(5)
root.right = TreeNode(15)
root.right.left = TreeNode(6)
root.right.right = TreeNode(20)
print(isValidBST(root)) # False
|
class CycleSetupCommon:
"""
realization needs self.h_int, self.gloc, self.g0, self.se, self.mu, self.global_moves,
self.quantum_numbers
"""
def initialize_cycle(self):
return {'h_int': self.h_int,'g_local': self.gloc, 'weiss_field': self.g0,
'self_energy': self.se, 'mu': self.mu, 'global_moves': self.global_moves,
'quantum_numbers': self.quantum_numbers}
def set_data(self, storage, load_mu = True):
"""
loads the data of g_imp_iw, g_weiss_iw, se_imp_iw, mu from storage into the corresponding
objects
The data is copied, storage returns objects that are all BlockGf's and can not init
a selfconsistency cycle
"""
g = storage.load('g_imp_iw')
self.gloc << g
try: # TODO backward compatibility
self.g0 << storage.load('g_weiss_iw')
except KeyError:
pass
self.se << storage.load('se_imp_iw')
if load_mu:
self.mu = storage.load('mu')
|
__info__ = dict(
project = "PyCAMIA",
package = "<main>",
author = "Yuncheng Zhou",
create = "2021-12",
fileinfo = "File of string operations. "
)
__all__ = """
str_len
str_slice
find_all
sorted_dict_repr
enclosed_object
tokenize
""".split()
def str_len(str_:str, r:int=2):
"""
Returen the ASCII string length of `str_`.
Args:
r: bytes a wide character stands for.
Example:
----------
>>> print(str_len("12"), len("你好"), str_len("你好"))
2 2 4
"""
return int(len(str_) + (r-1) * len([c for c in str_ if ord(u'\u4e00') <= ord(c) <= ord(u'\u9fa5')]))
def find_all(str_:str, key:str):
"""
Returen all the starting indices of string `key` in string `str_`.
Example:
----------
>>> find_all("abcaa", 'a')
[0, 3, 4]
"""
p, indices = -1, []
while True:
p = str_.find(key, p + 1)
if p < 0: break
indices.append(p)
return indices
def str_slice(str_:str, indices:list):
"""
Split the string `str_` by breaks in list `indices`.
Example:
----------
>>> str_slice("abcaa", [2,4])
["ab", "ca", "a"]
"""
indices.insert(0, 0); indices.append(len(str_))
return [str_[indices[i]:indices[i+1]] for i in range(len(indices) - 1)]
def sorted_dict_repr(d:dict, order:list):
"""
Representer of dictionary `d`, with key order `order`.
Example:
----------
>>> sorted_dict_repr({'a': 1, '0': 3}, ['0', 'a'])
"{'0': 3, 'a': 1}"
"""
return '{' + ', '.join([f"{repr(k)}: {repr(d[k])}" for k in order]) + '}'
def enclosed_object(str_, by=["([{", ")]}", "$`'\""], start=0):
"""
Return the first object enclosed with a whole pair of parenthesis in `str_` after index `start`.
Example:
----------
>>> enclosed_object("function(something inside), something else. ")
function(something inside)
"""
if len(by) == 3: left, right, both = by
elif len(by) == 2: left, right = by; both = ""
elif len(by) == 1: left = ""; right = ""; both = by[0]
else: raise TypeError("Invalid argument `by` for function `tokenize`. ")
depth = {'all': 0}
for i in range(start, len(str_)):
s = str_[i]
if s in right:
if depth.get(s, 0) == 0: return str_[start:i]
assert depth[s] > 0 and depth['all'] > 0
depth[s] -= 1
depth['all'] -= 1
if depth[s] == 0 and depth['all'] == 0: return str_[start:i+1]
elif s in left:
r = right[left.index(s)]
depth.setdefault(r, 0)
depth[r] += 1
depth['all'] += 1
elif s in both and str_[i-1] != '\\':
depth.setdefault(s, 0)
if depth[s] > 0:
depth[s] -= 1;
depth['all'] -= 1
if depth[s] == 0 and depth['all'] == 0: return str_[start:i+1]
else: depth[s] += 1; depth['all'] += 1
raise RuntimeError(f"Cannot find enclosed object from string {repr(str_)}.")
def tokenize(str_:str, sep=[' ', '\n'], by=["([{", ")]}", "$`'\""], start=0, strip='', keep_empty=True):
"""
Split the string `str_` by elements in `sep`, but keep enclosed objects not split.
Example:
----------
>>> tokenize("function(something inside), something else. ")
["function(something inside),", "something", "else.", ""]
"""
if isinstance(sep, str): sep = [sep]
if len(by) == 3: left, right, both = by
elif len(by) == 2: left, right = by; both = ""
elif len(by) == 1: left = ""; right = ""; both = by[0]
else: raise TypeError("Invalid argument `by` for function `tokenize`. ")
depth = {'all': 0}
tokens = []
p = start
for i in range(start, len(str_)):
s = str_[i]
both_done = False
if s in right:
if depth.get(s, 0) == 0: break
assert depth[s] > 0 and depth['all'] > 0
depth[s] -= 1
depth['all'] -= 1
elif s in both and str_[i-1] != '\\':
depth.setdefault(s, 0)
if depth[s] > 0:
depth[s] -= 1
depth['all'] -= 1
both_done = True
if depth['all'] == 0:
for x in sep:
if str_[i:i + len(x)] == x:
t = str_[p:i].strip(strip)
if keep_empty or t != '':
tokens.append(t)
p = i + len(x)
if s in left:
r = right[left.index(s)]
depth.setdefault(r, 0)
depth[r] += 1
depth['all'] += 1
elif both_done: pass
elif s in both and str_[i-1] != '\\':
depth.setdefault(s, 0)
if depth[s] == 0:
depth[s] += 1
depth['all'] += 1
t = str_[p:].strip(strip)
if keep_empty or t != '':
tokens.append(t)
return tokens
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.