content
stringlengths 7
1.05M
|
|---|
class Carta():
CARTAS_VALORES = {
"3": 10,
"2": 9,
"1": 8,
"13": 7,
"12": 6,
"11": 5,
"7": 4,
"6": 3,
"5": 2,
"4": 1
}
NAIPES_VALORES = {
"Paus": 4,
"Copas": 3,
"Espadas": 2,
"Moles": 1
}
def __init__(self, numero, naipe):
self.numero = numero
self.naipe = naipe
def verificarCarta(self, carta_jogador_01, carta_jogador_02):
if self.CARTAS_VALORES[str(carta_jogador_01.numero)] > self.CARTAS_VALORES[str(carta_jogador_02.numero)]:
return carta_jogador_01
elif self.CARTAS_VALORES[str(carta_jogador_01.retornarNumero())] < self.CARTAS_VALORES[str(carta_jogador_02.retornarNumero())]:
return carta_jogador_02
else:
return "Empate"
def verificarManilha(self, carta_jogador_01, carta_jogador_02):
if self.NAIPES_VALORES[carta_jogador_01.naipe] > self.NAIPES_VALORES[carta_jogador_02.naipe]:
return carta_jogador_01
elif self.NAIPES_VALORES[carta_jogador_01.naipe] < self.NAIPES_VALORES[carta_jogador_02.naipe]:
return carta_jogador_02
else:
raise "Erro"
def printarCarta(self):
if self.numero == 1:
print(f"A de {self.naipe}")
elif self.numero == 13:
print(f"K de {self.naipe}")
elif self.numero == 12:
print(f"J de {self.naipe}")
elif self.numero == 11:
print(f"Q de {self.naipe}")
else:
print(f"{self.numero} de {self.naipe}")
def retornarNumero(self):
return self.numero
def retornarNaipe(self):
return self.naipe
|
def subUnsort(A):
n = len(A)
for i in range(0, n - 1):
if A[i] > A[i + 1]:
break
if i == n - 1:
return -1
start = i
for i in range(n - 1, start, -1):
if A[i] < A[start] or A[i] < A[i - 1]:
break
end = i
min = A[start]
max = A[start]
for i in range(start, end):
if A[i] < min:
min = A[i]
if A[i] > max:
max = A[i]
for i in range (0, start):
if A[i] > min:
start = i
break
for i in range (n-1, end, -1):
if A[i] < max:
end = i
break
return [start,end]
print(subUnsort([2, 6, 4, 8, 10, 9, 15]))
|
#!/usr/bin/env python3
#pylint: disable=missing-docstring
class DeviceNotFoundException(Exception):
status_code = 404
def __init__(self, message):
Exception.__init__(self)
self.message = message
def to_dict(self):
return {'message': self.message}
class UpstreamApiException(Exception):
status_code = 502
def __init__(self, message):
Exception.__init__(self)
self.message = message
def to_dict(self):
return {'message': self.message}
|
#validation DS
server_fields = {
"match_keys": "['id', 'mac_address', 'cluster_id', 'ip_address', 'tag', 'where']",
"obj_name": "server",
"primary_keys": "['id', 'mac_address']",
"id": "",
"host_name": "",
"mac_address": "",
"ip_address": "",
"parameters": """{
'interface_name': ''
}""",
"roles": [],
"cluster_id": "",
"subnet_mask": "",
"gateway": "",
"network": {},
"contrail": {},
"top_of_rack" : {},
"password": "",
"domain": "",
"email": "",
"ipmi_username": "",
"ipmi_type": "",
"ipmi_password": "",
"ipmi_address": "",
"ipmi_interface": "",
"tag": None,
"base_image_id": "",
"ssh_public_key": "",
"ssh_private_key" : "",
"package_image_id": ""
}
cluster_fields = {
"match_keys": "['id', 'where']",
"obj_name": "cluster",
"id": "",
"email": "",
"primary_keys": "['id']",
"base_image_id": "",
"package_image_id": "",
"parameters": """{
}"""
}
image_fields = {
"match_keys": "['id', 'where']",
"obj_name": "image",
"primary_keys": "['id']",
"id": "",
"category": "",
"type": "",
"version": "",
"path": "",
"parameters": """{
"kickstart": "",
"kickseed":""
}"""
}
fru_fields = {
"id": "",
"fru_description": "",
"board_serial_number": "",
"chassis_type": "",
"chassis_serial_number": "",
"board_mfg_date": "",
"board_manufacturer": "",
"board_product_name": "",
"board_part_number": "",
"product_manfacturer": "",
"product_name": "",
"product_part_number": ""
}
dhcp_host_fields = {
"match_keys": "['host_fqdn']",
"primary_keys": "['host_fqdn']",
"obj_name": "dhcp_host",
"host_fqdn": "",
"mac_address": "",
"ip_address": "",
"host_name": "",
"parameters": """{
}"""
}
dhcp_subnet_fields = {
"match_keys": "['subnet_address']",
"primary_keys": "['subnet_address']",
"obj_name": "dhcp_subnet",
"subnet_address": "",
"subnet_mask": "",
"subnet_gateway": "",
"subnet_domain": "",
"search_domains_list": [],
"dns_server_list": [],
"parameters": """{
}""",
"default_lease_time": 21600,
"max_lease_time": 43200
}
default_kernel_trusty = "3.13.0-106"
default_kernel_xenial = "4.4.0-38"
email_events = ["reimage_started", "reimage_completed", "provision_completed"]
server_blocked_fields = ["ssh_private_key"]
default_global_ansible_config = {
"ssl_certs_src_dir": "/etc/contrail_smgr/puppet/ssl",
"tor_ca_cert_file": "/etc/contrail_smgr/puppet/ssl/ca-cert.pem",
"tor_ssl_certs_src_dir": "/etc/contrail_smgr/puppet/ssl/tor",
"docker_install_method": "package",
"docker_package_name": "docker-engine",
"contrail_compute_mode": "bare_metal",
"docker_registry_insecure": True,
"docker_network_bridge": False,
"enable_lbaas": True
}
|
Node11 = {"ip":"10.1.3.11",
"user":"marian",
"password":"descartes"}
Node17 = {"ip":"10.1.3.17",
"user":"marian",
"password":"descartes"}
|
user_name,age = input("Enter the name and age to watch the movie : ").split()
age = int(age)
conduction = user_name[0].lower()
if conduction == 'a' and age >= 10 :
print(f"Hello {user_name}!! \n You can watch the coco movie ")
else :
if age < 10:
print("Your age is smaller then limit to watch the movie ")
else:
print("You can't procedue, Sorry!!")
|
class TimeoutError(Exception):
"""
Indicates a database operation timed out in some way.
"""
pass
|
def test_can_withdraw_as_alice(nft_funded, alice, bob, accounts, beneficiary):
nft_funded.withdraw({"from": alice})
init_balance = beneficiary.balance()
accounts[1].transfer(nft_funded, 10 ** 18)
nft_funded.mint({"from": bob})
nft_funded.withdraw({"from": alice})
final_balance = beneficiary.balance()
assert final_balance - init_balance == 10 ** 18
def test_can_withdraw_as_bob(nft_funded, alice, bob, accounts, beneficiary):
nft_funded.withdraw({"from": alice})
init_balance = beneficiary.balance()
accounts[1].transfer(nft_funded, 10 ** 18)
nft_funded.mint({"from": bob})
nft_funded.withdraw({"from": bob})
final_balance = beneficiary.balance()
assert final_balance - init_balance == 10 ** 18
def test_bob_gets_nothing_on_withdraw(nft_funded, bob):
bob_balance = bob.balance()
nft_funded.withdraw({"from": bob})
assert bob.balance() <= bob_balance
def test_withdrawal_increases_balance(nft_funded, alice, accounts, beneficiary):
init_balance = beneficiary.balance()
accounts[3].transfer(nft_funded, 10 ** 18)
nft_funded.withdraw({"from": alice})
final_balance = beneficiary.balance()
assert final_balance > init_balance
def test_can_receive_funds_through_fallback(nft, alice, bob, accounts, beneficiary):
init_balance = beneficiary.balance()
bob_balance = bob.balance()
accounts[3].transfer(nft, 10 ** 18)
bob.transfer(nft, bob_balance)
nft.withdraw({"from": alice})
final_balance = beneficiary.balance()
assert final_balance - init_balance >= bob_balance
|
# based on Rob Pike's talk “Lexical scanning in Go”
# http://youtu.be/HxaD_trXwRE
# http://golang.org/src/pkg/text/template/parse/lex.go
LEFT_DELIM = '{{'
RIGHT_DELIM = '}}'
PIPE = '|'
LEFT_LINK_DELIM = '[['
RIGHT_LINK_DELIM = ']]'
LEFT_COMMENT_DELIM = '<!--'
RIGHT_COMMENT_DELIM = '-->'
class Lexer:
def __init__(self):
self.input = ''
self.start = 0
self.pos = 0
self.tmpl_depth = 0 # depth of template delimiters
self.items = []
def emit(self, type):
val = self.input[self.start:self.pos]
self.items.append((type, val))
self.start = self.pos
def eof(self):
return self.pos >= len(self.input)
# get the next character
def next(self):
if self.eof():
return None
n = self.input[self.pos]
self.pos += 1
return n
# check whether <value> is ahead
def ahead(self, value):
if self.eof():
return False
return self.input.startswith(value, self.pos)
def lex_text(l):
while True:
for check in (LEFT_DELIM, LEFT_COMMENT_DELIM):
if l.ahead(check):
if l.pos > l.start:
l.emit('text')
if check == LEFT_DELIM: return lex_left_tmpl
if check == LEFT_COMMENT_DELIM: return lex_comment
if l.next() is None: break
# reached EOF
if(l.pos > l.start): l.emit('text')
return None
def lex_left_tmpl(l):
l.pos += len(LEFT_DELIM)
l.tmpl_depth += 1
l.emit('left_tmpl')
return lex_inside_tmpl
def lex_inside_tmpl(l):
while True:
if l.ahead(LEFT_LINK_DELIM):
return lex_link
for check in (LEFT_DELIM, RIGHT_DELIM, PIPE):
if l.ahead(check):
if l.pos > l.start:
l.emit('param')
if check == LEFT_DELIM: return lex_left_tmpl
if check == RIGHT_DELIM: return lex_right_tmpl
if check == PIPE: return lex_param_delim
if l.next() is None: break
# reached EOF (input is invalid)
if(l.pos > l.start): l.emit('text')
return None
def lex_param_delim(l):
l.pos += len(PIPE)
l.emit('param_delim')
return lex_inside_tmpl
def lex_right_tmpl(l):
l.pos += len(RIGHT_DELIM)
l.tmpl_depth -= 1
l.emit('right_tmpl')
if l.tmpl_depth == 0: return lex_text
return lex_inside_tmpl
def lex_link(l):
l.pos += len(LEFT_LINK_DELIM)
while True:
if l.ahead(RIGHT_LINK_DELIM):
l.pos += len(RIGHT_LINK_DELIM)
return lex_inside_tmpl # don't emit link, treat it as part of the param
if l.next() is None: break
# reached EOF (invalid input)
if l.pos > l.start: l.emit('text')
return None
def lex_comment(l):
l.pos += len(LEFT_COMMENT_DELIM)
l.emit('left_comment')
while True:
if l.ahead(RIGHT_COMMENT_DELIM):
l.emit('comment')
l.pos += len(RIGHT_COMMENT_DELIM)
l.emit('right_comment')
return lex_text
if l.next() is None: break
#reached EOF (invalid input)
if l.pos > l.start: l.emit('text')
return None
def lex(input):
lexer = Lexer()
lexer.input = input
state = lex_text
while state:
state = state(lexer)
return lexer.items
|
class Solution:
def solve(self, nums):
numsDict = {}
for i in nums:
if i in numsDict:
numsDict[i] += 1
else:
numsDict[i] = 1
for num in numsDict:
if num == numsDict[num]:
return True
return False
|
# noinspection SqlNoDataSourceInspection,SqlDialectInspection
class Postgres:
"""
Provides functions to query PostgreSQL
:param str table: Param to select the right table
:param str column: Param to search duplicate or unique on
"""
def __init__(self, table: str, column: str) -> None:
self.table = table
self.column = column
if not all(isinstance(x, str) for x in [self.table, self.column]):
raise TypeError(f"The 'table' and/or 'column' must be a string!")
def select_pk_name_query(self) -> str:
"""
:return: Postgres query to select the primary key
"""
return f"SELECT a.attname " \
f"FROM pg_index AS i " \
f"JOIN pg_attribute AS a " \
f"ON a.attrelid = i.indrelid " \
f"AND a.attnum = ANY(i.indkey) " \
f"WHERE i.indrelid = '{self.table}'::regclass " \
f"AND i.indisprimary;"
def select_duplicate_query(self) -> str:
"""
:return: Postgres query to select the duplicate entries
"""
return f"SELECT t.* " \
f"FROM {self.table} AS t " \
f"INNER JOIN (" \
f"SELECT {self.column} " \
f"FROM {self.table} " \
f"GROUP BY {self.column} " \
f"HAVING ( COUNT(*) > 1 )" \
f") dt ON t.{self.column}=dt.{self.column}"
def select_duplicate_pk_query(self, pk: str) -> str:
"""
:param pk: Primary key of the table
:return: Postgres query to select the pk of the duplicate entries
"""
return f"SELECT t.{pk} " \
f"FROM {self.table} AS t " \
f"INNER JOIN (" \
f"SELECT {self.column} " \
f"FROM {self.table} " \
f"GROUP BY {self.column} " \
f"HAVING ( COUNT(*) > 1 )" \
f") dt ON t.{self.column}=dt.{self.column}"
def select_unique_query(self) -> str:
"""
:return: Postgres query to select the unique entries
"""
return f"SELECT t.* " \
f"FROM {self.table} AS t " \
f"INNER JOIN (" \
f"SELECT {self.column} " \
f"FROM {self.table} " \
f"GROUP BY {self.column} " \
f"HAVING ( COUNT(*) = 1 )" \
f") dt ON t.{self.column}=dt.{self.column}"
def select_unique_pk_query(self, pk: str) -> str:
"""
:param pk: Primary key of the table
:return: Postgres query to select the pk of the unique entries
"""
return f"SELECT t.{pk} " \
f"FROM {self.table} AS t " \
f"INNER JOIN (" \
f"SELECT {self.column} " \
f"FROM {self.table} " \
f"GROUP BY {self.column} " \
f"HAVING ( COUNT(*) = 1 )" \
f") dt ON t.{self.column}=dt.{self.column}"
# noinspection SqlNoDataSourceInspection,SqlDialectInspection
class MySQL:
"""
Provides functions to query MySQL
:param str table: Param to select the right table
:param str column: Param to search duplicate or unique on
"""
def __init__(self, table: str, column: str) -> None:
self.table = table
self.column = column
if not all(isinstance(x, str) for x in [self.table, self.column]):
raise TypeError(f"The 'table' and/or 'column' must be a string!")
def select_pk_name_query(self) -> str:
"""
:return: MySQL query to select the primary key
"""
return f"SELECT k.COLUMN_NAME " \
f"FROM information_schema.table_constraints t " \
f"LEFT JOIN information_schema.key_column_usage k " \
f"USING(constraint_name,table_schema,table_name) " \
f"WHERE t.constraint_type='PRIMARY KEY' " \
f"AND t.table_schema=DATABASE() " \
f"AND t.table_name='{self.table}'"
def select_duplicate_query(self) -> str:
"""
:return: MySQL query to select the duplicate entries
"""
return f"SELECT t.* " \
f"FROM {self.table} AS t " \
f"INNER JOIN (" \
f"SELECT {self.column} " \
f"FROM {self.table} " \
f"GROUP BY {self.column} " \
f"HAVING ( COUNT(*) > 1 )" \
f") dt ON t.{self.column}=dt.{self.column}"
def select_duplicate_pk_query(self, pk: str) -> str:
"""
:param pk: Primary key of the table
:return: MySQL query to select the pk of the duplicate entries
"""
return f"SELECT t.{pk} " \
f"FROM {self.table} AS t " \
f"INNER JOIN (" \
f"SELECT {self.column} " \
f"FROM {self.table} " \
f"GROUP BY {self.column} " \
f"HAVING ( COUNT(*) > 1 )" \
f") dt ON t.{self.column}=dt.{self.column}"
def select_unique_query(self) -> str:
"""
:return: MySQL query to select the unique entries
"""
return f"SELECT t.* " \
f"FROM {self.table} AS t " \
f"INNER JOIN (" \
f"SELECT {self.column} " \
f"FROM {self.table} " \
f"GROUP BY {self.column} " \
f"HAVING ( COUNT(*) = 1 )" \
f") dt ON t.{self.column}=dt.{self.column}"
def select_unique_pk_query(self, pk: str) -> str:
"""
:param pk: Primary key of the table
:return: MySQL query to select the pk of the unique entries
"""
return f"SELECT t.{pk} " \
f"FROM {self.table} AS t " \
f"INNER JOIN (" \
f"SELECT {self.column} " \
f"FROM {self.table} " \
f"GROUP BY {self.column} " \
f"HAVING ( COUNT(*) = 1 )" \
f") dt ON t.{self.column}=dt.{self.column}"
|
# Author: veelion
db_host = 'localhost'
db_db = 'crawler'
db_user = 'your-user'
db_password = 'your-password'
|
BCT_ADDRESS = '0x2f800db0fdb5223b3c3f354886d907a671414a7f'
NCT_ADDRESS = '0xd838290e877e0188a4a44700463419ed96c16107'
UBO_ADDRESS = '0x2b3ecb0991af0498ece9135bcd04013d7993110c'
NBO_ADDRESS = '0x6bca3b77c1909ce1a4ba1a20d1103bde8d222e48'
GRAY = '#232B2B'
DARK_GRAY = '#343a40'
FIGURE_BG_COLOR = '#202020'
MCO2_ADDRESS = '0xfC98e825A2264D890F9a1e68ed50E1526abCcacD'
MCO2_ADDRESS_MATIC = '0xaa7dbd1598251f856c12f63557a4c4397c253cea'
VERRA_FALLBACK_NOTE = "Note: Off-Chain Verra Registry data is not updated, we are temporarily using fallback data"
KLIMA_RETIRED_NOTE = "Note: This only includes Retired Tonnes coming through the KlimaDAO retirement aggregator tool"
VERRA_FALLBACK_URL = 'https://prod-klimadao-data.nyc3.digitaloceanspaces.com/verra_registry_fallback_data.csv'
rename_map = {
'carbonOffsets_bridges_value': 'Quantity',
'carbonOffsets_bridges_timestamp': 'Date',
'carbonOffsets_bridge': 'Bridge',
'carbonOffsets_region': 'Region',
'carbonOffsets_vintage': 'Vintage',
'carbonOffsets_projectID': 'Project ID',
'carbonOffsets_standard': 'Standard',
'carbonOffsets_methodology': 'Methodology',
'carbonOffsets_country': 'Country',
'carbonOffsets_category': 'Project Type',
'carbonOffsets_name': 'Name',
'carbonOffsets_tokenAddress': 'Token Address',
'carbonOffsets_balanceBCT': 'BCT Quantity',
'carbonOffsets_balanceNCT': 'NCT Quantity',
'carbonOffsets_balanceUBO': 'UBO Quantity',
'carbonOffsets_balanceNBO': 'NBO Quantity',
'carbonOffsets_totalBridged': 'Total Quantity',
}
mco2_bridged_rename_map = {
'batches_id': 'ID',
'batches_serialNumber': 'Serial Number',
'batches_timestamp': 'Date',
'batches_tokenAddress': 'Token Address',
'batches_vintage': 'Vintage',
'batches_projectID': 'Project ID',
'batches_value': 'Quantity',
'batches_originaltx': 'Original Tx Address',
}
retires_rename_map = {
'retires_value': 'Quantity',
'retires_timestamp': 'Date',
'retires_offset_bridge': 'Bridge',
'retires_offset_region': 'Region',
'retires_offset_vintage': 'Vintage',
'retires_offset_projectID': 'Project ID',
'retires_offset_standard': 'Standard',
'retires_offset_methodology': 'Methodology',
'retires_offset_country': 'Country',
'retires_offset_category': 'Project Type',
'retires_offset_name': 'Name',
'retires_offset_tokenAddress': 'Token Address',
'retires_offset_totalRetired': 'Total Quantity',
}
bridges_rename_map = {
'bridges_value': 'Quantity',
'bridges_timestamp': 'Date',
'bridges_transaction_id': 'Tx Address',
}
redeems_rename_map = {
'redeems_value': 'Quantity',
'redeems_timestamp': 'Date',
'redeems_pool': 'Pool',
'redeems_offset_region': 'Region',
}
deposits_rename_map = {
'deposits_value': 'Quantity',
'deposits_timestamp': 'Date',
'deposits_pool': 'Pool',
'deposits_offset_region': 'Region',
}
pool_retires_rename_map = {
'klimaRetires_amount': 'Quantity',
'klimaRetires_timestamp': 'Date',
'klimaRetires_pool': 'Pool',
}
verra_rename_map = {
'issuanceDate': 'Issuance Date',
'programObjectives': 'Sustainable Development Goals',
'instrumentType': 'Credit Type',
'vintageStart': 'Vintage Start',
'vintageEnd': 'Vintage End',
'reportingPeriodStart': 'Reporting Period Start',
'reportingPeriodEnd': 'Reporting Period End',
'resourceIdentifier': 'ID',
'resourceName': 'Name',
'region': 'Region',
'country': 'Country',
'protocolCategory': 'Project Type',
'protocol': 'Methodology',
'totalVintageQuantity': 'Total Vintage Quantity',
'quantity': 'Quantity Issued',
'serialNumbers': 'Serial Number',
'additionalCertifications': 'Additional Certifications',
'retiredCancelled': 'Is Cancelled',
'retireOrCancelDate': 'Retirement/Cancellation Date',
'retirementBeneficiary': 'Retirement Beneficiary',
'retirementReason': 'Retirement Reason',
'retirementDetails': 'Retirement Details',
'inputTypes': 'Input Type',
'holdingIdentifier': 'Holding ID'
}
merge_columns = ["ID", "Name", "Region", "Country",
"Project Type", "Methodology", "Toucan"]
verra_columns = ['Issuance Date', 'Sustainable Development Goals',
'Credit Type', 'Vintage Start', 'Vintage End', 'Reporting Period Start', 'Reporting Period End', 'ID',
'Name', 'Region', 'Country', 'Project Type', 'Methodology', 'Total Vintage Quantity',
'Quantity Issued', 'Serial Number', 'Additional Certifications',
'Is Cancelled', 'Retirement/Cancellation Date', 'Retirement Beneficiary', 'Retirement Reason',
'Retirement Details', 'Input Type', 'Holding ID']
mco2_verra_rename_map = {
'Project Name': 'Name',
'Quantity of Credits': 'Quantity',
}
|
#!/usr/bin/env python
# encoding: utf-8
"""
permutation_ii.py
Created by Shengwei on 2014-07-15.
"""
# https://oj.leetcode.com/problems/permutations-ii/
# tags: medium / hard, numbers, permutation, dp, recursion
"""
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
[1,1,2] have the following unique permutations:
[1,1,2], [1,2,1], and [2,1,1].
"""
class Solution:
# @param nums, a list of integer
# @return a list of lists of integers
def permuteUnique(self, nums):
if len(nums) <= 1:
return [nums]
all_perm = []
processed = set()
for i in xrange(len(nums)):
single = nums[i]
if single in processed:
continue
processed.add(single)
rest = nums[:i] + nums[i+1:]
for each in self.permuteUnique(rest):
all_perm.append(each + [single])
return all_perm
|
class BaseValidator:
"""
Base class for validator
"""
def is_applicable(self, schema):
raise NotImplementedError()
def validate_type(self, upstream, downstream):
raise NotImplementedError()
|
CrfSegMoodPath = 'E:\python_code\Djangotest2\cmdb\model\msr.crfsuite'
HmmDIC = 'E:\python_code\Djangotest2\cmdb\model\HMMDic.pkl'
HmmDISTRIBUTION = 'E:\python_code\Djangotest2\cmdb\model\HMMDistribution.pkl'
CrfNERMoodPath = 'E:\python_code\Djangotest2\cmdb\model\PKU.crfsuite'
BiLSTMCXPath = 'E:\python_code\Djangotest2\cmdb\model\BiLSTMCX'
BiLSTMNERPath = 'E:\python_code\Djangotest2\cmdb\model\BiLSTMNER'
|
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class RoleCreateIpConfigParametersEnum(object):
"""Implementation of the 'Role_CreateIpConfigParameters' enum.
Specifies the interface role.
'kPrimary' indicates a primary role.
'kSecondary' indicates a secondary role.
Attributes:
KPRIMARY: TODO: type description here.
KSECONDARY: TODO: type description here.
"""
KPRIMARY = 'kPrimary'
KSECONDARY = 'kSecondary'
|
n1 = float(input("Digite sua primeira nota: "))
n2 = float(input("Digite sua segunda nota: "))
n3 = float(input("Digite sua terceira nota: "))
n4 = float(input("Digite sua quarta nota: "))
media = (n1 + n2 + n3 + n4) / 4
print("Sua média é de: ",media)
|
#
# @lc app=leetcode.cn id=50 lang=python3
#
# [50] Pow(x, n)
#
n = 5
x = 6
x & 1
# @lc code=start
class Solution:
def myPow(self, x: float, n: int) -> float:
ans = 0
pow_n = x
if n > 0:
while x > 0:
if x & 1 == 1:
ans += pow_n
x = x >> 1
pow_n *= pow_n
# @lc code=end
|
class UnknownList(Exception):
pass
class InsufficientPermissions(Exception):
pass
class AlreadySubscribed(Exception):
pass
class NotSubscribed(Exception):
pass
class ClosedSubscription(Exception):
pass
class ClosedUnsubscription(Exception):
pass
class UnknownFlag(Exception):
pass
class UnknownOption(Exception):
pass
class ModeratedMessageNotFound(Exception):
pass
|
# -*- coding: utf-8 -*-
"""Release data for the IPython project."""
#-----------------------------------------------------------------------------
# Copyright (c) 2008, IPython Development Team.
# Copyright (c) 2001, Fernando Perez <fernando.perez@colorado.edu>
# Copyright (c) 2001, Janko Hauser <jhauser@zscout.de>
# Copyright (c) 2001, Nathaniel Gray <n8gray@caltech.edu>
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
# IPython version information. An empty _version_extra corresponds to a full
# release. 'dev' as a _version_extra string means this is a development
# version
_version_major = 8
_version_minor = 0
_version_patch = 1
_version_extra = ".dev"
# _version_extra = "rc1"
_version_extra = "" # Uncomment this for full releases
# Construct full version string from these.
_ver = [_version_major, _version_minor, _version_patch]
__version__ = '.'.join(map(str, _ver))
if _version_extra:
__version__ = __version__ + _version_extra
version = __version__ # backwards compatibility name
version_info = (_version_major, _version_minor, _version_patch, _version_extra)
# Change this when incrementing the kernel protocol version
kernel_protocol_version_info = (5, 0)
kernel_protocol_version = "%i.%i" % kernel_protocol_version_info
license = 'BSD'
authors = {'Fernando' : ('Fernando Perez','fperez.net@gmail.com'),
'Janko' : ('Janko Hauser','jhauser@zscout.de'),
'Nathan' : ('Nathaniel Gray','n8gray@caltech.edu'),
'Ville' : ('Ville Vainio','vivainio@gmail.com'),
'Brian' : ('Brian E Granger', 'ellisonbg@gmail.com'),
'Min' : ('Min Ragan-Kelley', 'benjaminrk@gmail.com'),
'Thomas' : ('Thomas A. Kluyver', 'takowl@gmail.com'),
'Jorgen' : ('Jorgen Stenarson', 'jorgen.stenarson@bostream.nu'),
'Matthias' : ('Matthias Bussonnier', 'bussonniermatthias@gmail.com'),
}
author = 'The IPython Development Team'
author_email = 'ipython-dev@python.org'
|
heroes_number = int(input())
heroes_list = dict()
for heroes in range(heroes_number):
hero = input().split(' ')
hero_name = hero[0]
hero_hit_points = int(hero[1])
hero_mana_points = int(hero[2])
heroes_list[hero_name] = {'HP': hero_hit_points, 'MP': hero_mana_points}
command = input()
while command != 'End':
current_command = command.split(' - ')
action = current_command[0]
name_of_hero = current_command[1]
if action == 'CastSpell':
mp_needed = int(current_command[2])
spell_name = current_command[3]
if heroes_list[name_of_hero]['MP'] >= mp_needed:
heroes_list[name_of_hero]['MP'] -= mp_needed
print(f"{name_of_hero} has successfully cast {spell_name} and now has {heroes_list[name_of_hero]['MP']} MP!")
else:
print(f"{name_of_hero} does not have enough MP to cast {spell_name}!")
elif action == 'TakeDamage':
damage = int(current_command[2])
attacker = current_command[3]
heroes_list[name_of_hero]['HP'] -= damage
if heroes_list[name_of_hero]['HP'] > 0:
print(f"{name_of_hero} was hit for {damage} HP by {attacker} and now has {heroes_list[name_of_hero]['HP']} HP left!")
else:
del heroes_list[name_of_hero]
print(f"{name_of_hero} has been killed by {attacker}!")
elif action == 'Recharge':
amount = int(current_command[2])
heroes_list[name_of_hero]['MP'] += amount
if heroes_list[name_of_hero]['MP'] >= 200:
print(f"{name_of_hero} recharged for {abs(heroes_list[name_of_hero]['MP'] - 200 - amount)} MP!")
heroes_list[name_of_hero]['MP'] = 200
else:
print(f"{name_of_hero} recharged for {amount} MP!")
elif action == 'Heal':
heal_amount = int(current_command[2])
heroes_list[name_of_hero]['HP'] += heal_amount
if heroes_list[name_of_hero]['HP'] >= 100:
print(f"{name_of_hero} healed for {abs(heroes_list[name_of_hero]['HP'] - 100 - heal_amount)} HP!")
heroes_list[name_of_hero]['HP'] = 100
else:
print(f"{name_of_hero} healed for {heal_amount} HP!")
command = input()
for hero in heroes_list:
print(f"{hero}")
print(f" HP: {heroes_list[hero]['HP']}")
print(f" MP: {heroes_list[hero]['MP']}")
|
#!/usr/bin/python
# ==============================================================================
# Author: Tao Li (taoli@ucsd.edu)
# Date: May 1, 2015
# Question: 083-Remove-Duplicates-from-Sorted-List
# Link: https://leetcode.com/problems/remove-duplicates-from-sorted-list/
# ==============================================================================
# Given a sorted linked list, delete all duplicates such that each element
# appear only once.
#
# For example,
# Given 1->1->2, return 1->2.
# Given 1->1->2->3->3, return 1->2->3.
# ==============================================================================
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param {ListNode} head
# @return {ListNode}
def deleteDuplicates(self, head):
ptr = head
while ptr:
ptr.next = self.findNext(ptr)
ptr = ptr.next
return head
def findNext(self, head):
if not head or not head.next:
return None
elif head.val != head.next.val:
return head.next
else:
return self.findNext(head.next)
|
class INPUT:
def __init__(self):
self.l=open(0).read().split()[::-1]
self.length=len(self.l)
return
def stream(self,k=1,f=int,f2=False):
assert(-1<k)
m=self.length
if m==0 or m<k:
raise Exception("There is no input!")
elif f!=str:
if k==0:
self.length=0
return list(map(f,self.l[::-1]))
if k==1 and not f2:
self.length-=1
return f(self.l.pop())
if k==1 and f2:
self.length-=1
return [f(self.l.pop())]
ret=[]
for _ in [0]*k:
ret.append(f(self.l.pop()))
self.length-=k
return ret
else:
if k==0:
self.length=0
return self.l[::-1]
if k==1 and not f2:
self.length-=1
return self.l.pop()
if k==1 and f2:
self.length-=1
return [self.l.pop()]
ret=[]
for _ in [0]*k:
ret.append(self.l.pop())
self.length-=k
return ret
pin=INPUT().stream
"""
pin(number[default:1],f[default:int],f2[default:False])
if number==0 -> return left all
listを変数で受け取るとき、必ずlistをTrueにすること。
"""
def main():
N=pin(1)
A,B,C=sorted(pin(0))
ans=9999
for i in range(9999):
n=N-C*i
if n<0:
break
for j in range(9999-i):
m=n-B*j
if m>=0 and m%A==0:
ans=min(ans,i+j+m//A)
elif m<0:
break
print(ans)
return
main()
|
"""
Exercício Python 7:
Desenvolva um programa que leia as duas
notas de um aluno, calcule e mostre a sua média.
"""
n1 = float(input('Digite nota AV: '))
n2 = float(input('Digite Nota AVS: '))
n3 = float(input('Digite nota VR: '))
#media = (n1+n2+n3)/3
print('A media do aluno é {:.1f}'.format((n1+n2+n3)/3))
|
#Check if NOT
txt = "Hello buddie unu!"
print("owo" not in txt)
txt = "The best things in life are free!"
if "expensive" not in txt:
print("Yes, 'expensive' is NOT present.")
'''
Terminal:
True
Yes, 'expensive' is NOT present.
'''
#https://www.w3schools.com/python/python_strings.asp
|
# SPDX-License-Identifier: BSD-3-Clause
# Copyright Contributors to the OpenColorIO Project.
class FileTransform:
"""
FileTransform
"""
def __init__(self):
pass
def getSrc(self):
pass
def setSrc(self, src):
pass
def getCCCId(self):
pass
def setCCCId(self, cccid):
pass
def getInterpolation(self):
pass
def setInterpolation(self, interp):
pass
def getNumFormats(self):
pass
def getFormatNameByIndex(self, index):
pass
def getFormatExtensionByIndex(self, index):
pass
|
class InternalError(Exception):
pass
class InvalidAccessError(Exception):
pass
class InvalidStateError(Exception):
pass
|
{
'targets': [
{
'target_name': 'profiler',
'sources': [
'cpu_profiler.cc',
'graph_edge.cc',
'graph_node.cc',
'heap_profiler.cc',
'profile.cc',
'profile_node.cc',
'profiler.cc',
'snapshot.cc',
],
}
]
}
|
def Insertionsort(A):
for i in range(1, len(A)):
tmp = A[i]
k = i
while k > 0 and tmp < A[k - 1]:
A[k] = A[k - 1]
k -= 1
A[k] = tmp
A = [54, 26, 93, 17, 77, 31, 44, 55, 20]
Insertionsort(A)
print(A)
|
class policy_name_protection():
def __init__(self,name_protection):
self.np=name_protection
def __call__(self,target):
try:
if target.policy.has_key('name_protection')==True:
if target.policy.get('name_protection')==False and self.np==True:
target.policy['name_protection']=self.np
else:
target.policy['name_protection']=self.np
except AttributeError:
target.policy={'name_protection':self.np}
return target
class policy_replay_protection():
def __init__(self,replay_time,replay_protection=True):
self.rp=replay_protection
if type(replay_time) is int:
if replay_time>0:
self.rt=replay_time
else:
self.rt=0
elif replay_time.isdigit() == True:
self.rt=int(replay_time)
else:
self.rt=0
self.rp=False
def __call__(self,target):
try:
if target.policy.has_key('replay_protection')==True:
target.policy['replay_protection']['enable']=self.rp
target.policy['replay_protection']['interval']=self.rt
else:
target.policy['replay_protection']={'enable':self.rp,'interval':self.rt}
except AttributeError:
target.policy={'replay_protection':{'enable':self.rp,'interval':self.rt}}
return target
class policy():
def __init__(self,**kwargs):
self.__dict__.update(kwargs)
def __call__(self,target):
tmp_pol = {}
for x in self.__dict__.keys():
if len(self.__dict__[x])==1 and isinstance(self.__dict__[x][0],str)==True:
if self.__dict__[x][0].lower()=='control' or self.__dict__[x][0].lower()=='c':
tmp_pol[x]={'action':'control',}
elif self.__dict__[x][1].lower()=='control' or self.__dict__[x][1].lower()=='c':
tmp_pol[x]={'action':'control',}
elif len(self.__dict__[x])==2 and isinstance(self.__dict__[x][0],str)==True or isinstance(self.__dict__[x][1],str)==True:
if self.__dict__[x][0].lower()=='validate' or self.__dict__[x][0].lower()=='v':
tmp_pol[x]={'action':'validate','value':self.__dict__[x][1]}
elif self.__dict__[x][1].lower()=='validate' or self.__dict__[x][1].lower()=='v':
tmp_pol[x]={'action':'validate','value':self.__dict__[x][0]}
try:
if target.policy.has_key('parameter_protection')==True:
target.policy['parameter_protection'].update(tmp_pol)
else:
target.policy['parameter_protection']=tmp_pol
except AttributeError:
target.policy={'parameter_protection':tmp_pol}
return target
|
'''
Leetcode problem No 300 Longest Increasing Subsequence
Solution written by Xuqiang Fang on 20 June, 2018
'''
class Solution(object):
########
'''
This is a classic problem and the following is a classic solution in O(nlogn)
tails is an array storing the smallest tail of all increasing subsequences with length i+1 in tails[i].
For example, say we have nums = [4,5,6,3], then all the available increasing subsequences are:
len = 1 : [4], [5], [6], [3] => tails[0] = 3
len = 2 : [4, 5], [5, 6] => tails[1] = 5
len = 3 : [4, 5, 6] => tails[2] = 6
We can easily prove that tails is a increasing array.
Therefore it is possible to do a binary search in tails array to find the one needs update.
Each time we only do one of the two:
(1) if x is larger than all tails, append it, increase the size by 1
When we traverse the nums array from left to right, the current biggest would always be at the end
(2) if tails[i-1] < x <= tails[i], update tails[i]
When situation 2 happens, we can replace tails[i] but still the final length won't change
Doing so will maintain the tails invariant. The the final answer is just the size.
'''
#######
def lengthOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
tails = [0] * len(nums)
ans = 0
for x in nums:
i, j = 0, ans
while i < j:
m = (i+j) >> 1
if x > tails[m]:
i = m + 1
else:
j = m
tails[i] = x
if i == ans:
ans += 1
return ans
def main():
s = Solution()
nums = [10,9,2,5,3,7,101,18]
print(s.lengthOfLIS(nums))
main()
|
#!/usr/bin/env python3
# Problem Set 4A
# Name: John L. Jones
# Collaborators:
# Time Spent: x:xx
def get_permutations(sequence):
'''
Enumerate all permutations of a given string
sequence (string): an arbitrary string to permute. Assume that it is a
non-empty string.
You MUST use recursion for this part. Non-recursive solutions will not be
accepted.
Returns: a list of all permutations of sequence
Example:
>>> get_permutations('abc')
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
Note: depending on your implementation, you may return the permutations in
a different order than what is listed here.
'''
permutations = []
if len(sequence) <= 1:
permutations.append(sequence)
else:
sub_perms = get_permutations(sequence[1:])
for s in sub_perms:
for i in range(len(s)+1):
permutations.append(s[:i] + sequence[0] + s[i:])
return permutations
if __name__ == '__main__':
# # Put three example test cases here (for your sanity, limit your inputs
# to be three characters or fewer as you will have n! permutations for a
# sequence of length n)
example_input = 'a'
print('Input:', example_input)
print('Expected Output:', ['a'])
print('Actual Output: ', get_permutations(example_input))
example_input = 'ab'
print('')
print('Input:', example_input)
expected_output = ['ab', 'ba']
expected_output.sort()
actual_output = get_permutations(example_input)
actual_output.sort()
print('Expected Output:', expected_output)
print('Actual Output: ', actual_output)
example_input = 'abc'
print('')
print('Input:', example_input)
expected_output = ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
expected_output.sort()
actual_output = get_permutations(example_input)
actual_output.sort()
print('Expected Output:', expected_output)
print('Actual Output: ', actual_output)
example_input = 'cat'
print('')
print('Input:', example_input)
expected_output = ['cat', 'act', 'atc', 'tca', 'cta', 'tac']
expected_output.sort()
actual_output = get_permutations(example_input)
actual_output.sort()
print('Expected Output:', expected_output)
print('Actual Output: ', actual_output)
example_input = 'zyx'
print('')
print('Input:', example_input)
expected_output = ['zyx', 'zxy', 'yzx', 'yxz', 'xyz', 'xzy']
expected_output.sort()
actual_output = get_permutations(example_input)
actual_output.sort()
print('Expected Output:', expected_output)
print('Actual Output: ', actual_output)
|
def function(param, param1):
pass
def result():
pass
function(result<arg1>(), result())
|
'''
- Leetcode problem: 5
- Difficulty: Medium
- Brief problem description:
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example:
Input: "cbbd"
Output: "bb"
- Solution Summary:
1. There are 2N-1 centres, expend each centre to check the longest palindromic substring.
- Used Resources:
--- Bo Zhou
'''
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
longestStr = ""
for i in range(len(s)):
palStr = self.expendStr(s, i, 1)
if len(palStr) > len(longestStr):
longestStr = palStr
if i < len(s) - 1:
palStr = self.expendStr(s, i, 2)
if len(palStr) > len(longestStr):
longestStr = palStr
return longestStr
def expendStr(self, s, i, num):
result = ""
if num == 1:
left = i - 1
right = i + 1
result = s[i]
if num == 2:
left = i
right = i + 1
while left >= 0 and right <= len(s) - 1:
if s[left] == s[right]:
result = s[left] + result + s[right]
else:
break
left -= 1
right += 1
return result
if __name__ == "__main__":
test = Solution()
testStr1 = "cbbd"
testStr2 = "babad"
print(test.longestPalindrome(testStr1))
print(test.longestPalindrome(testStr2))
|
# Rescebe os valores de entrada.
P1 = float(input())
P2 = float(input())
Ml = float(input())
# Calculo da media parcial.
Mp = (2 * P1 + 3 * P2) / 5.0
# Regras para aprovação.
if Ml < 5.0 or Mp < 5.0:
M = min(Mp, 4.9)
else:
M = (3 * Mp + 2 * Ml) / 5.0
if 5.0 > M >= 2.5:
E = float(input())
F = (M + E) / 2.0
else:
F = M
# Imprime os resultados.
print("%.1f" % Mp)
print("%.1f" % M)
print("%.1f" % F)
|
# https://open.kattis.com/problems/stockbroker
# init values
cash = 100
shares = 0
prices = []
#first input: num days (1-365)
num_days = int(input())
#next inputs: values on each day (1-500)
for _ in range(num_days):
prices.append(int(input()))
for i in range(len(prices)-1):
if prices[i] < prices[i+1]:
#buy
if (shares + (cash // prices[i])) > 100000:
cash = cash - ((100000 - shares)*prices[i])
shares = 100000
else:
shares += cash // prices[i]
cash = cash % prices[i]
elif prices[i] > prices[i+1]:
#sell
cash += shares * prices[i]
shares = 0
if shares > 0:
cash += shares * prices[-1]
print(cash)
|
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
res = len(nums)
for i in xrange(len(nums)):
res ^= nums[i]
res ^= i
return res
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Les fonctions et les exceptions
Quelques exemples de fonctions
"""
def ask_ok(prompt, retries=3, reminder='Essayes encore!'):
while True:
ok = input(prompt).upper()
if ok in ('Y', 'YES', 'O', 'OUI'):
return True
if ok in ('N', 'NO', 'NON'):
return False
retries -= 1
if retries < 1:
raise ValueError('Invalid Answer')
print(reminder)
try:
if ask_ok('Aimes tu les patates ? => '):
print('Tu as bien raison ;)')
else:
print('C\'est dommage ;(')
except ValueError:
print('Et alors t\'as pas compris la question ?')
|
"""coding: utf-8"""
#切片
class Solution:
def isPalindrome(self, x: int) -> bool:
x = str(x)
if x == x[::-1]:
return True
else:
return False
if __name__=='__main__':
a=Solution()
print(a.isPalindrome(12421))
|
class RequestInfo:
def __init__(self,
human_string, # human-readable string (will be printed for Human object)
action_requested, # action requested ('card' + index of card / 'opponent' / 'guess')
current_hand = [], # player's current hand
discard_pile = [], # discard pile
move_history = [], # list of player moves
players_active_status = [], # players' active status (active / lost)
players_protection_status = [], # players' protection status (protected / not protected)
invalid_moves = [], # invalid moves (optional) - an assist from Game
valid_moves = [], # valid moves (optional) - an assist from Game
players_active = [], # list of currently active players
players_protected = []): # Protection status of all players (including inactive ones)
self.human_string = human_string
self.action_requested = action_requested
self.current_hand = current_hand
self.discard_pile = discard_pile
self.move_history = move_history
self.players_active_status = players_active_status
self.players_protection_status = players_protection_status
self.invalid_moves = invalid_moves
self.valid_moves = valid_moves
self.players_active = players_active
self.players_protected = players_protected
def get_request_info(self):
return ({'human_string' : self.human_string,
'action_requested' : self.action_requested,
'current_hand' : self.current_hand,
'discard_pile' : self.discard_pile,
'move_history' : self.move_history,
'players_active_status' : self.players_active_status,
'players_protection_status' : self.players_protection_status,
'invalid_moves' : self.invalid_moves,
'valid_moves' : self.valid_moves,
'players_active' : self.players_active,
'players_protected' : self.players_protected})
|
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# Copyright (c) 2019, Eurecat / UPF
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the <organization> nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# @file echogram.py
# @author Andrés Pérez-López
# @date 30/07/2019
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
class Echogram:
"""
Class holding echogram information.
Parameters
----------
value : 2D ndarray, dimension = (n, nSH)
time : 1D ndarray, dimension = (n), values must be positive
order : 2D ndarray, dimension = (n, C), dtype=int
coords : 2D ndarray, dimension = (n, C)
"""
def __init__(self, value, time, order, coords):
self.value = value
self.time = time
self.order = order
self.coords = coords
class QuantisedEchogram:
"""
Class holding quantised echogram information.
Parameters
----------
value : 2D ndarray, dimension = (n, nSH)
time : 1D ndarray, dimension = (n), values must be positive
isActive: boolean
"""
def __init__(self, value, time, isActive):
self.value = value
self.time = time
self.isActive = isActive
|
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def maxDepth(self, root):
"""
:type root: Node
:rtype: int
"""
stack = []
if root is not None:
stack.append((1, root))
depth = 0
while stack != []:
current_depth, root = stack.pop()
if root is not None:
depth = max(depth, current_depth)
for c in root.children:
stack.append((current_depth + 1, c))
return depth
|
__author__ = '@dominofire'
class Task:
"""
Represents a task in the workflow
"""
def __init__(self, name, cmd):
self.name = name
""" A name for the task that is unique among workflow scope """
self.command = cmd
""" A valid bash command to be executed """
# Used in workflow management
self.parents = []
""" A list of Tasks that immediately precedes this task in the Workflow """
# Used in workflow management
self.successors = []
""" A list of Tasks that immediately precedes this task in the Workflow """
self.dependency_names = []
""" A list of strings that contains the names of the most inmediate tasks that depends this Task """
self.complexity_factor = 1
""" A measurement that represents how difficult is this Task. A high value on the complexity factor
means that it will take more time and resources to completely execute this task"""
self.grid_params = {}
""" Parameters used in this task. If it is not empty, this task is generated by Grid Search"""
self.param_grid = {}
""" Parameter Grid to be expanded in this task """
self.include_files = []
""" Paths that points to files required to execute this task """
self.download_files = []
""" Paths that downloads files stored in the cloud """
def add_parent(self, task):
self.parents.append(task)
def add_successor(self, task):
self.successors.append(task)
def __eq__(self, other):
if not isinstance(other, Task):
return False
return self.name == other.name
def __hash__(self):
"""
Useful for building dictionaries an sets
:return:
"""
return self.name.__hash__()
def __repr__(self):
return 'Task:{0}'.format(self.name)
def __str__(self):
return self.__repr__()
|
class RawMemory(object):
'''Represents raw memory.'''
def __init__(self):
self._pointer_to_object = {}
self._object_to_pointer = {}
# address 0 won't be used
self._current_pointer = 0
def get_pointer(self, obj):
assert obj in self._object_to_pointer
return self._object_to_pointer[obj]
def dereference_pointer(self, pointer):
assert pointer in self._pointer_to_object
return self._pointer_to_object[pointer]
def allocate(self, obj):
new_pointer = self._current_pointer + 1
self._current_pointer = new_pointer
self._pointer_to_object[new_pointer] = obj
self._object_to_pointer[obj] = new_pointer
return new_pointer
class Node(object):
def __init__(self, value):
self.value = value
self.both = 0
class XORLinkedList(object):
'''Compact double-linked list.
>>> l = XORLinkedList()
>>> l.add(5)
>>> l.add(8)
>>> l.add(50)
>>> l.add(23)
>>> l.get(0)
5
>>> l.get(1)
8
>>> l.get(2)
50
>>> l.get(3)
23
'''
def __init__(self):
self.mem = RawMemory()
self.begin_node_pointer = 0
self.amount = 0
def add(self, element):
# instead of inserting at the end, we insert at the beginning and change the get function
new_node = Node(element)
new_node_pointer = self.mem.allocate(new_node)
if self.begin_node_pointer != 0:
old_node = self.mem.dereference_pointer(self.begin_node_pointer)
# old_node.both is the following node xor'd with 0, and a ^ 0 = a
old_node.both = old_node.both ^ new_node_pointer
new_node.both = self.begin_node_pointer ^ 0
self.begin_node_pointer = new_node_pointer
self.amount += 1
def get(self, index):
assert index in range(self.amount), "Index not in linked list"
# instead of inserting at the end, we insert at the beginning and change the get function
index = self.amount - index - 1
previous_pointer = 0
current_pointer = self.begin_node_pointer
for _ in range(index):
next_pointer = self.mem.dereference_pointer(current_pointer).both ^ previous_pointer
previous_pointer, current_pointer = (current_pointer, next_pointer)
return self.mem.dereference_pointer(current_pointer).value
|
class Paginator:
def __init__(self, configuration, request):
self.configuration = configuration
self.page = request.args.get('page', 1, type=int)
self.page_size = request.args.get('page_size', configuration.per_page, type=int)
if self.page_size > configuration.max_page_size:
self.page_size = configuration.max_page_size
def items(self, query):
return query.paginate(self.page, self.page_size, False).items
|
'''
Python To-Do
A simple to-do list program using text files to hold tasks
Authored by: Bryce Buchanan
'''
# TO DO 1. Convert to class
# TO DO 2. Allow editing of tasks
# TO DO 3. Detemine and implement best data structure
# TO DO 4. File I/O
# TO DO 5. GUI
#class ToDoItem:
# def __init__(self, task):
# self.task = task
# self.next = None
# def get(self):
# return self.task
class ToDoModule:
def __init__(self, toDoList, completedTasks, head = None):
self.toDoList = toDoList
self.completedTasks = completedTasks
self.head = head
def add(self):
self.toDoList.append(input('Type your task here: '))
def completeTask(self):
while (1):
try:
completed = int(input('Which task number would you like to complete? (Enter index): '))
break
except ValueError:
print('Not a valid task number')
self.completedTasks.append(self.toDoList[completed - 1])
del self.toDoList[completed - 1]
def printTasks(self):
for task in self.toDoList:
index = "{}".format(self.toDoList.index(task) + 1)
print(index + '. ' + task + '\n')
print('\n')
def printCompleted(self):
for task in self.completedTasks:
index = "{}".format(self.completedTasks.index(task) + 1)
print(index + '. ' + task, end = '\n')
print('\n')
|
EXECUTE_MODE_AUTO = "auto"
EXECUTE_MODE_ASYNC = "async"
EXECUTE_MODE_SYNC = "sync"
EXECUTE_MODE_OPTIONS = frozenset([
EXECUTE_MODE_AUTO,
EXECUTE_MODE_ASYNC,
EXECUTE_MODE_SYNC,
])
EXECUTE_CONTROL_OPTION_ASYNC = "async-execute"
EXECUTE_CONTROL_OPTION_SYNC = "sync-execute"
EXECUTE_CONTROL_OPTIONS = frozenset([
EXECUTE_CONTROL_OPTION_ASYNC,
EXECUTE_CONTROL_OPTION_SYNC,
])
EXECUTE_RESPONSE_RAW = "raw"
EXECUTE_RESPONSE_DOCUMENT = "document"
EXECUTE_RESPONSE_OPTIONS = frozenset([
EXECUTE_RESPONSE_RAW,
EXECUTE_RESPONSE_DOCUMENT,
])
EXECUTE_TRANSMISSION_MODE_VALUE = "value"
EXECUTE_TRANSMISSION_MODE_REFERENCE = "reference"
EXECUTE_TRANSMISSION_MODE_OPTIONS = frozenset([
EXECUTE_TRANSMISSION_MODE_VALUE,
EXECUTE_TRANSMISSION_MODE_REFERENCE,
])
|
# -*- coding: utf-8 -*-
# @Author : LG
"""
执行用时:40 ms, 在所有 Python3 提交中击败了98.48% 的用户
内存消耗:13.7 MB, 在所有 Python3 提交中击败了6.28% 的用户
解题思路:
现将对行进行翻转,将每行第一个变为1
其次,对列进行变换,如果本列0数量较多,则翻转
"""
class Solution:
def matrixScore(self, A: List[List[int]]) -> int:
m, n = len(A), len(A[0])
for i in range(m): # 按行,如果每行第一个为0,则翻转该行
if A[i][0] == 0:
A[i] = [1 if a == 0 else 0 for a in A[i]]
for j in range(n): # 按列
sum_ = 0
for i in range(m):
sum_ += A[i][j] # 统计本行非0值
if sum_ < m/2: # 如果非0值少,则翻转该列
for i in range(m):
A[i][j] = 0 if A[i][j] == 1 else 1
result = 0
for a in A:
result += int('0b'+''.join([str(aa) for aa in a]), base=2)
return result
|
# Euler problem 90: Cube digit pairs
def solve():
# Find all possible dies with 6 digits on faces out of 10 combinations
options = []
find_options(options, [])
count = 0
# Figure out which combinations of two dies make a square
for die1 in options:
for die2 in options:
if is_solution(die1, die2):
count += 1
# Devide by 2 because dices can be interchanges (symmetry)
print(count // 2)
def find_options(options, die):
if len(die) == 6:
options.append(die)
return
if len(die) == 0:
start = 0
else:
start = die[-1] + 1
for d in range(start, 10):
find_options(options, die + [d])
def is_solution(die1, die2):
if not digits_match(die1, die2, 0, 1):
return False
if not digits_match(die1, die2, 0, 4):
return False
if not digits_match(die1, die2, 0, 9) and not digits_match(die1, die2, 0, 6):
return False
if not digits_match(die1, die2, 1, 6) and not digits_match(die1, die2, 1, 9):
return False
if not digits_match(die1, die2, 2, 5):
return False
if not digits_match(die1, die2, 3, 6) and not digits_match(die1, die2, 3, 9):
return False
if not digits_match(die1, die2, 4, 9) and not digits_match(die1, die2, 4, 6):
return False
if not digits_match(die1, die2, 6, 4) and not digits_match(die1, die2, 9, 4):
return False
if not digits_match(die1, die2, 8, 1):
return False
return True
def digits_match(die1, die2, digit1, digit2):
if (digit1 in die1) and (digit2 in die2):
return True
if (digit2 in die1) and (digit1 in die2):
return True
return False
solve()
|
class SimHash:
def __init__(self, bit=64, limit=3):
self.bit = bit
self.limit = limit
self.docs = []
def compute_bits(self, text):
word_hash = []
for word in text:
word_hash.append(hash(word))
hash_bits = []
while len(hash_bits) < self.bit:
bit = 0
for i, word in enumerate(word_hash):
if word & 1:
bit += 1
else:
bit -= 1
word_hash[i] = word >> 1
hash_bits.append(bit)
# print(hash_bits)
return int(''.join(['1' if b > 0 else '0' for b in hash_bits[::-1]]), 2)
def hamming_distance(self, x, y):
return bin(x ^ y).count('1')
def add_doc(self, text):
text_bits = self.compute_bits(text)
for doc in self.docs:
if self.hamming_distance(doc, text_bits) < self.limit:
return False
self.docs.append(text_bits)
return True
def compare(self, x, y):
bit_x = self.compute_bits(x)
bit_y = self.compute_bits(y)
print('x: {}\ny: {}'.format(bin(bit_x), bin(bit_y)))
return self.hamming_distance(bit_x, bit_y)
class SegmentSimHash(SimHash):
def __init__(self, bit=64, limit=3, num_segment=4):
super().__init__(bit, limit)
self.docs = {}
assert bit % num_segment == 0
self.num_segment = num_segment
self.seg_length = bit // num_segment
self.masks = [int('1' * self.seg_length + '0' * self.seg_length * i, 2)
for i in range(num_segment)]
def compute_segments(self, text):
text_bits = super().compute_bits(text)
segments = [(text_bits & self.masks[i]) >> i * self.seg_length
for i in range(self.num_segment)]
return text_bits, segments
def add_doc(self, text):
text_bits, segments = self.compute_segments(text)
# find similar doc
for seg in segments:
if seg in self.docs:
for doc_seg in self.docs[seg]:
if super().hamming_distance(text_bits, doc_seg) < self.limit:
return False
# add to docs
for seg in segments:
if seg not in self.docs:
self.docs[seg] = set()
self.docs[seg].add(text_bits)
return True
if __name__ == '__main__':
text = ['we all scream for ice cream', 'we all scream for ice']
simhash = SimHash()
print(simhash.compare(text[0], text[1]))
segment = SegmentSimHash()
for t in text:
segment.add_doc(t)
print(segment.docs)
|
# Curso Introdução a Linguagem Python - MIT MISTI Brazil–Unicamp
# Ana Luísa Fogarin - 03/02/2021
# a193948@dac.unicamp.br
# SET 1 - Problema 5 - Festa da Pizza
size = 'small'
toppings = ['presunto', 'abacaxi']
if size == 'small':
base_value = 14
elif size == 'medium':
base_value = 16
else:
base_value = 18
for n, flavor in enumerate(toppings):
m = len(flavor)
porcent = (12 + n + m)/100# 12 + n + m (%)
price_flavor = base_value * porcent
base_value += price_flavor
if 'bacon' in toppings:
base_value += 0.1 * base_value
if 'anchovas' in toppings:
base_value += 0.1 * base_value
out = base_value
print(out)
|
# Write a function that takes a string as input and returns the string reversed.
class Solution(object):
def reverseString(self, s):
return s[::-1]
|
# Curso Introdução a Linguagem Python - MIT MISTI Brazil–Unicamp
# Ana Luísa Fogarin - 11/02/2021
# a193948@dac.unicamp.br
# SET 4 - Problema 3 - Fração
class Rational:
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
def get_numerator(self):
return self.numerator
def get_denominator(self):
return self.denominator
def to_float(self):
return self.numerator/self.denominator
def reciprocal(self):
'''
Retorna o recíproco desse número como uma instância de Rational
'''
return Rational(self.denominator,self.numerator)
def reduce(self):
'''
Retorna o número Rational equivalente, mas reduzido aos termos mais baixos
Encontrar o máximo divisor comum dos dois números
'''
maximum_divisor = mdc(self.numerator, self.denominator)
return Rational(self.numerator/maximum_divisor, self.denominator/maximum_divisor)
def __add__(self, other):
'''
Retorna a soma da instância original e other
- Se other for uma instancia de Rational ou Int -> retorna nova instância de Rational
- Se other foi uma instância de float -> retornar um float
- Se nao, retornar None
'''
if isinstance(other, Rational):
new_numerator = (self.numerator * other.denominator) + (other.numerator * self.denominator)
new_denominator = self.denominator * other.denominator
return Rational(new_numerator, new_denominator).reduce()
if isinstance(other, int):
new_numerator = self.numerator + (other.numerator * self.denominator)
return Rational(new_numerator, self.denominator).reduce()
if isinstance(other, float):
return ((self.numerator/self.denominator) + other)
return None
def __mul__(self, other):
'''
Retorna a multiplicação da instância original e other, mesmas regras do add
'''
if isinstance(other, Rational):
return Rational(self.numerator * other.numerator, self.denominator * other.denominator)
elif isinstance(other, int):
return Rational(self.numerator * other, self.denominator)
elif isinstance(other, float):
return ((self.numerator * other)/self.denominator)
return None
def __truediv__(self, other):
'''
Retorna o resultado da divisão da instancia original por other, mesma regras de add
'''
if isinstance(other, Rational):
return Rational(self.numerator * other.denominator, self.denominator * other.numerator)
elif isinstance(other, int):
return Rational(self.numerator, self.denominator * other)
elif isinstance(other, float):
return ((self.numerator / self.denominator) / other)
return None
def __sub__(self, other):
'''
Subtração instancia original e other
'''
if isinstance(other, Rational):
new_numerator = (self.numerator * other.denominator) - (other.numerator * self.denominator)
new_denominator = self.denominator * other.denominator
return Rational(new_numerator, new_denominator).reduce()
elif isinstance(other, int):
return Rational(self.numerator - (other * self.denominator), self.denominator).reduce()
elif isinstance(other, float):
return ((self.numerator/self.denominator) - other)
return None
def mdc(num1, num2):
'''
Calcula o máximo divisor comum entre os números
'''
while num2:
num1, num2 = num2, num1 % num2
return num1
fracao = Rational(1, 2)
fracao2 = Rational(3, 4)
soma = fracao + fracao2
print(soma.get_numerator(), soma.get_denominator())
|
# Copyright 2018, Michael DeHaan LLC
# License: Apache License Version 2.0 + Commons Clause
# ---------------------------------------------------------------------------
# workers.py - configuration related to worker setup. This file *CAN* be
# different per worker.
# ---------------------------------------------------------------------------
BUILD_ROOT = "/tmp/vespene/buildroot/"
# ---------------------------------------------------------------------------
# all of these settings deal with serving up the buildroot.
# to disable file serving thorugh Django you can set this to FALSE
FILESERVING_ENABLED = True
FILESERVING_PORT = 8000
# leave this blank and the system will try to figure this out
# the setup scripts will usually set this to `hostname` though if
# unset the registration code will run `hostname`
FILESERVING_HOSTNAME = ""
FILESERVING_URL="/srv"
# if you disable fileserving but are using triggers to copy build roots
# to some other location (perhaps NFS served up by a web server or an FTP
# server) you can set this FILESERVING_ENABLED to False and the following pattern will
# be used instead to generate web links in the main GUI. If this pattern
# is set the links to the built-in fileserver will NOT be rendered, but this will
# not turn on the fileserver. To do that, set FILESERVING_ENABLED to False also
# BUILDROOT_WEB_LINK = "http://build-fileserver.example.com/builds/{{ build.id }}"
BUILDROOT_WEB_LINK = ""
|
#1016
#ENTRADA DE DADOS
entrada = int(input())
#SE O CARRO Y CONSEGUE SE DISTANCIAR EM CADA MINUTO 500metros = 0.5km
tempo = entrada/0.5
print(int(tempo), 'minutos')
|
# Licensed under a 3-clause BSD style license - see LICENSE.rst
# coding: utf8
class ConsumerSequential():
"""`ConsumerSequential` class represents a Consumer pipeline Step.
"""
def __init__(
self, coroutine, name=None):
"""
Parameters
----------
coroutine : Class instance that contains init, run and finish methods
"""
self.name = name
self.coroutine = coroutine
self.running = 0
self.nb_job_done = 0
def init(self):
"""
Initialise coroutine sockets and poller
Returns
-------
True if coroutine init method returns True, otherwise False
"""
if self.name is None:
self.name = "Consumer"
if self.coroutine is None:
return False
if self.coroutine.init() == False:
return False
return True
def run(self,inputs=None):
""" Executes coroutine run method
Parameters
----------
inputs: input for coroutine.run
"""
self.coroutine.run(inputs)
self.nb_job_done+=1
def finish(self):
"""
Call coroutine finish method
"""
self.coroutine.finish()
return True
|
"""
0056. Merge Intervals
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.
NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.
"""
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
if not intervals:
return []
intervals = sorted(intervals, key = lambda x: x[0])
res = []
for elem in intervals:
if len(res) == 0 or res[-1][1] < elem[0]:
res.append(elem)
else:
res[-1][1] = max(res[-1][1], elem[1])
return res
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
if not intervals:
return []
intervals = sorted(intervals, key = lambda x: x[0])
res = [intervals[0]]
for i in range(1, len(intervals)):
if intervals[i][0] > res[-1][1]:
res.append(intervals[i])
else:
res[-1][1] = max(res[-1][1], intervals[i][1])
return res
|
class InsertQueryComposer(object):
_insert_part = None
_values_part_template = None
_values_part = None
values_count = None
def __init__(self, table_name, columns):
columns_clause = ""
values_clause = ""
for column in columns:
columns_clause += "`{column_name}`, ".format(
column_name=column['Field'])
val = "{{0[{column_name}]}}, "
values_clause += val.format(column_name=column['Field'])
columns_clause = columns_clause.rstrip(", ")
values_clause = values_clause.rstrip(", ")
self._insert_part = "INSERT INTO `" + table_name + "` (" + columns_clause + ") VALUES"
self._values_part_template = "(" + values_clause + "),"
self._values_part = ""
self.values_count = 0
def add_value(self, record):
self._values_part += self._values_part_template.format(record)
self.values_count += 1
def get_query(self):
if self.values_count == 0:
raise Exception("No values provided to InsertQueryComposer")
self._values_part = self._values_part.rstrip(",")
return "{insert}{values};".format(insert=self._insert_part, values=self._values_part)
def reset(self):
self.values_count = 0
self._values_part = ""
|
# parsetable.py
# This file is automatically generated. Do not edit.
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'AND ARRAY ASSIGNMENT BINDIGSEQ CASE CHAR COLON COMMA COMMENT CONST DIGSEQ DIV DO DOT DOTDOT DOWNTO ELSE END EQUAL FOR FORWARD FUNCTION GE GOTO GT HEXDIGSEQ IDENTIFIER IF IN LABEL LBRAC LE LPAREN LT MINUS MOD NIL NOT NOTEQUAL OCTDIGSEQ OF OR OTHERWISE PACKED PBEGIN PFILE PLUS PROCEDURE PROGRAM RBRAC REALNUMBER RECORD REPEAT RPAREN SEMICOLON SET SLASH STAR STARSTAR STRING THEN TO TYPE UNTIL UPARROW UNPACKED VAR WHILE WITHfile : program\n program : PROGRAM identifier LPAREN identifier_list RPAREN semicolon block DOT\n program : PROGRAM identifier semicolon block DOTidentifier_list : identifier_list comma identifieridentifier_list : identifierblock : label_declaration_part constant_definition_part type_definition_part variable_declaration_part procedure_and_function_declaration_part statement_partlabel_declaration_part : LABEL label_list semicolonlabel_declaration_part : emptylabel_list : label_list comma labellabel_list : labellabel : DIGSEQconstant_definition_part : CONST constant_listconstant_definition_part : emptyconstant_list : constant_list constant_definitionconstant_list : constant_definitionconstant_definition : identifier EQUAL cexpression semicoloncexpression : csimple_expressioncexpression : csimple_expression relop csimple_expressioncsimple_expression : ctermcsimple_expression : csimple_expression addop ctermcterm : cfactorcterm : cterm mulop cfactorcfactor : sign cfactorcfactor : cprimarycprimary : identifiercprimary : LPAREN cexpression RPARENcprimary : unsigned_constantcprimary : NOT cprimaryconstant : non_stringconstant : sign non_stringconstant : STRINGconstant : CHARsign : PLUSsign : MINUSnon_string : DIGSEQnon_string : identifiernon_string : REALNUMBERtype_definition_part : TYPE type_definition_listtype_definition_part : emptytype_definition_list : type_definition_list type_definitiontype_definition_list : type_definitiontype_definition : identifier EQUAL type_denoter semicolontype_denoter : identifiertype_denoter : new_typenew_type : new_ordinal_typenew_type : new_structured_typenew_type : new_pointer_typenew_ordinal_type : enumerated_typenew_ordinal_type : subrange_typeenumerated_type : LPAREN identifier_list RPARENsubrange_type : constant DOTDOT constantnew_structured_type : structured_typenew_structured_type : PACKED structured_typestructured_type : array_typestructured_type : record_typestructured_type : set_typestructured_type : file_typearray_type : ARRAY LBRAC index_list RBRAC OF component_typeindex_list : index_list comma index_typeindex_list : index_typeindex_type : ordinal_typeordinal_type : new_ordinal_typeordinal_type : identifiercomponent_type : type_denoterrecord_type : RECORD record_section_list ENDrecord_type : RECORD record_section_list semicolon variant_part ENDrecord_type : RECORD variant_part ENDrecord_section_list : record_section_list semicolon record_sectionrecord_section_list : record_sectionrecord_section : identifier_list COLON type_denotervariant_selector : tag_field COLON tag_typevariant_selector : tag_typevariant_list : variant_list semicolon variantvariant_list : variantvariant : case_constant_list COLON LPAREN record_section_list RPARENvariant : case_constant_list COLON LPAREN record_section_list semicolon variant_part RPARENvariant : case_constant_list COLON LPAREN variant_part RPARENvariant_part : CASE variant_selector OF variant_listvariant_part : CASE variant_selector OF variant_list semicolonvariant_part : emptycase_constant_list : case_constant_list comma case_constantcase_constant_list : case_constantcase_constant : constantcase_constant : constant DOTDOT constanttag_field : identifiertag_type : identifierset_type : SET OF base_typebase_type : ordinal_typefile_type : PFILE OF component_typenew_pointer_type : UPARROW domain_typedomain_type : identifiervariable_declaration_part : VAR variable_declaration_list semicolonvariable_declaration_part : emptyvariable_declaration_list : variable_declaration_list semicolon variable_declarationvariable_declaration_list : variable_declarationvariable_declaration : identifier_list COLON type_denoterprocedure_and_function_declaration_part : proc_or_func_declaration_list semicolonprocedure_and_function_declaration_part : emptyproc_or_func_declaration_list : proc_or_func_declaration_list semicolon proc_or_func_declarationproc_or_func_declaration_list : proc_or_func_declarationproc_or_func_declaration : procedure_declarationproc_or_func_declaration : function_declarationprocedure_declaration : procedure_heading semicolon procedure_blockprocedure_heading : procedure_identificationprocedure_heading : procedure_identification formal_parameter_listformal_parameter_list : LPAREN formal_parameter_section_list RPARENformal_parameter_section_list : formal_parameter_section_list semicolon formal_parameter_sectionformal_parameter_section_list : formal_parameter_sectionformal_parameter_section : value_parameter_specificationformal_parameter_section : variable_parameter_specificationformal_parameter_section : procedural_parameter_specificationformal_parameter_section : functional_parameter_specificationvalue_parameter_specification : identifier_list COLON identifier\n variable_parameter_specification : VAR identifier_list COLON identifier\n procedural_parameter_specification : procedure_headingfunctional_parameter_specification : function_headingprocedure_identification : PROCEDURE identifierprocedure_block : block\n function_declaration : function_identification semicolon function_block\n function_declaration : function_heading semicolon function_blockfunction_heading : FUNCTION identifier COLON result_typefunction_heading : FUNCTION identifier formal_parameter_list COLON result_typeresult_type : identifierfunction_identification : FUNCTION identifierfunction_block : blockstatement_part : compound_statementcompound_statement : PBEGIN statement_sequence ENDstatement_sequence : statement_sequence semicolon statementstatement_sequence : statementstatement : open_statementstatement : closed_statementopen_statement : label COLON non_labeled_open_statementopen_statement : non_labeled_open_statementclosed_statement : label COLON non_labeled_closed_statementclosed_statement : non_labeled_closed_statementnon_labeled_open_statement : open_with_statementnon_labeled_open_statement : open_if_statementnon_labeled_open_statement : open_while_statementnon_labeled_open_statement : open_for_statement\n non_labeled_closed_statement : assignment_statement\n | procedure_statement\n | goto_statement\n | compound_statement\n | case_statement\n | repeat_statement\n | closed_with_statement\n | closed_if_statement\n | closed_while_statement\n | closed_for_statement\n | empty\n repeat_statement : REPEAT statement_sequence UNTIL boolean_expressionopen_while_statement : WHILE boolean_expression DO open_statementclosed_while_statement : WHILE boolean_expression DO closed_statementopen_for_statement : FOR control_variable ASSIGNMENT initial_value direction final_value DO open_statementclosed_for_statement : FOR control_variable ASSIGNMENT initial_value direction final_value DO closed_statementopen_with_statement : WITH record_variable_list DO open_statementclosed_with_statement : WITH record_variable_list DO closed_statementopen_if_statement : IF boolean_expression THEN statementopen_if_statement : IF boolean_expression THEN closed_statement ELSE open_statementclosed_if_statement : IF boolean_expression THEN closed_statement ELSE closed_statementassignment_statement : variable_access ASSIGNMENT expressionvariable_access : identifiervariable_access : indexed_variablevariable_access : field_designatorvariable_access : variable_access UPARROWindexed_variable : variable_access LBRAC index_expression_list RBRACindex_expression_list : index_expression_list comma index_expressionindex_expression_list : index_expressionindex_expression : expressionfield_designator : variable_access DOT identifierprocedure_statement : identifier paramsprocedure_statement : identifierparams : LPAREN actual_parameter_list RPARENactual_parameter_list : actual_parameter_list comma actual_parameteractual_parameter_list : actual_parameteractual_parameter : expressionactual_parameter : expression COLON expressionactual_parameter : expression COLON expression COLON expressiongoto_statement : GOTO labelcase_statement : CASE case_index OF case_list_element_list END\n case_statement : CASE case_index OF case_list_element_list SEMICOLON END\n case_statement : CASE case_index OF case_list_element_list semicolon otherwisepart statement ENDcase_statement : CASE case_index OF case_list_element_list semicolon otherwisepart statement SEMICOLON ENDcase_index : expression\n case_list_element_list : case_list_element_list semicolon case_list_element\n case_list_element_list : case_list_elementcase_list_element : case_constant_list COLON statementotherwisepart : OTHERWISEotherwisepart : OTHERWISE COLONcontrol_variable : identifierinitial_value : expressiondirection : TOdirection : DOWNTOfinal_value : expressionrecord_variable_list : record_variable_list comma variable_accessrecord_variable_list : variable_accessboolean_expression : expressionexpression : simple_expressionexpression : simple_expression relop simple_expressionsimple_expression : termsimple_expression : simple_expression addop termterm : factorterm : term mulop factorfactor : sign factorfactor : primaryprimary : variable_accessprimary : unsigned_constantprimary : function_designatorprimary : set_constructorprimary : LPAREN expression RPARENprimary : NOT primaryunsigned_constant : unsigned_numberunsigned_constant : STRINGunsigned_constant : NILunsigned_constant : CHARunsigned_number : unsigned_integerunsigned_number : unsigned_realunsigned_integer : DIGSEQunsigned_integer : HEXDIGSEQunsigned_integer : OCTDIGSEQunsigned_integer : BINDIGSEQunsigned_real : REALNUMBERfunction_designator : identifier paramsset_constructor : LBRAC member_designator_list RBRACset_constructor : LBRAC RBRAC\n member_designator_list : member_designator_list comma member_designator\n member_designator_list : member_designatormember_designator : member_designator DOTDOT expressionmember_designator : expressionaddop : PLUSaddop : MINUSaddop : ORmulop : STARmulop : SLASHmulop : DIVmulop : MODmulop : ANDrelop : EQUALrelop : NOTEQUALrelop : LTrelop : GTrelop : LErelop : GErelop : INidentifier : IDENTIFIERsemicolon : SEMICOLONcomma : COMMAempty : '
_lr_action_items = {'OTHERWISE':([370,371,],[390,-246,]),'NOTEQUAL':([5,62,63,65,66,68,69,70,72,73,74,75,77,78,79,80,81,83,132,146,189,192,219,220,222,230,231,233,234,235,236,239,241,243,247,288,292,298,299,304,326,327,328,331,334,354,],[-245,-19,-222,-215,-217,-212,-219,136,-213,-24,-27,-21,-220,-218,-214,-221,-216,-25,-23,-28,-164,-163,-22,-20,-26,-205,-208,-206,-202,136,-207,-200,-209,-162,-165,-204,-225,-211,-223,-170,-201,-210,-224,-203,-166,-173,]),'STAR':([5,62,63,65,66,68,69,72,73,74,75,77,78,79,80,81,83,132,146,189,192,219,220,222,230,231,233,234,236,239,241,243,247,288,292,298,299,304,326,327,328,331,334,354,],[-245,127,-222,-215,-217,-212,-219,-213,-24,-27,-21,-220,-218,-214,-221,-216,-25,-23,-28,-164,-163,-22,127,-26,-205,-208,-206,-202,-207,127,-209,-162,-165,-204,-225,-211,-223,-170,127,-210,-224,-203,-166,-173,]),'SLASH':([5,62,63,65,66,68,69,72,73,74,75,77,78,79,80,81,83,132,146,189,192,219,220,222,230,231,233,234,236,239,241,243,247,288,292,298,299,304,326,327,328,331,334,354,],[-245,129,-222,-215,-217,-212,-219,-213,-24,-27,-21,-220,-218,-214,-221,-216,-25,-23,-28,-164,-163,-22,129,-26,-205,-208,-206,-202,-207,129,-209,-162,-165,-204,-225,-211,-223,-170,129,-210,-224,-203,-166,-173,]),'DO':([5,63,65,66,68,69,72,77,78,79,80,81,189,192,230,231,233,234,235,236,239,240,241,243,244,247,249,250,251,288,292,298,299,304,325,326,327,328,331,334,338,354,377,380,395,396,424,],[-245,-222,-215,-217,-212,-219,-213,-220,-218,-214,-221,-216,-164,-163,-205,-208,-206,-202,-198,-207,-200,297,-209,-162,-197,-165,305,-196,-162,-204,-225,-211,-223,-170,-199,-201,-210,-224,-203,-166,-195,-173,397,401,408,-194,426,]),'ASSIGNMENT':([5,164,187,189,192,247,254,255,304,334,379,],[-245,246,-162,-164,-163,-165,308,-190,-170,-166,400,]),'THEN':([5,63,65,66,68,69,72,77,78,79,80,81,189,192,230,231,233,234,235,236,239,241,243,244,247,259,288,292,298,299,304,325,326,327,328,331,334,354,382,],[-245,-222,-215,-217,-212,-219,-213,-220,-218,-214,-221,-216,-164,-163,-205,-208,-206,-202,-198,-207,-200,-209,-162,-197,-165,312,-204,-225,-211,-223,-170,-199,-201,-210,-224,-203,-166,-173,402,]),'EQUAL':([5,30,40,62,63,65,66,68,69,70,72,73,74,75,77,78,79,80,81,83,132,146,189,192,219,220,222,230,231,233,234,235,236,239,241,243,247,288,292,298,299,304,326,327,328,331,334,354,],[-245,42,61,-19,-222,-215,-217,-212,-219,138,-213,-24,-27,-21,-220,-218,-214,-221,-216,-25,-23,-28,-164,-163,-22,-20,-26,-205,-208,-206,-202,138,-207,-200,-209,-162,-165,-204,-225,-211,-223,-170,-201,-210,-224,-203,-166,-173,]),'GOTO':([6,91,178,229,256,297,305,312,372,378,381,389,390,397,401,402,407,408,419,426,],[-246,179,179,179,179,179,179,179,179,179,179,179,-188,179,179,179,-189,179,179,179,]),'LABEL':([6,7,33,93,95,96,],[-246,11,11,11,11,11,]),'CHAR':([6,24,42,61,64,67,71,76,82,98,126,127,128,129,130,131,133,134,135,136,137,138,139,140,141,142,143,144,162,168,186,202,206,213,218,232,237,238,242,245,246,261,277,289,290,296,307,308,311,317,323,329,330,335,347,353,355,356,363,368,370,371,373,374,375,376,386,400,403,418,],[-246,-247,65,120,65,-34,-33,65,65,120,-237,-233,65,-234,-235,-236,65,-241,65,-239,-243,-238,-232,-240,-242,-230,-244,-231,65,65,65,120,120,120,120,65,65,65,65,65,65,65,120,65,65,65,120,65,65,120,120,65,65,65,65,65,65,65,120,120,120,-246,120,65,-193,-192,120,65,65,65,]),'PBEGIN':([6,7,9,10,15,17,25,27,28,29,31,33,35,37,38,39,41,47,49,60,86,91,93,95,96,97,147,178,214,229,256,297,305,312,372,378,381,389,390,397,401,402,407,408,419,426,],[-246,-248,-8,-248,-248,-13,-248,-39,-12,-15,-7,-248,-248,-93,-41,-38,-14,91,-98,-40,-97,91,-248,-248,-248,-92,-16,91,-42,91,91,91,91,91,91,91,91,91,-188,91,91,91,-189,91,91,91,]),'WHILE':([6,91,178,229,256,297,305,312,372,378,381,389,390,397,401,402,407,408,419,426,],[-246,162,162,162,162,162,162,347,162,162,347,162,-188,347,347,347,-189,162,347,347,]),'PROGRAM':([0,],[3,]),'REPEAT':([6,91,178,229,256,297,305,312,372,378,381,389,390,397,401,402,407,408,419,426,],[-246,178,178,178,178,178,178,178,178,178,178,178,-188,178,178,178,-189,178,178,178,]),'CONST':([6,7,9,10,31,33,93,95,96,],[-246,-248,-8,16,-7,-248,-248,-248,-248,]),'DIV':([5,62,63,65,66,68,69,72,73,74,75,77,78,79,80,81,83,132,146,189,192,219,220,222,230,231,233,234,236,239,241,243,247,288,292,298,299,304,326,327,328,331,334,354,],[-245,130,-222,-215,-217,-212,-219,-213,-24,-27,-21,-220,-218,-214,-221,-216,-25,-23,-28,-164,-163,-22,130,-26,-205,-208,-206,-202,-207,130,-209,-162,-165,-204,-225,-211,-223,-170,130,-210,-224,-203,-166,-173,]),'WITH':([6,91,178,229,256,297,305,312,372,378,381,389,390,397,401,402,407,408,419,426,],[-246,166,166,166,166,166,166,350,166,166,350,166,-188,350,350,350,-189,166,350,350,]),'MINUS':([5,6,24,42,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,83,98,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,146,162,168,186,189,192,202,206,213,218,219,220,221,222,230,231,232,233,234,235,236,237,238,239,241,243,245,246,247,261,277,288,289,290,292,296,298,299,304,307,308,311,317,323,325,326,327,328,329,330,331,334,335,347,353,354,355,356,363,368,370,371,373,374,375,376,386,400,403,418,],[-245,-246,-247,67,67,-19,-222,67,-215,-217,-34,-212,-219,144,-33,-213,-24,-27,-21,67,-220,-218,-214,-221,-216,-25,67,-237,-233,67,-234,-235,-236,-23,67,-241,67,-239,-243,-238,-232,-240,-242,-230,-244,-231,-28,67,67,67,-164,-163,67,67,67,67,-22,-20,144,-26,-205,-208,67,-206,-202,144,-207,67,67,-200,-209,-162,67,67,-165,67,67,-204,67,67,-225,67,-211,-223,-170,67,67,67,67,67,144,-201,-210,-224,67,67,-203,-166,67,67,67,-173,67,67,67,67,67,-246,67,67,-193,-192,67,67,67,67,]),'DOT':([5,12,44,89,90,164,187,189,192,228,233,243,247,250,251,304,334,338,],[-245,21,85,-6,-126,248,-162,-164,-163,-127,248,-162,-165,248,-162,-170,-166,248,]),'REALNUMBER':([6,24,42,61,64,67,71,76,82,98,102,126,127,128,129,130,131,133,134,135,136,137,138,139,140,141,142,143,144,162,168,186,202,206,213,218,232,237,238,242,245,246,261,277,289,290,296,307,308,311,317,323,329,330,335,347,353,355,356,363,368,370,371,373,374,375,376,386,400,403,418,],[-246,-247,63,100,63,-34,-33,63,63,100,100,-237,-233,63,-234,-235,-236,63,-241,63,-239,-243,-238,-232,-240,-242,-230,-244,-231,63,63,63,100,100,100,100,63,63,63,63,63,63,63,100,63,63,63,100,63,63,100,100,63,63,63,63,63,63,63,100,100,100,-246,100,63,-193,-192,100,63,63,63,]),'CASE':([6,91,110,178,229,256,275,297,305,312,372,378,381,389,390,397,401,402,404,407,408,419,421,426,],[-246,168,207,168,168,168,207,168,168,168,168,168,168,168,-188,168,168,168,207,-189,168,168,207,168,]),'LE':([5,62,63,65,66,68,69,70,72,73,74,75,77,78,79,80,81,83,132,146,189,192,219,220,222,230,231,233,234,235,236,239,241,243,247,288,292,298,299,304,326,327,328,331,334,354,],[-245,-19,-222,-215,-217,-212,-219,141,-213,-24,-27,-21,-220,-218,-214,-221,-216,-25,-23,-28,-164,-163,-22,-20,-26,-205,-208,-206,-202,141,-207,-200,-209,-162,-165,-204,-225,-211,-223,-170,-201,-210,-224,-203,-166,-173,]),'RPAREN':([5,6,13,14,34,46,62,63,65,66,68,69,70,72,73,74,75,77,78,79,80,81,83,87,94,100,101,103,104,105,107,109,111,114,116,117,119,120,121,122,124,125,132,145,146,149,150,152,153,156,157,158,159,189,192,203,204,205,208,212,215,216,217,219,220,221,222,224,230,231,233,234,235,236,239,241,243,247,263,264,265,266,267,268,269,274,276,281,282,283,284,286,288,291,292,298,299,304,313,314,315,316,319,321,324,325,326,327,328,331,334,354,357,359,362,383,384,386,387,404,405,411,412,413,420,421,422,425,427,],[-245,-246,-5,22,-4,-104,-19,-222,-215,-217,-212,-219,-17,-213,-24,-27,-21,-220,-218,-214,-221,-216,-25,-105,-117,-37,-57,-45,-46,-55,-31,-29,-48,-49,-56,-35,-54,-32,-52,-44,-47,-43,-23,222,-28,-109,-110,-111,224,-115,-112,-116,-108,-164,-163,-36,-30,-53,-69,-80,-90,-91,281,-22,-20,-18,-26,-106,-205,-208,-206,-202,-198,-207,-200,-209,-162,-165,-123,-121,-51,-87,-88,-62,-63,-65,-67,-50,-64,-89,-107,-113,-204,327,-225,-211,-223,-170,354,-175,-176,-122,-68,-70,-114,-199,-201,-210,-224,-203,-166,-173,-74,-78,-66,-174,-177,-79,-58,-248,-73,-178,420,422,-75,-248,-77,427,-76,]),'SEMICOLON':([4,5,6,18,19,20,22,43,45,46,48,51,53,54,55,56,57,59,62,63,65,66,68,69,70,72,73,74,75,77,78,79,80,81,83,84,87,89,90,91,92,94,100,101,103,104,105,107,109,111,113,114,116,117,119,120,121,122,124,125,132,146,148,149,150,152,153,156,157,158,159,160,161,163,165,167,170,171,172,174,175,176,177,178,180,181,182,183,184,185,187,188,189,190,191,192,195,196,197,198,199,200,201,203,204,205,208,209,215,216,219,220,221,222,224,228,229,230,231,233,234,235,236,239,241,243,244,247,256,257,258,260,263,264,265,266,267,268,269,274,276,281,282,283,284,286,287,288,292,297,298,299,303,304,305,309,310,312,316,319,321,324,325,326,327,328,331,332,333,334,336,337,340,342,346,348,352,354,357,359,362,369,372,378,381,387,389,390,391,392,393,397,398,399,401,402,405,406,407,408,410,412,414,416,417,419,420,422,423,426,427,],[6,-245,-246,6,-10,-11,6,-9,6,-104,-100,6,6,-102,-101,6,6,-95,-19,-222,-215,-217,-212,-219,-17,-213,-24,-27,-21,-220,-218,-214,-221,-216,-25,6,-105,-6,-126,-248,-124,-117,-37,-57,-45,-46,-55,-31,-29,-48,6,-49,-56,-35,-54,-32,-52,-44,-47,-43,-23,-28,-99,-109,-110,-111,6,-115,-112,-116,-108,-147,6,-142,-136,-131,-143,-140,-141,-129,-138,-150,-145,-248,-148,-139,-130,-144,-137,-149,-172,-146,-164,-133,-135,-163,-119,-125,-103,-118,-120,-94,-96,-36,-30,-53,-69,6,-90,-91,-22,-20,-18,-26,-106,-127,-248,-205,-208,-206,-202,-198,-207,-200,-209,-162,-197,-165,-248,6,-179,-171,-123,-121,-51,-87,-88,-62,-63,-65,-67,-50,-64,-89,-107,-113,-128,-204,-225,-248,-211,-223,-161,-170,-248,-132,-134,-248,-122,-68,-70,-114,-199,-201,-210,-224,-203,-153,-152,-166,-157,-156,-186,371,-151,-131,-158,-173,-74,6,-66,-180,-248,-248,-248,-58,-248,-188,-185,-181,-187,-248,-160,-159,-248,-248,-73,415,-189,-248,-131,6,-182,-155,-154,-248,-75,-77,-183,-248,-76,]),'RECORD':([61,98,106,218,277,363,],[110,110,110,110,110,110,]),'RBRAC':([5,63,65,66,68,69,72,77,78,79,80,81,100,107,109,111,114,117,120,189,192,203,204,230,231,233,234,235,236,238,239,241,243,247,265,268,269,278,279,280,281,288,292,293,294,295,298,299,300,301,302,304,325,326,327,328,331,334,354,364,365,366,367,],[-245,-222,-215,-217,-212,-219,-213,-220,-218,-214,-221,-216,-37,-31,-29,-48,-49,-35,-32,-164,-163,-36,-30,-205,-208,-206,-202,-198,-207,292,-200,-209,-162,-165,-51,-62,-63,-60,-61,322,-50,-204,-225,328,-227,-229,-211,-223,334,-168,-169,-170,-199,-201,-210,-224,-203,-166,-173,-59,-226,-228,-167,]),'PLUS':([5,6,24,42,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,83,98,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,146,162,168,186,189,192,202,206,213,218,219,220,221,222,230,231,232,233,234,235,236,237,238,239,241,243,245,246,247,261,277,288,289,290,292,296,298,299,304,307,308,311,317,323,325,326,327,328,329,330,331,334,335,347,353,354,355,356,363,368,370,371,373,374,375,376,386,400,403,418,],[-245,-246,-247,71,71,-19,-222,71,-215,-217,-34,-212,-219,142,-33,-213,-24,-27,-21,71,-220,-218,-214,-221,-216,-25,71,-237,-233,71,-234,-235,-236,-23,71,-241,71,-239,-243,-238,-232,-240,-242,-230,-244,-231,-28,71,71,71,-164,-163,71,71,71,71,-22,-20,142,-26,-205,-208,71,-206,-202,142,-207,71,71,-200,-209,-162,71,71,-165,71,71,-204,71,71,-225,71,-211,-223,-170,71,71,71,71,71,142,-201,-210,-224,71,71,-203,-166,71,71,71,-173,71,71,71,71,71,-246,71,71,-193,-192,71,71,71,71,]),'DOTDOT':([5,63,65,66,68,69,72,77,78,79,80,81,99,100,107,109,117,120,125,189,192,203,204,230,231,233,234,235,236,239,241,243,247,269,288,292,294,295,298,299,304,325,326,327,328,331,334,339,354,365,366,],[-245,-222,-215,-217,-212,-219,-213,-220,-218,-214,-221,-216,202,-37,-31,-29,-35,-32,-36,-164,-163,-36,-30,-205,-208,-206,-202,-198,-207,-200,-209,-162,-165,-36,-204,-225,330,-229,-211,-223,-170,-199,-201,-210,-224,-203,-166,368,-173,330,-228,]),'TO':([5,63,65,66,68,69,72,77,78,79,80,81,189,192,230,231,233,234,235,236,239,241,243,247,288,292,298,299,304,325,326,327,328,331,334,344,345,354,409,],[-245,-222,-215,-217,-212,-219,-213,-220,-218,-214,-221,-216,-164,-163,-205,-208,-206,-202,-198,-207,-200,-209,-162,-165,-204,-225,-211,-223,-170,-199,-201,-210,-224,-203,-166,376,-191,-173,376,]),'LT':([5,62,63,65,66,68,69,70,72,73,74,75,77,78,79,80,81,83,132,146,189,192,219,220,222,230,231,233,234,235,236,239,241,243,247,288,292,298,299,304,326,327,328,331,334,354,],[-245,-19,-222,-215,-217,-212,-219,140,-213,-24,-27,-21,-220,-218,-214,-221,-216,-25,-23,-28,-164,-163,-22,-20,-26,-205,-208,-206,-202,140,-207,-200,-209,-162,-165,-204,-225,-211,-223,-170,-201,-210,-224,-203,-166,-173,]),'COLON':([5,13,20,34,58,63,65,66,68,69,72,77,78,79,80,81,92,100,107,109,117,120,155,173,189,192,193,203,204,211,223,224,226,230,231,233,234,235,236,239,241,243,247,271,272,288,292,298,299,304,315,325,326,327,328,331,334,339,341,343,351,354,358,384,388,390,394,],[-245,-5,-11,-4,98,-222,-215,-217,-212,-219,-213,-220,-218,-214,-221,-216,194,-37,-31,-29,-35,-32,227,256,-164,-163,262,-36,-30,277,194,-106,285,-205,-208,-206,-202,-198,-207,-200,-209,-162,-165,-85,318,-204,-225,-211,-223,-170,356,-199,-201,-210,-224,-203,-166,-83,-82,372,381,-173,385,403,-84,407,-81,]),'PACKED':([61,98,218,277,363,],[106,106,106,106,106,]),'HEXDIGSEQ':([24,42,64,67,71,76,82,126,127,128,129,130,131,133,134,135,136,137,138,139,140,141,142,143,144,162,168,186,232,237,238,242,245,246,261,289,290,296,308,311,329,330,335,347,353,355,356,374,375,376,400,403,418,],[-247,69,69,-34,-33,69,69,-237,-233,69,-234,-235,-236,69,-241,69,-239,-243,-238,-232,-240,-242,-230,-244,-231,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,-193,-192,69,69,69,]),'COMMA':([5,13,14,18,19,20,34,43,58,63,65,66,68,69,72,77,78,79,80,81,100,107,109,111,114,117,120,155,189,192,203,204,211,217,226,230,231,233,234,235,236,239,241,243,247,249,250,251,265,268,269,278,279,280,281,288,292,293,294,295,298,299,300,301,302,304,313,314,315,325,326,327,328,331,334,338,339,341,343,354,358,364,365,366,367,380,383,384,388,394,411,],[-245,-5,24,24,-10,-11,-4,-9,24,-222,-215,-217,-212,-219,-213,-220,-218,-214,-221,-216,-37,-31,-29,-48,-49,-35,-32,24,-164,-163,-36,-30,24,24,24,-205,-208,-206,-202,-198,-207,-200,-209,-162,-165,24,-196,-162,-51,-62,-63,-60,-61,24,-50,-204,-225,24,-227,-229,-211,-223,24,-168,-169,-170,24,-175,-176,-199,-201,-210,-224,-203,-166,-195,-83,-82,24,-173,24,-59,-226,-228,-167,24,-174,-177,-84,-81,-178,]),'ARRAY':([61,98,106,218,277,363,],[112,112,112,112,112,112,]),'IDENTIFIER':([3,6,8,16,23,24,26,28,29,36,38,39,41,42,50,52,60,61,64,67,71,76,82,88,91,97,98,102,110,115,118,126,127,128,129,130,131,133,134,135,136,137,138,139,140,141,142,143,144,147,151,154,162,166,168,169,178,186,194,202,206,207,213,214,218,225,227,229,232,237,238,242,245,246,248,256,261,262,275,277,285,289,290,296,297,305,306,307,308,311,312,317,318,323,329,330,335,347,349,350,353,355,356,363,368,370,371,372,373,374,375,376,378,381,386,389,390,397,400,401,402,403,404,407,408,418,419,421,426,],[5,-246,5,5,5,-247,5,5,-15,5,-41,5,-14,5,5,5,-40,5,5,-34,-33,5,5,5,5,5,5,5,5,5,5,-237,-233,5,-234,-235,-236,5,-241,5,-239,-243,-238,-232,-240,-242,-230,-244,-231,-16,5,5,5,5,5,5,5,5,5,5,5,5,5,-42,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,-246,5,5,5,-193,-192,5,5,5,5,-188,5,5,5,5,5,5,-189,5,5,5,5,5,]),'$end':([1,2,21,85,],[-1,0,-3,-2,]),'FUNCTION':([6,7,9,10,15,17,25,27,28,29,31,33,35,37,38,39,41,60,86,88,93,95,96,97,147,214,225,],[-246,-248,-8,-248,-248,-13,-248,-39,-12,-15,-7,-248,50,-93,-41,-38,-14,-40,50,151,-248,-248,-248,-92,-16,-42,151,]),'GT':([5,62,63,65,66,68,69,70,72,73,74,75,77,78,79,80,81,83,132,146,189,192,219,220,222,230,231,233,234,235,236,239,241,243,247,288,292,298,299,304,326,327,328,331,334,354,],[-245,-19,-222,-215,-217,-212,-219,134,-213,-24,-27,-21,-220,-218,-214,-221,-216,-25,-23,-28,-164,-163,-22,-20,-26,-205,-208,-206,-202,134,-207,-200,-209,-162,-165,-204,-225,-211,-223,-170,-201,-210,-224,-203,-166,-173,]),'END':([5,6,20,63,65,66,68,69,72,77,78,79,80,81,91,100,101,103,104,105,107,109,110,111,114,116,117,119,120,121,122,124,125,160,161,163,165,167,170,171,172,174,175,176,177,180,181,182,183,184,185,187,188,189,190,191,192,203,204,205,208,209,210,212,215,216,228,229,230,231,233,234,235,236,239,241,243,244,247,256,258,260,265,266,267,268,269,274,275,276,281,282,283,287,288,292,297,298,299,303,304,305,309,310,312,319,320,321,325,326,327,328,331,332,333,334,336,337,340,342,346,348,352,354,357,359,362,369,371,372,378,381,386,387,389,390,391,392,393,397,398,399,401,402,405,406,407,408,410,414,415,416,417,419,420,422,423,426,427,],[-245,-246,-11,-222,-215,-217,-212,-219,-213,-220,-218,-214,-221,-216,-248,-37,-57,-45,-46,-55,-31,-29,-248,-48,-49,-56,-35,-54,-32,-52,-44,-47,-43,-147,228,-142,-136,-131,-143,-140,-141,-129,-138,-150,-145,-148,-139,-130,-144,-137,-149,-172,-146,-164,-133,-135,-163,-36,-30,-53,-69,274,276,-80,-90,-91,-127,-248,-205,-208,-206,-202,-198,-207,-200,-209,-162,-197,-165,-248,-179,-171,-51,-87,-88,-62,-63,-65,-248,-67,-50,-64,-89,-128,-204,-225,-248,-211,-223,-161,-170,-248,-132,-134,-248,-68,362,-70,-199,-201,-210,-224,-203,-153,-152,-166,-157,-156,-186,369,-151,-131,-158,-173,-74,-78,-66,-180,392,-248,-248,-248,-79,-58,-248,-188,-185,-181,-187,-248,-160,-159,-248,-248,-73,414,-189,-248,-131,-182,423,-155,-154,-248,-75,-77,-183,-248,-76,]),'STRING':([6,24,42,61,64,67,71,76,82,98,126,127,128,129,130,131,133,134,135,136,137,138,139,140,141,142,143,144,162,168,186,202,206,213,218,232,237,238,242,245,246,261,277,289,290,296,307,308,311,317,323,329,330,335,347,353,355,356,363,368,370,371,373,374,375,376,386,400,403,418,],[-246,-247,72,107,72,-34,-33,72,72,107,-237,-233,72,-234,-235,-236,72,-241,72,-239,-243,-238,-232,-240,-242,-230,-244,-231,72,72,72,107,107,107,107,72,72,72,72,72,72,72,107,72,72,72,107,72,72,107,107,72,72,72,72,72,72,72,107,107,107,-246,107,72,-193,-192,107,72,72,72,]),'FOR':([6,91,178,229,256,297,305,312,372,378,381,389,390,397,401,402,407,408,419,426,],[-246,169,169,169,169,169,169,349,169,169,349,169,-188,349,349,349,-189,169,349,349,]),'UPARROW':([5,61,98,164,187,189,192,218,233,243,247,250,251,277,304,334,338,363,],[-245,115,115,247,-162,-164,-163,115,247,-162,-165,247,-162,115,-170,-166,247,115,]),'ELSE':([5,20,63,65,66,68,69,72,77,78,79,80,81,160,163,170,171,172,176,177,180,183,185,187,188,189,191,192,228,230,231,233,234,235,236,239,241,243,244,247,256,258,260,288,292,297,298,299,303,304,305,310,312,325,326,327,328,331,332,334,336,346,348,354,369,378,381,392,397,398,401,402,408,410,414,416,419,423,426,],[-245,-11,-222,-215,-217,-212,-219,-213,-220,-218,-214,-221,-216,-147,-142,-143,-140,-141,-150,-145,-148,-144,-149,-172,-146,-164,-135,-163,-127,-205,-208,-206,-202,-198,-207,-200,-209,-162,-197,-165,-248,-179,-171,-204,-225,-248,-211,-223,-161,-170,-248,-134,-248,-199,-201,-210,-224,-203,-153,-166,-157,-151,378,-173,-180,-248,-248,-181,-248,-160,-248,-248,-248,419,-182,-155,-248,-183,-248,]),'GE':([5,62,63,65,66,68,69,70,72,73,74,75,77,78,79,80,81,83,132,146,189,192,219,220,222,230,231,233,234,235,236,239,241,243,247,288,292,298,299,304,326,327,328,331,334,354,],[-245,-19,-222,-215,-217,-212,-219,137,-213,-24,-27,-21,-220,-218,-214,-221,-216,-25,-23,-28,-164,-163,-22,-20,-26,-205,-208,-206,-202,137,-207,-200,-209,-162,-165,-204,-225,-211,-223,-170,-201,-210,-224,-203,-166,-173,]),'SET':([61,98,106,218,277,363,],[108,108,108,108,108,108,]),'LPAREN':([4,5,24,42,46,61,64,67,71,76,82,92,94,98,126,127,128,129,130,131,133,134,135,136,137,138,139,140,141,142,143,144,162,168,186,187,206,213,218,223,232,237,238,242,243,245,246,261,277,289,290,296,308,311,323,329,330,335,347,353,355,356,363,374,375,376,385,400,403,418,],[8,-245,-247,76,88,118,76,-34,-33,76,76,88,-117,118,-237,-233,76,-234,-235,-236,76,-241,76,-239,-243,-238,-232,-240,-242,-230,-244,-231,237,237,237,261,118,118,118,88,237,237,237,237,261,237,237,237,118,237,237,237,237,237,118,237,237,237,237,237,237,237,118,237,-193,-192,404,237,237,237,]),'IN':([5,62,63,65,66,68,69,70,72,73,74,75,77,78,79,80,81,83,132,146,189,192,219,220,222,230,231,233,234,235,236,239,241,243,247,288,292,298,299,304,326,327,328,331,334,354,],[-245,-19,-222,-215,-217,-212,-219,143,-213,-24,-27,-21,-220,-218,-214,-221,-216,-25,-23,-28,-164,-163,-22,-20,-26,-205,-208,-206,-202,143,-207,-200,-209,-162,-165,-204,-225,-211,-223,-170,-201,-210,-224,-203,-166,-173,]),'VAR':([6,7,9,10,15,17,25,27,28,29,31,33,38,39,41,60,88,93,95,96,147,214,225,],[-246,-248,-8,-248,-248,-13,36,-39,-12,-15,-7,-248,-41,-38,-14,-40,154,-248,-248,-248,-16,-42,154,]),'UNTIL':([5,6,20,63,65,66,68,69,72,77,78,79,80,81,160,163,165,167,170,171,172,174,175,176,177,178,180,181,182,183,184,185,187,188,189,190,191,192,228,229,230,231,233,234,235,236,239,241,243,244,247,256,257,258,260,287,288,292,297,298,299,303,304,305,309,310,312,325,326,327,328,331,332,333,334,336,337,346,348,352,354,369,378,381,392,397,398,399,401,402,408,410,414,416,417,419,423,426,],[-245,-246,-11,-222,-215,-217,-212,-219,-213,-220,-218,-214,-221,-216,-147,-142,-136,-131,-143,-140,-141,-129,-138,-150,-145,-248,-148,-139,-130,-144,-137,-149,-172,-146,-164,-133,-135,-163,-127,-248,-205,-208,-206,-202,-198,-207,-200,-209,-162,-197,-165,-248,311,-179,-171,-128,-204,-225,-248,-211,-223,-161,-170,-248,-132,-134,-248,-199,-201,-210,-224,-203,-153,-152,-166,-157,-156,-151,-131,-158,-173,-180,-248,-248,-181,-248,-160,-159,-248,-248,-248,-131,-182,-155,-154,-248,-183,-248,]),'PROCEDURE':([6,7,9,10,15,17,25,27,28,29,31,33,35,37,38,39,41,60,86,88,93,95,96,97,147,214,225,],[-246,-248,-8,-248,-248,-13,-248,-39,-12,-15,-7,-248,52,-93,-41,-38,-14,-40,52,52,-248,-248,-248,-92,-16,-42,52,]),'IF':([6,91,178,229,256,297,305,312,372,378,381,389,390,397,401,402,407,408,419,426,],[-246,186,186,186,186,186,186,353,186,186,353,186,-188,353,353,353,-189,186,353,353,]),'AND':([5,62,63,65,66,68,69,72,73,74,75,77,78,79,80,81,83,132,146,189,192,219,220,222,230,231,233,234,236,239,241,243,247,288,292,298,299,304,326,327,328,331,334,354,],[-245,126,-222,-215,-217,-212,-219,-213,-24,-27,-21,-220,-218,-214,-221,-216,-25,-23,-28,-164,-163,-22,126,-26,-205,-208,-206,-202,-207,126,-209,-162,-165,-204,-225,-211,-223,-170,126,-210,-224,-203,-166,-173,]),'OCTDIGSEQ':([24,42,64,67,71,76,82,126,127,128,129,130,131,133,134,135,136,137,138,139,140,141,142,143,144,162,168,186,232,237,238,242,245,246,261,289,290,296,308,311,329,330,335,347,353,355,356,374,375,376,400,403,418,],[-247,77,77,-34,-33,77,77,-237,-233,77,-234,-235,-236,77,-241,77,-239,-243,-238,-232,-240,-242,-230,-244,-231,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,-193,-192,77,77,77,]),'LBRAC':([5,24,67,71,112,126,127,129,130,131,134,136,137,138,139,140,141,142,143,144,162,164,168,186,187,189,192,232,233,237,238,242,243,245,246,247,250,251,261,289,290,296,304,308,311,329,330,334,335,338,347,353,355,356,374,375,376,400,403,418,],[-245,-247,-34,-33,213,-237,-233,-234,-235,-236,-241,-239,-243,-238,-232,-240,-242,-230,-244,-231,238,245,238,238,-162,-164,-163,238,245,238,238,238,-162,238,238,-165,245,-162,238,238,238,238,-170,238,238,238,238,-166,238,245,238,238,238,238,238,-193,-192,238,238,238,]),'NIL':([24,42,64,67,71,76,82,126,127,128,129,130,131,133,134,135,136,137,138,139,140,141,142,143,144,162,168,186,232,237,238,242,245,246,261,289,290,296,308,311,329,330,335,347,353,355,356,374,375,376,400,403,418,],[-247,79,79,-34,-33,79,79,-237,-233,79,-234,-235,-236,79,-241,79,-239,-243,-238,-232,-240,-242,-230,-244,-231,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,-193,-192,79,79,79,]),'PFILE':([61,98,106,218,277,363,],[123,123,123,123,123,123,]),'OF':([5,63,65,66,68,69,72,77,78,79,80,81,108,123,189,192,230,231,233,234,235,236,239,241,243,247,252,253,270,271,273,288,292,298,299,304,322,325,326,327,328,331,334,354,360,361,],[-245,-222,-215,-217,-212,-219,-213,-220,-218,-214,-221,-216,206,218,-164,-163,-205,-208,-206,-202,-198,-207,-200,-209,-162,-165,307,-184,317,-86,-72,-204,-225,-211,-223,-170,363,-199,-201,-210,-224,-203,-166,-173,-86,-71,]),'DOWNTO':([5,63,65,66,68,69,72,77,78,79,80,81,189,192,230,231,233,234,235,236,239,241,243,247,288,292,298,299,304,325,326,327,328,331,334,344,345,354,409,],[-245,-222,-215,-217,-212,-219,-213,-220,-218,-214,-221,-216,-164,-163,-205,-208,-206,-202,-198,-207,-200,-209,-162,-165,-204,-225,-211,-223,-170,-199,-201,-210,-224,-203,-166,375,-191,-173,375,]),'BINDIGSEQ':([24,42,64,67,71,76,82,126,127,128,129,130,131,133,134,135,136,137,138,139,140,141,142,143,144,162,168,186,232,237,238,242,245,246,261,289,290,296,308,311,329,330,335,347,353,355,356,374,375,376,400,403,418,],[-247,80,80,-34,-33,80,80,-237,-233,80,-234,-235,-236,80,-241,80,-239,-243,-238,-232,-240,-242,-230,-244,-231,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,-193,-192,80,80,80,]),'NOT':([24,42,64,67,71,76,82,126,127,128,129,130,131,133,134,135,136,137,138,139,140,141,142,143,144,162,168,186,232,237,238,242,245,246,261,289,290,296,308,311,329,330,335,347,353,355,356,374,375,376,400,403,418,],[-247,82,82,-34,-33,82,82,-237,-233,82,-234,-235,-236,82,-241,82,-239,-243,-238,-232,-240,-242,-230,-244,-231,242,242,242,242,242,242,242,242,242,242,242,242,242,242,242,242,242,242,242,242,242,242,242,-193,-192,242,242,242,]),'DIGSEQ':([6,11,24,32,42,61,64,67,71,76,82,91,98,102,126,127,128,129,130,131,133,134,135,136,137,138,139,140,141,142,143,144,162,168,178,179,186,202,206,213,218,229,232,237,238,242,245,246,261,277,289,290,296,297,305,307,308,311,312,317,323,329,330,335,347,353,355,356,363,368,370,371,372,373,374,375,376,378,386,389,390,397,400,401,402,403,407,408,418,419,426,],[-246,20,-247,20,78,117,78,-34,-33,78,78,20,117,117,-237,-233,78,-234,-235,-236,78,-241,78,-239,-243,-238,-232,-240,-242,-230,-244,-231,78,78,20,20,78,117,117,117,117,20,78,78,78,78,78,78,78,117,78,78,78,20,20,117,78,78,20,117,117,78,78,78,78,78,78,78,117,117,117,-246,20,117,78,-193,-192,20,117,20,-188,20,78,20,20,78,-189,20,78,20,20,]),'TYPE':([6,7,9,10,15,17,28,29,31,33,41,93,95,96,147,],[-246,-248,-8,-248,26,-13,-12,-15,-7,-248,-14,-248,-248,-248,-16,]),'OR':([5,62,63,65,66,68,69,70,72,73,74,75,77,78,79,80,81,83,132,146,189,192,219,220,221,222,230,231,233,234,235,236,239,241,243,247,288,292,298,299,304,325,326,327,328,331,334,354,],[-245,-19,-222,-215,-217,-212,-219,139,-213,-24,-27,-21,-220,-218,-214,-221,-216,-25,-23,-28,-164,-163,-22,-20,139,-26,-205,-208,-206,-202,139,-207,-200,-209,-162,-165,-204,-225,-211,-223,-170,139,-201,-210,-224,-203,-166,-173,]),'MOD':([5,62,63,65,66,68,69,72,73,74,75,77,78,79,80,81,83,132,146,189,192,219,220,222,230,231,233,234,236,239,241,243,247,288,292,298,299,304,326,327,328,331,334,354,],[-245,131,-222,-215,-217,-212,-219,-213,-24,-27,-21,-220,-218,-214,-221,-216,-25,-23,-28,-164,-163,-22,131,-26,-205,-208,-206,-202,-207,131,-209,-162,-165,-204,-225,-211,-223,-170,131,-210,-224,-203,-166,-173,]),}
_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 = {'cterm':([42,76,133,135,],[62,62,220,62,]),'file_type':([61,98,106,218,277,363,],[101,101,101,101,101,101,]),'variable_declaration_part':([25,],[35,]),'closed_if_statement':([91,178,229,256,297,305,312,372,378,381,389,397,401,402,408,419,426,],[160,160,160,160,160,160,160,160,160,160,160,160,160,160,160,160,160,]),'new_type':([61,98,218,277,363,],[122,122,122,122,122,]),'comma':([14,18,58,155,211,217,226,249,280,293,300,313,343,358,380,],[23,32,23,23,23,23,23,306,323,329,335,355,373,373,306,]),'closed_statement':([91,178,229,297,305,312,372,378,389,397,401,402,408,419,426,],[167,167,167,332,336,348,167,398,167,332,336,410,416,398,416,]),'otherwisepart':([370,],[389,]),'final_value':([374,418,],[395,424,]),'field_designator':([91,162,166,168,178,186,229,232,237,238,242,245,246,256,261,289,290,296,297,305,306,308,311,312,329,330,335,347,350,353,355,356,372,374,378,381,389,397,400,401,402,403,408,418,419,426,],[189,189,189,189,189,189,189,189,189,189,189,189,189,189,189,189,189,189,189,189,189,189,189,189,189,189,189,189,189,189,189,189,189,189,189,189,189,189,189,189,189,189,189,189,189,189,]),'procedure_statement':([91,178,229,256,297,305,312,372,378,381,389,397,401,402,408,419,426,],[172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,172,]),'index_type':([213,323,],[278,364,]),'enumerated_type':([61,98,206,213,218,277,323,363,],[111,111,111,111,111,111,111,111,]),'program':([0,],[1,]),'variable_parameter_specification':([88,225,],[150,150,]),'type_definition_list':([26,],[39,]),'formal_parameter_list':([46,92,223,],[87,193,193,]),'formal_parameter_section_list':([88,],[153,]),'index_expression_list':([245,],[300,]),'index_list':([213,],[280,]),'domain_type':([115,],[215,]),'cfactor':([42,64,76,128,133,135,],[75,132,75,219,75,75,]),'case_list_element':([307,370,],[340,391,]),'case_constant':([307,317,370,373,386,],[341,341,341,394,341,]),'case_list_element_list':([307,],[342,]),'type_definition':([26,39,],[38,60,]),'term':([162,168,186,237,238,245,246,261,289,290,308,311,329,330,335,347,353,355,356,374,400,403,418,],[239,239,239,239,239,239,239,239,239,326,239,239,239,239,239,239,239,239,239,239,239,239,239,]),'closed_with_statement':([91,178,229,256,297,305,312,372,378,381,389,397,401,402,408,419,426,],[188,188,188,188,188,188,188,188,188,188,188,188,188,188,188,188,188,]),'record_type':([61,98,106,218,277,363,],[105,105,105,105,105,105,]),'boolean_expression':([162,186,311,347,353,],[240,259,346,377,382,]),'actual_parameter':([261,355,],[314,383,]),'identifier':([3,8,16,23,26,28,36,39,42,50,52,61,64,76,82,88,91,97,98,102,110,115,118,128,133,135,151,154,162,166,168,169,178,186,194,202,206,207,213,218,225,227,229,232,237,238,242,245,246,248,256,261,262,275,277,285,289,290,296,297,305,306,307,308,311,312,317,318,323,329,330,335,347,349,350,353,355,356,363,368,370,372,373,374,378,381,386,389,397,400,401,402,403,404,408,418,419,421,426,],[4,13,30,34,40,30,13,40,83,92,94,125,83,83,83,13,187,13,125,203,13,216,13,83,83,83,223,13,243,251,243,255,187,243,263,203,269,271,269,125,13,286,187,243,243,243,243,243,243,304,187,243,263,13,125,324,243,243,243,187,187,251,203,243,243,187,203,360,269,243,243,243,243,255,251,243,243,243,125,203,203,187,203,243,187,187,203,187,187,243,187,187,243,13,187,243,187,13,187,]),'unsigned_integer':([42,64,76,82,128,133,135,162,168,186,232,237,238,242,245,246,261,289,290,296,308,311,329,330,335,347,353,355,356,374,400,403,418,],[81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,]),'actual_parameter_list':([261,],[313,]),'label_list':([11,],[18,]),'sign':([42,61,64,76,98,128,133,135,162,168,186,202,206,213,218,232,237,238,245,246,261,277,289,290,296,307,308,311,317,323,329,330,335,347,353,355,356,363,368,370,373,374,386,400,403,418,],[64,102,64,64,102,64,64,64,232,232,232,102,102,102,102,232,232,232,232,232,232,102,232,232,232,102,232,232,102,102,232,232,232,232,232,232,232,102,102,102,102,232,102,232,232,232,]),'procedure_identification':([35,86,88,225,],[46,46,46,46,]),'goto_statement':([91,178,229,256,297,305,312,372,378,381,389,397,401,402,408,419,426,],[163,163,163,163,163,163,163,163,163,163,163,163,163,163,163,163,163,]),'unsigned_real':([42,64,76,82,128,133,135,162,168,186,232,237,238,242,245,246,261,289,290,296,308,311,329,330,335,347,353,355,356,374,400,403,418,],[66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,]),'open_with_statement':([91,178,229,256,297,305,312,372,378,381,389,397,401,402,408,419,426,],[165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,165,]),'tag_field':([207,],[272,]),'simple_expression':([162,168,186,237,238,245,246,261,289,308,311,329,330,335,347,353,355,356,374,400,403,418,],[235,235,235,235,235,235,235,235,325,235,235,235,235,235,235,235,235,235,235,235,235,235,]),'constant_definition_part':([10,],[15,]),'ordinal_type':([206,213,323,],[267,279,279,]),'compound_statement':([47,91,178,229,256,297,305,312,372,378,381,389,397,401,402,408,419,426,],[90,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,170,]),'member_designator_list':([238,],[293,]),'statement_part':([47,],[89,]),'label':([11,32,91,178,179,229,297,305,312,372,378,389,397,401,402,408,419,426,],[19,43,173,173,258,173,173,173,351,173,173,173,351,351,351,173,351,351,]),'proc_or_func_declaration':([35,86,],[48,148,]),'unsigned_number':([42,64,76,82,128,133,135,162,168,186,232,237,238,242,245,246,261,289,290,296,308,311,329,330,335,347,353,355,356,374,400,403,418,],[68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,]),'type_denoter':([61,98,218,277,363,],[113,201,282,321,282,]),'procedural_parameter_specification':([88,225,],[152,152,]),'closed_while_statement':([91,178,229,256,297,305,312,372,378,381,389,397,401,402,408,419,426,],[180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,180,]),'cprimary':([42,64,76,82,128,133,135,],[73,73,73,146,73,73,73,]),'open_for_statement':([91,178,229,256,297,305,312,372,378,381,389,397,401,402,408,419,426,],[181,181,181,181,181,181,181,181,181,181,181,181,181,181,181,181,181,]),'record_variable_list':([166,350,],[249,380,]),'set_type':([61,98,106,218,277,363,],[116,116,116,116,116,116,]),'case_statement':([91,178,229,256,297,305,312,372,378,381,389,397,401,402,408,419,426,],[183,183,183,183,183,183,183,183,183,183,183,183,183,183,183,183,183,]),'open_if_statement':([91,178,229,256,297,305,312,372,378,381,389,397,401,402,408,419,426,],[184,184,184,184,184,184,184,184,184,184,184,184,184,184,184,184,184,]),'array_type':([61,98,106,218,277,363,],[119,119,119,119,119,119,]),'case_index':([168,],[252,]),'type_definition_part':([15,],[25,]),'constant_list':([16,],[28,]),'function_declaration':([35,86,],[54,54,]),'component_type':([218,363,],[283,387,]),'function_heading':([35,86,88,225,],[56,56,158,158,]),'label_declaration_part':([7,33,93,95,96,],[10,10,10,10,10,]),'expression':([162,168,186,237,238,245,246,261,308,311,329,330,335,347,353,355,356,374,400,403,418,],[244,253,244,291,295,302,303,315,345,244,295,366,302,244,244,315,384,396,345,411,396,]),'new_pointer_type':([61,98,218,277,363,],[124,124,124,124,124,]),'index_expression':([245,335,],[301,367,]),'mulop':([62,220,239,326,],[128,128,296,296,]),'statement_sequence':([91,178,],[161,257,]),'cexpression':([42,76,],[84,145,]),'indexed_variable':([91,162,166,168,178,186,229,232,237,238,242,245,246,256,261,289,290,296,297,305,306,308,311,312,329,330,335,347,350,353,355,356,372,374,378,381,389,397,400,401,402,403,408,418,419,426,],[192,192,192,192,192,192,192,192,192,192,192,192,192,192,192,192,192,192,192,192,192,192,192,192,192,192,192,192,192,192,192,192,192,192,192,192,192,192,192,192,192,192,192,192,192,192,]),'primary':([162,168,186,232,237,238,242,245,246,261,289,290,296,308,311,329,330,335,347,353,355,356,374,400,403,418,],[230,230,230,230,230,230,298,230,230,230,230,230,230,230,230,230,230,230,230,230,230,230,230,230,230,230,]),'control_variable':([169,349,],[254,379,]),'constant_definition':([16,28,],[29,41,]),'set_constructor':([162,168,186,232,237,238,242,245,246,261,289,290,296,308,311,329,330,335,347,353,355,356,374,400,403,418,],[241,241,241,241,241,241,241,241,241,241,241,241,241,241,241,241,241,241,241,241,241,241,241,241,241,241,]),'proc_or_func_declaration_list':([35,],[45,]),'value_parameter_specification':([88,225,],[149,149,]),'variable_declaration':([36,97,],[59,200,]),'assignment_statement':([91,178,229,256,297,305,312,372,378,381,389,397,401,402,408,419,426,],[171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,]),'params':([187,243,],[260,299,]),'statement':([91,178,229,312,372,389,402,],[174,174,287,352,393,406,352,]),'csimple_expression':([42,76,135,],[70,70,221,]),'non_labeled_open_statement':([91,178,229,256,297,305,312,372,378,381,389,397,401,402,408,419,426,],[190,190,190,309,190,190,190,190,190,309,190,190,190,190,190,190,190,]),'empty':([7,10,15,25,33,35,91,93,95,96,110,178,229,256,275,297,305,312,372,378,381,389,397,401,402,404,408,419,421,426,],[9,17,27,37,9,49,176,9,9,9,212,176,176,176,212,176,176,176,176,176,176,176,176,176,176,212,176,176,212,176,]),'repeat_statement':([91,178,229,256,297,305,312,372,378,381,389,397,401,402,408,419,426,],[177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,177,]),'addop':([70,221,235,325,],[133,133,290,290,]),'direction':([344,409,],[374,418,]),'subrange_type':([61,98,206,213,218,277,323,363,],[114,114,114,114,114,114,114,114,]),'factor':([162,168,186,232,237,238,245,246,261,289,290,296,308,311,329,330,335,347,353,355,356,374,400,403,418,],[234,234,234,288,234,234,234,234,234,234,234,331,234,234,234,234,234,234,234,234,234,234,234,234,234,]),'open_statement':([91,178,229,297,305,312,372,378,389,397,401,402,408,419,426,],[182,182,182,333,337,182,182,399,182,333,337,182,417,399,417,]),'record_section_list':([110,404,],[209,412,]),'variable_declaration_list':([36,],[57,]),'closed_for_statement':([91,178,229,256,297,305,312,372,378,381,389,397,401,402,408,419,426,],[185,185,185,185,185,185,185,185,185,185,185,185,185,185,185,185,185,]),'new_ordinal_type':([61,98,206,213,218,277,323,363,],[103,103,268,268,103,103,268,103,]),'procedure_heading':([35,86,88,225,],[53,53,156,156,]),'record_section':([110,275,404,421,],[208,319,208,319,]),'procedure_declaration':([35,86,],[55,55,]),'initial_value':([308,400,],[344,409,]),'variant_list':([317,],[359,]),'non_labeled_closed_statement':([91,178,229,256,297,305,312,372,378,381,389,397,401,402,408,419,426,],[191,191,191,310,191,191,191,191,191,310,191,191,191,191,191,191,191,]),'functional_parameter_specification':([88,225,],[157,157,]),'constant':([61,98,202,206,213,218,277,307,317,323,363,368,370,373,386,],[99,99,265,99,99,99,99,339,339,99,99,388,339,339,339,]),'semicolon':([4,18,22,45,51,53,56,57,84,113,153,161,209,257,342,359,412,],[7,31,33,86,93,95,96,97,147,214,225,229,275,229,370,386,421,]),'function_designator':([162,168,186,232,237,238,242,245,246,261,289,290,296,308,311,329,330,335,347,353,355,356,374,400,403,418,],[231,231,231,231,231,231,231,231,231,231,231,231,231,231,231,231,231,231,231,231,231,231,231,231,231,231,]),'new_structured_type':([61,98,218,277,363,],[104,104,104,104,104,]),'file':([0,],[2,]),'variant_selector':([207,],[270,]),'procedure_and_function_declaration_part':([35,],[47,]),'non_string':([61,98,102,202,206,213,218,277,307,317,323,363,368,370,373,386,],[109,109,204,109,109,109,109,109,109,109,109,109,109,109,109,109,]),'variable_access':([91,162,166,168,178,186,229,232,237,238,242,245,246,256,261,289,290,296,297,305,306,308,311,312,329,330,335,347,350,353,355,356,372,374,378,381,389,397,400,401,402,403,408,418,419,426,],[164,233,250,233,164,233,164,233,233,233,233,233,233,164,233,233,233,233,164,164,338,233,233,164,233,233,233,233,250,233,233,233,164,233,164,164,164,164,233,164,164,233,164,233,164,164,]),'base_type':([206,],[266,]),'member_designator':([238,329,],[294,365,]),'structured_type':([61,98,106,218,277,363,],[121,121,205,121,121,121,]),'open_while_statement':([91,178,229,256,297,305,312,372,378,381,389,397,401,402,408,419,426,],[175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,175,]),'procedure_block':([95,],[197,]),'variant':([317,386,],[357,405,]),'unsigned_constant':([42,64,76,82,128,133,135,162,168,186,232,237,238,242,245,246,261,289,290,296,308,311,329,330,335,347,353,355,356,374,400,403,418,],[74,74,74,74,74,74,74,236,236,236,236,236,236,236,236,236,236,236,236,236,236,236,236,236,236,236,236,236,236,236,236,236,236,]),'function_identification':([35,86,],[51,51,]),'variant_part':([110,275,404,421,],[210,320,413,425,]),'function_block':([93,96,],[195,199,]),'identifier_list':([8,36,88,97,110,118,154,225,275,404,421,],[14,58,155,58,211,217,226,155,211,211,211,]),'case_constant_list':([307,317,370,386,],[343,358,343,358,]),'relop':([70,235,],[135,289,]),'formal_parameter_section':([88,225,],[159,284,]),'block':([7,33,93,95,96,],[12,44,196,198,196,]),'result_type':([194,262,],[264,316,]),'tag_type':([207,318,],[273,361,]),}
_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' -> file","S'",1,None,None,None),
('file -> program','file',1,'p_file_1','parser.py',57),
('program -> PROGRAM identifier LPAREN identifier_list RPAREN semicolon block DOT','program',8,'p_program_1','parser.py',63),
('program -> PROGRAM identifier semicolon block DOT','program',5,'p_program_2','parser.py',70),
('identifier_list -> identifier_list comma identifier','identifier_list',3,'p_identifier_list_1','parser.py',76),
('identifier_list -> identifier','identifier_list',1,'p_identifier_list_2','parser.py',82),
('block -> label_declaration_part constant_definition_part type_definition_part variable_declaration_part procedure_and_function_declaration_part statement_part','block',6,'p_block_1','parser.py',88),
('label_declaration_part -> LABEL label_list semicolon','label_declaration_part',3,'p_label_declaration_part_1','parser.py',94),
('label_declaration_part -> empty','label_declaration_part',1,'p_label_declaration_part_2','parser.py',100),
('label_list -> label_list comma label','label_list',3,'p_label_list_1','parser.py',105),
('label_list -> label','label_list',1,'p_label_list_2','parser.py',111),
('label -> DIGSEQ','label',1,'p_label_1','parser.py',117),
('constant_definition_part -> CONST constant_list','constant_definition_part',2,'p_constant_definition_part_1','parser.py',123),
('constant_definition_part -> empty','constant_definition_part',1,'p_constant_definition_part_2','parser.py',128),
('constant_list -> constant_list constant_definition','constant_list',2,'p_constant_list_1','parser.py',133),
('constant_list -> constant_definition','constant_list',1,'p_constant_list_2','parser.py',139),
('constant_definition -> identifier EQUAL cexpression semicolon','constant_definition',4,'p_constant_definition_1','parser.py',145),
('cexpression -> csimple_expression','cexpression',1,'p_cexpression_1','parser.py',151),
('cexpression -> csimple_expression relop csimple_expression','cexpression',3,'p_cexpression_2','parser.py',156),
('csimple_expression -> cterm','csimple_expression',1,'p_csimple_expression_1','parser.py',162),
('csimple_expression -> csimple_expression addop cterm','csimple_expression',3,'p_csimple_expression_2','parser.py',167),
('cterm -> cfactor','cterm',1,'p_cterm_1','parser.py',173),
('cterm -> cterm mulop cfactor','cterm',3,'p_cterm_2','parser.py',178),
('cfactor -> sign cfactor','cfactor',2,'p_cfactor_1','parser.py',184),
('cfactor -> cprimary','cfactor',1,'p_cfactor_2','parser.py',190),
('cprimary -> identifier','cprimary',1,'p_cprimary_1','parser.py',195),
('cprimary -> LPAREN cexpression RPAREN','cprimary',3,'p_cprimary_2','parser.py',200),
('cprimary -> unsigned_constant','cprimary',1,'p_cprimary_3','parser.py',205),
('cprimary -> NOT cprimary','cprimary',2,'p_cprimary_4','parser.py',210),
('constant -> non_string','constant',1,'p_constant_1','parser.py',216),
('constant -> sign non_string','constant',2,'p_constant_2','parser.py',221),
('constant -> STRING','constant',1,'p_constant_3','parser.py',227),
('constant -> CHAR','constant',1,'p_constant_4','parser.py',233),
('sign -> PLUS','sign',1,'p_sign_1','parser.py',239),
('sign -> MINUS','sign',1,'p_sign_2','parser.py',244),
('non_string -> DIGSEQ','non_string',1,'p_non_string_1','parser.py',249),
('non_string -> identifier','non_string',1,'p_non_string_2','parser.py',255),
('non_string -> REALNUMBER','non_string',1,'p_non_string_3','parser.py',261),
('type_definition_part -> TYPE type_definition_list','type_definition_part',2,'p_type_definition_part_1','parser.py',267),
('type_definition_part -> empty','type_definition_part',1,'p_type_definition_part_2','parser.py',272),
('type_definition_list -> type_definition_list type_definition','type_definition_list',2,'p_type_definition_list_1','parser.py',277),
('type_definition_list -> type_definition','type_definition_list',1,'p_type_definition_list_2','parser.py',283),
('type_definition -> identifier EQUAL type_denoter semicolon','type_definition',4,'p_type_definition_1','parser.py',289),
('type_denoter -> identifier','type_denoter',1,'p_type_denoter_1','parser.py',295),
('type_denoter -> new_type','type_denoter',1,'p_type_denoter_2','parser.py',301),
('new_type -> new_ordinal_type','new_type',1,'p_new_type_1','parser.py',306),
('new_type -> new_structured_type','new_type',1,'p_new_type_2','parser.py',311),
('new_type -> new_pointer_type','new_type',1,'p_new_type_3','parser.py',316),
('new_ordinal_type -> enumerated_type','new_ordinal_type',1,'p_new_ordinal_type_1','parser.py',321),
('new_ordinal_type -> subrange_type','new_ordinal_type',1,'p_new_ordinal_type_2','parser.py',326),
('enumerated_type -> LPAREN identifier_list RPAREN','enumerated_type',3,'p_enumerated_type_1','parser.py',331),
('subrange_type -> constant DOTDOT constant','subrange_type',3,'p_subrange_type_1','parser.py',337),
('new_structured_type -> structured_type','new_structured_type',1,'p_new_structured_type_1','parser.py',343),
('new_structured_type -> PACKED structured_type','new_structured_type',2,'p_new_structured_type_2','parser.py',348),
('structured_type -> array_type','structured_type',1,'p_structured_type_1','parser.py',354),
('structured_type -> record_type','structured_type',1,'p_structured_type_2','parser.py',359),
('structured_type -> set_type','structured_type',1,'p_structured_type_3','parser.py',364),
('structured_type -> file_type','structured_type',1,'p_structured_type_4','parser.py',369),
('array_type -> ARRAY LBRAC index_list RBRAC OF component_type','array_type',6,'p_array_type_1','parser.py',375),
('index_list -> index_list comma index_type','index_list',3,'p_index_list_1','parser.py',381),
('index_list -> index_type','index_list',1,'p_index_list_2','parser.py',387),
('index_type -> ordinal_type','index_type',1,'p_index_type_1','parser.py',393),
('ordinal_type -> new_ordinal_type','ordinal_type',1,'p_ordinal_type_1','parser.py',398),
('ordinal_type -> identifier','ordinal_type',1,'p_ordinal_type_2','parser.py',403),
('component_type -> type_denoter','component_type',1,'p_component_type_1','parser.py',408),
('record_type -> RECORD record_section_list END','record_type',3,'p_record_type_1','parser.py',413),
('record_type -> RECORD record_section_list semicolon variant_part END','record_type',5,'p_record_type_2','parser.py',419),
('record_type -> RECORD variant_part END','record_type',3,'p_record_type_3','parser.py',425),
('record_section_list -> record_section_list semicolon record_section','record_section_list',3,'p_record_section_list_1','parser.py',431),
('record_section_list -> record_section','record_section_list',1,'p_record_section_list_2','parser.py',437),
('record_section -> identifier_list COLON type_denoter','record_section',3,'p_record_section_1','parser.py',443),
('variant_selector -> tag_field COLON tag_type','variant_selector',3,'p_variant_selector_1','parser.py',449),
('variant_selector -> tag_type','variant_selector',1,'p_variant_selector_2','parser.py',455),
('variant_list -> variant_list semicolon variant','variant_list',3,'p_variant_list_1','parser.py',461),
('variant_list -> variant','variant_list',1,'p_variant_list_2','parser.py',467),
('variant -> case_constant_list COLON LPAREN record_section_list RPAREN','variant',5,'p_variant_1','parser.py',473),
('variant -> case_constant_list COLON LPAREN record_section_list semicolon variant_part RPAREN','variant',7,'p_variant_2','parser.py',479),
('variant -> case_constant_list COLON LPAREN variant_part RPAREN','variant',5,'p_variant_3','parser.py',485),
('variant_part -> CASE variant_selector OF variant_list','variant_part',4,'p_variant_part_1','parser.py',491),
('variant_part -> CASE variant_selector OF variant_list semicolon','variant_part',5,'p_variant_part_2','parser.py',497),
('variant_part -> empty','variant_part',1,'p_variant_part_3','parser.py',503),
('case_constant_list -> case_constant_list comma case_constant','case_constant_list',3,'p_case_constant_list_1','parser.py',508),
('case_constant_list -> case_constant','case_constant_list',1,'p_case_constant_list_2','parser.py',514),
('case_constant -> constant','case_constant',1,'p_case_constant_1','parser.py',520),
('case_constant -> constant DOTDOT constant','case_constant',3,'p_case_constant_2','parser.py',526),
('tag_field -> identifier','tag_field',1,'p_tag_field_1','parser.py',532),
('tag_type -> identifier','tag_type',1,'p_tag_type_1','parser.py',537),
('set_type -> SET OF base_type','set_type',3,'p_set_type_1','parser.py',542),
('base_type -> ordinal_type','base_type',1,'p_base_type_1','parser.py',548),
('file_type -> PFILE OF component_type','file_type',3,'p_file_type_1','parser.py',553),
('new_pointer_type -> UPARROW domain_type','new_pointer_type',2,'p_new_pointer_type_1','parser.py',559),
('domain_type -> identifier','domain_type',1,'p_domain_type_1','parser.py',565),
('variable_declaration_part -> VAR variable_declaration_list semicolon','variable_declaration_part',3,'p_variable_declaration_part_1','parser.py',571),
('variable_declaration_part -> empty','variable_declaration_part',1,'p_variable_declaration_part_2','parser.py',576),
('variable_declaration_list -> variable_declaration_list semicolon variable_declaration','variable_declaration_list',3,'p_variable_declaration_list_1','parser.py',581),
('variable_declaration_list -> variable_declaration','variable_declaration_list',1,'p_variable_declaration_list_2','parser.py',587),
('variable_declaration -> identifier_list COLON type_denoter','variable_declaration',3,'p_variable_declaration_1','parser.py',593),
('procedure_and_function_declaration_part -> proc_or_func_declaration_list semicolon','procedure_and_function_declaration_part',2,'p_procedure_and_function_declaration_part_1','parser.py',599),
('procedure_and_function_declaration_part -> empty','procedure_and_function_declaration_part',1,'p_procedure_and_function_declaration_part_2','parser.py',604),
('proc_or_func_declaration_list -> proc_or_func_declaration_list semicolon proc_or_func_declaration','proc_or_func_declaration_list',3,'p_proc_or_func_declaration_list_1','parser.py',609),
('proc_or_func_declaration_list -> proc_or_func_declaration','proc_or_func_declaration_list',1,'p_proc_or_func_declaration_list_2','parser.py',615),
('proc_or_func_declaration -> procedure_declaration','proc_or_func_declaration',1,'p_proc_or_func_declaration_1','parser.py',621),
('proc_or_func_declaration -> function_declaration','proc_or_func_declaration',1,'p_proc_or_func_declaration_2','parser.py',626),
('procedure_declaration -> procedure_heading semicolon procedure_block','procedure_declaration',3,'p_procedure_declaration_1','parser.py',631),
('procedure_heading -> procedure_identification','procedure_heading',1,'p_procedure_heading_1','parser.py',637),
('procedure_heading -> procedure_identification formal_parameter_list','procedure_heading',2,'p_procedure_heading_2','parser.py',643),
('formal_parameter_list -> LPAREN formal_parameter_section_list RPAREN','formal_parameter_list',3,'p_formal_parameter_list_1','parser.py',649),
('formal_parameter_section_list -> formal_parameter_section_list semicolon formal_parameter_section','formal_parameter_section_list',3,'p_formal_parameter_section_list_1','parser.py',654),
('formal_parameter_section_list -> formal_parameter_section','formal_parameter_section_list',1,'p_formal_parameter_section_list_2','parser.py',660),
('formal_parameter_section -> value_parameter_specification','formal_parameter_section',1,'p_formal_parameter_section_1','parser.py',666),
('formal_parameter_section -> variable_parameter_specification','formal_parameter_section',1,'p_formal_parameter_section_2','parser.py',671),
('formal_parameter_section -> procedural_parameter_specification','formal_parameter_section',1,'p_formal_parameter_section_3','parser.py',676),
('formal_parameter_section -> functional_parameter_specification','formal_parameter_section',1,'p_formal_parameter_section_4','parser.py',681),
('value_parameter_specification -> identifier_list COLON identifier','value_parameter_specification',3,'p_value_parameter_specification_1','parser.py',686),
('variable_parameter_specification -> VAR identifier_list COLON identifier','variable_parameter_specification',4,'p_variable_parameter_specification_1','parser.py',693),
('procedural_parameter_specification -> procedure_heading','procedural_parameter_specification',1,'p_procedural_parameter_specification_1','parser.py',700),
('functional_parameter_specification -> function_heading','functional_parameter_specification',1,'p_functional_parameter_specification_1','parser.py',706),
('procedure_identification -> PROCEDURE identifier','procedure_identification',2,'p_procedure_identification_1','parser.py',712),
('procedure_block -> block','procedure_block',1,'p_procedure_block_1','parser.py',717),
('function_declaration -> function_identification semicolon function_block','function_declaration',3,'p_function_declaration_1','parser.py',723),
('function_declaration -> function_heading semicolon function_block','function_declaration',3,'p_function_declaration_2','parser.py',730),
('function_heading -> FUNCTION identifier COLON result_type','function_heading',4,'p_function_heading_1','parser.py',736),
('function_heading -> FUNCTION identifier formal_parameter_list COLON result_type','function_heading',5,'p_function_heading_2','parser.py',742),
('result_type -> identifier','result_type',1,'p_result_type_1','parser.py',748),
('function_identification -> FUNCTION identifier','function_identification',2,'p_function_identification_1','parser.py',754),
('function_block -> block','function_block',1,'p_function_block_1','parser.py',760),
('statement_part -> compound_statement','statement_part',1,'p_statement_part_1','parser.py',765),
('compound_statement -> PBEGIN statement_sequence END','compound_statement',3,'p_compound_statement_1','parser.py',770),
('statement_sequence -> statement_sequence semicolon statement','statement_sequence',3,'p_statement_sequence_1','parser.py',775),
('statement_sequence -> statement','statement_sequence',1,'p_statement_sequence_2','parser.py',781),
('statement -> open_statement','statement',1,'p_statement_1','parser.py',787),
('statement -> closed_statement','statement',1,'p_statement_2','parser.py',792),
('open_statement -> label COLON non_labeled_open_statement','open_statement',3,'p_open_statement_1','parser.py',797),
('open_statement -> non_labeled_open_statement','open_statement',1,'p_open_statement_2','parser.py',803),
('closed_statement -> label COLON non_labeled_closed_statement','closed_statement',3,'p_closed_statement_1','parser.py',808),
('closed_statement -> non_labeled_closed_statement','closed_statement',1,'p_closed_statement_2','parser.py',814),
('non_labeled_open_statement -> open_with_statement','non_labeled_open_statement',1,'p_non_labeled_open_statement_1','parser.py',819),
('non_labeled_open_statement -> open_if_statement','non_labeled_open_statement',1,'p_non_labeled_open_statement_2','parser.py',824),
('non_labeled_open_statement -> open_while_statement','non_labeled_open_statement',1,'p_non_labeled_open_statement_3','parser.py',829),
('non_labeled_open_statement -> open_for_statement','non_labeled_open_statement',1,'p_non_labeled_open_statement_4','parser.py',834),
('non_labeled_closed_statement -> assignment_statement','non_labeled_closed_statement',1,'p_non_labeled_closed_statement','parser.py',840),
('non_labeled_closed_statement -> procedure_statement','non_labeled_closed_statement',1,'p_non_labeled_closed_statement','parser.py',841),
('non_labeled_closed_statement -> goto_statement','non_labeled_closed_statement',1,'p_non_labeled_closed_statement','parser.py',842),
('non_labeled_closed_statement -> compound_statement','non_labeled_closed_statement',1,'p_non_labeled_closed_statement','parser.py',843),
('non_labeled_closed_statement -> case_statement','non_labeled_closed_statement',1,'p_non_labeled_closed_statement','parser.py',844),
('non_labeled_closed_statement -> repeat_statement','non_labeled_closed_statement',1,'p_non_labeled_closed_statement','parser.py',845),
('non_labeled_closed_statement -> closed_with_statement','non_labeled_closed_statement',1,'p_non_labeled_closed_statement','parser.py',846),
('non_labeled_closed_statement -> closed_if_statement','non_labeled_closed_statement',1,'p_non_labeled_closed_statement','parser.py',847),
('non_labeled_closed_statement -> closed_while_statement','non_labeled_closed_statement',1,'p_non_labeled_closed_statement','parser.py',848),
('non_labeled_closed_statement -> closed_for_statement','non_labeled_closed_statement',1,'p_non_labeled_closed_statement','parser.py',849),
('non_labeled_closed_statement -> empty','non_labeled_closed_statement',1,'p_non_labeled_closed_statement','parser.py',850),
('repeat_statement -> REPEAT statement_sequence UNTIL boolean_expression','repeat_statement',4,'p_repeat_statement_1','parser.py',858),
('open_while_statement -> WHILE boolean_expression DO open_statement','open_while_statement',4,'p_open_while_statement_1','parser.py',864),
('closed_while_statement -> WHILE boolean_expression DO closed_statement','closed_while_statement',4,'p_closed_while_statement_1','parser.py',870),
('open_for_statement -> FOR control_variable ASSIGNMENT initial_value direction final_value DO open_statement','open_for_statement',8,'p_open_for_statement_1','parser.py',876),
('closed_for_statement -> FOR control_variable ASSIGNMENT initial_value direction final_value DO closed_statement','closed_for_statement',8,'p_closed_for_statement_1','parser.py',882),
('open_with_statement -> WITH record_variable_list DO open_statement','open_with_statement',4,'p_open_with_statement_1','parser.py',888),
('closed_with_statement -> WITH record_variable_list DO closed_statement','closed_with_statement',4,'p_closed_with_statement_1','parser.py',894),
('open_if_statement -> IF boolean_expression THEN statement','open_if_statement',4,'p_open_if_statement_1','parser.py',900),
('open_if_statement -> IF boolean_expression THEN closed_statement ELSE open_statement','open_if_statement',6,'p_open_if_statement_2','parser.py',906),
('closed_if_statement -> IF boolean_expression THEN closed_statement ELSE closed_statement','closed_if_statement',6,'p_closed_if_statement_1','parser.py',912),
('assignment_statement -> variable_access ASSIGNMENT expression','assignment_statement',3,'p_assignment_statement_1','parser.py',918),
('variable_access -> identifier','variable_access',1,'p_variable_access_1','parser.py',924),
('variable_access -> indexed_variable','variable_access',1,'p_variable_access_2','parser.py',930),
('variable_access -> field_designator','variable_access',1,'p_variable_access_3','parser.py',935),
('variable_access -> variable_access UPARROW','variable_access',2,'p_variable_access_4','parser.py',940),
('indexed_variable -> variable_access LBRAC index_expression_list RBRAC','indexed_variable',4,'p_indexed_variable_1','parser.py',946),
('index_expression_list -> index_expression_list comma index_expression','index_expression_list',3,'p_index_expression_list_1','parser.py',952),
('index_expression_list -> index_expression','index_expression_list',1,'p_index_expression_list_2','parser.py',958),
('index_expression -> expression','index_expression',1,'p_index_expression_1','parser.py',964),
('field_designator -> variable_access DOT identifier','field_designator',3,'p_field_designator_1','parser.py',969),
('procedure_statement -> identifier params','procedure_statement',2,'p_procedure_statement_1','parser.py',975),
('procedure_statement -> identifier','procedure_statement',1,'p_procedure_statement_2','parser.py',981),
('params -> LPAREN actual_parameter_list RPAREN','params',3,'p_params_1','parser.py',987),
('actual_parameter_list -> actual_parameter_list comma actual_parameter','actual_parameter_list',3,'p_actual_parameter_list_1','parser.py',992),
('actual_parameter_list -> actual_parameter','actual_parameter_list',1,'p_actual_parameter_list_2','parser.py',998),
('actual_parameter -> expression','actual_parameter',1,'p_actual_parameter_1','parser.py',1004),
('actual_parameter -> expression COLON expression','actual_parameter',3,'p_actual_parameter_2','parser.py',1010),
('actual_parameter -> expression COLON expression COLON expression','actual_parameter',5,'p_actual_parameter_3','parser.py',1017),
('goto_statement -> GOTO label','goto_statement',2,'p_goto_statement_1','parser.py',1024),
('case_statement -> CASE case_index OF case_list_element_list END','case_statement',5,'p_case_statement_1','parser.py',1030),
('case_statement -> CASE case_index OF case_list_element_list SEMICOLON END','case_statement',6,'p_case_statement_2','parser.py',1037),
('case_statement -> CASE case_index OF case_list_element_list semicolon otherwisepart statement END','case_statement',8,'p_case_statement_3','parser.py',1044),
('case_statement -> CASE case_index OF case_list_element_list semicolon otherwisepart statement SEMICOLON END','case_statement',9,'p_case_statement_4','parser.py',1050),
('case_index -> expression','case_index',1,'p_case_index_1','parser.py',1056),
('case_list_element_list -> case_list_element_list semicolon case_list_element','case_list_element_list',3,'p_case_list_element_list_1','parser.py',1062),
('case_list_element_list -> case_list_element','case_list_element_list',1,'p_case_list_element_list_2','parser.py',1069),
('case_list_element -> case_constant_list COLON statement','case_list_element',3,'p_case_list_element_1','parser.py',1075),
('otherwisepart -> OTHERWISE','otherwisepart',1,'p_otherwisepart_1','parser.py',1081),
('otherwisepart -> OTHERWISE COLON','otherwisepart',2,'p_otherwisepart_2','parser.py',1086),
('control_variable -> identifier','control_variable',1,'p_control_variable_1','parser.py',1091),
('initial_value -> expression','initial_value',1,'p_initial_value_1','parser.py',1096),
('direction -> TO','direction',1,'p_direction_1','parser.py',1101),
('direction -> DOWNTO','direction',1,'p_direction_2','parser.py',1106),
('final_value -> expression','final_value',1,'p_final_value_1','parser.py',1111),
('record_variable_list -> record_variable_list comma variable_access','record_variable_list',3,'p_record_variable_list_1','parser.py',1116),
('record_variable_list -> variable_access','record_variable_list',1,'p_record_variable_list_2','parser.py',1122),
('boolean_expression -> expression','boolean_expression',1,'p_boolean_expression_1','parser.py',1128),
('expression -> simple_expression','expression',1,'p_expression_1','parser.py',1133),
('expression -> simple_expression relop simple_expression','expression',3,'p_expression_2','parser.py',1138),
('simple_expression -> term','simple_expression',1,'p_simple_expression_1','parser.py',1144),
('simple_expression -> simple_expression addop term','simple_expression',3,'p_simple_expression_2','parser.py',1149),
('term -> factor','term',1,'p_term_1','parser.py',1155),
('term -> term mulop factor','term',3,'p_term_2','parser.py',1160),
('factor -> sign factor','factor',2,'p_factor_1','parser.py',1166),
('factor -> primary','factor',1,'p_factor_2','parser.py',1172),
('primary -> variable_access','primary',1,'p_primary_1','parser.py',1177),
('primary -> unsigned_constant','primary',1,'p_primary_2','parser.py',1183),
('primary -> function_designator','primary',1,'p_primary_3','parser.py',1188),
('primary -> set_constructor','primary',1,'p_primary_4','parser.py',1193),
('primary -> LPAREN expression RPAREN','primary',3,'p_primary_5','parser.py',1198),
('primary -> NOT primary','primary',2,'p_primary_6','parser.py',1203),
('unsigned_constant -> unsigned_number','unsigned_constant',1,'p_unsigned_constant_1','parser.py',1209),
('unsigned_constant -> STRING','unsigned_constant',1,'p_unsigned_constant_2','parser.py',1214),
('unsigned_constant -> NIL','unsigned_constant',1,'p_unsigned_constant_3','parser.py',1220),
('unsigned_constant -> CHAR','unsigned_constant',1,'p_unsigned_constant_4','parser.py',1226),
('unsigned_number -> unsigned_integer','unsigned_number',1,'p_unsigned_number_1','parser.py',1232),
('unsigned_number -> unsigned_real','unsigned_number',1,'p_unsigned_number_2','parser.py',1237),
('unsigned_integer -> DIGSEQ','unsigned_integer',1,'p_unsigned_integer_1','parser.py',1242),
('unsigned_integer -> HEXDIGSEQ','unsigned_integer',1,'p_unsigned_integer_2','parser.py',1248),
('unsigned_integer -> OCTDIGSEQ','unsigned_integer',1,'p_unsigned_integer_3','parser.py',1254),
('unsigned_integer -> BINDIGSEQ','unsigned_integer',1,'p_unsigned_integer_4','parser.py',1260),
('unsigned_real -> REALNUMBER','unsigned_real',1,'p_unsigned_real_1','parser.py',1266),
('function_designator -> identifier params','function_designator',2,'p_function_designator_1','parser.py',1272),
('set_constructor -> LBRAC member_designator_list RBRAC','set_constructor',3,'p_set_constructor_1','parser.py',1278),
('set_constructor -> LBRAC RBRAC','set_constructor',2,'p_set_constructor_2','parser.py',1284),
('member_designator_list -> member_designator_list comma member_designator','member_designator_list',3,'p_member_designator_list_1','parser.py',1291),
('member_designator_list -> member_designator','member_designator_list',1,'p_member_designator_list_2','parser.py',1298),
('member_designator -> member_designator DOTDOT expression','member_designator',3,'p_member_designator_1','parser.py',1304),
('member_designator -> expression','member_designator',1,'p_member_designator_2','parser.py',1310),
('addop -> PLUS','addop',1,'p_addop_1','parser.py',1315),
('addop -> MINUS','addop',1,'p_addop_2','parser.py',1321),
('addop -> OR','addop',1,'p_addop_3','parser.py',1327),
('mulop -> STAR','mulop',1,'p_mulop_1','parser.py',1333),
('mulop -> SLASH','mulop',1,'p_mulop_2','parser.py',1339),
('mulop -> DIV','mulop',1,'p_mulop_3','parser.py',1345),
('mulop -> MOD','mulop',1,'p_mulop_4','parser.py',1351),
('mulop -> AND','mulop',1,'p_mulop_5','parser.py',1357),
('relop -> EQUAL','relop',1,'p_relop_1','parser.py',1363),
('relop -> NOTEQUAL','relop',1,'p_relop_2','parser.py',1369),
('relop -> LT','relop',1,'p_relop_3','parser.py',1375),
('relop -> GT','relop',1,'p_relop_4','parser.py',1381),
('relop -> LE','relop',1,'p_relop_5','parser.py',1387),
('relop -> GE','relop',1,'p_relop_6','parser.py',1393),
('relop -> IN','relop',1,'p_relop_7','parser.py',1399),
('identifier -> IDENTIFIER','identifier',1,'p_identifier_1','parser.py',1405),
('semicolon -> SEMICOLON','semicolon',1,'p_semicolon_1','parser.py',1411),
('comma -> COMMA','comma',1,'p_comma_1','parser.py',1416),
('empty -> <empty>','empty',0,'p_empty_1','parser.py',1429),
]
|
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http: // www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Const Class
# this is a auto generated file generated by Cheetah
# Libre Office Version: 7.3
# Namespace: com.sun.star.form
class FormComponentType(object):
"""
Const Class
These constants specify the class types used to identify a component.
See Also:
`API FormComponentType <https://api.libreoffice.org/docs/idl/ref/namespacecom_1_1sun_1_1star_1_1form_1_1FormComponentType.html>`_
"""
__ooo_ns__: str = 'com.sun.star.form'
__ooo_full_ns__: str = 'com.sun.star.form.FormComponentType'
__ooo_type_name__: str = 'const'
CONTROL = 1
"""
This generic identifier is for controls which cannot be identified by another specific identifier.
"""
COMMANDBUTTON = 2
"""
specifies a control that is used to begin, interrupt, or end a process.
"""
RADIOBUTTON = 3
"""
specifies a control that acts like a radio button.
Grouped together, such radio buttons present a set of two or more mutually exclusive choices to the user.
"""
IMAGEBUTTON = 4
"""
specifies a control that displays an image that responds to mouse clicks.
"""
CHECKBOX = 5
"""
specifies a control that is used to check or uncheck to turn an option on or off.
"""
LISTBOX = 6
"""
specifies a control that displays a list from which the user can select one or more items.
"""
COMBOBOX = 7
"""
specifies a control that is used when a list box combined with a static text control or an edit control is needed.
"""
GROUPBOX = 8
"""
specifies a control that displays a frame around a group of controls with or without a caption.
"""
TEXTFIELD = 9
"""
specifies a control that is a text component that allows for the editing of a single line of text.
"""
FIXEDTEXT = 10
"""
specifies a control to display a fixed text, usually used to label other controls.
"""
GRIDCONTROL = 11
"""
is a table like control to display database data.
"""
FILECONTROL = 12
"""
specifies a control which can be used to enter text, extended by an (user-startable) file dialog to browse for files.
"""
HIDDENCONTROL = 13
"""
specifies a control that should not be visible.
"""
IMAGECONTROL = 14
"""
specifies a control to display an image.
"""
DATEFIELD = 15
"""
specifies a control to display and edit a date value.
"""
TIMEFIELD = 16
"""
specifies a control to display and edit a time value.
"""
NUMERICFIELD = 17
"""
specifies a field to display and edit a numeric value.
"""
CURRENCYFIELD = 18
"""
specifies a field to display and edit a currency value.
"""
PATTERNFIELD = 19
"""
specifies a control to display and edit a string according to a pattern.
"""
SCROLLBAR = 20
"""
specifies a control to display and edit, in the form of a scrollbar, a value from a continuous value range
"""
SPINBUTTON = 21
"""
specifies a control to edit, in the form of a spin field, a value from a continuous range of values
"""
NAVIGATIONBAR = 22
"""
specifies a control which provides controller functionality for the com.sun.star.form.component.DataForm it belongs to, such as functionality to navigate or filter this form.
"""
__all__ = ['FormComponentType']
|
# program to display student's marks from record
student_n = 'Soyuj'
marks = {'James': 90, 'Jules': 55, 'Arthur': 77}
for student in marks:
if student == student_n:
print(marks[student])
break
else:
print('No entry with that name found.')
|
# COMPARANDO NÚMEROS
num1 = int(input("Primeiro valor: "))
num2 = int(input("Segundo valor: "))
print("-=" * 10)
if num1 > num2:
print("Primeiro valor MAIOR.")
elif num2 > num1:
print("Segundo valor MAIOR.")
else:
print("Os dois valores são iguais.")
|
def shouldAttack(target):
return target and target.type != "burl"
while True:
enemy = hero.findNearestEnemy()
if shouldAttack(enemy):
hero.attack(enemy)
|
# Author: Chaojie Wang <xd_silly@163.com>; Jiawen Wu <wjw19960807@163.com>; Wei Zhao <13279389260@163.com>
# License: BSD-3-Claus
class Params(object):
def __init__(self):
"""
The basic class for storing the parameters in the probabilistic model
"""
super(Params, self).__init__()
class Basic_Model(object):
def __init__(self, *args, **kwargs):
"""
The basic model for all probabilistic models in this package
Attributes:
@public:
global_params : [Params] the global parameters of the probabilistic model
local_params : [Params] the local parameters of the probabilistic model
@private:
_model_setting : [Params] the model settings of the probabilistic model
_hyper_params : [Params] the hyper parameters of the probabilistic model
"""
super(Basic_Model, self).__init__()
setattr(self, 'global_params', Params())
setattr(self, 'local_params', Params())
setattr(self, '_model_setting', Params())
setattr(self, '_hyper_params', Params())
|
class AbstractPoint(object):
__slots__ = ('x', 'y')
def __init__(self, x, y):
self.x = self.field()(x)
self.y = self.field()(y)
def __neg__(self):
return self.neg()
def __add__(self, other):
return self.add(other)
def __sub__(self, other):
return self.add(other.neg())
def __mul__(self, n):
return self.mul(n)
def __iter__(self):
return iter([self.x, self.y])
def __eq__(self, other: 'AbstractPoint'):
return other is not None and self.x == other.x and self.y == other.y
def __bool__(self):
return self != self.zero()
def __repr__(self):
return f'{type(self).__name__}(x={self.x}, y={self.y})'
@classmethod
def generator(cls):
raise NotImplementedError
@classmethod
def zero(cls):
return None
@classmethod
def field(cls):
# Field used for X and Y coordinates
raise NotImplementedError
@classmethod
def order(cls):
return cls.group().order()
@classmethod
def group(cls):
# Group
raise NotImplementedError
def neg(self):
raise NotImplementedError
def add(self, other: 'AbstractPoint'):
raise NotImplementedError
def double(self, other: 'AbstractPoint'):
raise NotImplementedError
def mul(self, scalar):
scalar = int(scalar)
if scalar == 1:
return self
p = self
a = self.zero()
while scalar != 0:
if (scalar & 1) != 0:
a = p.add(a)
p = p.double()
scalar = scalar // 2
return a
class AbstractPointG1(AbstractPoint):
def pairing(self, other: 'AbstractPointG2'):
return self.group().pairing(self, other)
class AbstractPointG2(AbstractPoint):
def pairing(self, other: AbstractPointG1):
return self.group().pairing(other, self)
class AbstractGroup(object):
@classmethod
def order(cls):
raise NotImplementedError
@classmethod
def G1(cls):
"""Returns class for G1 group"""
raise NotImplementedError
@classmethod
def G2(cls):
"""Returns class for G2 group"""
raise NotImplementedError
@classmethod
def GT(cls):
"""Returns class for target group"""
raise NotImplementedError
@classmethod
def pairing(cls, a: AbstractPointG1, b: AbstractPointG2):
assert isinstance(a, self.G1())
assert isinstance(b, self.G2())
raise NotImplementedError
|
class Animal:
cat = "cat"
dog = "dog"
panda = "panda"
koala = "koala"
fox = "fox"
bird = "bird"
racoon = "racoon"
kangaroo = "kangaroo"
elephant = "elephant"
giraffe = "giraffe"
whale = "whale"
birb = "birb"
raccoon = "raccoon"
class Gif:
wink = "wink"
pat = "pat"
hug = "hug"
facepalm = "face-palm"
class Filter:
greyscale = "greyscale"
invert = "invert"
invertgreyscale = "invertgreyscale"
brightness = "brightness"
threshold = "threshold"
sepia = "sepia"
red = "red"
green = "green"
blue = "blue"
blurple = "blurple"
pixelate = "pixelate"
blur = "blur"
gay = "gay"
glass = "glass"
wasted = "wasted"
triggered = "triggered"
spin = "spin"
|
##### Functions ################################################################
def lgis3( seq, count ):
'''
Returns reversed version of (a) longest increasing subsequence.
seq: the sequence for which (a) longest increasing subsequence is desired.
count: number of items in seq
Notes:
Uses "Patience Sorting"
Each 'pile' is a subsequence with the opposite polarity {decreasing} to
that of the desired longest subsequence {increasing}
**LOGIC**: when backtracking, once an element from a pile is selected,
all elements to the left are larger, and all to the right are smaller
THUS only one element from each pile can be used in an increasing subseq
'''
# list of lists of decreasing subsequences
piles = []
# all possible indices that could be used for decreasing subsequences
# -- i.e. if whole sequence is increasing
pile_indices = range(count)
# loop appends each item to the end of first 'pile' for which it continues
# the descending subsequence
# the second value in each tuple is the index + 1 of the preceeding
# pile's last element (or -1 if no preceeding pile)
# this allows the traceback to find the last element from the
# preceeding pile that was added before this element
for item in seq:
# using for & break is simpler and faster than the original
# elminating range(len(piles)) and catching the exception when going
# beyond the end of the list (instead of using else) gives an
# additional slight improvement in speed
try:
for j in pile_indices:
if piles[j][-1][0] > item:
# pile index
idx = j
# append tuple comprising the current item and the position
# of the preceeding pile's last element (for traceback)
piles[idx].append(
(
item,
len(piles[idx-1]) if idx > 0 else -1
)
)
# resume outer loop
break
except:
# start a new pile each time the current element is larger than the
# last element of all current piles
piles.append(
[(
item,
# length of the last 'pile' (before this one is created)
len(piles[-1]) if piles else -1
)]
)
# the increasing subsequence (reversed)
result = []
# backward pointer -- index of last item in the preceeding pile that was
# added before the current item
point_back = -1
# reverse iteration over the piles
for i in range( len(piles) - 1, -1, -1 ):
result.append( piles[i][point_back][0] )
point_back = piles[i][point_back][1] - 1
return result
##### Execution ################################################################
# read permutation from file
with open('input.txt', 'r') as infile:
# size of permutation
count = int(infile.readline().strip())
# sequence of permutation
seq = [int(item) for item in infile.readline().split()]
# write results to file
with open('output.txt', 'w') as outfile:
outfile.write(
" ".join(map(str, lgis3(seq, count)[::-1])) +
'\n' +
" ".join(map(str, lgis3(seq[::-1], count)))
)
|
# Copyright 2017 John McGehee
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This module is for testing pyfakefs
:py:class:`fake_filesystem_unittest.Patcher`. It defines attributes that have
the same names as file modules, sudh as 'io` and `path`. Since these are not
modules, :py:class:`fake_filesystem_unittest.Patcher` should not patch them.
Whenever a new module is added to
:py:meth:`fake_filesystem_unittest.Patcher._findModules`, the corresponding
attribute should be added here and in the test
:py:class:`fake_filesystem_unittest_test.TestAttributesWithFakeModuleNames`.
"""
os = 'os attribute value'
path = 'path attribute value'
pathlib = 'pathlib attribute value'
shutil = 'shutil attribute value'
io = 'io attribute value'
|
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: promotions
Description :
date: 2022/2/13
-------------------------------------------------
"""
def fidelity_promo(order):
"""为积分为1000或以上的顾客提供5%折扣"""
return order.total() * .05 if order.customer.fidelity >= 1000 else 0
def bulk_item_promo(order):
"""单个商品为20个或以上时提供10%折扣"""
discount = 0
for item in order.cart:
if item.quantity >= 20:
discount += item.total() * .1
return discount
def large_order_promo(order):
"""订单中的不同商品达到10个或以上时提供7%折扣"""
distinct_items = {item.product for item in order.cart}
if len(distinct_items) >= 10:
return order.total() * .07
return 0
|
class Customer(object):
def __init__(self, match, customer, **kwargs):
self.id = kwargs.get('id', None)
self.match = match
self.customer = customer
def __repr__(self):
return 'Customer(id=%r, match=%r, customer=%r)' % (
self.id, self.match, self.customer)
@classmethod
def parse(cls, json):
return Customer(
id=json.get('id', None),
match=json.get('match', None),
customer=json.get('customer', None)
)
def tabular(self):
return {
'id': self.id,
'match': self.match,
'customer': self.customer
}
|
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 2 22:24:05 2019
@author: Pooyan
"""
#this code must be checked
x=10
if x<20:
print('hello...')
else:
print('good Bye')
|
# -*- coding: utf-8 -*-
"""
322. Coin Change
You are given coins of different denominations and a total amount of money amount.
Write a function to compute the fewest number of coins that you need to make up that amount.
If that amount of money cannot be made up by any combination of the coins, return -1.
Note:
You may assume that you have an infinite number of each kind of coin.
"""
class Solution:
def __init__(self):
self.cache = {0: 0}
def coinChange(self, coins, amount):
if amount < 0:
return -1
if amount == 0:
return 0
if amount in self.cache:
return self.cache[amount]
coins = sorted(coins)
coin = 1
while coin <= amount:
if coin in coins:
count = 1
else:
tmp = []
for i in coins[::-1]:
res = coin - i
if res < 0:
continue
c = self.cache[res]
if c > 0:
tmp.append(c)
if tmp == []:
count = -1
else:
count = min(tmp) + 1
self.cache[coin] = count
coin += 1
return self.cache[amount]
|
{
'variables': {
'zmq_shared%': 'false',
'zmq_draft%': 'false',
'zmq_no_sync_resolve%': 'false',
},
'targets': [
{
'target_name': 'libzmq',
'type': 'none',
'conditions': [
["zmq_shared == 'false'", {
'actions': [{
'action_name': 'build_libzmq',
'inputs': ['package.json'],
'outputs': ['libzmq/lib'],
'action': ['sh', '<(PRODUCT_DIR)/../../script/build.sh', '<(target_arch)'],
}],
}],
],
},
{
'target_name': 'zeromq',
'dependencies': ['libzmq'],
'sources': [
'src/context.cc',
'src/incoming_msg.cc',
'src/module.cc',
'src/observer.cc',
'src/outgoing_msg.cc',
'src/proxy.cc',
'src/socket.cc',
],
'include_dirs': [
"vendor",
'<(PRODUCT_DIR)/../libzmq/include',
],
'defines': [
'NAPI_VERSION=3',
'NAPI_DISABLE_CPP_EXCEPTIONS',
'ZMQ_STATIC',
],
'conditions': [
["zmq_draft == 'true'", {
'defines': [
'ZMQ_BUILD_DRAFT_API',
],
}],
["zmq_no_sync_resolve == 'true'", {
'defines': [
'ZMQ_NO_SYNC_RESOLVE',
],
}],
["zmq_shared == 'true'", {
'link_settings': {
'libraries': ['-lzmq'],
},
}, {
'conditions': [
['OS != "win"', {
'libraries': [
'<(PRODUCT_DIR)/../libzmq/lib/libzmq.a',
],
}],
['OS == "win"', {
'msbuild_toolset': 'v141',
'libraries': [
'<(PRODUCT_DIR)/../libzmq/lib/libzmq',
'ws2_32.lib',
'iphlpapi',
],
}],
],
}],
],
'configurations': {
'Debug': {
'conditions': [
['OS == "linux" or OS == "freebsd" or OS == "openbsd" or OS == "solaris"', {
'cflags_cc!': [
'-std=gnu++0x',
'-std=gnu++1y'
],
'cflags_cc+': [
'-std=c++17',
'-Wno-missing-field-initializers',
],
}],
['OS == "mac"', {
'xcode_settings': {
# https://pewpewthespells.com/blog/buildsettings.html
'CLANG_CXX_LIBRARY': 'libc++',
'CLANG_CXX_LANGUAGE_STANDARD': 'c++17',
'MACOSX_DEPLOYMENT_TARGET': '10.9',
'WARNING_CFLAGS': [
'-Wextra',
'-Wno-unused-parameter',
'-Wno-missing-field-initializers',
],
},
}],
['OS == "win"', {
'msvs_settings': {
'VCCLCompilerTool': {
# 0 - MultiThreaded (/MT)
# 1 - MultiThreadedDebug (/MTd)
# 2 - MultiThreadedDLL (/MD)
# 3 - MultiThreadedDebugDLL (/MDd)
'RuntimeLibrary': 3,
'AdditionalOptions': [
'-std:c++17',
],
},
},
}],
],
},
'Release': {
'conditions': [
['OS == "linux" or OS == "freebsd" or OS == "openbsd" or OS == "solaris"', {
'cflags_cc!': [
'-std=gnu++0x',
'-std=gnu++1y'
],
'cflags_cc+': [
'-std=c++17',
'-flto',
'-Wno-missing-field-initializers',
],
}],
['OS == "mac"', {
# https://pewpewthespells.com/blog/buildsettings.html
'xcode_settings': {
'CLANG_CXX_LIBRARY': 'libc++',
'CLANG_CXX_LANGUAGE_STANDARD': 'c++17',
'MACOSX_DEPLOYMENT_TARGET': '10.9',
'LLVM_LTO': 'YES',
'GCC_OPTIMIZATION_LEVEL': '3',
'DEPLOYMENT_POSTPROCESSING': 'YES',
'GCC_SYMBOLS_PRIVATE_EXTERN': 'YES',
'DEAD_CODE_STRIPPING': 'YES',
},
}],
['OS == "win"', {
'msvs_settings': {
'VCCLCompilerTool': {
# 0 - MultiThreaded (/MT)
# 1 - MultiThreadedDebug (/MTd)
# 2 - MultiThreadedDLL (/MD)
# 3 - MultiThreadedDebugDLL (/MDd)
'RuntimeLibrary': 2,
'AdditionalOptions': [
'-std:c++17',
],
},
'VCLinkerTool': {
'AdditionalOptions': ['/ignore:4099'],
},
},
}],
],
},
},
},
],
}
|
#n! = 1 * 2 * 3 * 4 ..... * n
#n! = [1 * 2 * 3 * 4 ..... n-1]* n
#n! = n * (n-1)!
# n = 7
# product = 1
# for i in range(n):
# product = product * (i+1)
# print(product)
def factorial_iter(n):
product = 1
for i in range(n):
product = product * (i+1)
return product
def factorial_recursive(n):
if n == 1 or n ==0:
return 1
return n * factorial_recursive(n-1)
# f = factorial_iter(5)
f = factorial_recursive(3)
print(f)
|
def remove_whilespace_nodes(node, unlink=False):
"""Removes all of the whitespace-only text decendants of a DOM node.
When creating a DOM from an XML source, XML parsers are required to
consider several conditions when deciding whether to include
whitespace-only text nodes. This function ignores all of those
conditions and removes all whitespace-only text decendants of the
specified node. If the unlink flag is specified, the removed text
nodes are unlinked so that their storage can be reclaimed. If the
specified node is a whitespace-only text node then it is left
unmodified."""
remove_list = []
for child in node.childNodes:
if child.nodeType == dom.Node.TEXT_NODE and \
not child.data.strip():
remove_list.append(child)
elif child.hasChildNodes():
remove_whilespace_nodes(child, unlink)
for node in remove_list:
node.parentNode.removeChild(node)
if unlink:
node.unlink()
|
"""
16204. 카드 뽑기
작성자: xCrypt0r
언어: Python 3
사용 메모리: 29,380 KB
소요 시간: 76 ms
해결 날짜: 2020년 9월 13일
"""
def main():
N, M, K = map(int, input().split())
print(min(M, K) - max(M, K) + N)
if __name__ == '__main__':
main()
|
"""
image process detail
byte, int, float, double, rgb
"""
|
n1 = int(input('Digite o valor: '))
n2 = int(input('Digite o valor: '))
s = n1+n2
print('A soma de {} e {} é {}'.format(n1, n2, s))
|
#!/usr/bin/env python2
# The MIT License (MIT)
#
# Copyright (c) 2015 Shane O'Connor
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
rgb_colors = dict(
neon_green = '#39FF14',
brown = '#774400',
purple = '#440077',
cornflower_blue = '#6495ED',
firebrick = '#B22222',
)
|
class Cell:
def __init__(self, c=' '):
self.c = c
self.highlight = {}
def __mul__(self, n):
return [Cell(self.c) for i in range(n)]
def __str__(self):
return self.c
class Highlight:
def __init__(self, line, highlight):
self.line = line
self.highlight = highlight
self.start = 0
self.end = 0
def s(self):
return (self.line, self.start, self.end, tuple(self.highlight.items()))
def __eq__(self, h):
return self.s() == h.s()
def __hash__(self):
return hash((self.line, self.start, self.end, tuple(self.highlight.items())))
class Screen:
def __init__(self):
self.x = 0
self.y = 0
self.resize(1, 1)
self.highlight = {}
self.changes = 0
def resize(self, w, h):
self.w = w
self.h = h
# TODO: should resize clear?
self.screen = [Cell() * w for i in range(h)]
self.scroll_region = [0, self.h, 0, self.w]
# clamp cursor
self.x = min(self.x, w - 1)
self.y = min(self.y, h - 1)
def clear(self):
self.resize(self.w, self.h)
def scroll(self, dy):
ya, yb = self.scroll_region[0:2]
xa, xb = self.scroll_region[2:4]
yi = (ya, yb)
if dy < 0:
yi = (yb, ya - 1)
for y in range(yi[0], yi[1], int(dy / abs(dy))):
if ya <= y + dy < yb:
self.screen[y][xa:xb] = self.screen[y + dy][xa:xb]
else:
self.screen[y][xa:xb] = Cell() * (xb - xa)
def redraw(self, updates):
blacklist = [
'mode_change',
'bell', 'mouse_on', 'highlight_set',
'update_fb', 'update_bg', 'update_sp', 'clear',
]
changed = False
for cmd in updates:
if not cmd:
continue
name, args = cmd[0], cmd[1:]
if name == 'cursor_goto':
self.y, self.x = args[0]
elif name == 'eol_clear':
changed = True
self.screen[self.y][self.x:] = Cell() * (self.w - self.x)
elif name == 'put':
changed = True
for cs in args:
for c in cs:
cell = self.screen[self.y][self.x]
cell.c = c
cell.highlight = self.highlight
self.x += 1
# TODO: line wrap is not specified, neither is wrapping off the end. semi-sane defaults.
if self.x >= self.w:
self.x = 0
self.y += 1
if self.y >= self.h:
self.y = 0
elif name == 'resize':
changed = True
self.resize(*args[0])
elif name == 'highlight_set':
self.highlight = args[0][0]
elif name == 'set_scroll_region':
self.scroll_region = args[0]
elif name == 'scroll':
changed = True
self.scroll(args[0][0])
elif name in blacklist:
pass
# else:
# print('unknown update cmd', name)
if changed:
self.changes += 1
def highlights(self):
hlset = []
for y, line in enumerate(self.screen):
cur = {}
h = None
for x, cell in enumerate(line):
if h and cur and cell.highlight == cur:
h.end = x + 1
else:
cur = cell.highlight
if cur:
h = Highlight(y, cur)
h.start = x
h.end = x + 1
hlset.append(h)
return hlset
def p(self):
print('-' * self.w)
print(str(self))
print('-' * self.w)
def __setitem__(self, xy, c):
x, y = xy
try:
cell = self.screen[y][x]
cell.c = c
cell.highlight = self.highlight
except IndexError:
pass
def __getitem__(self, y):
if isinstance(y, tuple):
return self.screen[y[1]][y[0]]
return ''.join(str(c) for c in self.screen[y])
def __str__(self):
return '\n'.join([self[y] for y in range(self.h)])
|
def parse_args(r_args):
columns = r_args.get('columns')
args = {key:value for (key,value) in r_args.items() if key not in ('columns', 'api_key')}
return columns, args
|
class Solution:
def updateMatrix(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
queue = collections.deque()
for i, row in enumerate(matrix):
for j, val in enumerate(row):
if val == 0:
queue.append((i, j))
else:
matrix[i][j] = float('inf')
m, n = len(matrix), len(matrix[0])
step = 0
while queue:
step += 1
size = len(queue)
for _ in range(size):
i, j = queue.popleft()
for di, dj in ((-1, 0), (1, 0), (0, 1), (0, -1)):
newi, newj = i + di, j + dj
if 0 <= newi < m and 0 <= newj < n and matrix[newi][newj] == float('inf'):
matrix[newi][newj] = step
queue.append((newi, newj))
return matrix
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Config(object):
config = None
def __init__(self, config):
self.config = config
def __str__(self):
return str(self.config)
def __getitem__(self, item):
return self.config[item]
def interactive(self):
return self.config['app']['interactive']
def dry(self):
return self.config['app']['dry']
def log_file(self):
return self.config['app']['log-file']
def log_level(self):
return self.config['app']['log-level']
def pid_file(self):
return self.config['app']['pid_file']
def ch_config_folder(self):
return self.config['manager']['config-folder']
def ch_config_file(self):
return self.config['manager']['config.xml']
def ch_config_user_file(self):
return self.config['manager']['user.xml']
def ssh_username(self):
return self.config['ssh']['username']
def ssh_password(self):
return self.config['ssh']['password']
def ssh_port(self):
return self.config['ssh']['port']
|
palavra = ('Curso', 'Video', 'Python')
qualPalavra = 0
qualLetra = 0
while True:
if palavra[qualPalavra][qualLetra] in 'AaEeIiOoUu':
print(palavra[qualPalavra])
|
# -*- coding: utf-8 -*-
"""
@project: Sorting-Algorithms
@version: v1.0.0
@file: heap_sort.py
@brief: Heap Sort
@software: PyCharm
@author: Kai Sun
@email: autosunkai@gmail.com
@date: 2021/8/4 20:42
@updated: 2021/8/4 20:42
"""
def build_heap(arr):
for i in range(len(arr) // 2 - 1, -1, -1): # 从 n / 2 - 1 到 0 开始建堆
heapify(arr, len(arr), i)
def heapify(arr, n, i):
"""
:param arr: 要建堆的数组
:param n: 堆的长度
:param i: 要入堆的元素的索引
:return: None
"""
left = 2 * i + 1 # 左子节点
right = 2 * i + 2 # 右子节点
largest = i
if left < n and arr[left] > arr[largest]:
largest = left
if right < n and arr[right] > arr[largest]:
largest = right
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
heapify(arr, n, largest)
def heap_sort(arr):
build_heap(arr)
for l in range(len(arr) - 1, 0, -1): # 从 n - 1 到 1 重复堆化
arr[0], arr[l] = arr[l], arr[0]
heapify(arr, l, 0)
return arr
|
""" This file is create and managed by Tahir Iqbal
----------------------------------------------
It can be use only for education purpose
"""
# Printing Single and Double Quote
# single quote should print in double quotes
single = "Python's"
print(single)
# double quote should print in single quotes
double = 'Python"s'
print(double)
# single quote prints in single quotes use \ sign
singles = 'Python\'s'
print(singles)
# double quote prints in double quotes use \ sign
doubles = "Python\"s"
print(doubles)
|
'''
Created on 2016年2月8日
@author: Darren
'''
'''
Greedy Gift Givers
A group of NP (2 ≤ NP ≤ 10) uniquely named friends has decided to exchange gifts of money. Each of these friends might or might not give some money to any or all of the other friends. Likewise, each friend might or might not receive money from any or all of the other friends. Your goal in this problem is to deduce how much more money each person gives than they receive.
The rules for gift-giving are potentially different than you might expect. Each person sets aside a certain amount of money to give and divides this money evenly among all those to whom he or she is giving a gift. No fractional money is available, so dividing 3 among 2 friends would be 1 each for the friends with 1 left over -- that 1 left over stays in the giver's "account".
In any group of friends, some people are more giving than others (or at least may have more acquaintances) and some people have more money than others.
Given a group of friends, no one of whom has a name longer than 14 characters, the money each person in the group spends on gifts, and a (sub)list of friends to whom each person gives gifts, determine how much more (or less) each person in the group gives than they receive.
IMPORTANT NOTE
The grader machine is a Linux machine that uses standard Unix conventions: end of line is a single character often known as '\n'. This differs from Windows, which ends lines with two charcters, '\n' and '\r'. Do not let your program get trapped by this!
PROGRAM NAME: gift1
INPUT FORMAT
Line 1: The single integer, NP
Lines 2..NP+1: Each line contains the name of a group member
Lines NP+2..end: NP groups of lines organized like this:
The first line in the group tells the person's name who will be giving gifts.
The second line in the group contains two numbers: The initial amount of money (in the range 0..2000) to be divided up into gifts by the giver and then the number of people to whom the giver will give gifts, NGi (0 ≤ NGi ≤ NP-1).
If NGi is nonzero, each of the next NGi lines lists the the name of a recipient of a gift.
SAMPLE INPUT (file gift1.in)
5
dave
laura
owen
vick
amr
dave
200 3
laura
owen
vick
owen
500 1
dave
amr
150 2
vick
owen
laura
0 2
amr
vick
vick
0 0
OUTPUT FORMAT
The output is NP lines, each with the name of a person followed by a single blank followed by the net gain or loss (final_money_value - initial_money_value) for that person. The names should be printed in the same order they appear on line 2 of the input.
All gifts are integers. Each person gives the same integer amount of money to each friend to whom any money is given, and gives as much as possible that meets this constraint. Any money not given is kept by the giver.
SAMPLE OUTPUT (file gift1.out)
dave 302
laura 66
owen -359
vick 141
amr -150
'''
def gift1():
file_in=open("gift1.in", "r")
N=int(file_in.readline())
person=[]
d={}
for _count in range(N):
name=file_in.readline().strip()
person.append(name)
d[name]=0
for _count in range(N):
name=file_in.readline().strip()
money,receiver_count=list(map(int,file_in.readline().strip().split(" ")))
if receiver_count==0:
continue
each_money=money//receiver_count
d[name]-=each_money*receiver_count
for person_count in range(receiver_count):
receiver=file_in.readline().strip()
d[receiver]+=each_money
for name in person:
print(name,d[name])
gift1()
|
"""California county names"""
bay_area_counties = [
"alameda",
"contra_costa",
"marin",
"napa",
"san_francisco",
"san_mateo",
"santa_clara",
"sonoma",
"solano"
]
other_ca_counties = [
"amador",
"butte",
"calaveras",
"colusa",
"del_norte",
"el_dorado",
"fresno",
"glenn",
"humboldt",
"imperial",
"inyo",
"kern",
"kings",
"lake",
"lassen",
"los_angeles",
"madera",
"mariposa",
"mendocino",
"merced",
"modoc",
"mono",
"monterey",
"nevada",
"orange",
"placer",
"plumas",
"riverside",
"sacramento",
"san_benito",
"san_bernardino",
"san_diego",
"san_joaquin",
"san_luis_obispo",
"santa_barbara",
"santa_cruz",
"shasta",
"siskiyou",
"stanislaus",
"sutter",
"tehama",
"trinity",
"tulare",
"tuolumne",
"ventura",
"yolo",
"yuba"
]
|
def to_batch_seq(batch):
q_seq = []
history = []
label = []
for item in batch:
q_seq.append(item['question_tokens'])
history.append(item["history"])
label.append(item["label"])
return q_seq, history, label
# CHANGED
def to_batch_tables(batch, table_type):
# col_lens = []
col_seq = []
tname_seqs = []
par_tnum_seqs = []
foreign_keys = []
for item in batch:
ts = item["ts"]
tname_toks = [x.split(" ") for x in ts[0]]
col_type = ts[2]
cols = [x.split(" ") for xid, x in ts[1]]
tab_seq = [xid for xid, x in ts[1]]
cols_add = []
for tid, col, ct in zip(tab_seq, cols, col_type):
col_one = [ct]
if tid == -1:
tabn = ["all"]
else:
if table_type == "no":
tabn = []
elif table_type == "struct":
tabn = []
else:
tabn = tname_toks[tid]
for t in tabn:
if t not in col:
col_one.append(t)
col_one.extend(col)
cols_add.append(col_one)
col_seq.append(cols_add)
tname_seqs.append(tname_toks)
par_tnum_seqs.append(tab_seq)
foreign_keys.append(ts[3])
return col_seq, tname_seqs, par_tnum_seqs, foreign_keys
def to_batch_from_candidates(par_tab_nums, batch):
from_candidates = []
for idx, item in enumerate(batch):
table_candidate = item["from"]
col_candidates = [0]
for col, par in enumerate(par_tab_nums[idx]):
if str(par) in table_candidate:
col_candidates.append(col)
from_candidates.append(col_candidates)
return from_candidates
def make_compound_table(dev_db_compound_num, table_dict, my_db_id, db_ids):
if dev_db_compound_num == 0:
return table_dict[my_db_id]
selected_db_ids = random.sample(db_ids, dev_db_compound_num)
if my_db_id in selected_db_ids:
selected_db_ids.remove(my_db_id)
compound_table = deepcopy(table_dict[my_db_id])
for dev_db_id in selected_db_ids:
new_table = table_dict[dev_db_id]
if random.randint(0, 10) < 5:
new_table = compound_table
compound_table = deepcopy(table_dict[dev_db_id])
compound_table = append_table(compound_table, new_table)
return compound_table
def append_table(compound_table, new_table):
for table_name in new_table["table_names"]:
if table_name in compound_table["table_names"]:
return compound_table
new_table_offset = len(compound_table["table_names"])
new_column_offset = len(compound_table["column_names"]) - 1
compound_table["table_names"].extend(new_table["table_names"])
compound_table["table_names_original"].extend(new_table["table_names_original"])
for p in new_table["primary_keys"]:
compound_table["primary_keys"].append(p + new_column_offset)
for f, p in new_table["foreign_keys"]:
compound_table["foreign_keys"].append([f + new_column_offset, p + new_column_offset])
compound_table["column_types"].extend(new_table["column_types"])
for t, name in new_table["column_names_original"][1:]:
compound_table["column_names_original"].append([t + new_table_offset, name])
for t, name in new_table["column_names"][1:]:
compound_table["column_names"].append([t + new_table_offset, name])
return compound_table
def index_to_column_name(index, table):
column_name = table["column_names"][index][1]
table_index = table["column_names"][index][0]
table_name = table["table_names"][table_index]
return table_name, column_name, index
|
def horn(coefs, x0):
n = len(coefs)
b = coefs[0]
for index in range(1,n):
b = coefs[index] + b * x0
return b
j=horn([2,2,3,-21,8],8)
print(j)
|
nome = input('Qual o seu nome?')
print('É um grande prazer te conhecer,', nome)
idade = input('Quantos anos você tem?')
print('Bacana que você tem', idade,'anos', nome,'!')
filho = input('Você tem filhos?')
print('Que bacana!')
nomeFilho = input('Qual o nome do seu filho?')
print('Então ele se chama', nomeFilho, '!')
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
# SOURCE: https://www.codewars.com/kata/5ef9ca8b76be6d001d5e1c3e/train/python
def chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(l), n):
yield l[i: i + n]
# Task 1: Encode function
#
# Implement the encode function, using the following steps:
# - convert every letter of the text to its ASCII value;
# - convert ASCII values to 8-bit binary;
# - triple every bit;
# - concatenate the result;
#
# For example:
# input: "hey"
# --> 104, 101, 121 // ASCII values
# --> 01101000, 01100101, 01111001 // binary
# --> 000111111000111000000000 000111111000000111000111 000111111111111000000111 // tripled
# --> "000111111000111000000000000111111000000111000111000111111111111000000111" // concatenated
def encode(text: str) -> str:
return ''.join(
''.join(b * 3 for b in f"{ord(c):08b}") # Tripled bits
for c in text
)
# Task 2: Decode function:
# Check if any errors happened and correct them. Errors will be only bit flips, and not a loss of bits:
# - 111 --> 101 : this can and will happen
# - 111 --> 11 : this cannot happen
#
# Note: the length of the input string is also always divisible by 24 so that you can convert it to an ASCII value.
#
# Steps:
# - Split the input into groups of three characters;
# - Check if an error occurred: replace each group with the character that occurs most often,
# e.g. 010 --> 0, 110 --> 1, etc;
# - Take each group of 8 characters and convert that binary number;
# - Convert the binary values to decimal (ASCII);
# - Convert the ASCII values to characters and concatenate the result
#
# For example:
# input: "100111111000111001000010000111111000000111001111000111110110111000010111"
# --> 100, 111, 111, 000, 111, 001, ... // triples
# --> 0, 1, 1, 0, 1, 0, ... // corrected bits
# --> 01101000, 01100101, 01111001 // bytes
# --> 104, 101, 121 // ASCII values
# --> "hey"
def decode(bits: str) -> str:
bit_items = []
for tripled_bits in chunks(bits, 3):
sums = sum(map(int, tripled_bits))
# Example: 110 or 111 -> 1 and 000 -> 0 or 001 -> 0
bit_items.append('1' if sums == 2 or sums == 3 else '0')
binary = ''.join(bit_items)
items = []
for byte in chunks(binary, 8):
items.append(chr(int(byte, 2)))
return ''.join(items)
if __name__ == '__main__':
text = 'hey'
encoded = encode(text)
print(encoded)
assert encoded == '000111111000111000000000000111111000000111000111000111111111111000000111'
decoded = decode(encoded)
print(decoded)
assert text == decoded
invalid_encoded = '100111111000111001000010000111111000000111001111000111110110111000010111'
decoded = decode(invalid_encoded)
print(decoded)
assert text == decoded
|
class TradingDayData:
def __init__(self, pricebars, tradingday):
self.__pricebars = pricebars
self.__tradingday = tradingday
@property
def price_bars(self):
return self.__pricebars
|
# MEDIUM
# since this is looking for permutation, the Time would be O(N!)
# 1. first check if the input can form a palindrome => only <=1 odd occured char can used
# 2. only permutate the half of the input == permutation II
# eg. input = "aabb"
# only permutate ["a","b"], append reversed(input) to the end
# Time O(N/2 !) Space O(N)
class Solution:
def generatePalindromes(self, s: str) -> List[str]:
check = [0]* 128
half = [0]* (len(s)//2)
if not self.canPalin(s,check):
return []
k = 0
ch =0
for i in range(128):
if check[i]%2== 1:
ch = chr(i)
for j in range(check[i]//2):
half[k] = chr(i)
k +=1
print(ch)
print(half)
result = set([])
self.dfs(half,0,ch,result)
return list(result)
def dfs(self,half,index,ch,result):
if index == len(half):
if ch:
result.add("".join(half) + ch + "".join(reversed(half)) )
else:
result.add("".join(half) + "".join(reversed(half)) )
return
check = set([])
for i in range(index,len(half)):
if half[i] not in check:
check.add(half[i])
half[i],half[index] = half[index],half[i]
self.dfs(half,index+1,ch,result)
half[i],half[index] = half[index],half[i]
def isPalin(self,s):
i,j = 0,len(s)-1
while i<j:
if s[i]!= s[j]:
return False
i+= 1
j -= 1
return True
def canPalin(self,s,check):
count = 0
for i in range(len(s)):
t = ord(s[i])
check[t] += 1
if check[t] %2 == 0:
count -= 1
else:
count += 1
return count <= 1
|
'''
Created on 15 May 2018
@author: igoroya
'''
def read_text(file_path):
my_file = open(file_path, 'r', encoding="utf-8")
text = my_file.read()
my_file.close()
return text
def print_text(text):
print(text)
def get_lines(text):
return text.split("\n")
def get_words(text):
words = []
lines = get_lines(text)
for entry in lines:
for w in entry.split(" "):
words.append(w)
return words
def get_letters(text):
letters = []
words = get_words(text)
for w in words:
for letter in w:
letters.append(letter)
return letters
def print_words(words):
for word in words:
print(word)
def get_text_stats(text):
lines = len(get_lines(text))
words = len(get_words(text))
letters = len(get_letters(text))
print('Text Stats')
print('lines: {}, words: {}, letters: {}'.format(lines, words, letters))
def find_letter_occurences(text):
letter_set = set(get_letters(text.lower()))
letter_occurence = dict()
for letter in letter_set:
letter_occurence[count_occurrences(text, letter)] = letter
print(sorted(letter_occurence))
print('Occurrence of letters')
print('Letter: times')
for key in sorted(letter_occurence, reverse=True):
print("%s: %s" % (letter_occurence[key], key))
def count_occurrences(text, letter):
return text.count(letter)
if __name__ == '__main__':
text = read_text('Text')
get_text_stats(text)
print()
find_letter_occurences(text)
|
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
if not s:
return True
m, n = 0, len(s) - 1
i, j = 0, len(t) - 1
while i <= j and m <= n:
if t[i] == s[m]:
m += 1
i += 1
else:
i += 1
if t[j] == s[n]:
j -= 1
n -= 1
else:
j -= 1
return m > n
s = Solution()
print(s.isSubsequence("aa", "ahbgdc"))
|
# Exemplo estrutura dicionário em python
contatosTelefone = {
"Joao": "11-99999-9999",
"Maria": "11-98888-8888"
}
#Exibindo chaves do dicionário
print("Keys: ",contatosTelefone.keys())
#Exibindo valores do dicioário
print("Valores: ",contatosTelefone.values())
#Exibindo chaves e valoreas através do laço for
for chave,valor in contatosTelefone.items():
print(chave,"->",valor)
|
"""
Copyright 2015 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
class ZoneFile(object):
def __init__(self, origin, ttl, records):
self.origin = origin
self.ttl = ttl
self.records = records
def __str__(self):
return str(self.__dict__)
def __repr__(self):
return str(self)
def __eq__(self, other):
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self.__eq__(other)
@classmethod
def from_text(cls, text):
"""Return a ZoneFile from a string containing the zone file contents"""
# filter out empty lines and strip all leading/trailing whitespace.
# this assumes no multiline records
lines = [x.strip() for x in text.split('\n') if x.strip()]
assert lines[0].startswith('$ORIGIN')
assert lines[1].startswith('$TTL')
return ZoneFile(
origin=lines[0].split(' ')[1],
ttl=int(lines[1].split(' ')[1]),
records=[ZoneFileRecord.from_text(x) for x in lines[2:]],
)
class ZoneFileRecord(object):
def __init__(self, name, type, data):
self.name = str(name)
self.type = str(type)
self.data = str(data)
def __str__(self):
return str(self.__dict__)
def __repr__(self):
return str(self)
def __eq__(self, other):
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self.__eq__(other)
def __hash__(self):
return hash(tuple(sorted(self.__dict__.items())))
@classmethod
def from_text(cls, text):
"""Create a ZoneFileRecord from a line of text of a zone file, like:
mydomain.com. IN NS ns1.example.com.
"""
# assumes records don't have a TTL between the name and the class.
# assumes no parentheses in the record, all on a single line.
parts = [x for x in text.split(' ', 4) if x.strip()]
name, rclass, rtype, data = parts
assert rclass == 'IN'
return cls(name=name, type=rtype, data=data)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
"""
def add_two(a, b):
return a + b
if __name__ == "__main__":
# print(add_two.__code__)
pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.